Chore: Remove Dispatch and AddHandler (#42603)

* Remove Dispatch

* Remove context.TODO()

* Remove AddHandler and Dispatch
pull/41988/head
idafurjes 4 years ago committed by GitHub
parent e79fe8e84e
commit c80e7764d8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      pkg/api/admin_provisioning.go
  2. 2
      pkg/api/dashboard.go
  3. 14
      pkg/api/dashboard_snapshot.go
  4. 2
      pkg/api/plugins.go
  5. 4
      pkg/api/stars.go
  6. 8
      pkg/api/team.go
  7. 6
      pkg/api/team_members.go
  8. 49
      pkg/bus/bus.go
  9. 10
      pkg/bus/bus_test.go
  10. 2
      pkg/cmd/grafana-cli/commands/reset_password_command.go
  11. 2
      pkg/middleware/org_redirect.go
  12. 4
      pkg/plugins/ifaces.go
  13. 14
      pkg/plugins/manager/dashboards.go
  14. 2
      pkg/plugins/manager/dashboards_test.go
  15. 4
      pkg/plugins/plugindashboards/service.go
  16. 4
      pkg/services/contexthandler/contexthandler.go
  17. 6
      pkg/services/dashboards/dashboard_service.go
  18. 2
      pkg/services/dashboards/folder_service.go
  19. 6
      pkg/services/guardian/guardian.go
  20. 2
      pkg/services/provisioning/dashboards/file_reader.go
  21. 4
      pkg/services/provisioning/dashboards/file_reader_test.go
  22. 14
      pkg/services/provisioning/notifiers/alert_notifications.go
  23. 17
      pkg/services/provisioning/plugins/plugin_provisioner.go
  24. 4
      pkg/services/provisioning/plugins/plugin_provisioner_test.go
  25. 12
      pkg/services/provisioning/provisioning.go
  26. 2
      pkg/services/provisioning/provisioning_mock.go
  27. 6
      pkg/services/teamguardian/team.go
  28. 8
      pkg/services/teamguardian/teams_test.go

@ -25,7 +25,7 @@ func (hs *HTTPServer) AdminProvisioningReloadDatasources(c *models.ReqContext) r
} }
func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *models.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionPlugins() err := hs.ProvisioningService.ProvisionPlugins(c.Req.Context())
if err != nil { if err != nil {
return response.Error(500, "Failed to reload plugins config", err) return response.Error(500, "Failed to reload plugins config", err)
} }

@ -223,7 +223,7 @@ func getDashboardHelper(ctx context.Context, orgID int64, id int64, uid string)
func (hs *HTTPServer) DeleteDashboardBySlug(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDashboardBySlug(c *models.ReqContext) response.Response {
query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: web.Params(c.Req)[":slug"]} query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: web.Params(c.Req)[":slug"]}
if err := bus.Dispatch(&query); err != nil { if err := bus.DispatchCtx(c.Req.Context(), &query); err != nil {
return response.Error(500, "Failed to retrieve dashboards by slug", err) return response.Error(500, "Failed to retrieve dashboards by slug", err)
} }

@ -134,7 +134,7 @@ func CreateDashboardSnapshot(c *models.ReqContext) response.Response {
metrics.MApiDashboardSnapshotCreate.Inc() metrics.MApiDashboardSnapshotCreate.Inc()
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.DispatchCtx(c.Req.Context(), &cmd); err != nil {
c.JsonApiErr(500, "Failed to create snapshot", err) c.JsonApiErr(500, "Failed to create snapshot", err)
return nil return nil
} }
@ -158,7 +158,7 @@ func GetDashboardSnapshot(c *models.ReqContext) response.Response {
query := &models.GetDashboardSnapshotQuery{Key: key} query := &models.GetDashboardSnapshotQuery{Key: key}
err := bus.Dispatch(query) err := bus.DispatchCtx(c.Req.Context(), query)
if err != nil { if err != nil {
return response.Error(500, "Failed to get dashboard snapshot", err) return response.Error(500, "Failed to get dashboard snapshot", err)
} }
@ -226,7 +226,7 @@ func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) response.Response
query := &models.GetDashboardSnapshotQuery{DeleteKey: key} query := &models.GetDashboardSnapshotQuery{DeleteKey: key}
err := bus.Dispatch(query) err := bus.DispatchCtx(c.Req.Context(), query)
if err != nil { if err != nil {
return response.Error(500, "Failed to get dashboard snapshot", err) return response.Error(500, "Failed to get dashboard snapshot", err)
} }
@ -240,7 +240,7 @@ func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) response.Response
cmd := &models.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey} cmd := &models.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey}
if err := bus.Dispatch(cmd); err != nil { if err := bus.DispatchCtx(c.Req.Context(), cmd); err != nil {
return response.Error(500, "Failed to delete dashboard snapshot", err) return response.Error(500, "Failed to delete dashboard snapshot", err)
} }
@ -259,7 +259,7 @@ func DeleteDashboardSnapshot(c *models.ReqContext) response.Response {
query := &models.GetDashboardSnapshotQuery{Key: key} query := &models.GetDashboardSnapshotQuery{Key: key}
err := bus.Dispatch(query) err := bus.DispatchCtx(c.Req.Context(), query)
if err != nil { if err != nil {
return response.Error(500, "Failed to get dashboard snapshot", err) return response.Error(500, "Failed to get dashboard snapshot", err)
} }
@ -288,7 +288,7 @@ func DeleteDashboardSnapshot(c *models.ReqContext) response.Response {
cmd := &models.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey} cmd := &models.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey}
if err := bus.Dispatch(cmd); err != nil { if err := bus.DispatchCtx(c.Req.Context(), cmd); err != nil {
return response.Error(500, "Failed to delete dashboard snapshot", err) return response.Error(500, "Failed to delete dashboard snapshot", err)
} }
@ -314,7 +314,7 @@ func SearchDashboardSnapshots(c *models.ReqContext) response.Response {
SignedInUser: c.SignedInUser, SignedInUser: c.SignedInUser,
} }
err := bus.Dispatch(&searchQuery) err := bus.DispatchCtx(c.Req.Context(), &searchQuery)
if err != nil { if err != nil {
return response.Error(500, "Search failed", err) return response.Error(500, "Search failed", err)
} }

