dashboards.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package plugins
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. m "github.com/grafana/grafana/pkg/models"
  8. )
  9. type PluginDashboardInfoDTO struct {
  10. PluginId string `json:"pluginId"`
  11. Title string `json:"title"`
  12. Imported bool `json:"imported"`
  13. ImportedUri string `json:"importedUri"`
  14. ImportedRevision int64 `json:"importedRevision"`
  15. Revision int64 `json:"revision"`
  16. Description string `json:"description"`
  17. Path string `json:"path"`
  18. }
  19. func GetPluginDashboards(orgId int64, pluginId string) ([]*PluginDashboardInfoDTO, error) {
  20. plugin, exists := Plugins[pluginId]
  21. if !exists {
  22. return nil, PluginNotFoundError{pluginId}
  23. }
  24. result := make([]*PluginDashboardInfoDTO, 0)
  25. for _, include := range plugin.Includes {
  26. if include.Type == PluginTypeDashboard {
  27. if dashInfo, err := getDashboardImportStatus(orgId, plugin, include.Path); err != nil {
  28. return nil, err
  29. } else {
  30. result = append(result, dashInfo)
  31. }
  32. }
  33. }
  34. return result, nil
  35. }
  36. func loadPluginDashboard(pluginId, path string) (*m.Dashboard, error) {
  37. plugin, exists := Plugins[pluginId]
  38. if !exists {
  39. return nil, PluginNotFoundError{pluginId}
  40. }
  41. dashboardFilePath := filepath.Join(plugin.PluginDir, path)
  42. reader, err := os.Open(dashboardFilePath)
  43. if err != nil {
  44. return nil, err
  45. }
  46. defer reader.Close()
  47. data, err := simplejson.NewFromReader(reader)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return m.NewDashboardFromJson(data), nil
  52. }
  53. func getDashboardImportStatus(orgId int64, plugin *PluginBase, path string) (*PluginDashboardInfoDTO, error) {
  54. res := &PluginDashboardInfoDTO{}
  55. var dashboard *m.Dashboard
  56. var err error
  57. if dashboard, err = loadPluginDashboard(plugin.Id, path); err != nil {
  58. return nil, err
  59. }
  60. res.Path = path
  61. res.PluginId = plugin.Id
  62. res.Title = dashboard.Title
  63. res.Revision = dashboard.Data.Get("revision").MustInt64(1)
  64. query := m.GetDashboardQuery{OrgId: orgId, Slug: dashboard.Slug}
  65. if err := bus.Dispatch(&query); err != nil {
  66. if err != m.ErrDashboardNotFound {
  67. return nil, err
  68. }
  69. } else {
  70. res.Imported = true
  71. res.ImportedUri = "db/" + query.Result.Slug
  72. res.ImportedRevision = query.Result.Data.Get("revision").MustInt64(1)
  73. }
  74. return res, nil
  75. }