services.go 2.1 KB

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