grafana_path.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package utils
  2. import (
  3. "os"
  4. "path"
  5. "path/filepath"
  6. "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
  7. "golang.org/x/xerrors"
  8. )
  9. func GetGrafanaPluginDir(currentOS string) string {
  10. if rootPath, ok := tryGetRootForDevEnvironment(); ok {
  11. return filepath.Join(rootPath, "data/plugins")
  12. }
  13. return returnOsDefault(currentOS)
  14. }
  15. // getGrafanaRoot tries to get root of directory when developing grafana ie repo root. It is not perfect it just
  16. // checks what is the binary path and tries to guess based on that but if it is not running in dev env you get a bogus
  17. // path back.
  18. func getGrafanaRoot() (string, error) {
  19. ex, err := os.Executable()
  20. if err != nil {
  21. return "", xerrors.New("Failed to get executable path")
  22. }
  23. exPath := filepath.Dir(ex)
  24. _, last := path.Split(exPath)
  25. if last == "bin" {
  26. // In dev env the executable for current platform is created in 'bin/' dir
  27. return filepath.Join(exPath, ".."), nil
  28. }
  29. // But at the same time there are per platform directories that contain the binaries and can also be used.
  30. return filepath.Join(exPath, "../.."), nil
  31. }
  32. // tryGetRootForDevEnvironment returns root path if we are in dev environment. It checks if conf/defaults.ini exists
  33. // which should only exist in dev. Second param is false if we are not in dev or if it wasn't possible to determine it.
  34. func tryGetRootForDevEnvironment() (string, bool) {
  35. rootPath, err := getGrafanaRoot()
  36. if err != nil {
  37. logger.Error("Could not get executable path. Assuming non dev environment.", err)
  38. return "", false
  39. }
  40. defaultsPath := filepath.Join(rootPath, "conf/defaults.ini")
  41. _, err = os.Stat(defaultsPath)
  42. if err != nil {
  43. return "", false
  44. }
  45. return rootPath, true
  46. }
  47. func returnOsDefault(currentOs string) string {
  48. switch currentOs {
  49. case "windows":
  50. return "../data/plugins"
  51. case "darwin":
  52. return "/usr/local/var/lib/grafana/plugins"
  53. case "freebsd":
  54. return "/var/db/grafana/plugins"
  55. case "openbsd":
  56. return "/var/grafana/plugins"
  57. default: //"linux"
  58. return "/var/lib/grafana/plugins"
  59. }
  60. }