@ -172,7 +172,7 @@ func (hs *HTTPServer) UpdatePluginSetting(c *models.ReqContext) response.Respons
func (hs *HTTPServer) GetPluginDashboards(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginDashboards(c *models.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
list, err := hs.pluginDashboardManager.GetPluginDashboards(c.OrgId, pluginID) list, err := hs.pluginDashboardManager.GetPluginDashboards(c.Req.Context(), c.OrgId, pluginID)
if err != nil { if err != nil {
var notFound plugins.NotFoundError var notFound plugins.NotFoundError
if errors.As(err, &notFound) { if errors.As(err, &notFound) {

@ -13,7 +13,7 @@ func StarDashboard(c *models.ReqContext) response.Response {
return response.Error(400, "Missing dashboard id", nil) return response.Error(400, "Missing dashboard id", nil)
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.DispatchCtx(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "Failed to star dashboard", err) return response.Error(500, "Failed to star dashboard", err)
} }
@ -27,7 +27,7 @@ func UnstarDashboard(c *models.ReqContext) response.Response {
return response.Error(400, "Missing dashboard id", nil) return response.Error(400, "Missing dashboard id", nil)
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.DispatchCtx(c.Req.Context(), &cmd); err != nil {
return response.Error(500, "Failed to unstar dashboard", err) return response.Error(500, "Failed to unstar dashboard", err)
} }

@ -61,7 +61,7 @@ func (hs *HTTPServer) UpdateTeam(c *models.ReqContext) response.Response {
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
cmd.Id = c.ParamsInt64(":teamId") cmd.Id = c.ParamsInt64(":teamId")
if err := teamguardian.CanAdmin(hs.Bus, cmd.OrgId, cmd.Id, c.SignedInUser); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, cmd.OrgId, cmd.Id, c.SignedInUser); err != nil {
return response.Error(403, "Not allowed to update team", err) return response.Error(403, "Not allowed to update team", err)
} }
@ -81,7 +81,7 @@ func (hs *HTTPServer) DeleteTeamByID(c *models.ReqContext) response.Response {
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
user := c.SignedInUser user := c.SignedInUser
if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, user); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, orgId, teamId, user); err != nil {
return response.Error(403, "Not allowed to delete team", err) return response.Error(403, "Not allowed to delete team", err)
} }
@ -161,7 +161,7 @@ func (hs *HTTPServer) GetTeamPreferences(c *models.ReqContext) response.Response
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
orgId := c.OrgId orgId := c.OrgId
if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, c.SignedInUser); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, orgId, teamId, c.SignedInUser); err != nil {
return response.Error(403, "Not allowed to view team preferences.", err) return response.Error(403, "Not allowed to view team preferences.", err)
} }
@ -177,7 +177,7 @@ func (hs *HTTPServer) UpdateTeamPreferences(c *models.ReqContext) response.Respo
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
orgId := c.OrgId orgId := c.OrgId
if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, c.SignedInUser); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, orgId, teamId, c.SignedInUser); err != nil {
return response.Error(403, "Not allowed to update team preferences.", err) return response.Error(403, "Not allowed to update team preferences.", err)
} }

@ -51,7 +51,7 @@ func (hs *HTTPServer) AddTeamMember(c *models.ReqContext) response.Response {
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
cmd.TeamId = c.ParamsInt64(":teamId") cmd.TeamId = c.ParamsInt64(":teamId")
if err := teamguardian.CanAdmin(hs.Bus, cmd.OrgId, cmd.TeamId, c.SignedInUser); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, cmd.OrgId, cmd.TeamId, c.SignedInUser); err != nil {
return response.Error(403, "Not allowed to add team member", err) return response.Error(403, "Not allowed to add team member", err)
} }
@ -82,7 +82,7 @@ func (hs *HTTPServer) UpdateTeamMember(c *models.ReqContext) response.Response {
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
orgId := c.OrgId orgId := c.OrgId
if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, c.SignedInUser); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, orgId, teamId, c.SignedInUser); err != nil {
return response.Error(403, "Not allowed to update team member", err) return response.Error(403, "Not allowed to update team member", err)
} }
@ -109,7 +109,7 @@ func (hs *HTTPServer) RemoveTeamMember(c *models.ReqContext) response.Response {
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
userId := c.ParamsInt64(":userId") userId := c.ParamsInt64(":userId")
if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, c.SignedInUser); err != nil { if err := teamguardian.CanAdmin(c.Req.Context(), hs.Bus, orgId, teamId, c.SignedInUser); err != nil {
return response.Error(403, "Not allowed to remove team member", err) return response.Error(403, "Not allowed to remove team member", err)
} }

