services.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/franela/goreq"
  6. "github.com/grafana/grafana/pkg/cmd/grafana-cli/log"
  7. m "github.com/grafana/grafana/pkg/cmd/grafana-cli/models"
  8. "path"
  9. )
  10. var IoHelper m.IoUtil = IoUtilImp{}
  11. func ListAllPlugins() (m.PluginRepo, error) {
  12. res, _ := goreq.Request{Uri: "https://raw.githubusercontent.com/grafana/grafana-plugin-repository/master/repo.json"}.Do()
  13. var resp m.PluginRepo
  14. err := res.Body.FromJsonTo(&resp)
  15. if err != nil {
  16. return m.PluginRepo{}, errors.New("Could not load plugin data")
  17. }
  18. return resp, nil
  19. }
  20. func ReadPlugin(pluginDir, pluginName string) (m.InstalledPlugin, error) {
  21. pluginDataPath := path.Join(pluginDir, pluginName, "plugin.json")
  22. pluginData, _ := IoHelper.ReadFile(pluginDataPath)
  23. res := m.InstalledPlugin{}
  24. json.Unmarshal(pluginData, &res)
  25. if res.Info.Version == "" {
  26. res.Info.Version = "0.0.0"
  27. }
  28. if res.Id == "" {
  29. return m.InstalledPlugin{}, errors.New("could not read find plugin " + pluginName)
  30. }
  31. return res, nil
  32. }
  33. func GetLocalPlugins(pluginDir string) []m.InstalledPlugin {
  34. result := make([]m.InstalledPlugin, 0)
  35. files, _ := IoHelper.ReadDir(pluginDir)
  36. for _, f := range files {
  37. res, err := ReadPlugin(pluginDir, f.Name())
  38. if err == nil {
  39. result = append(result, res)
  40. }
  41. }
  42. return result
  43. }
  44. func RemoveInstalledPlugin(pluginPath, id string) error {
  45. log.Infof("Removing plugin: %v\n", id)
  46. return IoHelper.RemoveAll(path.Join(pluginPath, id))
  47. }
  48. func GetPlugin(id string) (m.Plugin, error) {
  49. resp, err := ListAllPlugins()
  50. if err != nil {
  51. }
  52. for _, i := range resp.Plugins {
  53. if i.Id == id {
  54. return i, nil
  55. }
  56. }
  57. return m.Plugin{}, errors.New("could not find plugin named \"" + id + "\"")
  58. }