From 57b20335e68a52659c9b7506891f41a7912ab5c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Agn=C3=A8s=20Toulet?= <35176601+AgnesToulet@users.noreply.github.com> Date: Mon, 27 Sep 2021 09:04:36 +0200 Subject: [PATCH] LibraryPanels: Refactor to use context.Context instead of models.ReqContext (#39561) --- pkg/api/dashboard.go | 6 +- pkg/api/dashboard_test.go | 18 +-- pkg/api/folder.go | 2 +- pkg/api/plugins.go | 4 +- pkg/services/libraryelements/api.go | 14 +-- pkg/services/libraryelements/database.go | 119 +++++++++--------- .../libraryelements/libraryelements.go | 34 ++--- .../libraryelements_delete_test.go | 2 +- .../libraryelements_get_test.go | 2 +- .../libraryelements/libraryelements_test.go | 6 +- pkg/services/librarypanels/librarypanels.go | 27 ++-- .../librarypanels/librarypanels_test.go | 86 ++++++------- 12 files changed, 157 insertions(+), 163 deletions(-) diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index 850d1431b8d..ca4e8dc0df3 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -175,7 +175,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response { dash.Data.Set("version", dash.Version) // load library panels JSON for this dashboard - err = hs.LibraryPanelService.LoadLibraryPanelsForDashboard(c, dash) + err = hs.LibraryPanelService.LoadLibraryPanelsForDashboard(c.Req.Context(), dash) if err != nil { return response.Error(500, "Error while loading library panels", err) } @@ -244,7 +244,7 @@ func (hs *HTTPServer) deleteDashboard(c *models.ReqContext) response.Response { } // disconnect all library elements for this dashboard - err := hs.LibraryElementService.DisconnectElementsFromDashboard(c, dash.Id) + err := hs.LibraryElementService.DisconnectElementsFromDashboard(c.Req.Context(), dash.Id) if err != nil { hs.log.Error("Failed to disconnect library elements", "dashboard", dash.Id, "user", c.SignedInUser.UserId, "error", err) } @@ -370,7 +370,7 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboa } // connect library panels for this dashboard after the dashboard is stored and has an ID - err = hs.LibraryPanelService.ConnectLibraryPanelsForDashboard(c, dashboard) + err = hs.LibraryPanelService.ConnectLibraryPanelsForDashboard(c.Req.Context(), c.SignedInUser, dashboard) if err != nil { return response.Error(500, "Error while connecting library panels", err) } diff --git a/pkg/api/dashboard_test.go b/pkg/api/dashboard_test.go index 2d22f62e3e8..2e8f4fb1cf0 100644 --- a/pkg/api/dashboard_test.go +++ b/pkg/api/dashboard_test.go @@ -1262,7 +1262,7 @@ func (s mockDashboardProvisioningService) GetProvisionedDashboardDataByDashboard type mockLibraryPanelService struct { } -func (m *mockLibraryPanelService) LoadLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard) error { +func (m *mockLibraryPanelService) LoadLibraryPanelsForDashboard(c context.Context, dash *models.Dashboard) error { return nil } @@ -1270,42 +1270,42 @@ func (m *mockLibraryPanelService) CleanLibraryPanelsForDashboard(dash *models.Da return nil } -func (m *mockLibraryPanelService) ConnectLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard) error { +func (m *mockLibraryPanelService) ConnectLibraryPanelsForDashboard(c context.Context, signedInUser *models.SignedInUser, dash *models.Dashboard) error { return nil } -func (m *mockLibraryPanelService) ImportLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard, folderID int64) error { +func (m *mockLibraryPanelService) ImportLibraryPanelsForDashboard(c context.Context, signedInUser *models.SignedInUser, dash *models.Dashboard, folderID int64) error { return nil } type mockLibraryElementService struct { } -func (l *mockLibraryElementService) CreateElement(c *models.ReqContext, cmd libraryelements.CreateLibraryElementCommand) (libraryelements.LibraryElementDTO, error) { +func (l *mockLibraryElementService) CreateElement(c context.Context, signedInUser *models.SignedInUser, cmd libraryelements.CreateLibraryElementCommand) (libraryelements.LibraryElementDTO, error) { return libraryelements.LibraryElementDTO{}, nil } // GetElement gets an element from a UID. -func (l *mockLibraryElementService) GetElement(c *models.ReqContext, UID string) (libraryelements.LibraryElementDTO, error) { +func (l *mockLibraryElementService) GetElement(c context.Context, signedInUser *models.SignedInUser, UID string) (libraryelements.LibraryElementDTO, error) { return libraryelements.LibraryElementDTO{}, nil } // GetElementsForDashboard gets all connected elements for a specific dashboard. -func (l *mockLibraryElementService) GetElementsForDashboard(c *models.ReqContext, dashboardID int64) (map[string]libraryelements.LibraryElementDTO, error) { +func (l *mockLibraryElementService) GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]libraryelements.LibraryElementDTO, error) { return map[string]libraryelements.LibraryElementDTO{}, nil } // ConnectElementsToDashboard connects elements to a specific dashboard. -func (l *mockLibraryElementService) ConnectElementsToDashboard(c *models.ReqContext, elementUIDs []string, dashboardID int64) error { +func (l *mockLibraryElementService) ConnectElementsToDashboard(c context.Context, signedInUser *models.SignedInUser, elementUIDs []string, dashboardID int64) error { return nil } // DisconnectElementsFromDashboard disconnects elements from a specific dashboard. -func (l *mockLibraryElementService) DisconnectElementsFromDashboard(c *models.ReqContext, dashboardID int64) error { +func (l *mockLibraryElementService) DisconnectElementsFromDashboard(c context.Context, dashboardID int64) error { return nil } // DeleteLibraryElementsInFolder deletes all elements for a specific folder. -func (l *mockLibraryElementService) DeleteLibraryElementsInFolder(c *models.ReqContext, folderUID string) error { +func (l *mockLibraryElementService) DeleteLibraryElementsInFolder(c context.Context, signedInUser *models.SignedInUser, folderUID string) error { return nil } diff --git a/pkg/api/folder.go b/pkg/api/folder.go index b6e25130285..fa3543041cb 100644 --- a/pkg/api/folder.go +++ b/pkg/api/folder.go @@ -90,7 +90,7 @@ func (hs *HTTPServer) UpdateFolder(c *models.ReqContext, cmd models.UpdateFolder func (hs *HTTPServer) DeleteFolder(c *models.ReqContext) response.Response { // temporarily adding this function to HTTPServer, will be removed from HTTPServer when librarypanels featuretoggle is removed s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore) - err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c, macaron.Params(c.Req)[":uid"]) + err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c.Req.Context(), c.SignedInUser, macaron.Params(c.Req)[":uid"]) if err != nil { if errors.Is(err, libraryelements.ErrFolderHasConnectedLibraryElements) { return response.Error(403, "Folder could not be deleted because it contains library elements in use", err) diff --git a/pkg/api/plugins.go b/pkg/api/plugins.go index 5d0cadaa1fe..a99dd4e508a 100644 --- a/pkg/api/plugins.go +++ b/pkg/api/plugins.go @@ -224,12 +224,12 @@ func (hs *HTTPServer) ImportDashboard(c *models.ReqContext, apiCmd dtos.ImportDa return hs.dashboardSaveErrorToApiResponse(err) } - err = hs.LibraryPanelService.ImportLibraryPanelsForDashboard(c, dash, apiCmd.FolderId) + err = hs.LibraryPanelService.ImportLibraryPanelsForDashboard(c.Req.Context(), c.SignedInUser, dash, apiCmd.FolderId) if err != nil { return response.Error(500, "Error while importing library panels", err) } - err = hs.LibraryPanelService.ConnectLibraryPanelsForDashboard(c, dash) + err = hs.LibraryPanelService.ConnectLibraryPanelsForDashboard(c.Req.Context(), c.SignedInUser, dash) if err != nil { return response.Error(500, "Error while connecting library panels", err) } diff --git a/pkg/services/libraryelements/api.go b/pkg/services/libraryelements/api.go index 39ad46696cf..cfda6770fcb 100644 --- a/pkg/services/libraryelements/api.go +++ b/pkg/services/libraryelements/api.go @@ -26,7 +26,7 @@ func (l *LibraryElementService) registerAPIEndpoints() { // createHandler handles POST /api/library-elements. func (l *LibraryElementService) createHandler(c *models.ReqContext, cmd CreateLibraryElementCommand) response.Response { - element, err := l.createLibraryElement(c, cmd) + element, err := l.createLibraryElement(c.Req.Context(), c.SignedInUser, cmd) if err != nil { return toLibraryElementError(err, "Failed to create library element") } @@ -36,7 +36,7 @@ func (l *LibraryElementService) createHandler(c *models.ReqContext, cmd CreateLi // deleteHandler handles DELETE /api/library-elements/:uid. func (l *LibraryElementService) deleteHandler(c *models.ReqContext) response.Response { - err := l.deleteLibraryElement(c, macaron.Params(c.Req)[":uid"]) + err := l.deleteLibraryElement(c.Req.Context(), c.SignedInUser, macaron.Params(c.Req)[":uid"]) if err != nil { return toLibraryElementError(err, "Failed to delete library element") } @@ -46,7 +46,7 @@ func (l *LibraryElementService) deleteHandler(c *models.ReqContext) response.Res // getHandler handles GET /api/library-elements/:uid. func (l *LibraryElementService) getHandler(c *models.ReqContext) response.Response { - element, err := l.getLibraryElementByUid(c, macaron.Params(c.Req)[":uid"]) + element, err := l.getLibraryElementByUid(c.Req.Context(), c.SignedInUser, macaron.Params(c.Req)[":uid"]) if err != nil { return toLibraryElementError(err, "Failed to get library element") } @@ -66,7 +66,7 @@ func (l *LibraryElementService) getAllHandler(c *models.ReqContext) response.Res excludeUID: c.Query("excludeUid"), folderFilter: c.Query("folderFilter"), } - elementsResult, err := l.getAllLibraryElements(c, query) + elementsResult, err := l.getAllLibraryElements(c.Req.Context(), c.SignedInUser, query) if err != nil { return toLibraryElementError(err, "Failed to get library elements") } @@ -76,7 +76,7 @@ func (l *LibraryElementService) getAllHandler(c *models.ReqContext) response.Res // patchHandler handles PATCH /api/library-elements/:uid func (l *LibraryElementService) patchHandler(c *models.ReqContext, cmd patchLibraryElementCommand) response.Response { - element, err := l.patchLibraryElement(c, cmd, macaron.Params(c.Req)[":uid"]) + element, err := l.patchLibraryElement(c.Req.Context(), c.SignedInUser, cmd, macaron.Params(c.Req)[":uid"]) if err != nil { return toLibraryElementError(err, "Failed to update library element") } @@ -86,7 +86,7 @@ func (l *LibraryElementService) patchHandler(c *models.ReqContext, cmd patchLibr // getConnectionsHandler handles GET /api/library-panels/:uid/connections/. func (l *LibraryElementService) getConnectionsHandler(c *models.ReqContext) response.Response { - connections, err := l.getConnections(c, macaron.Params(c.Req)[":uid"]) + connections, err := l.getConnections(c.Req.Context(), c.SignedInUser, macaron.Params(c.Req)[":uid"]) if err != nil { return toLibraryElementError(err, "Failed to get connections") } @@ -96,7 +96,7 @@ func (l *LibraryElementService) getConnectionsHandler(c *models.ReqContext) resp // getByNameHandler handles GET /api/library-elements/name/:name/. func (l *LibraryElementService) getByNameHandler(c *models.ReqContext) response.Response { - elements, err := l.getLibraryElementsByName(c) + elements, err := l.getLibraryElementsByName(c.Req.Context(), c.SignedInUser, macaron.Params(c.Req)[":name"]) if err != nil { return toLibraryElementError(err, "Failed to get library element") } diff --git a/pkg/services/libraryelements/database.go b/pkg/services/libraryelements/database.go index aec3f1ff954..6def4bfee19 100644 --- a/pkg/services/libraryelements/database.go +++ b/pkg/services/libraryelements/database.go @@ -14,7 +14,6 @@ import ( "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore/migrator" "github.com/grafana/grafana/pkg/util" - "gopkg.in/macaron.v1" ) const ( @@ -91,7 +90,7 @@ func getLibraryElement(dialect migrator.Dialect, session *sqlstore.DBSession, ui } // createLibraryElement adds a library element. -func (l *LibraryElementService) createLibraryElement(c *models.ReqContext, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) { +func (l *LibraryElementService) createLibraryElement(c context.Context, signedInUser *models.SignedInUser, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) { if err := l.requireSupportedElementKind(cmd.Kind); err != nil { return LibraryElementDTO{}, err } @@ -106,7 +105,7 @@ func (l *LibraryElementService) createLibraryElement(c *models.ReqContext, cmd C } } element := LibraryElement{ - OrgID: c.SignedInUser.OrgId, + OrgID: signedInUser.OrgId, FolderID: cmd.FolderID, UID: createUID, Name: cmd.Name, @@ -117,16 +116,16 @@ func (l *LibraryElementService) createLibraryElement(c *models.ReqContext, cmd C Created: time.Now(), Updated: time.Now(), - CreatedBy: c.SignedInUser.UserId, - UpdatedBy: c.SignedInUser.UserId, + CreatedBy: signedInUser.UserId, + UpdatedBy: signedInUser.UserId, } if err := syncFieldsWithModel(&element); err != nil { return LibraryElementDTO{}, err } - err := l.SQLStore.WithTransactionalDbSession(c.Req.Context(), func(session *sqlstore.DBSession) error { - if err := l.requirePermissionsOnFolder(c.Req.Context(), c.SignedInUser, cmd.FolderID); err != nil { + err := l.SQLStore.WithTransactionalDbSession(c, func(session *sqlstore.DBSession) error { + if err := l.requirePermissionsOnFolder(c, signedInUser, cmd.FolderID); err != nil { return err } if _, err := session.Insert(&element); err != nil { @@ -155,13 +154,13 @@ func (l *LibraryElementService) createLibraryElement(c *models.ReqContext, cmd C Updated: element.Updated, CreatedBy: LibraryElementDTOMetaUser{ ID: element.CreatedBy, - Name: c.SignedInUser.Login, - AvatarURL: dtos.GetGravatarUrl(c.SignedInUser.Email), + Name: signedInUser.Login, + AvatarURL: dtos.GetGravatarUrl(signedInUser.Email), }, UpdatedBy: LibraryElementDTOMetaUser{ ID: element.UpdatedBy, - Name: c.SignedInUser.Login, - AvatarURL: dtos.GetGravatarUrl(c.SignedInUser.Email), + Name: signedInUser.Login, + AvatarURL: dtos.GetGravatarUrl(signedInUser.Email), }, }, } @@ -170,13 +169,13 @@ func (l *LibraryElementService) createLibraryElement(c *models.ReqContext, cmd C } // deleteLibraryElement deletes a library element. -func (l *LibraryElementService) deleteLibraryElement(c *models.ReqContext, uid string) error { - return l.SQLStore.WithTransactionalDbSession(c.Req.Context(), func(session *sqlstore.DBSession) error { - element, err := getLibraryElement(l.SQLStore.Dialect, session, uid, c.SignedInUser.OrgId) +func (l *LibraryElementService) deleteLibraryElement(c context.Context, signedInUser *models.SignedInUser, uid string) error { + return l.SQLStore.WithTransactionalDbSession(c, func(session *sqlstore.DBSession) error { + element, err := getLibraryElement(l.SQLStore.Dialect, session, uid, signedInUser.OrgId) if err != nil { return err } - if err := l.requirePermissionsOnFolder(c.Req.Context(), c.SignedInUser, element.FolderID); err != nil { + if err := l.requirePermissionsOnFolder(c, signedInUser, element.FolderID); err != nil { return err } var connectionIDs []struct { @@ -204,9 +203,9 @@ func (l *LibraryElementService) deleteLibraryElement(c *models.ReqContext, uid s } // getLibraryElements gets a Library Element where param == value -func getLibraryElements(c *models.ReqContext, store *sqlstore.SQLStore, params []Pair) ([]LibraryElementDTO, error) { +func getLibraryElements(c context.Context, store *sqlstore.SQLStore, signedInUser *models.SignedInUser, params []Pair) ([]LibraryElementDTO, error) { libraryElements := make([]LibraryElementWithMeta, 0) - err := store.WithDbSession(c.Req.Context(), func(session *sqlstore.DBSession) error { + err := store.WithDbSession(c, func(session *sqlstore.DBSession) error { builder := sqlstore.SQLBuilder{} builder.Write(selectLibraryElementDTOWithMeta) builder.Write(", 'General' as folder_name ") @@ -220,8 +219,8 @@ func getLibraryElements(c *models.ReqContext, store *sqlstore.SQLStore, params [ builder.Write(getFromLibraryElementDTOWithMeta(store.Dialect)) builder.Write(" INNER JOIN dashboard AS dashboard on le.folder_id = dashboard.id AND le.folder_id <> 0") writeParamSelectorSQL(&builder, params...) - if c.SignedInUser.OrgRole != models.ROLE_ADMIN { - builder.WriteDashboardPermissionFilter(c.SignedInUser, models.PERMISSION_VIEW) + if signedInUser.OrgRole != models.ROLE_ADMIN { + builder.WriteDashboardPermissionFilter(signedInUser, models.PERMISSION_VIEW) } builder.Write(` OR dashboard.id=0`) if err := session.SQL(builder.GetSQLString(), builder.GetParams()...).Find(&libraryElements); err != nil { @@ -274,8 +273,8 @@ func getLibraryElements(c *models.ReqContext, store *sqlstore.SQLStore, params [ } // getLibraryElementByUid gets a Library Element by uid. -func (l *LibraryElementService) getLibraryElementByUid(c *models.ReqContext, UID string) (LibraryElementDTO, error) { - libraryElements, err := getLibraryElements(c, l.SQLStore, []Pair{{key: "org_id", value: c.SignedInUser.OrgId}, {key: "uid", value: UID}}) +func (l *LibraryElementService) getLibraryElementByUid(c context.Context, signedInUser *models.SignedInUser, UID string) (LibraryElementDTO, error) { + libraryElements, err := getLibraryElements(c, l.SQLStore, signedInUser, []Pair{{key: "org_id", value: signedInUser.OrgId}, {key: "uid", value: UID}}) if err != nil { return LibraryElementDTO{}, err } @@ -287,12 +286,12 @@ func (l *LibraryElementService) getLibraryElementByUid(c *models.ReqContext, UID } // getLibraryElementByName gets a Library Element by name. -func (l *LibraryElementService) getLibraryElementsByName(c *models.ReqContext) ([]LibraryElementDTO, error) { - return getLibraryElements(c, l.SQLStore, []Pair{{"org_id", c.SignedInUser.OrgId}, {"name", macaron.Params(c.Req)[":name"]}}) +func (l *LibraryElementService) getLibraryElementsByName(c context.Context, signedInUser *models.SignedInUser, name string) ([]LibraryElementDTO, error) { + return getLibraryElements(c, l.SQLStore, signedInUser, []Pair{{"org_id", signedInUser.OrgId}, {"name", name}}) } // getAllLibraryElements gets all Library Elements. -func (l *LibraryElementService) getAllLibraryElements(c *models.ReqContext, query searchLibraryElementsQuery) (LibraryElementSearchResult, error) { +func (l *LibraryElementService) getAllLibraryElements(c context.Context, signedInUser *models.SignedInUser, query searchLibraryElementsQuery) (LibraryElementSearchResult, error) { elements := make([]LibraryElementWithMeta, 0) result := LibraryElementSearchResult{} if query.perPage <= 0 { @@ -309,14 +308,14 @@ func (l *LibraryElementService) getAllLibraryElements(c *models.ReqContext, quer if folderFilter.parseError != nil { return LibraryElementSearchResult{}, folderFilter.parseError } - err := l.SQLStore.WithDbSession(c.Context.Req.Context(), func(session *sqlstore.DBSession) error { + err := l.SQLStore.WithDbSession(c, func(session *sqlstore.DBSession) error { builder := sqlstore.SQLBuilder{} if folderFilter.includeGeneralFolder { builder.Write(selectLibraryElementDTOWithMeta) builder.Write(", 'General' as folder_name ") builder.Write(", '' as folder_uid ") builder.Write(getFromLibraryElementDTOWithMeta(l.SQLStore.Dialect)) - builder.Write(` WHERE le.org_id=? AND le.folder_id=0`, c.SignedInUser.OrgId) + builder.Write(` WHERE le.org_id=? AND le.folder_id=0`, signedInUser.OrgId) writeKindSQL(query, &builder) writeSearchStringSQL(query, l.SQLStore, &builder) writeExcludeSQL(query, &builder) @@ -328,7 +327,7 @@ func (l *LibraryElementService) getAllLibraryElements(c *models.ReqContext, quer builder.Write(", dashboard.uid as folder_uid ") builder.Write(getFromLibraryElementDTOWithMeta(l.SQLStore.Dialect)) builder.Write(" INNER JOIN dashboard AS dashboard on le.folder_id = dashboard.id AND le.folder_id<>0") - builder.Write(` WHERE le.org_id=?`, c.SignedInUser.OrgId) + builder.Write(` WHERE le.org_id=?`, signedInUser.OrgId) writeKindSQL(query, &builder) writeSearchStringSQL(query, l.SQLStore, &builder) writeExcludeSQL(query, &builder) @@ -336,8 +335,8 @@ func (l *LibraryElementService) getAllLibraryElements(c *models.ReqContext, quer if err := folderFilter.writeFolderFilterSQL(false, &builder); err != nil { return err } - if c.SignedInUser.OrgRole != models.ROLE_ADMIN { - builder.WriteDashboardPermissionFilter(c.SignedInUser, models.PERMISSION_VIEW) + if signedInUser.OrgRole != models.ROLE_ADMIN { + builder.WriteDashboardPermissionFilter(signedInUser, models.PERMISSION_VIEW) } if query.sortDirection == search.SortAlphaDesc.Name { builder.Write(" ORDER BY 1 DESC") @@ -385,7 +384,7 @@ func (l *LibraryElementService) getAllLibraryElements(c *models.ReqContext, quer var libraryElements []LibraryElement countBuilder := sqlstore.SQLBuilder{} countBuilder.Write("SELECT * FROM library_element AS le") - countBuilder.Write(` WHERE le.org_id=?`, c.SignedInUser.OrgId) + countBuilder.Write(` WHERE le.org_id=?`, signedInUser.OrgId) writeKindSQL(query, &countBuilder) writeSearchStringSQL(query, l.SQLStore, &countBuilder) writeExcludeSQL(query, &countBuilder) @@ -434,13 +433,13 @@ func (l *LibraryElementService) handleFolderIDPatches(ctx context.Context, eleme } // patchLibraryElement updates a Library Element. -func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd patchLibraryElementCommand, uid string) (LibraryElementDTO, error) { +func (l *LibraryElementService) patchLibraryElement(c context.Context, signedInUser *models.SignedInUser, cmd patchLibraryElementCommand, uid string) (LibraryElementDTO, error) { var dto LibraryElementDTO if err := l.requireSupportedElementKind(cmd.Kind); err != nil { return LibraryElementDTO{}, err } - err := l.SQLStore.WithTransactionalDbSession(c.Req.Context(), func(session *sqlstore.DBSession) error { - elementInDB, err := getLibraryElement(l.SQLStore.Dialect, session, uid, c.SignedInUser.OrgId) + err := l.SQLStore.WithTransactionalDbSession(c, func(session *sqlstore.DBSession) error { + elementInDB, err := getLibraryElement(l.SQLStore.Dialect, session, uid, signedInUser.OrgId) if err != nil { return err } @@ -457,7 +456,7 @@ func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd pa return errLibraryElementUIDTooLong } - _, err := getLibraryElement(l.SQLStore.Dialect, session, updateUID, c.SignedInUser.OrgId) + _, err := getLibraryElement(l.SQLStore.Dialect, session, updateUID, signedInUser.OrgId) if !errors.Is(err, ErrLibraryElementNotFound) { return errLibraryElementAlreadyExists } @@ -465,7 +464,7 @@ func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd pa var libraryElement = LibraryElement{ ID: elementInDB.ID, - OrgID: c.SignedInUser.OrgId, + OrgID: signedInUser.OrgId, FolderID: cmd.FolderID, UID: updateUID, Name: cmd.Name, @@ -477,7 +476,7 @@ func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd pa Created: elementInDB.Created, CreatedBy: elementInDB.CreatedBy, Updated: time.Now(), - UpdatedBy: c.SignedInUser.UserId, + UpdatedBy: signedInUser.UserId, } if cmd.Name == "" { @@ -486,7 +485,7 @@ func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd pa if cmd.Model == nil { libraryElement.Model = elementInDB.Model } - if err := l.handleFolderIDPatches(c.Req.Context(), &libraryElement, elementInDB.FolderID, cmd.FolderID, c.SignedInUser); err != nil { + if err := l.handleFolderIDPatches(c, &libraryElement, elementInDB.FolderID, cmd.FolderID, signedInUser); err != nil { return err } if err := syncFieldsWithModel(&libraryElement); err != nil { @@ -523,8 +522,8 @@ func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd pa }, UpdatedBy: LibraryElementDTOMetaUser{ ID: libraryElement.UpdatedBy, - Name: c.SignedInUser.Login, - AvatarURL: dtos.GetGravatarUrl(c.SignedInUser.Email), + Name: signedInUser.Login, + AvatarURL: dtos.GetGravatarUrl(signedInUser.Email), }, }, } @@ -536,10 +535,10 @@ func (l *LibraryElementService) patchLibraryElement(c *models.ReqContext, cmd pa } // getConnections gets all connections for a Library Element. -func (l *LibraryElementService) getConnections(c *models.ReqContext, uid string) ([]LibraryElementConnectionDTO, error) { +func (l *LibraryElementService) getConnections(c context.Context, signedInUser *models.SignedInUser, uid string) ([]LibraryElementConnectionDTO, error) { connections := make([]LibraryElementConnectionDTO, 0) - err := l.SQLStore.WithDbSession(c.Context.Req.Context(), func(session *sqlstore.DBSession) error { - element, err := getLibraryElement(l.SQLStore.Dialect, session, uid, c.SignedInUser.OrgId) + err := l.SQLStore.WithDbSession(c, func(session *sqlstore.DBSession) error { + element, err := getLibraryElement(l.SQLStore.Dialect, session, uid, signedInUser.OrgId) if err != nil { return err } @@ -550,8 +549,8 @@ func (l *LibraryElementService) getConnections(c *models.ReqContext, uid string) builder.Write(" LEFT JOIN " + l.SQLStore.Dialect.Quote("user") + " AS u1 ON lec.created_by = u1.id") builder.Write(" INNER JOIN dashboard AS dashboard on lec.connection_id = dashboard.id") builder.Write(` WHERE lec.element_id=?`, element.ID) - if c.SignedInUser.OrgRole != models.ROLE_ADMIN { - builder.WriteDashboardPermissionFilter(c.SignedInUser, models.PERMISSION_VIEW) + if signedInUser.OrgRole != models.ROLE_ADMIN { + builder.WriteDashboardPermissionFilter(signedInUser, models.PERMISSION_VIEW) } if err := session.SQL(builder.GetSQLString(), builder.GetParams()...).Find(&libraryElementConnections); err != nil { return err @@ -579,9 +578,9 @@ func (l *LibraryElementService) getConnections(c *models.ReqContext, uid string) } //getElementsForDashboardID gets all elements for a specific dashboard -func (l *LibraryElementService) getElementsForDashboardID(c *models.ReqContext, dashboardID int64) (map[string]LibraryElementDTO, error) { +func (l *LibraryElementService) getElementsForDashboardID(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error) { libraryElementMap := make(map[string]LibraryElementDTO) - err := l.SQLStore.WithDbSession(c.Context.Req.Context(), func(session *sqlstore.DBSession) error { + err := l.SQLStore.WithDbSession(c, func(session *sqlstore.DBSession) error { var libraryElements []LibraryElementWithMeta sql := selectLibraryElementDTOWithMeta + ", coalesce(dashboard.title, 'General') AS folder_name" + @@ -634,18 +633,18 @@ func (l *LibraryElementService) getElementsForDashboardID(c *models.ReqContext, } // connectElementsToDashboardID adds connections for all elements Library Elements in a Dashboard. -func (l *LibraryElementService) connectElementsToDashboardID(c *models.ReqContext, elementUIDs []string, dashboardID int64) error { - err := l.SQLStore.WithTransactionalDbSession(c.Req.Context(), func(session *sqlstore.DBSession) error { +func (l *LibraryElementService) connectElementsToDashboardID(c context.Context, signedInUser *models.SignedInUser, elementUIDs []string, dashboardID int64) error { + err := l.SQLStore.WithTransactionalDbSession(c, func(session *sqlstore.DBSession) error { _, err := session.Exec("DELETE FROM "+models.LibraryElementConnectionTableName+" WHERE kind=1 AND connection_id=?", dashboardID) if err != nil { return err } for _, elementUID := range elementUIDs { - element, err := getLibraryElement(l.SQLStore.Dialect, session, elementUID, c.SignedInUser.OrgId) + element, err := getLibraryElement(l.SQLStore.Dialect, session, elementUID, signedInUser.OrgId) if err != nil { return err } - if err := l.requirePermissionsOnFolder(c.Req.Context(), c.SignedInUser, element.FolderID); err != nil { + if err := l.requirePermissionsOnFolder(c, signedInUser, element.FolderID); err != nil { return err } @@ -654,7 +653,7 @@ func (l *LibraryElementService) connectElementsToDashboardID(c *models.ReqContex Kind: 1, ConnectionID: dashboardID, Created: time.Now(), - CreatedBy: c.SignedInUser.UserId, + CreatedBy: signedInUser.UserId, } if _, err := session.Insert(&connection); err != nil { if l.SQLStore.Dialect.IsUniqueConstraintViolation(err) { @@ -670,8 +669,8 @@ func (l *LibraryElementService) connectElementsToDashboardID(c *models.ReqContex } // disconnectElementsFromDashboardID deletes connections for all Library Elements in a Dashboard. -func (l *LibraryElementService) disconnectElementsFromDashboardID(c *models.ReqContext, dashboardID int64) error { - return l.SQLStore.WithTransactionalDbSession(c.Context.Req.Context(), func(session *sqlstore.DBSession) error { +func (l *LibraryElementService) disconnectElementsFromDashboardID(c context.Context, dashboardID int64) error { + return l.SQLStore.WithTransactionalDbSession(c, func(session *sqlstore.DBSession) error { _, err := session.Exec("DELETE FROM "+models.LibraryElementConnectionTableName+" WHERE kind=1 AND connection_id=?", dashboardID) if err != nil { return err @@ -681,12 +680,12 @@ func (l *LibraryElementService) disconnectElementsFromDashboardID(c *models.ReqC } // deleteLibraryElementsInFolderUID deletes all Library Elements in a folder. -func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c *models.ReqContext, folderUID string) error { - return l.SQLStore.WithTransactionalDbSession(c.Req.Context(), func(session *sqlstore.DBSession) error { +func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c context.Context, signedInUser *models.SignedInUser, folderUID string) error { + return l.SQLStore.WithTransactionalDbSession(c, func(session *sqlstore.DBSession) error { var folderUIDs []struct { ID int64 `xorm:"id"` } - err := session.SQL("SELECT id from dashboard WHERE uid=? AND org_id=? AND is_folder=?", folderUID, c.SignedInUser.OrgId, l.SQLStore.Dialect.BooleanStr(true)).Find(&folderUIDs) + err := session.SQL("SELECT id from dashboard WHERE uid=? AND org_id=? AND is_folder=?", folderUID, signedInUser.OrgId, l.SQLStore.Dialect.BooleanStr(true)).Find(&folderUIDs) if err != nil { return err } @@ -695,7 +694,7 @@ func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c *models.ReqCo } folderID := folderUIDs[0].ID - if err := l.requirePermissionsOnFolder(c.Req.Context(), c.SignedInUser, folderID); err != nil { + if err := l.requirePermissionsOnFolder(c, signedInUser, folderID); err != nil { return err } var connectionIDs []struct { @@ -704,7 +703,7 @@ func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c *models.ReqCo sql := "SELECT lec.connection_id FROM library_element AS le" sql += " INNER JOIN " + models.LibraryElementConnectionTableName + " AS lec on le.id = lec.element_id" sql += " WHERE le.folder_id=? AND le.org_id=?" - err = session.SQL(sql, folderID, c.SignedInUser.OrgId).Find(&connectionIDs) + err = session.SQL(sql, folderID, signedInUser.OrgId).Find(&connectionIDs) if err != nil { return err } @@ -715,7 +714,7 @@ func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c *models.ReqCo var elementIDs []struct { ID int64 `xorm:"id"` } - err = session.SQL("SELECT id from library_element WHERE folder_id=? AND org_id=?", folderID, c.SignedInUser.OrgId).Find(&elementIDs) + err = session.SQL("SELECT id from library_element WHERE folder_id=? AND org_id=?", folderID, signedInUser.OrgId).Find(&elementIDs) if err != nil { return err } @@ -725,7 +724,7 @@ func (l *LibraryElementService) deleteLibraryElementsInFolderUID(c *models.ReqCo return err } } - if _, err := session.Exec("DELETE FROM library_element WHERE folder_id=? AND org_id=?", folderID, c.SignedInUser.OrgId); err != nil { + if _, err := session.Exec("DELETE FROM library_element WHERE folder_id=? AND org_id=?", folderID, signedInUser.OrgId); err != nil { return err } diff --git a/pkg/services/libraryelements/libraryelements.go b/pkg/services/libraryelements/libraryelements.go index 1dedb8e640f..302b31a1b59 100644 --- a/pkg/services/libraryelements/libraryelements.go +++ b/pkg/services/libraryelements/libraryelements.go @@ -1,6 +1,8 @@ package libraryelements import ( + "context" + "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" @@ -21,12 +23,12 @@ func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore, routeRegister // Service is a service for operating on library elements. type Service interface { - CreateElement(c *models.ReqContext, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) - GetElement(c *models.ReqContext, UID string) (LibraryElementDTO, error) - GetElementsForDashboard(c *models.ReqContext, dashboardID int64) (map[string]LibraryElementDTO, error) - ConnectElementsToDashboard(c *models.ReqContext, elementUIDs []string, dashboardID int64) error - DisconnectElementsFromDashboard(c *models.ReqContext, dashboardID int64) error - DeleteLibraryElementsInFolder(c *models.ReqContext, folderUID string) error + CreateElement(c context.Context, signedInUser *models.SignedInUser, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) + GetElement(c context.Context, signedInUser *models.SignedInUser, UID string) (LibraryElementDTO, error) + GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error) + ConnectElementsToDashboard(c context.Context, signedInUser *models.SignedInUser, elementUIDs []string, dashboardID int64) error + DisconnectElementsFromDashboard(c context.Context, dashboardID int64) error + DeleteLibraryElementsInFolder(c context.Context, signedInUser *models.SignedInUser, folderUID string) error } // LibraryElementService is the service for the Library Element feature. @@ -38,31 +40,31 @@ type LibraryElementService struct { } // CreateElement creates a Library Element. -func (l *LibraryElementService) CreateElement(c *models.ReqContext, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) { - return l.createLibraryElement(c, cmd) +func (l *LibraryElementService) CreateElement(c context.Context, signedInUser *models.SignedInUser, cmd CreateLibraryElementCommand) (LibraryElementDTO, error) { + return l.createLibraryElement(c, signedInUser, cmd) } // GetElement gets an element from a UID. -func (l *LibraryElementService) GetElement(c *models.ReqContext, UID string) (LibraryElementDTO, error) { - return l.getLibraryElementByUid(c, UID) +func (l *LibraryElementService) GetElement(c context.Context, signedInUser *models.SignedInUser, UID string) (LibraryElementDTO, error) { + return l.getLibraryElementByUid(c, signedInUser, UID) } // GetElementsForDashboard gets all connected elements for a specific dashboard. -func (l *LibraryElementService) GetElementsForDashboard(c *models.ReqContext, dashboardID int64) (map[string]LibraryElementDTO, error) { +func (l *LibraryElementService) GetElementsForDashboard(c context.Context, dashboardID int64) (map[string]LibraryElementDTO, error) { return l.getElementsForDashboardID(c, dashboardID) } // ConnectElementsToDashboard connects elements to a specific dashboard. -func (l *LibraryElementService) ConnectElementsToDashboard(c *models.ReqContext, elementUIDs []string, dashboardID int64) error { - return l.connectElementsToDashboardID(c, elementUIDs, dashboardID) +func (l *LibraryElementService) ConnectElementsToDashboard(c context.Context, signedInUser *models.SignedInUser, elementUIDs []string, dashboardID int64) error { + return l.connectElementsToDashboardID(c, signedInUser, elementUIDs, dashboardID) } // DisconnectElementsFromDashboard disconnects elements from a specific dashboard. -func (l *LibraryElementService) DisconnectElementsFromDashboard(c *models.ReqContext, dashboardID int64) error { +func (l *LibraryElementService) DisconnectElementsFromDashboard(c context.Context, dashboardID int64) error { return l.disconnectElementsFromDashboardID(c, dashboardID) } // DeleteLibraryElementsInFolder deletes all elements for a specific folder. -func (l *LibraryElementService) DeleteLibraryElementsInFolder(c *models.ReqContext, folderUID string) error { - return l.deleteLibraryElementsInFolderUID(c, folderUID) +func (l *LibraryElementService) DeleteLibraryElementsInFolder(c context.Context, signedInUser *models.SignedInUser, folderUID string) error { + return l.deleteLibraryElementsInFolderUID(c, signedInUser, folderUID) } diff --git a/pkg/services/libraryelements/libraryelements_delete_test.go b/pkg/services/libraryelements/libraryelements_delete_test.go index 3f5d01fdf48..191bd7559c8 100644 --- a/pkg/services/libraryelements/libraryelements_delete_test.go +++ b/pkg/services/libraryelements/libraryelements_delete_test.go @@ -67,7 +67,7 @@ func TestDeleteLibraryElement(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.service.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) + err := sc.service.ConnectElementsToDashboard(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, []string{sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID}) diff --git a/pkg/services/libraryelements/libraryelements_get_test.go b/pkg/services/libraryelements/libraryelements_get_test.go index 6fd7585e14c..bfe375adb73 100644 --- a/pkg/services/libraryelements/libraryelements_get_test.go +++ b/pkg/services/libraryelements/libraryelements_get_test.go @@ -120,7 +120,7 @@ func TestGetLibraryElement(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.service.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) + err := sc.service.ConnectElementsToDashboard(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, []string{sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) expected := func(res libraryElementResult) libraryElementResult { diff --git a/pkg/services/libraryelements/libraryelements_test.go b/pkg/services/libraryelements/libraryelements_test.go index ac296bc9eab..28334377e53 100644 --- a/pkg/services/libraryelements/libraryelements_test.go +++ b/pkg/services/libraryelements/libraryelements_test.go @@ -59,10 +59,10 @@ func TestDeleteLibraryPanelsInFolder(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.service.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) + err := sc.service.ConnectElementsToDashboard(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, []string{sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) - err = sc.service.DeleteLibraryElementsInFolder(sc.reqContext, sc.folder.Uid) + err = sc.service.DeleteLibraryElementsInFolder(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, sc.folder.Uid) require.EqualError(t, err, ErrFolderHasConnectedLibraryElements.Error()) }) @@ -80,7 +80,7 @@ func TestDeleteLibraryPanelsInFolder(t *testing.T) { require.NotNil(t, result.Result) require.Equal(t, 2, len(result.Result.Elements)) - err = sc.service.DeleteLibraryElementsInFolder(sc.reqContext, sc.folder.Uid) + err = sc.service.DeleteLibraryElementsInFolder(sc.reqContext.Req.Context(), sc.reqContext.SignedInUser, sc.folder.Uid) require.NoError(t, err) resp = sc.service.getAllHandler(sc.reqContext) require.Equal(t, 200, resp.Status()) diff --git a/pkg/services/librarypanels/librarypanels.go b/pkg/services/librarypanels/librarypanels.go index ba53ac8f7f4..c23268a03a8 100644 --- a/pkg/services/librarypanels/librarypanels.go +++ b/pkg/services/librarypanels/librarypanels.go @@ -1,6 +1,7 @@ package librarypanels import ( + "context" "encoding/json" "errors" "fmt" @@ -27,10 +28,10 @@ func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore, routeRegister // Service is a service for operating on library panels. type Service interface { - LoadLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard) error + LoadLibraryPanelsForDashboard(c context.Context, dash *models.Dashboard) error CleanLibraryPanelsForDashboard(dash *models.Dashboard) error - ConnectLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard) error - ImportLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard, folderID int64) error + ConnectLibraryPanelsForDashboard(c context.Context, signedInUser *models.SignedInUser, dash *models.Dashboard) error + ImportLibraryPanelsForDashboard(c context.Context, signedInUser *models.SignedInUser, dash *models.Dashboard, folderID int64) error } // LibraryPanelService is the service for the Panel Library feature. @@ -44,7 +45,7 @@ type LibraryPanelService struct { // LoadLibraryPanelsForDashboard loops through all panels in dashboard JSON and replaces any library panel JSON // with JSON stored for library panel in db. -func (lps *LibraryPanelService) LoadLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard) error { +func (lps *LibraryPanelService) LoadLibraryPanelsForDashboard(c context.Context, dash *models.Dashboard) error { elements, err := lps.LibraryElementService.GetElementsForDashboard(c, dash.Id) if err != nil { return err @@ -195,7 +196,7 @@ func cleanLibraryPanelsRecursively(parent *simplejson.Json) error { } // ConnectLibraryPanelsForDashboard loops through all panels in dashboard JSON and connects any library panels to the dashboard. -func (lps *LibraryPanelService) ConnectLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard) error { +func (lps *LibraryPanelService) ConnectLibraryPanelsForDashboard(c context.Context, signedInUser *models.SignedInUser, dash *models.Dashboard) error { panels := dash.Data.Get("panels").MustArray() libraryPanels := make(map[string]string) err := connectLibraryPanelsRecursively(c, panels, libraryPanels) @@ -208,14 +209,14 @@ func (lps *LibraryPanelService) ConnectLibraryPanelsForDashboard(c *models.ReqCo elementUIDs = append(elementUIDs, libraryPanel) } - return lps.LibraryElementService.ConnectElementsToDashboard(c, elementUIDs, dash.Id) + return lps.LibraryElementService.ConnectElementsToDashboard(c, signedInUser, elementUIDs, dash.Id) } func isLibraryPanelOrRow(panel *simplejson.Json, panelType string) bool { return panel.Interface() != nil || panelType == "row" } -func connectLibraryPanelsRecursively(c *models.ReqContext, panels []interface{}, libraryPanels map[string]string) error { +func connectLibraryPanelsRecursively(c context.Context, panels []interface{}, libraryPanels map[string]string) error { for _, panel := range panels { panelAsJSON := simplejson.NewFromAny(panel) libraryPanel := panelAsJSON.Get("libraryPanel") @@ -249,11 +250,11 @@ func connectLibraryPanelsRecursively(c *models.ReqContext, panels []interface{}, } // ImportLibraryPanelsForDashboard loops through all panels in dashboard JSON and creates any missing library panels in the database. -func (lps *LibraryPanelService) ImportLibraryPanelsForDashboard(c *models.ReqContext, dash *models.Dashboard, folderID int64) error { - return importLibraryPanelsRecursively(c, lps.LibraryElementService, dash.Data, folderID) +func (lps *LibraryPanelService) ImportLibraryPanelsForDashboard(c context.Context, signedInUser *models.SignedInUser, dash *models.Dashboard, folderID int64) error { + return importLibraryPanelsRecursively(c, lps.LibraryElementService, signedInUser, dash.Data, folderID) } -func importLibraryPanelsRecursively(c *models.ReqContext, service libraryelements.Service, parent *simplejson.Json, folderID int64) error { +func importLibraryPanelsRecursively(c context.Context, service libraryelements.Service, signedInUser *models.SignedInUser, parent *simplejson.Json, folderID int64) error { panels := parent.Get("panels").MustArray() for _, panel := range panels { panelAsJSON := simplejson.NewFromAny(panel) @@ -265,7 +266,7 @@ func importLibraryPanelsRecursively(c *models.ReqContext, service libraryelement // we have a row if panelType == "row" { - err := importLibraryPanelsRecursively(c, service, panelAsJSON, folderID) + err := importLibraryPanelsRecursively(c, service, signedInUser, panelAsJSON, folderID) if err != nil { return err } @@ -282,7 +283,7 @@ func importLibraryPanelsRecursively(c *models.ReqContext, service libraryelement return errLibraryPanelHeaderNameMissing } - _, err := service.GetElement(c, UID) + _, err := service.GetElement(c, signedInUser, UID) if err == nil { continue } @@ -304,7 +305,7 @@ func importLibraryPanelsRecursively(c *models.ReqContext, service libraryelement Kind: int64(models.PanelElement), UID: UID, } - _, err = service.CreateElement(c, cmd) + _, err = service.CreateElement(c, signedInUser, cmd) if err != nil { return err } diff --git a/pkg/services/librarypanels/librarypanels_test.go b/pkg/services/librarypanels/librarypanels_test.go index ac82c2404bb..8ff38c5860a 100644 --- a/pkg/services/librarypanels/librarypanels_test.go +++ b/pkg/services/librarypanels/librarypanels_test.go @@ -4,13 +4,11 @@ import ( "context" "encoding/json" "fmt" - "net/http" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/require" - "gopkg.in/macaron.v1" "github.com/grafana/grafana/pkg/components/simplejson" dboards "github.com/grafana/grafana/pkg/dashboards" @@ -58,10 +56,10 @@ func TestLoadLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.elementService.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) + err := sc.elementService.ConnectElementsToDashboard(sc.ctx, sc.user, []string{sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) - err = sc.service.LoadLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err = sc.service.LoadLibraryPanelsForDashboard(sc.ctx, dashInDB) require.NoError(t, err) expectedJSON := map[string]interface{}{ "title": "Testing LoadLibraryPanelsForDashboard", @@ -138,7 +136,7 @@ func TestLoadLibraryPanelsForDashboard(t *testing.T) { `), Kind: int64(models.PanelElement), } - outsidePanel, err := sc.elementService.CreateElement(sc.reqContext, cmd) + outsidePanel, err := sc.elementService.CreateElement(sc.ctx, sc.user, cmd) require.NoError(t, err) dashJSON := map[string]interface{}{ "panels": []interface{}{ @@ -212,10 +210,10 @@ func TestLoadLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err = sc.elementService.ConnectElementsToDashboard(sc.reqContext, []string{outsidePanel.UID, sc.initialResult.Result.UID}, dashInDB.Id) + err = sc.elementService.ConnectElementsToDashboard(sc.ctx, sc.user, []string{outsidePanel.UID, sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) - err = sc.service.LoadLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err = sc.service.LoadLibraryPanelsForDashboard(sc.ctx, dashInDB) require.NoError(t, err) expectedJSON := map[string]interface{}{ "title": "Testing LoadLibraryPanelsForDashboard", @@ -367,10 +365,10 @@ func TestLoadLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.elementService.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) + err := sc.elementService.ConnectElementsToDashboard(sc.ctx, sc.user, []string{sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) - err = sc.service.LoadLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err = sc.service.LoadLibraryPanelsForDashboard(sc.ctx, dashInDB) require.EqualError(t, err, errLibraryPanelHeaderUIDMissing.Error()) }) @@ -408,7 +406,7 @@ func TestLoadLibraryPanelsForDashboard(t *testing.T) { } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.service.LoadLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err := sc.service.LoadLibraryPanelsForDashboard(sc.ctx, dashInDB) require.NoError(t, err) expectedJSON := map[string]interface{}{ "title": "Testing LoadLibraryPanelsForDashboard", @@ -538,7 +536,7 @@ func TestCleanLibraryPanelsForDashboard(t *testing.T) { `), Kind: int64(models.PanelElement), } - outsidePanel, err := sc.elementService.CreateElement(sc.reqContext, cmd) + outsidePanel, err := sc.elementService.CreateElement(sc.ctx, sc.user, cmd) require.NoError(t, err) dashJSON := map[string]interface{}{ "panels": []interface{}{ @@ -804,10 +802,10 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) { } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.service.ConnectLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err := sc.service.ConnectLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB) require.NoError(t, err) - elements, err := sc.elementService.GetElementsForDashboard(sc.reqContext, dashInDB.Id) + elements, err := sc.elementService.GetElementsForDashboard(sc.ctx, dashInDB.Id) require.NoError(t, err) require.Len(t, elements, 1) require.Equal(t, sc.initialResult.Result.UID, elements[sc.initialResult.Result.UID].UID) @@ -829,7 +827,7 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) { `), Kind: int64(models.PanelElement), } - outsidePanel, err := sc.elementService.CreateElement(sc.reqContext, cmd) + outsidePanel, err := sc.elementService.CreateElement(sc.ctx, sc.user, cmd) require.NoError(t, err) dashJSON := map[string]interface{}{ "panels": []interface{}{ @@ -904,10 +902,10 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) { } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err = sc.service.ConnectLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err = sc.service.ConnectLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB) require.NoError(t, err) - elements, err := sc.elementService.GetElementsForDashboard(sc.reqContext, dashInDB.Id) + elements, err := sc.elementService.GetElementsForDashboard(sc.ctx, dashInDB.Id) require.NoError(t, err) require.Len(t, elements, 2) require.Equal(t, sc.initialResult.Result.UID, elements[sc.initialResult.Result.UID].UID) @@ -950,13 +948,13 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) { } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err := sc.service.ConnectLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err := sc.service.ConnectLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB) require.EqualError(t, err, errLibraryPanelHeaderUIDMissing.Error()) }) scenarioWithLibraryPanel(t, "When an admin tries to store a dashboard with unused/removed library panels, it should disconnect unused/removed library panels", func(t *testing.T, sc scenarioContext) { - unused, err := sc.elementService.CreateElement(sc.reqContext, libraryelements.CreateLibraryElementCommand{ + unused, err := sc.elementService.CreateElement(sc.ctx, sc.user, libraryelements.CreateLibraryElementCommand{ FolderID: sc.folder.Id, Name: "Unused Libray Panel", Model: []byte(` @@ -1006,7 +1004,7 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - err = sc.elementService.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) + err = sc.elementService.ConnectElementsToDashboard(sc.ctx, sc.user, []string{sc.initialResult.Result.UID}, dashInDB.Id) require.NoError(t, err) panelJSON := []interface{}{ @@ -1037,10 +1035,10 @@ func TestConnectLibraryPanelsForDashboard(t *testing.T) { }, } dashInDB.Data.Set("panels", panelJSON) - err = sc.service.ConnectLibraryPanelsForDashboard(sc.reqContext, dashInDB) + err = sc.service.ConnectLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB) require.NoError(t, err) - elements, err := sc.elementService.GetElementsForDashboard(sc.reqContext, dashInDB.Id) + elements, err := sc.elementService.GetElementsForDashboard(sc.ctx, dashInDB.Id) require.NoError(t, err) require.Len(t, elements, 1) require.Equal(t, sc.initialResult.Result.UID, elements[sc.initialResult.Result.UID].UID) @@ -1089,13 +1087,13 @@ func TestImportLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - _, err := sc.elementService.GetElement(sc.reqContext, missingUID) + _, err := sc.elementService.GetElement(sc.ctx, sc.user, missingUID) require.EqualError(t, err, libraryelements.ErrLibraryElementNotFound.Error()) - err = sc.service.ImportLibraryPanelsForDashboard(sc.reqContext, dashInDB, 0) + err = sc.service.ImportLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB, 0) require.NoError(t, err) - element, err := sc.elementService.GetElement(sc.reqContext, missingUID) + element, err := sc.elementService.GetElement(sc.ctx, sc.user, missingUID) require.NoError(t, err) var expected = getExpected(t, element, missingUID, missingName, missingModel) var result = toLibraryElement(t, element) @@ -1138,13 +1136,13 @@ func TestImportLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - _, err := sc.elementService.GetElement(sc.reqContext, existingUID) + _, err := sc.elementService.GetElement(sc.ctx, sc.user, existingUID) require.NoError(t, err) - err = sc.service.ImportLibraryPanelsForDashboard(sc.reqContext, dashInDB, sc.folder.Id) + err = sc.service.ImportLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB, sc.folder.Id) require.NoError(t, err) - element, err := sc.elementService.GetElement(sc.reqContext, existingUID) + element, err := sc.elementService.GetElement(sc.ctx, sc.user, existingUID) require.NoError(t, err) var expected = getExpected(t, element, existingUID, existingName, sc.initialResult.Result.Model) expected.FolderID = sc.initialResult.Result.FolderID @@ -1238,15 +1236,15 @@ func TestImportLibraryPanelsForDashboard(t *testing.T) { Data: simplejson.NewFromAny(dashJSON), } dashInDB := createDashboard(t, sc.sqlStore, sc.user, &dash, sc.folder.Id) - _, err := sc.elementService.GetElement(sc.reqContext, outsideUID) + _, err := sc.elementService.GetElement(sc.ctx, sc.user, outsideUID) require.EqualError(t, err, libraryelements.ErrLibraryElementNotFound.Error()) - _, err = sc.elementService.GetElement(sc.reqContext, insideUID) + _, err = sc.elementService.GetElement(sc.ctx, sc.user, insideUID) require.EqualError(t, err, libraryelements.ErrLibraryElementNotFound.Error()) - err = sc.service.ImportLibraryPanelsForDashboard(sc.reqContext, dashInDB, 0) + err = sc.service.ImportLibraryPanelsForDashboard(sc.ctx, sc.user, dashInDB, 0) require.NoError(t, err) - element, err := sc.elementService.GetElement(sc.reqContext, outsideUID) + element, err := sc.elementService.GetElement(sc.ctx, sc.user, outsideUID) require.NoError(t, err) expected := getExpected(t, element, outsideUID, outsideName, outsideModel) result := toLibraryElement(t, element) @@ -1254,7 +1252,7 @@ func TestImportLibraryPanelsForDashboard(t *testing.T) { t.Fatalf("Result mismatch (-want +got):\n%s", diff) } - element, err = sc.elementService.GetElement(sc.reqContext, insideUID) + element, err = sc.elementService.GetElement(sc.ctx, sc.user, insideUID) require.NoError(t, err) expected = getExpected(t, element, insideUID, insideName, insideModel) result = toLibraryElement(t, element) @@ -1318,11 +1316,10 @@ type libraryPanelResult struct { } type scenarioContext struct { - ctx *macaron.Context + ctx context.Context service Service elementService libraryelements.Service - reqContext *models.ReqContext - user models.SignedInUser + user *models.SignedInUser folder *models.Folder initialResult libraryPanelResult sqlStore *sqlstore.SQLStore @@ -1407,13 +1404,13 @@ func getExpected(t *testing.T, res libraryelements.LibraryElementDTO, UID string } } -func createDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, user models.SignedInUser, dash *models.Dashboard, folderID int64) *models.Dashboard { +func createDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, user *models.SignedInUser, dash *models.Dashboard, folderID int64) *models.Dashboard { dash.FolderId = folderID dashItem := &dashboards.SaveDashboardDTO{ Dashboard: dash, Message: "", OrgId: user.OrgId, - User: &user, + User: user, Overwrite: false, } origUpdateAlerting := dashboards.UpdateAlerting @@ -1431,11 +1428,11 @@ func createDashboard(t *testing.T, sqlStore *sqlstore.SQLStore, user models.Sign return dashboard } -func createFolderWithACL(t *testing.T, sqlStore *sqlstore.SQLStore, title string, user models.SignedInUser, +func createFolderWithACL(t *testing.T, sqlStore *sqlstore.SQLStore, title string, user *models.SignedInUser, items []folderACLItem) *models.Folder { t.Helper() - s := dashboards.NewFolderService(user.OrgId, &user, sqlStore) + s := dashboards.NewFolderService(user.OrgId, user, sqlStore) t.Logf("Creating folder with title and UID %q", title) folder, err := s.CreateFolder(context.Background(), title, title) require.NoError(t, err) @@ -1487,7 +1484,7 @@ func scenarioWithLibraryPanel(t *testing.T, desc string, fn func(t *testing.T, s `), Kind: int64(models.PanelElement), } - resp, err := sc.elementService.CreateElement(sc.reqContext, command) + resp, err := sc.elementService.CreateElement(sc.ctx, sc.user, command) require.NoError(t, err) var model map[string]interface{} err = json.Unmarshal(resp.Model, &model) @@ -1518,7 +1515,6 @@ func testScenario(t *testing.T, desc string, fn func(t *testing.T, sc scenarioCo t.Helper() t.Run(desc, func(t *testing.T) { - ctx := macaron.Context{Req: &http.Request{}} cfg := setting.NewCfg() orgID := int64(1) role := models.ROLE_ADMIN @@ -1533,7 +1529,7 @@ func testScenario(t *testing.T, desc string, fn func(t *testing.T, sc scenarioCo LibraryElementService: &elementService, } - user := models.SignedInUser{ + user := &models.SignedInUser{ UserId: 1, Name: "Signed In User", Login: "signed_in_user", @@ -1556,14 +1552,10 @@ func testScenario(t *testing.T, desc string, fn func(t *testing.T, sc scenarioCo sc := scenarioContext{ user: user, - ctx: &ctx, + ctx: context.Background(), service: &service, elementService: &elementService, sqlStore: sqlStore, - reqContext: &models.ReqContext{ - Context: &ctx, - SignedInUser: &user, - }, } sc.folder = createFolderWithACL(t, sc.sqlStore, "ScenarioFolder", sc.user, []folderACLItem{})