@ -27,7 +27,6 @@ type TransactionManager interface {
// Bus type defines the bus interface structure // Bus type defines the bus interface structure
type Bus interface { type Bus interface {
Dispatch(msg Msg) error
DispatchCtx(ctx context.Context, msg Msg) error DispatchCtx(ctx context.Context, msg Msg) error
PublishCtx(ctx context.Context, msg Msg) error PublishCtx(ctx context.Context, msg Msg) error
@ -38,7 +37,6 @@ type Bus interface {
// callback returns an error. // callback returns an error.
InTransaction(ctx context.Context, fn func(ctx context.Context) error) error InTransaction(ctx context.Context, fn func(ctx context.Context) error) error
AddHandler(handler HandlerFunc)
AddHandlerCtx(handler HandlerFunc) AddHandlerCtx(handler HandlerFunc)
AddEventListenerCtx(handler HandlerFunc) AddEventListenerCtx(handler HandlerFunc)
@ -128,37 +126,6 @@ func (b *InProcBus) DispatchCtx(ctx context.Context, msg Msg) error {
return err.(error) return err.(error)
} }
// Dispatch function dispatch a message to the bus.
func (b *InProcBus) Dispatch(msg Msg) error {
var msgName = reflect.TypeOf(msg).Elem().Name()
withCtx := true
handler := b.handlersWithCtx[msgName]
if handler == nil {
withCtx = false
handler = b.handlers[msgName]
if handler == nil {
return ErrHandlerNotFound
}
}
var params = []reflect.Value{}
if withCtx {
if setting.Env == setting.Dev {
b.logger.Warn("Dispatch called with message handler registered using AddHandlerCtx and should be changed to use DispatchCtx", "msgName", msgName)
}
params = append(params, reflect.ValueOf(context.Background()))
}
params = append(params, reflect.ValueOf(msg))
ret := reflect.ValueOf(handler).Call(params)
err := ret[0].Interface()
if err == nil {
return nil
}
return err.(error)
}
// PublishCtx function publish a message to the bus listener. // PublishCtx function publish a message to the bus listener.
func (b *InProcBus) PublishCtx(ctx context.Context, msg Msg) error { func (b *InProcBus) PublishCtx(ctx context.Context, msg Msg) error {
var msgName = reflect.TypeOf(msg).Elem().Name() var msgName = reflect.TypeOf(msg).Elem().Name()
@ -205,12 +172,6 @@ func callListeners(listeners []HandlerFunc, params []reflect.Value) error {
return nil return nil
} }
func (b *InProcBus) AddHandler(handler HandlerFunc) {
handlerType := reflect.TypeOf(handler)
queryTypeName := handlerType.In(0).Elem().Name()
b.handlers[queryTypeName] = handler
}
func (b *InProcBus) AddHandlerCtx(handler HandlerFunc) { func (b *InProcBus) AddHandlerCtx(handler HandlerFunc) {
handlerType := reflect.TypeOf(handler) handlerType := reflect.TypeOf(handler)
queryTypeName := handlerType.In(1).Elem().Name() queryTypeName := handlerType.In(1).Elem().Name()
@ -232,12 +193,6 @@ func (b *InProcBus) AddEventListenerCtx(handler HandlerFunc) {
b.listenersWithCtx[eventName] = append(b.listenersWithCtx[eventName], handler) b.listenersWithCtx[eventName] = append(b.listenersWithCtx[eventName], handler)
} }
// AddHandler attaches a handler function to the global bus.
// Package level function.
func AddHandler(implName string, handler HandlerFunc) {
globalBus.AddHandler(handler)
}
// AddHandlerCtx attaches a handler function to the global bus context. // AddHandlerCtx attaches a handler function to the global bus context.
// Package level function. // Package level function.
func AddHandlerCtx(implName string, handler HandlerFunc) { func AddHandlerCtx(implName string, handler HandlerFunc) {
@ -250,10 +205,6 @@ func AddEventListenerCtx(handler HandlerFunc) {
globalBus.AddEventListenerCtx(handler) globalBus.AddEventListenerCtx(handler)
} }
func Dispatch(msg Msg) error {
return globalBus.Dispatch(msg)
}
func DispatchCtx(ctx context.Context, msg Msg) error { func DispatchCtx(ctx context.Context, msg Msg) error {
return globalBus.DispatchCtx(ctx, msg) return globalBus.DispatchCtx(ctx, msg)
} }

@ -23,7 +23,7 @@ func TestDispatch(t *testing.T) {
return nil return nil
}) })
err := bus.Dispatch(&testQuery{}) err := bus.DispatchCtx(context.Background(), &testQuery{})
require.NoError(t, err) require.NoError(t, err)
require.True(t, invoked, "expected handler to be called") require.True(t, invoked, "expected handler to be called")
@ -32,7 +32,7 @@ func TestDispatch(t *testing.T) {
func TestDispatch_NoRegisteredHandler(t *testing.T) { func TestDispatch_NoRegisteredHandler(t *testing.T) {
bus := New() bus := New()
err := bus.Dispatch(&testQuery{}) err := bus.DispatchCtx(context.Background(), &testQuery{})
require.Equal(t, err, ErrHandlerNotFound, require.Equal(t, err, ErrHandlerNotFound,
"expected bus to return HandlerNotFound since no handler is registered") "expected bus to return HandlerNotFound since no handler is registered")
} }
@ -47,7 +47,7 @@ func TestDispatch_ContextHandler(t *testing.T) {
return nil return nil
}) })
err := bus.Dispatch(&testQuery{}) err := bus.DispatchCtx(context.Background(), &testQuery{})
require.NoError(t, err) require.NoError(t, err)
require.True(t, invoked, "expected handler to be called") require.True(t, invoked, "expected handler to be called")
@ -105,7 +105,7 @@ func TestQuery(t *testing.T) {
q := &testQuery{} q := &testQuery{}
err := bus.Dispatch(q) err := bus.DispatchCtx(context.Background(), q)
require.NoError(t, err, "unable to dispatch query") require.NoError(t, err, "unable to dispatch query")
require.Equal(t, want, q.Resp) require.Equal(t, want, q.Resp)
@ -118,7 +118,7 @@ func TestQuery_HandlerReturnsError(t *testing.T) {
return errors.New("handler error") return errors.New("handler error")
}) })
err := bus.Dispatch(&testQuery{}) err := bus.DispatchCtx(context.Background(), &testQuery{})
require.Error(t, err, "expected error but got none") require.Error(t, err, "expected error but got none")
} }

