dashboards_updater.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package plugins
  2. import (
  3. "time"
  4. "github.com/grafana/grafana/pkg/bus"
  5. m "github.com/grafana/grafana/pkg/models"
  6. )
  7. func updateAppDashboards() {
  8. time.Sleep(time.Second * 1)
  9. plog.Debug("Looking for App Dashboard Updates")
  10. query := m.GetPluginSettingsQuery{OrgId: 0}
  11. if err := bus.Dispatch(&query); err != nil {
  12. plog.Error("Failed to get all plugin settings", "error", err)
  13. return
  14. }
  15. for _, pluginSetting := range query.Result {
  16. if appDef, exist := Apps[pluginSetting.PluginId]; exist {
  17. if appDef.Info.Version != pluginSetting.PluginVersion {
  18. handleAppPluginUpdated(appDef, pluginSetting.OrgId)
  19. }
  20. }
  21. }
  22. }
  23. func autoUpdateAppDashboard(pluginDashInfo *PluginDashboardInfoDTO, orgId int64) error {
  24. if dash, err := loadPluginDashboard(pluginDashInfo.PluginId, pluginDashInfo.Path); err != nil {
  25. return err
  26. } else {
  27. plog.Info("Auto updating App dashboard", "dashboard", dash.Title, "newRev", pluginDashInfo.Revision, "oldRev", pluginDashInfo.ImportedRevision)
  28. updateCmd := ImportDashboardCommand{
  29. OrgId: orgId,
  30. PluginId: pluginDashInfo.PluginId,
  31. Overwrite: true,
  32. Dashboard: dash.Data,
  33. UserId: 0,
  34. Path: pluginDashInfo.Path,
  35. }
  36. if err := bus.Dispatch(&updateCmd); err != nil {
  37. return err
  38. }
  39. }
  40. return nil
  41. }
  42. func handleAppPluginUpdated(appDef *AppPlugin, orgId int64) {
  43. plog.Info("App update detected", "pluginId", appDef.Id)
  44. // Get plugin dashboards
  45. if dashboards, err := GetPluginDashboards(orgId, appDef.Id); err != nil {
  46. plog.Error("Failed to load app dashboards", "error", err)
  47. return
  48. } else {
  49. // Update dashboards with updated revisions
  50. for _, dash := range dashboards {
  51. if dash.ImportedRevision != dash.Revision {
  52. if err := autoUpdateAppDashboard(dash, orgId); err != nil {
  53. plog.Error("Failed to auto update app dashboard", "pluginId", appDef.Id, "error", err)
  54. return
  55. }
  56. }
  57. }
  58. }
  59. // update version in plugin_setting table to mark that we have processed the update
  60. query := m.GetPluginSettingByIdQuery{PluginId: appDef.Id, OrgId: orgId}
  61. if err := bus.Dispatch(&query); err != nil {
  62. plog.Error("Failed to read plugin setting by id", "error", err)
  63. return
  64. }
  65. appSetting := query.Result
  66. cmd := m.UpdatePluginSettingVersionCmd{
  67. OrgId: appSetting.OrgId,
  68. PluginId: appSetting.PluginId,
  69. PluginVersion: appDef.Info.Version,
  70. }
  71. if err := bus.Dispatch(&cmd); err != nil {
  72. plog.Error("Failed to update plugin setting version", "error", err)
  73. }
  74. }