services.go 1.8 KB

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