@ -57,7 +57,7 @@ func resetPasswordCommand(c utils.CommandLine, sqlStore *sqlstore.SQLStore) erro
NewPassword: passwordHashed, NewPassword: passwordHashed,
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.DispatchCtx(context.Background(), &cmd); err != nil {
return errutil.Wrapf(err, "failed to update user password") return errutil.Wrapf(err, "failed to update user password")
} }

@ -34,7 +34,7 @@ func OrgRedirect(cfg *setting.Cfg) web.Handler {
} }
cmd := models.SetUsingOrgCommand{UserId: ctx.UserId, OrgId: orgId} cmd := models.SetUsingOrgCommand{UserId: ctx.UserId, OrgId: orgId}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.DispatchCtx(ctx.Req.Context(), &cmd); err != nil {
if ctx.IsApiRequest() { if ctx.IsApiRequest() {
ctx.JsonApiErr(404, "Not found", nil) ctx.JsonApiErr(404, "Not found", nil)
} else { } else {

@ -87,9 +87,9 @@ type PluginLoaderAuthorizer interface {
type PluginDashboardManager interface { type PluginDashboardManager interface {
// GetPluginDashboards gets dashboards for a certain org/plugin. // GetPluginDashboards gets dashboards for a certain org/plugin.
GetPluginDashboards(orgID int64, pluginID string) ([]*PluginDashboardInfoDTO, error) GetPluginDashboards(ctx context.Context, orgID int64, pluginID string) ([]*PluginDashboardInfoDTO, error)
// LoadPluginDashboard loads a plugin dashboard. // LoadPluginDashboard loads a plugin dashboard.
LoadPluginDashboard(pluginID, path string) (*models.Dashboard, error) LoadPluginDashboard(ctx context.Context, pluginID, path string) (*models.Dashboard, error)
// ImportDashboard imports a dashboard. // ImportDashboard imports a dashboard.
ImportDashboard(ctx context.Context, pluginID, path string, orgID, folderID int64, dashboardModel *simplejson.Json, ImportDashboard(ctx context.Context, pluginID, path string, orgID, folderID int64, dashboardModel *simplejson.Json,
overwrite bool, inputs []ImportDashboardInput, user *models.SignedInUser) (PluginDashboardInfoDTO, overwrite bool, inputs []ImportDashboardInput, user *models.SignedInUser) (PluginDashboardInfoDTO,

@ -12,8 +12,8 @@ import (
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
) )
func (m *PluginManager) GetPluginDashboards(orgID int64, pluginID string) ([]*plugins.PluginDashboardInfoDTO, error) { func (m *PluginManager) GetPluginDashboards(ctx context.Context, orgID int64, pluginID string) ([]*plugins.PluginDashboardInfoDTO, error) {
plugin, exists := m.Plugin(context.TODO(), pluginID) plugin, exists := m.Plugin(ctx, pluginID)
if !exists { if !exists {
return nil, plugins.NotFoundError{PluginID: pluginID} return nil, plugins.NotFoundError{PluginID: pluginID}
} }
@ -22,7 +22,7 @@ func (m *PluginManager) GetPluginDashboards(orgID int64, pluginID string) ([]*pl
// load current dashboards // load current dashboards
query := models.GetDashboardsByPluginIdQuery{OrgId: orgID, PluginId: pluginID} query := models.GetDashboardsByPluginIdQuery{OrgId: orgID, PluginId: pluginID}
if err := bus.Dispatch(&query); err != nil { if err := bus.DispatchCtx(ctx, &query); err != nil {
return nil, err return nil, err
} }
@ -32,7 +32,7 @@ func (m *PluginManager) GetPluginDashboards(orgID int64, pluginID string) ([]*pl
continue continue
} }
dashboard, err := m.LoadPluginDashboard(plugin.ID, include.Path) dashboard, err := m.LoadPluginDashboard(ctx, plugin.ID, include.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -72,8 +72,8 @@ func (m *PluginManager) GetPluginDashboards(orgID int64, pluginID string) ([]*pl
return result, nil return result, nil
} }
func (m *PluginManager) LoadPluginDashboard(pluginID, path string) (*models.Dashboard, error) { func (m *PluginManager) LoadPluginDashboard(ctx context.Context, pluginID, path string) (*models.Dashboard, error) {
plugin, exists := m.Plugin(context.TODO(), pluginID) plugin, exists := m.Plugin(ctx, pluginID)
if !exists { if !exists {
return nil, plugins.NotFoundError{PluginID: pluginID} return nil, plugins.NotFoundError{PluginID: pluginID}
} }
@ -108,7 +108,7 @@ func (m *PluginManager) ImportDashboard(ctx context.Context, pluginID, path stri
var dashboard *models.Dashboard var dashboard *models.Dashboard
if pluginID != "" { if pluginID != "" {
var err error var err error
if dashboard, err = m.LoadPluginDashboard(pluginID, path); err != nil { if dashboard, err = m.LoadPluginDashboard(ctx, pluginID, path); err != nil {
return plugins.PluginDashboardInfoDTO{}, &models.Dashboard{}, err return plugins.PluginDashboardInfoDTO{}, &models.Dashboard{}, err
} }
} else { } else {

@ -49,7 +49,7 @@ func TestGetPluginDashboards(t *testing.T) {
return nil return nil
}) })
dashboards, err := pm.GetPluginDashboards(1, "test-app") dashboards, err := pm.GetPluginDashboards(context.Background(), 1, "test-app")
require.NoError(t, err) require.NoError(t, err)
require.Len(t, dashboards, 2) require.Len(t, dashboards, 2)

@ -59,7 +59,7 @@ func (s *Service) syncPluginDashboards(ctx context.Context, plugin plugins.Plugi
s.logger.Info("Syncing plugin dashboards to DB", "pluginId", plugin.ID) s.logger.Info("Syncing plugin dashboards to DB", "pluginId", plugin.ID)
// Get plugin dashboards // Get plugin dashboards
dashboards, err := s.pluginDashboardManager.GetPluginDashboards(orgID, plugin.ID) dashboards, err := s.pluginDashboardManager.GetPluginDashboards(ctx, orgID, plugin.ID)
if err != nil { if err != nil {
s.logger.Error("Failed to load app dashboards", "error", err) s.logger.Error("Failed to load app dashboards", "error", err)
return return
@ -137,7 +137,7 @@ func (s *Service) handlePluginStateChanged(ctx context.Context, event *models.Pl
} }
func (s *Service) autoUpdateAppDashboard(ctx context.Context, pluginDashInfo *plugins.PluginDashboardInfoDTO, orgID int64) error { func (s *Service) autoUpdateAppDashboard(ctx context.Context, pluginDashInfo *plugins.PluginDashboardInfoDTO, orgID int64) error {
dash, err := s.pluginDashboardManager.LoadPluginDashboard(pluginDashInfo.PluginId, pluginDashInfo.Path) dash, err := s.pluginDashboardManager.LoadPluginDashboard(ctx, pluginDashInfo.PluginId, pluginDashInfo.Path)
if err != nil { if err != nil {
return err return err
} }

@ -204,7 +204,7 @@ func (h *ContextHandler) initContextWithAPIKey(reqContext *models.ReqContext) bo
// fetch key // fetch key
keyQuery := models.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId} keyQuery := models.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
if err := bus.Dispatch(&keyQuery); err != nil { if err := bus.DispatchCtx(reqContext.Req.Context(), &keyQuery); err != nil {
reqContext.JsonApiErr(401, InvalidAPIKey, err) reqContext.JsonApiErr(401, InvalidAPIKey, err)
return true return true
} }
@ -246,7 +246,7 @@ func (h *ContextHandler) initContextWithAPIKey(reqContext *models.ReqContext) bo
//Use service account linked to API key as the signed in user //Use service account linked to API key as the signed in user
query := models.GetSignedInUserQuery{UserId: apikey.ServiceAccountId, OrgId: apikey.OrgId} query := models.GetSignedInUserQuery{UserId: apikey.ServiceAccountId, OrgId: apikey.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.DispatchCtx(reqContext.Req.Context(), &query); err != nil {
reqContext.Logger.Error( reqContext.Logger.Error(
"Failed to link API key to service account in", "Failed to link API key to service account in",
"id", query.UserId, "id", query.UserId,

@ -33,7 +33,7 @@ type DashboardProvisioningService interface {
SaveFolderForProvisionedDashboards(context.Context, *SaveDashboardDTO) (*models.Dashboard, error) SaveFolderForProvisionedDashboards(context.Context, *SaveDashboardDTO) (*models.Dashboard, error)
GetProvisionedDashboardData(name string) ([]*models.DashboardProvisioning, error) GetProvisionedDashboardData(name string) ([]*models.DashboardProvisioning, error)
GetProvisionedDashboardDataByDashboardID(dashboardID int64) (*models.DashboardProvisioning, error) GetProvisionedDashboardDataByDashboardID(dashboardID int64) (*models.DashboardProvisioning, error)
UnprovisionDashboard(dashboardID int64) error UnprovisionDashboard(ctx context.Context, dashboardID int64) error
DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error
} }
@ -346,9 +346,9 @@ func (dr *dashboardServiceImpl) ImportDashboard(ctx context.Context, dto *SaveDa
// UnprovisionDashboard removes info about dashboard being provisioned. Used after provisioning configs are changed // UnprovisionDashboard removes info about dashboard being provisioned. Used after provisioning configs are changed
// and provisioned dashboards are left behind but not deleted. // and provisioned dashboards are left behind but not deleted.
func (dr *dashboardServiceImpl) UnprovisionDashboard(dashboardId int64) error { func (dr *dashboardServiceImpl) UnprovisionDashboard(ctx context.Context, dashboardId int64) error {
cmd := &models.UnprovisionDashboardCommand{Id: dashboardId} cmd := &models.UnprovisionDashboardCommand{Id: dashboardId}
return bus.Dispatch(cmd) return bus.DispatchCtx(ctx, cmd)
} }
type FakeDashboardService struct { type FakeDashboardService struct {

@ -209,7 +209,7 @@ func (dr *dashboardServiceImpl) DeleteFolder(ctx context.Context, uid string, fo
} }
deleteCmd := models.DeleteDashboardCommand{OrgId: dr.orgId, Id: dashFolder.Id, ForceDeleteFolderRules: forceDeleteRules} deleteCmd := models.DeleteDashboardCommand{OrgId: dr.orgId, Id: dashFolder.Id, ForceDeleteFolderRules: forceDeleteRules}
if err := bus.Dispatch(&deleteCmd); err != nil { if err := bus.DispatchCtx(ctx, &deleteCmd); err != nil {
return nil, toFolderError(err) return nil, toFolderError(err)
} }

@ -134,7 +134,7 @@ func (g *dashboardGuardianImpl) checkAcl(permission models.PermissionType, acl [
} }
// load teams // load teams
teams, err := g.getTeams() teams, err := g.getTeams(g.ctx)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -248,14 +248,14 @@ func (g *dashboardGuardianImpl) GetACLWithoutDuplicates() ([]*models.DashboardAc
return result, nil return result, nil
} }
func (g *dashboardGuardianImpl) getTeams() ([]*models.TeamDTO, error) { func (g *dashboardGuardianImpl) getTeams(ctx context.Context) ([]*models.TeamDTO, error) {
if g.teams != nil { if g.teams != nil {
return g.teams, nil return g.teams, nil
} }
query := models.GetTeamsByUserQuery{OrgId: g.orgId, UserId: g.user.UserId} query := models.GetTeamsByUserQuery{OrgId: g.orgId, UserId: g.user.UserId}
// TODO: Use bus.DispatchCtx(g.Ctx, &query) when GetTeamsByUserQuery supports context. // TODO: Use bus.DispatchCtx(g.Ctx, &query) when GetTeamsByUserQuery supports context.
err := bus.Dispatch(&query) err := bus.DispatchCtx(ctx, &query)
g.teams = query.Result g.teams = query.Result
return query.Result, err return query.Result, err

@ -200,7 +200,7 @@ func (fr *FileReader) handleMissingDashboardFiles(ctx context.Context, provision
// so afterwards the dashboard is considered unprovisioned. // so afterwards the dashboard is considered unprovisioned.
for _, dashboardID := range dashboardsToDelete { for _, dashboardID := range dashboardsToDelete {
fr.log.Debug("unprovisioning provisioned dashboard. missing on disk", "id", dashboardID) fr.log.Debug("unprovisioning provisioned dashboard. missing on disk", "id", dashboardID)
err := fr.dashboardProvisioningService.UnprovisionDashboard(dashboardID) err := fr.dashboardProvisioningService.UnprovisionDashboard(ctx, dashboardID)
if err != nil { if err != nil {
fr.log.Error("failed to unprovision dashboard", "dashboard_id", dashboardID, "error", err) fr.log.Error("failed to unprovision dashboard", "dashboard_id", dashboardID, "error", err)
} }

@ -608,7 +608,7 @@ func (s *fakeDashboardProvisioningService) SaveFolderForProvisionedDashboards(ct
return dto.Dashboard, nil return dto.Dashboard, nil
} }
func (s *fakeDashboardProvisioningService) UnprovisionDashboard(dashboardID int64) error { func (s *fakeDashboardProvisioningService) UnprovisionDashboard(ctx context.Context, dashboardID int64) error {
for key, val := range s.provisioned { for key, val := range s.provisioned {
for index, dashboard := range val { for index, dashboard := range val {
if dashboard.DashboardId == dashboardID { if dashboard.DashboardId == dashboardID {
@ -620,7 +620,7 @@ func (s *fakeDashboardProvisioningService) UnprovisionDashboard(dashboardID int6
} }
func (s *fakeDashboardProvisioningService) DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error { func (s *fakeDashboardProvisioningService) DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error {
err := s.UnprovisionDashboard(dashboardID) err := s.UnprovisionDashboard(ctx, dashboardID)
if err != nil { if err != nil {
return err return err
} }

@ -35,7 +35,7 @@ func (dc *NotificationProvisioner) apply(ctx context.Context, cfg *notifications
return err return err
} }
if err := dc.mergeNotifications(cfg.Notifications); err != nil { if err := dc.mergeNotifications(ctx, cfg.Notifications); err != nil {
return err return err
} }
@ -48,7 +48,7 @@ func (dc *NotificationProvisioner) deleteNotifications(ctx context.Context, noti
if notification.OrgID == 0 && notification.OrgName != "" { if notification.OrgID == 0 && notification.OrgName != "" {
getOrg := &models.GetOrgByNameQuery{Name: notification.OrgName} getOrg := &models.GetOrgByNameQuery{Name: notification.OrgName}
if err := bus.Dispatch(getOrg); err != nil { if err := bus.DispatchCtx(ctx, getOrg); err != nil {
return err return err
} }
notification.OrgID = getOrg.Result.Id notification.OrgID = getOrg.Result.Id
@ -73,11 +73,11 @@ func (dc *NotificationProvisioner) deleteNotifications(ctx context.Context, noti
return nil return nil
} }
func (dc *NotificationProvisioner) mergeNotifications(notificationToMerge []*notificationFromConfig) error { func (dc *NotificationProvisioner) mergeNotifications(ctx context.Context, notificationToMerge []*notificationFromConfig) error {
for _, notification := range notificationToMerge { for _, notification := range notificationToMerge {
if notification.OrgID == 0 && notification.OrgName != "" { if notification.OrgID == 0 && notification.OrgName != "" {
getOrg := &models.GetOrgByNameQuery{Name: notification.OrgName} getOrg := &models.GetOrgByNameQuery{Name: notification.OrgName}
if err := bus.Dispatch(getOrg); err != nil { if err := bus.DispatchCtx(ctx, getOrg); err != nil {
return err return err
} }
notification.OrgID = getOrg.Result.Id notification.OrgID = getOrg.Result.Id
@ -86,7 +86,7 @@ func (dc *NotificationProvisioner) mergeNotifications(notificationToMerge []*not
} }
cmd := &models.GetAlertNotificationsWithUidQuery{OrgId: notification.OrgID, Uid: notification.UID} cmd := &models.GetAlertNotificationsWithUidQuery{OrgId: notification.OrgID, Uid: notification.UID}
err := bus.Dispatch(cmd) err := bus.DispatchCtx(ctx, cmd)
if err != nil { if err != nil {
return err return err
} }
@ -106,7 +106,7 @@ func (dc *NotificationProvisioner) mergeNotifications(notificationToMerge []*not
SendReminder: notification.SendReminder, SendReminder: notification.SendReminder,
} }
if err := bus.Dispatch(insertCmd); err != nil { if err := bus.DispatchCtx(ctx, insertCmd); err != nil {
return err return err
} }
} else { } else {
@ -124,7 +124,7 @@ func (dc *NotificationProvisioner) mergeNotifications(notificationToMerge []*not
SendReminder: notification.SendReminder, SendReminder: notification.SendReminder,
} }
if err := bus.Dispatch(updateCmd); err != nil { if err := bus.DispatchCtx(ctx, updateCmd); err != nil {
return err return err
} }
} }

@ -1,6 +1,7 @@
package plugins package plugins
import ( import (
"context"
"errors" "errors"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@ -11,13 +12,13 @@ import (
// Provision scans a directory for provisioning config files // Provision scans a directory for provisioning config files
// and provisions the app in those files. // and provisions the app in those files.
func Provision(configDirectory string, pluginStore plugins.Store) error { func Provision(ctx context.Context, configDirectory string, pluginStore plugins.Store) error {
logger := log.New("provisioning.plugins") logger := log.New("provisioning.plugins")
ap := PluginProvisioner{ ap := PluginProvisioner{
log: logger, log: logger,
cfgProvider: newConfigReader(logger, pluginStore), cfgProvider: newConfigReader(logger, pluginStore),
} }
return ap.applyChanges(configDirectory) return ap.applyChanges(ctx, configDirectory)
} }
// PluginProvisioner is responsible for provisioning apps based on // PluginProvisioner is responsible for provisioning apps based on
@ -27,11 +28,11 @@ type PluginProvisioner struct {
cfgProvider configReader cfgProvider configReader
} }
func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error { func (ap *PluginProvisioner) apply(ctx context.Context, cfg *pluginsAsConfig) error {
for _, app := range cfg.Apps { for _, app := range cfg.Apps {
if app.OrgID == 0 && app.OrgName != "" { if app.OrgID == 0 && app.OrgName != "" {
getOrgQuery := &models.GetOrgByNameQuery{Name: app.OrgName} getOrgQuery := &models.GetOrgByNameQuery{Name: app.OrgName}
if err := bus.Dispatch(getOrgQuery); err != nil { if err := bus.DispatchCtx(ctx, getOrgQuery); err != nil {
return err return err
} }
app.OrgID = getOrgQuery.Result.Id app.OrgID = getOrgQuery.Result.Id
@ -40,7 +41,7 @@ func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error {
} }
query := &models.GetPluginSettingByIdQuery{OrgId: app.OrgID, PluginId: app.PluginID} query := &models.GetPluginSettingByIdQuery{OrgId: app.OrgID, PluginId: app.PluginID}
err := bus.Dispatch(query) err := bus.DispatchCtx(ctx, query)
if err != nil { if err != nil {
if !errors.Is(err, models.ErrPluginSettingNotFound) { if !errors.Is(err, models.ErrPluginSettingNotFound) {
return err return err
@ -59,7 +60,7 @@ func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error {
SecureJsonData: app.SecureJSONData, SecureJsonData: app.SecureJSONData,
PluginVersion: app.PluginVersion, PluginVersion: app.PluginVersion,
} }
if err := bus.Dispatch(cmd); err != nil { if err := bus.DispatchCtx(ctx, cmd); err != nil {
return err return err
} }
} }
@ -67,14 +68,14 @@ func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error {
return nil return nil
} }
func (ap *PluginProvisioner) applyChanges(configPath string) error { func (ap *PluginProvisioner) applyChanges(ctx context.Context, configPath string) error {
configs, err := ap.cfgProvider.readConfig(configPath) configs, err := ap.cfgProvider.readConfig(configPath)
if err != nil { if err != nil {
return err return err
} }
for _, cfg := range configs { for _, cfg := range configs {
if err := ap.apply(cfg); err != nil { if err := ap.apply(ctx, cfg); err != nil {
return err return err
} }
} }

@ -16,7 +16,7 @@ func TestPluginProvisioner(t *testing.T) {
expectedErr := errors.New("test") expectedErr := errors.New("test")
reader := &testConfigReader{err: expectedErr} reader := &testConfigReader{err: expectedErr}
ap := PluginProvisioner{log: log.New("test"), cfgProvider: reader} ap := PluginProvisioner{log: log.New("test"), cfgProvider: reader}
err := ap.applyChanges("") err := ap.applyChanges(context.Background(), "")
require.Equal(t, expectedErr, err) require.Equal(t, expectedErr, err)
}) })
@ -59,7 +59,7 @@ func TestPluginProvisioner(t *testing.T) {
} }
reader := &testConfigReader{result: cfg} reader := &testConfigReader{result: cfg}
ap := PluginProvisioner{log: log.New("test"), cfgProvider: reader} ap := PluginProvisioner{log: log.New("test"), cfgProvider: reader}
err := ap.applyChanges("") err := ap.applyChanges(context.Background(), "")
require.NoError(t, err) require.NoError(t, err)
require.Len(t, sentCommands, 4) require.Len(t, sentCommands, 4)

@ -38,7 +38,7 @@ type ProvisioningService interface {
registry.BackgroundService registry.BackgroundService
RunInitProvisioners(ctx context.Context) error RunInitProvisioners(ctx context.Context) error
ProvisionDatasources(ctx context.Context) error ProvisionDatasources(ctx context.Context) error
ProvisionPlugins() error ProvisionPlugins(ctx context.Context) error
ProvisionNotifications(ctx context.Context) error ProvisionNotifications(ctx context.Context) error
ProvisionDashboards(ctx context.Context) error ProvisionDashboards(ctx context.Context) error
GetDashboardProvisionerResolvedPath(name string) string GetDashboardProvisionerResolvedPath(name string) string
@ -61,7 +61,7 @@ func newProvisioningServiceImpl(
newDashboardProvisioner dashboards.DashboardProvisionerFactory, newDashboardProvisioner dashboards.DashboardProvisionerFactory,
provisionNotifiers func(context.Context, string, encryption.Internal) error, provisionNotifiers func(context.Context, string, encryption.Internal) error,
provisionDatasources func(context.Context, string) error, provisionDatasources func(context.Context, string) error,
provisionPlugins func(string, plugifaces.Store) error, provisionPlugins func(context.Context, string, plugifaces.Store) error,
) *ProvisioningServiceImpl { ) *ProvisioningServiceImpl {
return &ProvisioningServiceImpl{ return &ProvisioningServiceImpl{
log: log.New("provisioning"), log: log.New("provisioning"),
@ -83,7 +83,7 @@ type ProvisioningServiceImpl struct {
dashboardProvisioner dashboards.DashboardProvisioner dashboardProvisioner dashboards.DashboardProvisioner
provisionNotifiers func(context.Context, string, encryption.Internal) error provisionNotifiers func(context.Context, string, encryption.Internal) error
provisionDatasources func(context.Context, string) error provisionDatasources func(context.Context, string) error
provisionPlugins func(string, plugifaces.Store) error provisionPlugins func(context.Context, string, plugifaces.Store) error
mutex sync.Mutex mutex sync.Mutex
} }
@ -93,7 +93,7 @@ func (ps *ProvisioningServiceImpl) RunInitProvisioners(ctx context.Context) erro
return err return err
} }
err = ps.ProvisionPlugins() err = ps.ProvisionPlugins(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -141,9 +141,9 @@ func (ps *ProvisioningServiceImpl) ProvisionDatasources(ctx context.Context) err
return errutil.Wrap("Datasource provisioning error", err) return errutil.Wrap("Datasource provisioning error", err)
} }
func (ps *ProvisioningServiceImpl) ProvisionPlugins() error { func (ps *ProvisioningServiceImpl) ProvisionPlugins(ctx context.Context) error {
appPath := filepath.Join(ps.Cfg.ProvisioningPath, "plugins") appPath := filepath.Join(ps.Cfg.ProvisioningPath, "plugins")
err := ps.provisionPlugins(appPath, ps.pluginStore) err := ps.provisionPlugins(ctx, appPath, ps.pluginStore)
return errutil.Wrap("app provisioning error", err) return errutil.Wrap("app provisioning error", err)
} }

@ -47,7 +47,7 @@ func (mock *ProvisioningServiceMock) ProvisionDatasources(ctx context.Context) e
return nil return nil
} }
func (mock *ProvisioningServiceMock) ProvisionPlugins() error { func (mock *ProvisioningServiceMock) ProvisionPlugins(ctx context.Context) error {
mock.Calls.ProvisionPlugins = append(mock.Calls.ProvisionPlugins, nil) mock.Calls.ProvisionPlugins = append(mock.Calls.ProvisionPlugins, nil)
if mock.ProvisionPluginsFunc != nil { if mock.ProvisionPluginsFunc != nil {
return mock.ProvisionPluginsFunc() return mock.ProvisionPluginsFunc()

@ -1,11 +1,13 @@
package teamguardian package teamguardian
import ( import (
"context"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
func CanAdmin(bus bus.Bus, orgId int64, teamId int64, user *models.SignedInUser) error { func CanAdmin(ctx context.Context, bus bus.Bus, orgId int64, teamId int64, user *models.SignedInUser) error {
if user.OrgRole == models.ROLE_ADMIN { if user.OrgRole == models.ROLE_ADMIN {
return nil return nil
} }
@ -20,7 +22,7 @@ func CanAdmin(bus bus.Bus, orgId int64, teamId int64, user *models.SignedInUser)
UserId: user.UserId, UserId: user.UserId,
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.DispatchCtx(ctx, &cmd); err != nil {
return err return err
} }

@ -36,7 +36,7 @@ func TestUpdateTeam(t *testing.T) {
return nil return nil
}) })
err := CanAdmin(bus.GetBus(), testTeam.OrgId, testTeam.Id, &editor) err := CanAdmin(context.Background(), bus.GetBus(), testTeam.OrgId, testTeam.Id, &editor)
require.Equal(t, models.ErrNotAllowedToUpdateTeam, err) require.Equal(t, models.ErrNotAllowedToUpdateTeam, err)
}) })
}) })
@ -53,7 +53,7 @@ func TestUpdateTeam(t *testing.T) {
return nil return nil
}) })
err := CanAdmin(bus.GetBus(), testTeam.OrgId, testTeam.Id, &editor) err := CanAdmin(context.Background(), bus.GetBus(), testTeam.OrgId, testTeam.Id, &editor)
require.NoError(t, err) require.NoError(t, err)
}) })
}) })
@ -75,14 +75,14 @@ func TestUpdateTeam(t *testing.T) {
return nil return nil
}) })
err := CanAdmin(bus.GetBus(), testTeamOtherOrg.OrgId, testTeamOtherOrg.Id, &editor) err := CanAdmin(context.Background(), bus.GetBus(), testTeamOtherOrg.OrgId, testTeamOtherOrg.Id, &editor)
require.Equal(t, models.ErrNotAllowedToUpdateTeamInDifferentOrg, err) require.Equal(t, models.ErrNotAllowedToUpdateTeamInDifferentOrg, err)
}) })
}) })
t.Run("Given an org admin and a team", func(t *testing.T) { t.Run("Given an org admin and a team", func(t *testing.T) {
t.Run("Should be able to update the team", func(t *testing.T) { t.Run("Should be able to update the team", func(t *testing.T) {
err := CanAdmin(bus.GetBus(), testTeam.OrgId, testTeam.Id, &admin) err := CanAdmin(context.Background(), bus.GetBus(), testTeam.OrgId, testTeam.Id, &admin)
require.NoError(t, err) require.NoError(t, err)
}) })
}) })

Loading…
Cancel
Save