mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Chore: Rename Id to ID in alerting models (#62777)
* Chore: Rename Id to ID in alerting models * Add xorm tags for datasource * Add xorm tag for uid
This commit is contained in:
parent
48a374f50b
commit
23c27cffb3
@ -30,7 +30,7 @@ func (hs *HTTPServer) ValidateOrgAlert(c *contextmodel.ReqContext) {
|
|||||||
c.JsonApiErr(http.StatusBadRequest, "alertId is invalid", nil)
|
c.JsonApiErr(http.StatusBadRequest, "alertId is invalid", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
query := alertmodels.GetAlertByIdQuery{Id: id}
|
query := alertmodels.GetAlertByIdQuery{ID: id}
|
||||||
|
|
||||||
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
|
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -38,7 +38,7 @@ func (hs *HTTPServer) ValidateOrgAlert(c *contextmodel.ReqContext) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.OrgID != res.OrgId {
|
if c.OrgID != res.OrgID {
|
||||||
c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
|
c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -61,8 +61,8 @@ func (hs *HTTPServer) GetAlertStatesForDashboard(c *contextmodel.ReqContext) res
|
|||||||
}
|
}
|
||||||
|
|
||||||
query := alertmodels.GetAlertStatesForDashboardQuery{
|
query := alertmodels.GetAlertStatesForDashboardQuery{
|
||||||
OrgId: c.OrgID,
|
OrgID: c.OrgID,
|
||||||
DashboardId: c.QueryInt64("dashboardId"),
|
DashboardID: c.QueryInt64("dashboardId"),
|
||||||
}
|
}
|
||||||
|
|
||||||
res, err := hs.AlertEngine.AlertStore.GetAlertStatesForDashboard(c.Req.Context(), &query)
|
res, err := hs.AlertEngine.AlertStore.GetAlertStatesForDashboard(c.Req.Context(), &query)
|
||||||
@ -134,9 +134,9 @@ func (hs *HTTPServer) GetAlerts(c *contextmodel.ReqContext) response.Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
query := alertmodels.GetAlertsQuery{
|
query := alertmodels.GetAlertsQuery{
|
||||||
OrgId: c.OrgID,
|
OrgID: c.OrgID,
|
||||||
DashboardIDs: dashboardIDs,
|
DashboardIDs: dashboardIDs,
|
||||||
PanelId: c.QueryInt64("panelId"),
|
PanelID: c.QueryInt64("panelId"),
|
||||||
Limit: c.QueryInt64("limit"),
|
Limit: c.QueryInt64("limit"),
|
||||||
User: c.SignedInUser,
|
User: c.SignedInUser,
|
||||||
Query: c.Query("query"),
|
Query: c.Query("query"),
|
||||||
@ -153,7 +153,7 @@ func (hs *HTTPServer) GetAlerts(c *contextmodel.ReqContext) response.Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, alert := range res {
|
for _, alert := range res {
|
||||||
alert.Url = dashboards.GetDashboardURL(alert.DashboardUid, alert.DashboardSlug)
|
alert.URL = dashboards.GetDashboardURL(alert.DashboardUID, alert.DashboardSlug)
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.JSON(http.StatusOK, res)
|
return response.JSON(http.StatusOK, res)
|
||||||
@ -228,7 +228,7 @@ func (hs *HTTPServer) GetAlert(c *contextmodel.ReqContext) response.Response {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return response.Error(http.StatusBadRequest, "alertId is invalid", err)
|
return response.Error(http.StatusBadRequest, "alertId is invalid", err)
|
||||||
}
|
}
|
||||||
query := alertmodels.GetAlertByIdQuery{Id: id}
|
query := alertmodels.GetAlertByIdQuery{ID: id}
|
||||||
|
|
||||||
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
|
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -698,13 +698,13 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
|
|||||||
result := make(map[string]interface{})
|
result := make(map[string]interface{})
|
||||||
result["alertId"] = alertID
|
result["alertId"] = alertID
|
||||||
|
|
||||||
query := alertmodels.GetAlertByIdQuery{Id: alertID}
|
query := alertmodels.GetAlertByIdQuery{ID: alertID}
|
||||||
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
|
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return response.Error(500, "Get Alert failed", err)
|
return response.Error(500, "Get Alert failed", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
guardian, err := guardian.New(c.Req.Context(), res.DashboardId, c.OrgID, c.SignedInUser)
|
guardian, err := guardian.New(c.Req.Context(), res.DashboardID, c.OrgID, c.SignedInUser)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return response.ErrOrFallback(http.StatusInternalServerError, "Error while creating permission guardian", err)
|
return response.ErrOrFallback(http.StatusInternalServerError, "Error while creating permission guardian", err)
|
||||||
}
|
}
|
||||||
@ -728,8 +728,8 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmd := alertmodels.PauseAlertCommand{
|
cmd := alertmodels.PauseAlertCommand{
|
||||||
OrgId: c.OrgID,
|
OrgID: c.OrgID,
|
||||||
AlertIds: []int64{alertID},
|
AlertIDs: []int64{alertID},
|
||||||
Paused: dto.Paused,
|
Paused: dto.Paused,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -43,7 +43,7 @@ var secretsPluginError datasources.ErrDatasourceSecretsPluginUserFriendly
|
|||||||
// 403: forbiddenError
|
// 403: forbiddenError
|
||||||
// 500: internalServerError
|
// 500: internalServerError
|
||||||
func (hs *HTTPServer) GetDataSources(c *contextmodel.ReqContext) response.Response {
|
func (hs *HTTPServer) GetDataSources(c *contextmodel.ReqContext) response.Response {
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit}
|
query := datasources.GetDataSourcesQuery{OrgID: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query); err != nil {
|
||||||
return response.Error(500, "Failed to query datasources", err)
|
return response.Error(500, "Failed to query datasources", err)
|
||||||
@ -57,11 +57,11 @@ func (hs *HTTPServer) GetDataSources(c *contextmodel.ReqContext) response.Respon
|
|||||||
result := make(dtos.DataSourceList, 0)
|
result := make(dtos.DataSourceList, 0)
|
||||||
for _, ds := range filtered {
|
for _, ds := range filtered {
|
||||||
dsItem := dtos.DataSourceListItemDTO{
|
dsItem := dtos.DataSourceListItemDTO{
|
||||||
OrgId: ds.OrgId,
|
OrgId: ds.OrgID,
|
||||||
Id: ds.Id,
|
Id: ds.ID,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
Url: ds.Url,
|
Url: ds.URL,
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
TypeName: ds.Type,
|
TypeName: ds.Type,
|
||||||
Access: ds.Access,
|
Access: ds.Access,
|
||||||
@ -112,8 +112,8 @@ func (hs *HTTPServer) GetDataSourceById(c *contextmodel.ReqContext) response.Res
|
|||||||
return response.Error(http.StatusBadRequest, "id is invalid", nil)
|
return response.Error(http.StatusBadRequest, "id is invalid", nil)
|
||||||
}
|
}
|
||||||
query := datasources.GetDataSourceQuery{
|
query := datasources.GetDataSourceQuery{
|
||||||
Id: id,
|
ID: id,
|
||||||
OrgId: c.OrgID,
|
OrgID: c.OrgID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
||||||
@ -183,7 +183,7 @@ func (hs *HTTPServer) DeleteDataSourceById(c *contextmodel.ReqContext) response.
|
|||||||
return response.Error(500, "Failed to delete datasource", err)
|
return response.Error(500, "Failed to delete datasource", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
hs.Live.HandleDatasourceDelete(c.OrgID, ds.Uid)
|
hs.Live.HandleDatasourceDelete(c.OrgID, ds.UID)
|
||||||
|
|
||||||
return response.Success("Data source deleted")
|
return response.Success("Data source deleted")
|
||||||
}
|
}
|
||||||
@ -262,11 +262,11 @@ func (hs *HTTPServer) DeleteDataSourceByUID(c *contextmodel.ReqContext) response
|
|||||||
return response.Error(500, "Failed to delete datasource", err)
|
return response.Error(500, "Failed to delete datasource", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
hs.Live.HandleDatasourceDelete(c.OrgID, ds.Uid)
|
hs.Live.HandleDatasourceDelete(c.OrgID, ds.UID)
|
||||||
|
|
||||||
return response.JSON(http.StatusOK, util.DynMap{
|
return response.JSON(http.StatusOK, util.DynMap{
|
||||||
"message": "Data source deleted",
|
"message": "Data source deleted",
|
||||||
"id": ds.Id,
|
"id": ds.ID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -290,7 +290,7 @@ func (hs *HTTPServer) DeleteDataSourceByName(c *contextmodel.ReqContext) respons
|
|||||||
return response.Error(400, "Missing valid datasource name", nil)
|
return response.Error(400, "Missing valid datasource name", nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
getCmd := &datasources.GetDataSourceQuery{Name: name, OrgId: c.OrgID}
|
getCmd := &datasources.GetDataSourceQuery{Name: name, OrgID: c.OrgID}
|
||||||
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), getCmd); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), getCmd); err != nil {
|
||||||
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
return response.Error(404, "Data source not found", nil)
|
return response.Error(404, "Data source not found", nil)
|
||||||
@ -311,11 +311,11 @@ func (hs *HTTPServer) DeleteDataSourceByName(c *contextmodel.ReqContext) respons
|
|||||||
return response.Error(500, "Failed to delete datasource", err)
|
return response.Error(500, "Failed to delete datasource", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
hs.Live.HandleDatasourceDelete(c.OrgID, getCmd.Result.Uid)
|
hs.Live.HandleDatasourceDelete(c.OrgID, getCmd.Result.UID)
|
||||||
|
|
||||||
return response.JSON(http.StatusOK, util.DynMap{
|
return response.JSON(http.StatusOK, util.DynMap{
|
||||||
"message": "Data source deleted",
|
"message": "Data source deleted",
|
||||||
"id": getCmd.Result.Id,
|
"id": getCmd.Result.ID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -371,11 +371,11 @@ func (hs *HTTPServer) AddDataSource(c *contextmodel.ReqContext) response.Respons
|
|||||||
return response.Error(http.StatusBadRequest, "bad request data", err)
|
return response.Error(http.StatusBadRequest, "bad request data", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
datasourcesLogger.Debug("Received command to add data source", "url", cmd.Url)
|
datasourcesLogger.Debug("Received command to add data source", "url", cmd.URL)
|
||||||
cmd.OrgId = c.OrgID
|
cmd.OrgID = c.OrgID
|
||||||
cmd.UserId = c.UserID
|
cmd.UserID = c.UserID
|
||||||
if cmd.Url != "" {
|
if cmd.URL != "" {
|
||||||
if resp := validateURL(cmd.Type, cmd.Url); resp != nil {
|
if resp := validateURL(cmd.Type, cmd.URL); resp != nil {
|
||||||
return resp
|
return resp
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -404,7 +404,7 @@ func (hs *HTTPServer) AddDataSource(c *contextmodel.ReqContext) response.Respons
|
|||||||
ds := hs.convertModelToDtos(c.Req.Context(), cmd.Result)
|
ds := hs.convertModelToDtos(c.Req.Context(), cmd.Result)
|
||||||
return response.JSON(http.StatusOK, util.DynMap{
|
return response.JSON(http.StatusOK, util.DynMap{
|
||||||
"message": "Datasource added",
|
"message": "Datasource added",
|
||||||
"id": cmd.Result.Id,
|
"id": cmd.Result.ID,
|
||||||
"name": cmd.Result.Name,
|
"name": cmd.Result.Name,
|
||||||
"datasource": ds,
|
"datasource": ds,
|
||||||
})
|
})
|
||||||
@ -436,20 +436,20 @@ func (hs *HTTPServer) UpdateDataSourceByID(c *contextmodel.ReqContext) response.
|
|||||||
if err := web.Bind(c.Req, &cmd); err != nil {
|
if err := web.Bind(c.Req, &cmd); err != nil {
|
||||||
return response.Error(http.StatusBadRequest, "bad request data", err)
|
return response.Error(http.StatusBadRequest, "bad request data", err)
|
||||||
}
|
}
|
||||||
datasourcesLogger.Debug("Received command to update data source", "url", cmd.Url)
|
datasourcesLogger.Debug("Received command to update data source", "url", cmd.URL)
|
||||||
cmd.OrgId = c.OrgID
|
cmd.OrgID = c.OrgID
|
||||||
var err error
|
var err error
|
||||||
if cmd.Id, err = strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64); err != nil {
|
if cmd.ID, err = strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64); err != nil {
|
||||||
return response.Error(http.StatusBadRequest, "id is invalid", err)
|
return response.Error(http.StatusBadRequest, "id is invalid", err)
|
||||||
}
|
}
|
||||||
if resp := validateURL(cmd.Type, cmd.Url); resp != nil {
|
if resp := validateURL(cmd.Type, cmd.URL); resp != nil {
|
||||||
return resp
|
return resp
|
||||||
}
|
}
|
||||||
if err := validateJSONData(cmd.JsonData, hs.Cfg); err != nil {
|
if err := validateJSONData(cmd.JsonData, hs.Cfg); err != nil {
|
||||||
return response.Error(http.StatusBadRequest, "Failed to update datasource", err)
|
return response.Error(http.StatusBadRequest, "Failed to update datasource", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
ds, err := hs.getRawDataSourceById(c.Req.Context(), cmd.Id, cmd.OrgId)
|
ds, err := hs.getRawDataSourceById(c.Req.Context(), cmd.ID, cmd.OrgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
return response.Error(404, "Data source not found", nil)
|
return response.Error(404, "Data source not found", nil)
|
||||||
@ -480,9 +480,9 @@ func (hs *HTTPServer) UpdateDataSourceByUID(c *contextmodel.ReqContext) response
|
|||||||
if err := web.Bind(c.Req, &cmd); err != nil {
|
if err := web.Bind(c.Req, &cmd); err != nil {
|
||||||
return response.Error(http.StatusBadRequest, "bad request data", err)
|
return response.Error(http.StatusBadRequest, "bad request data", err)
|
||||||
}
|
}
|
||||||
datasourcesLogger.Debug("Received command to update data source", "url", cmd.Url)
|
datasourcesLogger.Debug("Received command to update data source", "url", cmd.URL)
|
||||||
cmd.OrgId = c.OrgID
|
cmd.OrgID = c.OrgID
|
||||||
if resp := validateURL(cmd.Type, cmd.Url); resp != nil {
|
if resp := validateURL(cmd.Type, cmd.URL); resp != nil {
|
||||||
return resp
|
return resp
|
||||||
}
|
}
|
||||||
if err := validateJSONData(cmd.JsonData, hs.Cfg); err != nil {
|
if err := validateJSONData(cmd.JsonData, hs.Cfg); err != nil {
|
||||||
@ -496,7 +496,7 @@ func (hs *HTTPServer) UpdateDataSourceByUID(c *contextmodel.ReqContext) response
|
|||||||
}
|
}
|
||||||
return response.Error(http.StatusInternalServerError, "Failed to update datasource", err)
|
return response.Error(http.StatusInternalServerError, "Failed to update datasource", err)
|
||||||
}
|
}
|
||||||
cmd.Id = ds.Id
|
cmd.ID = ds.ID
|
||||||
return hs.updateDataSourceByID(c, ds, cmd)
|
return hs.updateDataSourceByID(c, ds, cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -518,8 +518,8 @@ func (hs *HTTPServer) updateDataSourceByID(c *contextmodel.ReqContext, ds *datas
|
|||||||
}
|
}
|
||||||
|
|
||||||
query := datasources.GetDataSourceQuery{
|
query := datasources.GetDataSourceQuery{
|
||||||
Id: cmd.Id,
|
ID: cmd.ID,
|
||||||
OrgId: c.OrgID,
|
OrgID: c.OrgID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
||||||
@ -535,7 +535,7 @@ func (hs *HTTPServer) updateDataSourceByID(c *contextmodel.ReqContext, ds *datas
|
|||||||
|
|
||||||
return response.JSON(http.StatusOK, util.DynMap{
|
return response.JSON(http.StatusOK, util.DynMap{
|
||||||
"message": "Datasource updated",
|
"message": "Datasource updated",
|
||||||
"id": cmd.Id,
|
"id": cmd.ID,
|
||||||
"name": cmd.Name,
|
"name": cmd.Name,
|
||||||
"datasource": datasourceDTO,
|
"datasource": datasourceDTO,
|
||||||
})
|
})
|
||||||
@ -543,8 +543,8 @@ func (hs *HTTPServer) updateDataSourceByID(c *contextmodel.ReqContext, ds *datas
|
|||||||
|
|
||||||
func (hs *HTTPServer) getRawDataSourceById(ctx context.Context, id int64, orgID int64) (*datasources.DataSource, error) {
|
func (hs *HTTPServer) getRawDataSourceById(ctx context.Context, id int64, orgID int64) (*datasources.DataSource, error) {
|
||||||
query := datasources.GetDataSourceQuery{
|
query := datasources.GetDataSourceQuery{
|
||||||
Id: id,
|
ID: id,
|
||||||
OrgId: orgID,
|
OrgID: orgID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSource(ctx, &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(ctx, &query); err != nil {
|
||||||
@ -556,8 +556,8 @@ func (hs *HTTPServer) getRawDataSourceById(ctx context.Context, id int64, orgID
|
|||||||
|
|
||||||
func (hs *HTTPServer) getRawDataSourceByUID(ctx context.Context, uid string, orgID int64) (*datasources.DataSource, error) {
|
func (hs *HTTPServer) getRawDataSourceByUID(ctx context.Context, uid string, orgID int64) (*datasources.DataSource, error) {
|
||||||
query := datasources.GetDataSourceQuery{
|
query := datasources.GetDataSourceQuery{
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
OrgId: orgID,
|
OrgID: orgID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSource(ctx, &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(ctx, &query); err != nil {
|
||||||
@ -580,7 +580,7 @@ func (hs *HTTPServer) getRawDataSourceByUID(ctx context.Context, uid string, org
|
|||||||
// 403: forbiddenError
|
// 403: forbiddenError
|
||||||
// 500: internalServerError
|
// 500: internalServerError
|
||||||
func (hs *HTTPServer) GetDataSourceByName(c *contextmodel.ReqContext) response.Response {
|
func (hs *HTTPServer) GetDataSourceByName(c *contextmodel.ReqContext) response.Response {
|
||||||
query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgId: c.OrgID}
|
query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgID: c.OrgID}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
||||||
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
@ -607,7 +607,7 @@ func (hs *HTTPServer) GetDataSourceByName(c *contextmodel.ReqContext) response.R
|
|||||||
// 404: notFoundError
|
// 404: notFoundError
|
||||||
// 500: internalServerError
|
// 500: internalServerError
|
||||||
func (hs *HTTPServer) GetDataSourceIdByName(c *contextmodel.ReqContext) response.Response {
|
func (hs *HTTPServer) GetDataSourceIdByName(c *contextmodel.ReqContext) response.Response {
|
||||||
query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgId: c.OrgID}
|
query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgID: c.OrgID}
|
||||||
|
|
||||||
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
|
||||||
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
@ -618,7 +618,7 @@ func (hs *HTTPServer) GetDataSourceIdByName(c *contextmodel.ReqContext) response
|
|||||||
|
|
||||||
ds := query.Result
|
ds := query.Result
|
||||||
dtos := dtos.AnyId{
|
dtos := dtos.AnyId{
|
||||||
Id: ds.Id,
|
Id: ds.ID,
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.JSON(http.StatusOK, &dtos)
|
return response.JSON(http.StatusOK, &dtos)
|
||||||
@ -703,11 +703,11 @@ func (hs *HTTPServer) CallDatasourceResourceWithUID(c *contextmodel.ReqContext)
|
|||||||
|
|
||||||
func (hs *HTTPServer) convertModelToDtos(ctx context.Context, ds *datasources.DataSource) dtos.DataSource {
|
func (hs *HTTPServer) convertModelToDtos(ctx context.Context, ds *datasources.DataSource) dtos.DataSource {
|
||||||
dto := dtos.DataSource{
|
dto := dtos.DataSource{
|
||||||
Id: ds.Id,
|
Id: ds.ID,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
OrgId: ds.OrgId,
|
OrgId: ds.OrgID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
Url: ds.Url,
|
Url: ds.URL,
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
Access: ds.Access,
|
Access: ds.Access,
|
||||||
Database: ds.Database,
|
Database: ds.Database,
|
||||||
|
@ -91,7 +91,7 @@ func TestAddDataSource_InvalidURL(t *testing.T) {
|
|||||||
sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
||||||
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
||||||
Name: "Test",
|
Name: "Test",
|
||||||
Url: "invalid:url",
|
URL: "invalid:url",
|
||||||
Access: "direct",
|
Access: "direct",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
})
|
})
|
||||||
@ -122,7 +122,7 @@ func TestAddDataSource_URLWithoutProtocol(t *testing.T) {
|
|||||||
sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
||||||
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
||||||
Name: name,
|
Name: name,
|
||||||
Url: url,
|
URL: url,
|
||||||
Access: "direct",
|
Access: "direct",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
})
|
})
|
||||||
@ -152,7 +152,7 @@ func TestAddDataSource_InvalidJSONData(t *testing.T) {
|
|||||||
sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
||||||
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
||||||
Name: "Test",
|
Name: "Test",
|
||||||
Url: "localhost:5432",
|
URL: "localhost:5432",
|
||||||
Access: "direct",
|
Access: "direct",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
@ -176,7 +176,7 @@ func TestUpdateDataSource_InvalidURL(t *testing.T) {
|
|||||||
sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
||||||
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
||||||
Name: "Test",
|
Name: "Test",
|
||||||
Url: "invalid:url",
|
URL: "invalid:url",
|
||||||
Access: "direct",
|
Access: "direct",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
})
|
})
|
||||||
@ -204,7 +204,7 @@ func TestUpdateDataSource_InvalidJSONData(t *testing.T) {
|
|||||||
sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
||||||
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
||||||
Name: "Test",
|
Name: "Test",
|
||||||
Url: "localhost:5432",
|
URL: "localhost:5432",
|
||||||
Access: "direct",
|
Access: "direct",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
@ -236,7 +236,7 @@ func TestUpdateDataSource_URLWithoutProtocol(t *testing.T) {
|
|||||||
sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
|
||||||
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
|
||||||
Name: name,
|
Name: name,
|
||||||
Url: url,
|
URL: url,
|
||||||
Access: "direct",
|
Access: "direct",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
})
|
})
|
||||||
|
@ -262,7 +262,7 @@ func isSupportBundlesEnabled(hs *HTTPServer) bool {
|
|||||||
func (hs *HTTPServer) getFSDataSources(c *contextmodel.ReqContext, enabledPlugins EnabledPlugins) (map[string]plugins.DataSourceDTO, error) {
|
func (hs *HTTPServer) getFSDataSources(c *contextmodel.ReqContext, enabledPlugins EnabledPlugins) (map[string]plugins.DataSourceDTO, error) {
|
||||||
orgDataSources := make([]*datasources.DataSource, 0)
|
orgDataSources := make([]*datasources.DataSource, 0)
|
||||||
if c.OrgID != 0 {
|
if c.OrgID != 0 {
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit}
|
query := datasources.GetDataSourcesQuery{OrgID: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit}
|
||||||
err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query)
|
err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -283,15 +283,15 @@ func (hs *HTTPServer) getFSDataSources(c *contextmodel.ReqContext, enabledPlugin
|
|||||||
dataSources := make(map[string]plugins.DataSourceDTO)
|
dataSources := make(map[string]plugins.DataSourceDTO)
|
||||||
|
|
||||||
for _, ds := range orgDataSources {
|
for _, ds := range orgDataSources {
|
||||||
url := ds.Url
|
url := ds.URL
|
||||||
|
|
||||||
if ds.Access == datasources.DS_ACCESS_PROXY {
|
if ds.Access == datasources.DS_ACCESS_PROXY {
|
||||||
url = "/api/datasources/proxy/uid/" + ds.Uid
|
url = "/api/datasources/proxy/uid/" + ds.UID
|
||||||
}
|
}
|
||||||
|
|
||||||
dsDTO := plugins.DataSourceDTO{
|
dsDTO := plugins.DataSourceDTO{
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
URL: url,
|
URL: url,
|
||||||
@ -365,7 +365,7 @@ func (hs *HTTPServer) getFSDataSources(c *contextmodel.ReqContext, enabledPlugin
|
|||||||
|
|
||||||
if ds.Type == datasources.DS_PROMETHEUS {
|
if ds.Type == datasources.DS_PROMETHEUS {
|
||||||
// add unproxied server URL for link to Prometheus web UI
|
// add unproxied server URL for link to Prometheus web UI
|
||||||
ds.JsonData.Set("directUrl", ds.Url)
|
ds.JsonData.Set("directUrl", ds.URL)
|
||||||
}
|
}
|
||||||
|
|
||||||
dataSources[ds.Name] = dsDTO
|
dataSources[ds.Name] = dsDTO
|
||||||
|
@ -54,7 +54,7 @@ func NewDataSourceProxy(ds *datasources.DataSource, pluginRoutes []*plugins.Rout
|
|||||||
proxyPath string, cfg *setting.Cfg, clientProvider httpclient.Provider,
|
proxyPath string, cfg *setting.Cfg, clientProvider httpclient.Provider,
|
||||||
oAuthTokenService oauthtoken.OAuthTokenService, dsService datasources.DataSourceService,
|
oAuthTokenService oauthtoken.OAuthTokenService, dsService datasources.DataSourceService,
|
||||||
tracer tracing.Tracer) (*DataSourceProxy, error) {
|
tracer tracing.Tracer) (*DataSourceProxy, error) {
|
||||||
targetURL, err := datasource.ValidateURL(ds.Type, ds.Url)
|
targetURL, err := datasource.ValidateURL(ds.Type, ds.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -244,7 +244,7 @@ func (proxy *DataSourceProxy) director(req *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ApplyRoute(req.Context(), req, proxy.proxyPath, proxy.matchedRoute, DSInfo{
|
ApplyRoute(req.Context(), req, proxy.proxyPath, proxy.matchedRoute, DSInfo{
|
||||||
ID: proxy.ds.Id,
|
ID: proxy.ds.ID,
|
||||||
Updated: proxy.ds.Updated,
|
Updated: proxy.ds.Updated,
|
||||||
JSONData: jsonData,
|
JSONData: jsonData,
|
||||||
DecryptedSecureJSONData: decryptedValues,
|
DecryptedSecureJSONData: decryptedValues,
|
||||||
|
@ -121,7 +121,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
jd, err := ds.JsonData.Map()
|
jd, err := ds.JsonData.Map()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
dsInfo := DSInfo{
|
dsInfo := DSInfo{
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
Updated: ds.Updated,
|
Updated: ds.Updated,
|
||||||
JSONData: jd,
|
JSONData: jd,
|
||||||
DecryptedSecureJSONData: map[string]string{
|
DecryptedSecureJSONData: map[string]string{
|
||||||
@ -307,7 +307,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
jd, err := ds.JsonData.Map()
|
jd, err := ds.JsonData.Map()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
dsInfo := DSInfo{
|
dsInfo := DSInfo{
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
Updated: ds.Updated,
|
Updated: ds.Updated,
|
||||||
JSONData: jd,
|
JSONData: jd,
|
||||||
DecryptedSecureJSONData: map[string]string{
|
DecryptedSecureJSONData: map[string]string{
|
||||||
@ -372,7 +372,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("When proxying graphite", func(t *testing.T) {
|
t.Run("When proxying graphite", func(t *testing.T) {
|
||||||
var routes []*plugins.Route
|
var routes []*plugins.Route
|
||||||
ds := &datasources.DataSource{Url: "htttp://graphite:8080", Type: datasources.DS_GRAPHITE}
|
ds := &datasources.DataSource{URL: "htttp://graphite:8080", Type: datasources.DS_GRAPHITE}
|
||||||
ctx := &contextmodel.ReqContext{}
|
ctx := &contextmodel.ReqContext{}
|
||||||
|
|
||||||
sqlStore := db.InitTestDB(t)
|
sqlStore := db.InitTestDB(t)
|
||||||
@ -397,7 +397,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
t.Run("When proxying InfluxDB", func(t *testing.T) {
|
t.Run("When proxying InfluxDB", func(t *testing.T) {
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Type: datasources.DS_INFLUXDB_08,
|
Type: datasources.DS_INFLUXDB_08,
|
||||||
Url: "http://influxdb:8083",
|
URL: "http://influxdb:8083",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
User: "user",
|
User: "user",
|
||||||
}
|
}
|
||||||
@ -426,7 +426,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
|
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Url: "http://graphite:8086",
|
URL: "http://graphite:8086",
|
||||||
JsonData: json,
|
JsonData: json,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -458,7 +458,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
|
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Url: "http://graphite:8086",
|
URL: "http://graphite:8086",
|
||||||
JsonData: json,
|
JsonData: json,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -487,7 +487,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
t.Run("When proxying a custom datasource", func(t *testing.T) {
|
t.Run("When proxying a custom datasource", func(t *testing.T) {
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Type: "custom-datasource",
|
Type: "custom-datasource",
|
||||||
Url: "http://host/root/",
|
URL: "http://host/root/",
|
||||||
}
|
}
|
||||||
ctx := &contextmodel.ReqContext{}
|
ctx := &contextmodel.ReqContext{}
|
||||||
var routes []*plugins.Route
|
var routes []*plugins.Route
|
||||||
@ -515,7 +515,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
|
|||||||
t.Run("When proxying a datasource that has OAuth token pass-through enabled", func(t *testing.T) {
|
t.Run("When proxying a datasource that has OAuth token pass-through enabled", func(t *testing.T) {
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Type: "custom-datasource",
|
Type: "custom-datasource",
|
||||||
Url: "http://host/root/",
|
URL: "http://host/root/",
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"oauthPassThru": true,
|
"oauthPassThru": true,
|
||||||
}),
|
}),
|
||||||
@ -657,7 +657,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
t.Cleanup(backend.Close)
|
t.Cleanup(backend.Close)
|
||||||
|
|
||||||
ds := &datasources.DataSource{Url: backend.URL, Type: datasources.DS_GRAPHITE}
|
ds := &datasources.DataSource{URL: backend.URL, Type: datasources.DS_GRAPHITE}
|
||||||
|
|
||||||
responseWriter := web.NewResponseWriter("GET", httptest.NewRecorder())
|
responseWriter := web.NewResponseWriter("GET", httptest.NewRecorder())
|
||||||
|
|
||||||
@ -829,7 +829,7 @@ func TestNewDataSourceProxy_InvalidURL(t *testing.T) {
|
|||||||
}
|
}
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Type: "test",
|
Type: "test",
|
||||||
Url: "://host/root",
|
URL: "://host/root",
|
||||||
}
|
}
|
||||||
cfg := &setting.Cfg{}
|
cfg := &setting.Cfg{}
|
||||||
tracer := tracing.InitializeTracerForTest()
|
tracer := tracing.InitializeTracerForTest()
|
||||||
@ -853,7 +853,7 @@ func TestNewDataSourceProxy_ProtocolLessURL(t *testing.T) {
|
|||||||
}
|
}
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Type: "test",
|
Type: "test",
|
||||||
Url: "127.0.01:5432",
|
URL: "127.0.01:5432",
|
||||||
}
|
}
|
||||||
cfg := &setting.Cfg{}
|
cfg := &setting.Cfg{}
|
||||||
tracer := tracing.InitializeTracerForTest()
|
tracer := tracing.InitializeTracerForTest()
|
||||||
@ -901,7 +901,7 @@ func TestNewDataSourceProxy_MSSQL(t *testing.T) {
|
|||||||
cfg := &setting.Cfg{}
|
cfg := &setting.Cfg{}
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Type: "mssql",
|
Type: "mssql",
|
||||||
Url: tc.url,
|
URL: tc.url,
|
||||||
}
|
}
|
||||||
|
|
||||||
var routes []*plugins.Route
|
var routes []*plugins.Route
|
||||||
@ -916,7 +916,7 @@ func TestNewDataSourceProxy_MSSQL(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, &url.URL{
|
assert.Equal(t, &url.URL{
|
||||||
Scheme: "sqlserver",
|
Scheme: "sqlserver",
|
||||||
Host: ds.Url,
|
Host: ds.URL,
|
||||||
}, p.targetUrl)
|
}, p.targetUrl)
|
||||||
} else {
|
} else {
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
@ -930,7 +930,7 @@ func TestNewDataSourceProxy_MSSQL(t *testing.T) {
|
|||||||
func getDatasourceProxiedRequest(t *testing.T, ctx *contextmodel.ReqContext, cfg *setting.Cfg) *http.Request {
|
func getDatasourceProxiedRequest(t *testing.T, ctx *contextmodel.ReqContext, cfg *setting.Cfg) *http.Request {
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Type: "custom",
|
Type: "custom",
|
||||||
Url: "http://host/root/",
|
URL: "http://host/root/",
|
||||||
}
|
}
|
||||||
tracer := tracing.InitializeTracerForTest()
|
tracer := tracing.InitializeTracerForTest()
|
||||||
|
|
||||||
@ -999,12 +999,12 @@ func createAuthTest(t *testing.T, secretsStore secretskvs.SecretsKVStore, dsType
|
|||||||
|
|
||||||
test := &testCase{
|
test := &testCase{
|
||||||
datasource: &datasources.DataSource{
|
datasource: &datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: fmt.Sprintf("%s,%s,%s,%s", dsType, url, authType, authCheck),
|
Name: fmt.Sprintf("%s,%s,%s,%s", dsType, url, authType, authCheck),
|
||||||
Type: dsType,
|
Type: dsType,
|
||||||
JsonData: simplejson.New(),
|
JsonData: simplejson.New(),
|
||||||
Url: url,
|
URL: url,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
var message string
|
var message string
|
||||||
@ -1017,7 +1017,7 @@ func createAuthTest(t *testing.T, secretsStore secretskvs.SecretsKVStore, dsType
|
|||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = secretsStore.Set(context.Background(), test.datasource.OrgId, test.datasource.Name, "datasource", string(secureJsonData))
|
err = secretsStore.Set(context.Background(), test.datasource.OrgID, test.datasource.Name, "datasource", string(secureJsonData))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("%v should add basic auth username and password", dsType)
|
message = fmt.Sprintf("%v should add basic auth username and password", dsType)
|
||||||
@ -1028,7 +1028,7 @@ func createAuthTest(t *testing.T, secretsStore secretskvs.SecretsKVStore, dsType
|
|||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = secretsStore.Set(context.Background(), test.datasource.OrgId, test.datasource.Name, "datasource", string(secureJsonData))
|
err = secretsStore.Set(context.Background(), test.datasource.OrgID, test.datasource.Name, "datasource", string(secureJsonData))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
@ -27,10 +27,10 @@ func TestPasswordMigrationCommand(t *testing.T) {
|
|||||||
|
|
||||||
func passwordMigration(t *testing.T, session *db.Session, sqlstore db.DB) {
|
func passwordMigration(t *testing.T, session *db.Session, sqlstore db.DB) {
|
||||||
ds := []*datasources.DataSource{
|
ds := []*datasources.DataSource{
|
||||||
{Type: "influxdb", Name: "influxdb", Password: "foobar", Uid: "influx"},
|
{Type: "influxdb", Name: "influxdb", Password: "foobar", UID: "influx"},
|
||||||
{Type: "graphite", Name: "graphite", BasicAuthPassword: "foobar", Uid: "graphite"},
|
{Type: "graphite", Name: "graphite", BasicAuthPassword: "foobar", UID: "graphite"},
|
||||||
{Type: "prometheus", Name: "prometheus", Uid: "prom"},
|
{Type: "prometheus", Name: "prometheus", UID: "prom"},
|
||||||
{Type: "elasticsearch", Name: "elasticsearch", Password: "pwd", Uid: "elastic"},
|
{Type: "elasticsearch", Name: "elasticsearch", Password: "pwd", UID: "elastic"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// set required default values
|
// set required default values
|
||||||
|
@ -131,7 +131,7 @@ func (s *Service) buildGraph(req *Request) (*simple.DirectedGraph, error) {
|
|||||||
dp := simple.NewDirectedGraph()
|
dp := simple.NewDirectedGraph()
|
||||||
|
|
||||||
for _, query := range req.Queries {
|
for _, query := range req.Queries {
|
||||||
if query.DataSource == nil || query.DataSource.Uid == "" {
|
if query.DataSource == nil || query.DataSource.UID == "" {
|
||||||
return nil, fmt.Errorf("missing datasource uid in query with refId %v", query.RefID)
|
return nil, fmt.Errorf("missing datasource uid in query with refId %v", query.RefID)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -157,7 +157,7 @@ func (s *Service) buildGraph(req *Request) (*simple.DirectedGraph, error) {
|
|||||||
|
|
||||||
var node Node
|
var node Node
|
||||||
|
|
||||||
if IsDataSource(rn.DataSource.Uid) {
|
if IsDataSource(rn.DataSource.UID) {
|
||||||
node, err = buildCMDNode(dp, rn)
|
node, err = buildCMDNode(dp, rn)
|
||||||
} else {
|
} else {
|
||||||
node, err = s.buildDSNode(dp, rn, req)
|
node, err = s.buildDSNode(dp, rn, req)
|
||||||
|
@ -32,7 +32,7 @@ func TestServicebuildPipeLine(t *testing.T) {
|
|||||||
{
|
{
|
||||||
RefID: "B",
|
RefID: "B",
|
||||||
DataSource: &datasources.DataSource{
|
DataSource: &datasources.DataSource{
|
||||||
Uid: "Fake",
|
UID: "Fake",
|
||||||
},
|
},
|
||||||
TimeRange: AbsoluteTimeRange{},
|
TimeRange: AbsoluteTimeRange{},
|
||||||
},
|
},
|
||||||
@ -143,7 +143,7 @@ func TestServicebuildPipeLine(t *testing.T) {
|
|||||||
{
|
{
|
||||||
RefID: "C",
|
RefID: "C",
|
||||||
DataSource: &datasources.DataSource{
|
DataSource: &datasources.DataSource{
|
||||||
Uid: "Fake",
|
UID: "Fake",
|
||||||
},
|
},
|
||||||
TimeRange: AbsoluteTimeRange{},
|
TimeRange: AbsoluteTimeRange{},
|
||||||
},
|
},
|
||||||
@ -198,7 +198,7 @@ func TestServicebuildPipeLine(t *testing.T) {
|
|||||||
{
|
{
|
||||||
RefID: "C",
|
RefID: "C",
|
||||||
DataSource: &datasources.DataSource{
|
DataSource: &datasources.DataSource{
|
||||||
Uid: "Fake",
|
UID: "Fake",
|
||||||
},
|
},
|
||||||
TimeRange: AbsoluteTimeRange{},
|
TimeRange: AbsoluteTimeRange{},
|
||||||
},
|
},
|
||||||
@ -222,7 +222,7 @@ func TestServicebuildPipeLine(t *testing.T) {
|
|||||||
{
|
{
|
||||||
RefID: "B",
|
RefID: "B",
|
||||||
DataSource: &datasources.DataSource{
|
DataSource: &datasources.DataSource{
|
||||||
Uid: "Fake",
|
UID: "Fake",
|
||||||
},
|
},
|
||||||
TimeRange: AbsoluteTimeRange{},
|
TimeRange: AbsoluteTimeRange{},
|
||||||
},
|
},
|
||||||
|
@ -201,7 +201,7 @@ func (s *Service) buildDSNode(dp *simple.DirectedGraph, rn *rawNode, req *Reques
|
|||||||
// other nodes they must have already been executed and their results must
|
// other nodes they must have already been executed and their results must
|
||||||
// already by in vars.
|
// already by in vars.
|
||||||
func (dn *DSNode) Execute(ctx context.Context, now time.Time, _ mathexp.Vars, s *Service) (r mathexp.Results, e error) {
|
func (dn *DSNode) Execute(ctx context.Context, now time.Time, _ mathexp.Vars, s *Service) (r mathexp.Results, e error) {
|
||||||
logger := logger.FromContext(ctx).New("datasourceType", dn.datasource.Type, "queryRefId", dn.refID, "datasourceUid", dn.datasource.Uid, "datasourceVersion", dn.datasource.Version)
|
logger := logger.FromContext(ctx).New("datasourceType", dn.datasource.Type, "queryRefId", dn.refID, "datasourceUid", dn.datasource.UID, "datasourceVersion", dn.datasource.Version)
|
||||||
dsInstanceSettings, err := adapters.ModelToInstanceSettings(dn.datasource, s.decryptSecureJsonDataFn(ctx))
|
dsInstanceSettings, err := adapters.ModelToInstanceSettings(dn.datasource, s.decryptSecureJsonDataFn(ctx))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return mathexp.Results{}, fmt.Errorf("%v: %w", "failed to convert datasource instance settings", err)
|
return mathexp.Results{}, fmt.Errorf("%v: %w", "failed to convert datasource instance settings", err)
|
||||||
|
@ -79,8 +79,8 @@ func (s *Service) ExecutePipeline(ctx context.Context, now time.Time, pipeline D
|
|||||||
|
|
||||||
func DataSourceModel() *datasources.DataSource {
|
func DataSourceModel() *datasources.DataSource {
|
||||||
return &datasources.DataSource{
|
return &datasources.DataSource{
|
||||||
Id: DatasourceID,
|
ID: DatasourceID,
|
||||||
Uid: DatasourceUID,
|
UID: DatasourceUID,
|
||||||
Name: DatasourceUID,
|
Name: DatasourceUID,
|
||||||
Type: DatasourceType,
|
Type: DatasourceType,
|
||||||
JsonData: simplejson.New(),
|
JsonData: simplejson.New(),
|
||||||
|
@ -38,8 +38,8 @@ func TestService(t *testing.T) {
|
|||||||
{
|
{
|
||||||
RefID: "A",
|
RefID: "A",
|
||||||
DataSource: &datasources.DataSource{
|
DataSource: &datasources.DataSource{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Uid: "test",
|
UID: "test",
|
||||||
Type: "test",
|
Type: "test",
|
||||||
},
|
},
|
||||||
JSON: json.RawMessage(`{ "datasource": { "uid": "1" }, "intervalMs": 1000, "maxDataPoints": 1000 }`),
|
JSON: json.RawMessage(`{ "datasource": { "uid": "1" }, "intervalMs": 1000, "maxDataPoints": 1000 }`),
|
||||||
|
@ -79,7 +79,7 @@ func (s *Service) detectPrometheusVariant(ctx context.Context, ds *datasources.D
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ds.Url+"/api/v1/status/buildinfo", nil)
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ds.URL+"/api/v1/status/buildinfo", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Error("Failed to create Prometheus build info request", "error", err)
|
s.log.Error("Failed to create Prometheus build info request", "error", err)
|
||||||
return "", err
|
return "", err
|
||||||
|
@ -41,40 +41,40 @@ func TestDetectPrometheusVariant(t *testing.T) {
|
|||||||
statsService,
|
statsService,
|
||||||
withDatasources(mockDatasourceService{datasources: []*datasources.DataSource{
|
withDatasources(mockDatasourceService{datasources: []*datasources.DataSource{
|
||||||
{
|
{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Version: 1,
|
Version: 1,
|
||||||
Name: "Vanilla",
|
Name: "Vanilla",
|
||||||
Type: "prometheus",
|
Type: "prometheus",
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: vanilla.URL,
|
URL: vanilla.URL,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Id: 2,
|
ID: 2,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Version: 1,
|
Version: 1,
|
||||||
Name: "Mimir",
|
Name: "Mimir",
|
||||||
Type: "prometheus",
|
Type: "prometheus",
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: mimir.URL,
|
URL: mimir.URL,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Id: 3,
|
ID: 3,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Version: 1,
|
Version: 1,
|
||||||
Name: "Another Mimir",
|
Name: "Another Mimir",
|
||||||
Type: "prometheus",
|
Type: "prometheus",
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: mimir.URL,
|
URL: mimir.URL,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Id: 4,
|
ID: 4,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Version: 1,
|
Version: 1,
|
||||||
Name: "Cortex",
|
Name: "Cortex",
|
||||||
Type: "prometheus",
|
Type: "prometheus",
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: cortex.URL,
|
URL: cortex.URL,
|
||||||
},
|
},
|
||||||
}}),
|
}}),
|
||||||
)
|
)
|
||||||
|
@ -29,10 +29,10 @@ func ModelToInstanceSettings(ds *datasources.DataSource, decryptFn func(ds *data
|
|||||||
|
|
||||||
return &backend.DataSourceInstanceSettings{
|
return &backend.DataSourceInstanceSettings{
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
URL: ds.Url,
|
URL: ds.URL,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
Database: ds.Database,
|
Database: ds.Database,
|
||||||
User: ds.User,
|
User: ds.User,
|
||||||
BasicAuthEnabled: ds.BasicAuth,
|
BasicAuthEnabled: ds.BasicAuth,
|
||||||
|
@ -58,7 +58,7 @@ func setupFilterBenchmark(b *testing.B, numDs, numPermissions int) (db.DB, []acc
|
|||||||
for i := 1; i <= numDs; i++ {
|
for i := 1; i <= numDs; i++ {
|
||||||
err := store.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := store.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
Name: fmt.Sprintf("ds:%d", i),
|
Name: fmt.Sprintf("ds:%d", i),
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
})
|
})
|
||||||
require.NoError(b, err)
|
require.NoError(b, err)
|
||||||
}
|
}
|
||||||
|
@ -172,7 +172,7 @@ func TestFilter_Datasources(t *testing.T) {
|
|||||||
// seed 10 data sources
|
// seed 10 data sources
|
||||||
for i := 1; i <= 10; i++ {
|
for i := 1; i <= 10; i++ {
|
||||||
dsStore := dsService.CreateStore(store, log.New("accesscontrol.test"))
|
dsStore := dsService.CreateStore(store, log.New("accesscontrol.test"))
|
||||||
err := dsStore.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{Name: fmt.Sprintf("ds:%d", i), Uid: fmt.Sprintf("uid%d", i)})
|
err := dsStore.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{Name: fmt.Sprintf("ds:%d", i), UID: fmt.Sprintf("uid%d", i)})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -82,15 +82,15 @@ func GenerateDatasourcePermissions(b *testing.B, db *sqlstore.SQLStore, ac *stor
|
|||||||
dataSources := make([]int64, 0)
|
dataSources := make([]int64, 0)
|
||||||
for i := 0; i < dsNum; i++ {
|
for i := 0; i < dsNum; i++ {
|
||||||
addDSCommand := &datasources.AddDataSourceCommand{
|
addDSCommand := &datasources.AddDataSourceCommand{
|
||||||
OrgId: 0,
|
OrgID: 0,
|
||||||
Name: fmt.Sprintf("ds_%d", i),
|
Name: fmt.Sprintf("ds_%d", i),
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
}
|
}
|
||||||
dsStore := datasourcesService.CreateStore(db, log.New("publicdashboards.test"))
|
dsStore := datasourcesService.CreateStore(db, log.New("publicdashboards.test"))
|
||||||
_ = dsStore.AddDataSource(context.Background(), addDSCommand)
|
_ = dsStore.AddDataSource(context.Background(), addDSCommand)
|
||||||
dataSources = append(dataSources, addDSCommand.Result.Id)
|
dataSources = append(dataSources, addDSCommand.Result.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
userIds, teamIds := generateTeamsAndUsers(b, db, usersNum)
|
userIds, teamIds := generateTeamsAndUsers(b, db, usersNum)
|
||||||
|
@ -50,7 +50,7 @@ func (e *AlertEngine) mapRulesToUsageStats(ctx context.Context, rules []*models.
|
|||||||
for _, a := range rules {
|
for _, a := range rules {
|
||||||
dss, err := e.parseAlertRuleModel(a.Settings)
|
dss, err := e.parseAlertRuleModel(a.Settings)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
e.log.Debug("could not parse settings for alert rule", "id", a.Id)
|
e.log.Debug("could not parse settings for alert rule", "id", a.ID)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,7 +63,7 @@ func (e *AlertEngine) mapRulesToUsageStats(ctx context.Context, rules []*models.
|
|||||||
// map of datsource types and frequency
|
// map of datsource types and frequency
|
||||||
result := map[string]int{}
|
result := map[string]int{}
|
||||||
for k, v := range typeCount {
|
for k, v := range typeCount {
|
||||||
query := &datasources.GetDataSourceQuery{Id: k}
|
query := &datasources.GetDataSourceQuery{ID: k}
|
||||||
err := e.datasourceService.GetDataSource(ctx, query)
|
err := e.datasourceService.GetDataSource(ctx, query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return map[string]int{}, nil
|
return map[string]int{}, nil
|
||||||
|
@ -19,10 +19,10 @@ func TestAlertingUsageStats(t *testing.T) {
|
|||||||
store := &AlertStoreMock{}
|
store := &AlertStoreMock{}
|
||||||
dsMock := &fd.FakeDataSourceService{
|
dsMock := &fd.FakeDataSourceService{
|
||||||
DataSources: []*datasources.DataSource{
|
DataSources: []*datasources.DataSource{
|
||||||
{Id: 1, Type: datasources.DS_INFLUXDB},
|
{ID: 1, Type: datasources.DS_INFLUXDB},
|
||||||
{Id: 2, Type: datasources.DS_GRAPHITE},
|
{ID: 2, Type: datasources.DS_GRAPHITE},
|
||||||
{Id: 3, Type: datasources.DS_PROMETHEUS},
|
{ID: 3, Type: datasources.DS_PROMETHEUS},
|
||||||
{Id: 4, Type: datasources.DS_PROMETHEUS},
|
{ID: 4, Type: datasources.DS_PROMETHEUS},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
ae := &AlertEngine{
|
ae := &AlertEngine{
|
||||||
@ -43,10 +43,10 @@ func TestAlertingUsageStats(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return []*models.Alert{
|
return []*models.Alert{
|
||||||
{Id: 1, Settings: createFake("testdata/settings/one_condition.json")},
|
{ID: 1, Settings: createFake("testdata/settings/one_condition.json")},
|
||||||
{Id: 2, Settings: createFake("testdata/settings/two_conditions.json")},
|
{ID: 2, Settings: createFake("testdata/settings/two_conditions.json")},
|
||||||
{Id: 2, Settings: createFake("testdata/settings/three_conditions.json")},
|
{ID: 2, Settings: createFake("testdata/settings/three_conditions.json")},
|
||||||
{Id: 3, Settings: createFake("testdata/settings/empty.json")},
|
{ID: 3, Settings: createFake("testdata/settings/empty.json")},
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -142,15 +142,15 @@ func calculateInterval(timeRange legacydata.DataTimeRange, model *simplejson.Jso
|
|||||||
func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange legacydata.DataTimeRange,
|
func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange legacydata.DataTimeRange,
|
||||||
requestHandler legacydata.RequestHandler) (legacydata.DataTimeSeriesSlice, error) {
|
requestHandler legacydata.RequestHandler) (legacydata.DataTimeSeriesSlice, error) {
|
||||||
getDsInfo := &datasources.GetDataSourceQuery{
|
getDsInfo := &datasources.GetDataSourceQuery{
|
||||||
Id: c.Query.DatasourceID,
|
ID: c.Query.DatasourceID,
|
||||||
OrgId: context.Rule.OrgID,
|
OrgID: context.Rule.OrgID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := context.GetDataSource(context.Ctx, getDsInfo); err != nil {
|
if err := context.GetDataSource(context.Ctx, getDsInfo); err != nil {
|
||||||
return nil, fmt.Errorf("could not find datasource: %w", err)
|
return nil, fmt.Errorf("could not find datasource: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := context.RequestValidator.Validate(getDsInfo.Result.Url, nil)
|
err := context.RequestValidator.Validate(getDsInfo.Result.URL, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("access denied: %w", err)
|
return nil, fmt.Errorf("access denied: %w", err)
|
||||||
}
|
}
|
||||||
@ -182,7 +182,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange l
|
|||||||
RefID: q.RefID,
|
RefID: q.RefID,
|
||||||
Model: q.Model,
|
Model: q.Model,
|
||||||
Datasource: simplejson.NewFromAny(map[string]interface{}{
|
Datasource: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"id": q.DataSource.Id,
|
"id": q.DataSource.ID,
|
||||||
"name": q.DataSource.Name,
|
"name": q.DataSource.Name,
|
||||||
}),
|
}),
|
||||||
MaxDataPoints: q.MaxDataPoints,
|
MaxDataPoints: q.MaxDataPoints,
|
||||||
|
@ -151,7 +151,7 @@ func applyScenario(t *testing.T, timeRange string, dataSourceJsonData *simplejso
|
|||||||
Store: store,
|
Store: store,
|
||||||
DatasourceService: &fd.FakeDataSourceService{
|
DatasourceService: &fd.FakeDataSourceService{
|
||||||
DataSources: []*datasources.DataSource{
|
DataSources: []*datasources.DataSource{
|
||||||
{Id: 1, Type: datasources.DS_GRAPHITE, JsonData: dataSourceJsonData},
|
{ID: 1, Type: datasources.DS_GRAPHITE, JsonData: dataSourceJsonData},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -48,7 +48,7 @@ func TestQueryCondition(t *testing.T) {
|
|||||||
Store: store,
|
Store: store,
|
||||||
DatasourceService: &fd.FakeDataSourceService{
|
DatasourceService: &fd.FakeDataSourceService{
|
||||||
DataSources: []*datasources.DataSource{
|
DataSources: []*datasources.DataSource{
|
||||||
{Id: 1, Type: datasources.DS_GRAPHITE},
|
{ID: 1, Type: datasources.DS_GRAPHITE},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -129,7 +129,7 @@ func TestEngineProcessJob(t *testing.T) {
|
|||||||
|
|
||||||
store := &AlertStoreMock{}
|
store := &AlertStoreMock{}
|
||||||
dsMock := &fd.FakeDataSourceService{
|
dsMock := &fd.FakeDataSourceService{
|
||||||
DataSources: []*datasources.DataSource{{Id: 1, Type: datasources.DS_PROMETHEUS}},
|
DataSources: []*datasources.DataSource{{ID: 1, Type: datasources.DS_PROMETHEUS}},
|
||||||
}
|
}
|
||||||
engine := ProvideAlertEngine(nil, nil, nil, usMock, encService, nil, tracer, store, setting.NewCfg(), nil, nil, localcache.New(time.Minute, time.Minute), dsMock, annotationstest.NewFakeAnnotationsRepo())
|
engine := ProvideAlertEngine(nil, nil, nil, usMock, encService, nil, tracer, store, setting.NewCfg(), nil, nil, localcache.New(time.Minute, time.Minute), dsMock, annotationstest.NewFakeAnnotationsRepo())
|
||||||
setting.AlertingEvaluationTimeout = 30 * time.Second
|
setting.AlertingEvaluationTimeout = 30 * time.Second
|
||||||
|
@ -52,14 +52,14 @@ func (e *DashAlertExtractorService) lookupQueryDataSource(ctx context.Context, p
|
|||||||
}
|
}
|
||||||
|
|
||||||
if dsName == "" && dsUid == "" {
|
if dsName == "" && dsUid == "" {
|
||||||
query := &datasources.GetDefaultDataSourceQuery{OrgId: orgID}
|
query := &datasources.GetDefaultDataSourceQuery{OrgID: orgID}
|
||||||
if err := e.datasourceService.GetDefaultDataSource(ctx, query); err != nil {
|
if err := e.datasourceService.GetDefaultDataSource(ctx, query); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return query.Result, nil
|
return query.Result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
query := &datasources.GetDataSourceQuery{Name: dsName, Uid: dsUid, OrgId: orgID}
|
query := &datasources.GetDataSourceQuery{Name: dsName, UID: dsUid, OrgID: orgID}
|
||||||
if err := e.datasourceService.GetDataSource(ctx, query); err != nil {
|
if err := e.datasourceService.GetDataSource(ctx, query); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -175,10 +175,10 @@ func (e *DashAlertExtractorService) getAlertFromPanels(ctx context.Context, json
|
|||||||
}
|
}
|
||||||
|
|
||||||
alert := &models.Alert{
|
alert := &models.Alert{
|
||||||
DashboardId: dashAlertInfo.Dash.ID,
|
DashboardID: dashAlertInfo.Dash.ID,
|
||||||
OrgId: dashAlertInfo.OrgID,
|
OrgID: dashAlertInfo.OrgID,
|
||||||
PanelId: panelID,
|
PanelID: panelID,
|
||||||
Id: jsonAlert.Get("id").MustInt64(),
|
ID: jsonAlert.Get("id").MustInt64(),
|
||||||
Name: jsonAlert.Get("name").MustString(),
|
Name: jsonAlert.Get("name").MustString(),
|
||||||
Handler: jsonAlert.Get("handler").MustInt64(),
|
Handler: jsonAlert.Get("handler").MustInt64(),
|
||||||
Message: jsonAlert.Get("message").MustString(),
|
Message: jsonAlert.Get("message").MustString(),
|
||||||
@ -196,9 +196,9 @@ func (e *DashAlertExtractorService) getAlertFromPanels(ctx context.Context, json
|
|||||||
if panelQuery == nil {
|
if panelQuery == nil {
|
||||||
var reason string
|
var reason string
|
||||||
if UAEnabled(ctx) {
|
if UAEnabled(ctx) {
|
||||||
reason = fmt.Sprintf("Alert on PanelId: %v refers to query(%s) that cannot be found. Legacy alerting queries are not able to be removed at this time in order to preserve the ability to rollback to previous versions of Grafana", alert.PanelId, queryRefID)
|
reason = fmt.Sprintf("Alert on PanelId: %v refers to query(%s) that cannot be found. Legacy alerting queries are not able to be removed at this time in order to preserve the ability to rollback to previous versions of Grafana", alert.PanelID, queryRefID)
|
||||||
} else {
|
} else {
|
||||||
reason = fmt.Sprintf("Alert on PanelId: %v refers to query(%s) that cannot be found", alert.PanelId, queryRefID)
|
reason = fmt.Sprintf("Alert on PanelId: %v refers to query(%s) that cannot be found", alert.PanelID, queryRefID)
|
||||||
}
|
}
|
||||||
return nil, ValidationError{Reason: reason}
|
return nil, ValidationError{Reason: reason}
|
||||||
}
|
}
|
||||||
@ -221,7 +221,7 @@ func (e *DashAlertExtractorService) getAlertFromPanels(ctx context.Context, json
|
|||||||
return nil, datasources.ErrDataSourceAccessDenied
|
return nil, datasources.ErrDataSourceAccessDenied
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonQuery.SetPath([]string{"datasourceId"}, datasource.Id)
|
jsonQuery.SetPath([]string{"datasourceId"}, datasource.ID)
|
||||||
|
|
||||||
if interval, err := panel.Get("interval").String(); err == nil {
|
if interval, err := panel.Get("interval").String(); err == nil {
|
||||||
panelQuery.Set("interval", interval)
|
panelQuery.Set("interval", interval)
|
||||||
@ -250,7 +250,7 @@ func (e *DashAlertExtractorService) getAlertFromPanels(ctx context.Context, json
|
|||||||
|
|
||||||
func validateAlertRule(alert *models.Alert) error {
|
func validateAlertRule(alert *models.Alert) error {
|
||||||
if !alert.ValidDashboardPanel() {
|
if !alert.ValidDashboardPanel() {
|
||||||
return ValidationError{Reason: fmt.Sprintf("Panel id is not correct, alertName=%v, panelId=%v", alert.Name, alert.PanelId)}
|
return ValidationError{Reason: fmt.Sprintf("Panel id is not correct, alertName=%v, panelId=%v", alert.Name, alert.PanelID)}
|
||||||
}
|
}
|
||||||
if !alert.ValidTags() {
|
if !alert.ValidTags() {
|
||||||
return ValidationError{Reason: "Invalid tags, must be less than 100 characters"}
|
return ValidationError{Reason: "Invalid tags, must be less than 100 characters"}
|
||||||
@ -301,7 +301,7 @@ func (e *DashAlertExtractorService) extractAlerts(ctx context.Context, validateF
|
|||||||
// in the first validation pass.
|
// in the first validation pass.
|
||||||
func (e *DashAlertExtractorService) ValidateAlerts(ctx context.Context, dashAlertInfo DashAlertInfo) error {
|
func (e *DashAlertExtractorService) ValidateAlerts(ctx context.Context, dashAlertInfo DashAlertInfo) error {
|
||||||
_, err := e.extractAlerts(ctx, func(alert *models.Alert) error {
|
_, err := e.extractAlerts(ctx, func(alert *models.Alert) error {
|
||||||
if alert.OrgId == 0 || alert.PanelId == 0 {
|
if alert.OrgID == 0 || alert.PanelID == 0 {
|
||||||
return errors.New("missing OrgId, PanelId or both")
|
return errors.New("missing OrgId, PanelId or both")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
@ -27,8 +27,8 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// mock data
|
// mock data
|
||||||
defaultDs := &datasources.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true, Uid: "def-uid"}
|
defaultDs := &datasources.DataSource{ID: 12, OrgID: 1, Name: "I am default", IsDefault: true, UID: "def-uid"}
|
||||||
graphite2Ds := &datasources.DataSource{Id: 15, OrgId: 1, Name: "graphite2", Uid: "graphite2-uid"}
|
graphite2Ds := &datasources.DataSource{ID: 15, OrgID: 1, Name: "graphite2", UID: "graphite2-uid"}
|
||||||
|
|
||||||
json, err := os.ReadFile("./testdata/graphite-alert.json")
|
json, err := os.ReadFile("./testdata/graphite-alert.json")
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
@ -36,7 +36,7 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
dsPermissions := permissions.NewMockDatasourcePermissionService()
|
dsPermissions := permissions.NewMockDatasourcePermissionService()
|
||||||
dsPermissions.DsResult = []*datasources.DataSource{
|
dsPermissions.DsResult = []*datasources.DataSource{
|
||||||
{
|
{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,7 +74,7 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
dashJSON, err := simplejson.NewJson(json)
|
dashJSON, err := simplejson.NewJson(json)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
dsService.ExpectedDatasource = &datasources.DataSource{Id: 12}
|
dsService.ExpectedDatasource = &datasources.DataSource{ID: 12}
|
||||||
alerts, err := extractor.GetAlerts(context.Background(), DashAlertInfo{
|
alerts, err := extractor.GetAlerts(context.Background(), DashAlertInfo{
|
||||||
User: nil,
|
User: nil,
|
||||||
Dash: dashboards.NewDashboardFromJson(dashJSON),
|
Dash: dashboards.NewDashboardFromJson(dashJSON),
|
||||||
@ -86,7 +86,7 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
require.Len(t, alerts, 2)
|
require.Len(t, alerts, 2)
|
||||||
|
|
||||||
for _, v := range alerts {
|
for _, v := range alerts {
|
||||||
require.EqualValues(t, v.DashboardId, 57)
|
require.EqualValues(t, v.DashboardID, 57)
|
||||||
require.NotEmpty(t, v.Name)
|
require.NotEmpty(t, v.Name)
|
||||||
require.NotEmpty(t, v.Message)
|
require.NotEmpty(t, v.Message)
|
||||||
|
|
||||||
@ -100,8 +100,8 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
require.EqualValues(t, alerts[0].Frequency, 60)
|
require.EqualValues(t, alerts[0].Frequency, 60)
|
||||||
require.EqualValues(t, alerts[1].Frequency, 60)
|
require.EqualValues(t, alerts[1].Frequency, 60)
|
||||||
|
|
||||||
require.EqualValues(t, alerts[0].PanelId, 3)
|
require.EqualValues(t, alerts[0].PanelID, 3)
|
||||||
require.EqualValues(t, alerts[1].PanelId, 4)
|
require.EqualValues(t, alerts[1].PanelID, 4)
|
||||||
|
|
||||||
require.Equal(t, alerts[0].For, time.Minute*2)
|
require.Equal(t, alerts[0].For, time.Minute*2)
|
||||||
require.Equal(t, alerts[1].For, time.Duration(0))
|
require.Equal(t, alerts[1].For, time.Duration(0))
|
||||||
@ -173,7 +173,7 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
dashJSON, err := simplejson.NewJson(panelWithoutSpecifiedDatasource)
|
dashJSON, err := simplejson.NewJson(panelWithoutSpecifiedDatasource)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
dsService.ExpectedDatasource = &datasources.DataSource{Id: 12}
|
dsService.ExpectedDatasource = &datasources.DataSource{ID: 12}
|
||||||
alerts, err := extractor.GetAlerts(context.Background(), DashAlertInfo{
|
alerts, err := extractor.GetAlerts(context.Background(), DashAlertInfo{
|
||||||
User: nil,
|
User: nil,
|
||||||
Dash: dashboards.NewDashboardFromJson(dashJSON),
|
Dash: dashboards.NewDashboardFromJson(dashJSON),
|
||||||
@ -230,7 +230,7 @@ func TestAlertRuleExtraction(t *testing.T) {
|
|||||||
require.Len(t, alerts, 1)
|
require.Len(t, alerts, 1)
|
||||||
|
|
||||||
for _, alert := range alerts {
|
for _, alert := range alerts {
|
||||||
require.EqualValues(t, alert.DashboardId, 4)
|
require.EqualValues(t, alert.DashboardID, 4)
|
||||||
|
|
||||||
conditions := alert.Settings.Get("conditions").MustArray()
|
conditions := alert.Settings.Get("conditions").MustArray()
|
||||||
cond := simplejson.NewFromAny(conditions[0])
|
cond := simplejson.NewFromAny(conditions[0])
|
||||||
@ -310,7 +310,7 @@ func TestFilterPermissionsErrors(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// mock data
|
// mock data
|
||||||
defaultDs := &datasources.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true, Uid: "def-uid"}
|
defaultDs := &datasources.DataSource{ID: 12, OrgID: 1, Name: "I am default", IsDefault: true, UID: "def-uid"}
|
||||||
|
|
||||||
json, err := os.ReadFile("./testdata/graphite-alert.json")
|
json, err := os.ReadFile("./testdata/graphite-alert.json")
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
@ -67,11 +67,11 @@ func (s ExecutionErrorOption) ToAlertState() AlertStateType {
|
|||||||
|
|
||||||
// swagger:model LegacyAlert
|
// swagger:model LegacyAlert
|
||||||
type Alert struct {
|
type Alert struct {
|
||||||
Id int64
|
ID int64 `xorm:"pk autoincr 'id'"`
|
||||||
Version int64
|
Version int64
|
||||||
OrgId int64
|
OrgID int64 `xorm:"org_id"`
|
||||||
DashboardId int64
|
DashboardID int64 `xorm:"dashboard_id"`
|
||||||
PanelId int64
|
PanelID int64 `xorm:"panel_id"`
|
||||||
Name string
|
Name string
|
||||||
Message string
|
Message string
|
||||||
Severity string // Unused
|
Severity string // Unused
|
||||||
@ -93,7 +93,7 @@ type Alert struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *Alert) ValidDashboardPanel() bool {
|
func (a *Alert) ValidDashboardPanel() bool {
|
||||||
return a.OrgId != 0 && a.DashboardId != 0 && a.PanelId != 0
|
return a.OrgID != 0 && a.DashboardID != 0 && a.PanelID != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Alert) ValidTags() bool {
|
func (a *Alert) ValidTags() bool {
|
||||||
@ -141,8 +141,8 @@ func (a *Alert) GetTagsFromSettings() []*tag.Tag {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type PauseAlertCommand struct {
|
type PauseAlertCommand struct {
|
||||||
OrgId int64
|
OrgID int64 `xorm:"org_id"`
|
||||||
AlertIds []int64
|
AlertIDs []int64 `xorm:"alert_ids"`
|
||||||
ResultCount int64
|
ResultCount int64
|
||||||
Paused bool
|
Paused bool
|
||||||
}
|
}
|
||||||
@ -153,8 +153,8 @@ type PauseAllAlertCommand struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SetAlertStateCommand struct {
|
type SetAlertStateCommand struct {
|
||||||
AlertId int64
|
AlertID int64 `xorm:"alert_id"`
|
||||||
OrgId int64
|
OrgID int64 `xorm:"org_id"`
|
||||||
State AlertStateType
|
State AlertStateType
|
||||||
Error string
|
Error string
|
||||||
EvalData *simplejson.Json
|
EvalData *simplejson.Json
|
||||||
@ -162,10 +162,10 @@ type SetAlertStateCommand struct {
|
|||||||
|
|
||||||
// Queries
|
// Queries
|
||||||
type GetAlertsQuery struct {
|
type GetAlertsQuery struct {
|
||||||
OrgId int64
|
OrgID int64 `xorm:"org_id"`
|
||||||
State []string
|
State []string
|
||||||
DashboardIDs []int64
|
DashboardIDs []int64 `xorm:"dashboard_ids"`
|
||||||
PanelId int64
|
PanelID int64 `xorm:"panel_id"`
|
||||||
Limit int64
|
Limit int64
|
||||||
Query string
|
Query string
|
||||||
User *user.SignedInUser
|
User *user.SignedInUser
|
||||||
@ -174,33 +174,33 @@ type GetAlertsQuery struct {
|
|||||||
type GetAllAlertsQuery struct{}
|
type GetAllAlertsQuery struct{}
|
||||||
|
|
||||||
type GetAlertByIdQuery struct {
|
type GetAlertByIdQuery struct {
|
||||||
Id int64
|
ID int64 `xorm:"id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetAlertStatesForDashboardQuery struct {
|
type GetAlertStatesForDashboardQuery struct {
|
||||||
OrgId int64
|
OrgID int64 `xorm:"org_id"`
|
||||||
DashboardId int64
|
DashboardID int64 `xorm:"dashboard_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AlertListItemDTO struct {
|
type AlertListItemDTO struct {
|
||||||
Id int64 `json:"id"`
|
ID int64 `json:"id" xorm:"id"`
|
||||||
DashboardId int64 `json:"dashboardId"`
|
DashboardID int64 `json:"dashboardId" xorm:"dashboard_id"`
|
||||||
DashboardUid string `json:"dashboardUid"`
|
DashboardUID string `json:"dashboardUid" xorm:"dashboard_uid"`
|
||||||
DashboardSlug string `json:"dashboardSlug"`
|
DashboardSlug string `json:"dashboardSlug"`
|
||||||
PanelId int64 `json:"panelId"`
|
PanelID int64 `json:"panelId" xorm:"panel_id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
State AlertStateType `json:"state"`
|
State AlertStateType `json:"state"`
|
||||||
NewStateDate time.Time `json:"newStateDate"`
|
NewStateDate time.Time `json:"newStateDate"`
|
||||||
EvalDate time.Time `json:"evalDate"`
|
EvalDate time.Time `json:"evalDate"`
|
||||||
EvalData *simplejson.Json `json:"evalData"`
|
EvalData *simplejson.Json `json:"evalData"`
|
||||||
ExecutionError string `json:"executionError"`
|
ExecutionError string `json:"executionError"`
|
||||||
Url string `json:"url"`
|
URL string `json:"url" xorm:"url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AlertStateInfoDTO struct {
|
type AlertStateInfoDTO struct {
|
||||||
Id int64 `json:"id"`
|
ID int64 `json:"id" xorm:"id"`
|
||||||
DashboardId int64 `json:"dashboardId"`
|
DashboardID int64 `json:"dashboardId" xorm:"dashboard_id"`
|
||||||
PanelId int64 `json:"panelId"`
|
PanelID int64 `json:"panelId" xorm:"panel_id"`
|
||||||
State AlertStateType `json:"state"`
|
State AlertStateType `json:"state"`
|
||||||
NewStateDate time.Time `json:"newStateDate"`
|
NewStateDate time.Time `json:"newStateDate"`
|
||||||
}
|
}
|
||||||
|
@ -40,7 +40,7 @@ func (arr *defaultRuleReader) fetch(ctx context.Context) []*Rule {
|
|||||||
res := make([]*Rule, 0)
|
res := make([]*Rule, 0)
|
||||||
for _, ruleDef := range alerts {
|
for _, ruleDef := range alerts {
|
||||||
if model, err := NewRuleFromDBAlert(ctx, arr.sqlStore, ruleDef, false); err != nil {
|
if model, err := NewRuleFromDBAlert(ctx, arr.sqlStore, ruleDef, false); err != nil {
|
||||||
arr.log.Error("Could not build alert model for rule", "ruleId", ruleDef.Id, "error", err)
|
arr.log.Error("Could not build alert model for rule", "ruleId", ruleDef.ID, "error", err)
|
||||||
} else {
|
} else {
|
||||||
res = append(res, model)
|
res = append(res, model)
|
||||||
}
|
}
|
||||||
|
@ -52,8 +52,8 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error {
|
|||||||
handler.log.Info("New state change", "ruleId", evalContext.Rule.ID, "newState", evalContext.Rule.State, "prev state", evalContext.PrevAlertState)
|
handler.log.Info("New state change", "ruleId", evalContext.Rule.ID, "newState", evalContext.Rule.State, "prev state", evalContext.PrevAlertState)
|
||||||
|
|
||||||
cmd := &models.SetAlertStateCommand{
|
cmd := &models.SetAlertStateCommand{
|
||||||
AlertId: evalContext.Rule.ID,
|
AlertID: evalContext.Rule.ID,
|
||||||
OrgId: evalContext.Rule.OrgID,
|
OrgID: evalContext.Rule.OrgID,
|
||||||
State: evalContext.Rule.State,
|
State: evalContext.Rule.State,
|
||||||
Error: executionError,
|
Error: executionError,
|
||||||
EvalData: annotationData,
|
EvalData: annotationData,
|
||||||
|
@ -147,10 +147,10 @@ func getForValue(rawFor string) (time.Duration, error) {
|
|||||||
// alert to an in-memory version.
|
// alert to an in-memory version.
|
||||||
func NewRuleFromDBAlert(ctx context.Context, store AlertStore, ruleDef *models.Alert, logTranslationFailures bool) (*Rule, error) {
|
func NewRuleFromDBAlert(ctx context.Context, store AlertStore, ruleDef *models.Alert, logTranslationFailures bool) (*Rule, error) {
|
||||||
model := &Rule{}
|
model := &Rule{}
|
||||||
model.ID = ruleDef.Id
|
model.ID = ruleDef.ID
|
||||||
model.OrgID = ruleDef.OrgId
|
model.OrgID = ruleDef.OrgID
|
||||||
model.DashboardID = ruleDef.DashboardId
|
model.DashboardID = ruleDef.DashboardID
|
||||||
model.PanelID = ruleDef.PanelId
|
model.PanelID = ruleDef.PanelID
|
||||||
model.Name = ruleDef.Name
|
model.Name = ruleDef.Name
|
||||||
model.Message = ruleDef.Message
|
model.Message = ruleDef.Message
|
||||||
model.State = ruleDef.State
|
model.State = ruleDef.State
|
||||||
@ -170,7 +170,7 @@ func NewRuleFromDBAlert(ctx context.Context, store AlertStore, ruleDef *models.A
|
|||||||
for _, v := range ruleDef.Settings.Get("notifications").MustArray() {
|
for _, v := range ruleDef.Settings.Get("notifications").MustArray() {
|
||||||
jsonModel := simplejson.NewFromAny(v)
|
jsonModel := simplejson.NewFromAny(v)
|
||||||
if id, err := jsonModel.Get("id").Int64(); err == nil {
|
if id, err := jsonModel.Get("id").Int64(); err == nil {
|
||||||
uid, err := translateNotificationIDToUID(ctx, store, id, ruleDef.OrgId)
|
uid, err := translateNotificationIDToUID(ctx, store, id, ruleDef.OrgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !errors.Is(err, models.ErrAlertNotificationFailedTranslateUniqueID) {
|
if !errors.Is(err, models.ErrAlertNotificationFailedTranslateUniqueID) {
|
||||||
logger.Error("Failed to translate notification id to uid", "error", err.Error(), "dashboardId", model.DashboardID, "alert", model.Name, "panelId", model.PanelID, "notificationId", id)
|
logger.Error("Failed to translate notification id to uid", "error", err.Error(), "dashboardId", model.DashboardID, "alert", model.Name, "panelId", model.PanelID, "notificationId", id)
|
||||||
|
@ -124,10 +124,10 @@ func TestAlertRuleModel(t *testing.T) {
|
|||||||
require.Nil(t, jsonErr)
|
require.Nil(t, jsonErr)
|
||||||
|
|
||||||
alert := &models.Alert{
|
alert := &models.Alert{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
DashboardId: 1,
|
DashboardID: 1,
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
|
|
||||||
Settings: alertJSON,
|
Settings: alertJSON,
|
||||||
}
|
}
|
||||||
@ -163,10 +163,10 @@ func TestAlertRuleModel(t *testing.T) {
|
|||||||
require.Nil(t, jsonErr)
|
require.Nil(t, jsonErr)
|
||||||
|
|
||||||
alert := &models.Alert{
|
alert := &models.Alert{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
DashboardId: 1,
|
DashboardID: 1,
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
|
|
||||||
Settings: alertJSON,
|
Settings: alertJSON,
|
||||||
}
|
}
|
||||||
@ -193,10 +193,10 @@ func TestAlertRuleModel(t *testing.T) {
|
|||||||
require.Nil(t, jsonErr)
|
require.Nil(t, jsonErr)
|
||||||
|
|
||||||
alert := &models.Alert{
|
alert := &models.Alert{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
DashboardId: 1,
|
DashboardID: 1,
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
Frequency: 0,
|
Frequency: 0,
|
||||||
|
|
||||||
Settings: alertJSON,
|
Settings: alertJSON,
|
||||||
@ -231,10 +231,10 @@ func TestAlertRuleModel(t *testing.T) {
|
|||||||
require.Nil(t, jsonErr)
|
require.Nil(t, jsonErr)
|
||||||
|
|
||||||
alert := &models.Alert{
|
alert := &models.Alert{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
DashboardId: 1,
|
DashboardID: 1,
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
Frequency: 0,
|
Frequency: 0,
|
||||||
|
|
||||||
Settings: alertJSON,
|
Settings: alertJSON,
|
||||||
|
@ -56,7 +56,7 @@ func ProvideAlertStore(
|
|||||||
func (ss *sqlStore) GetAlertById(ctx context.Context, query *alertmodels.GetAlertByIdQuery) (res *alertmodels.Alert, err error) {
|
func (ss *sqlStore) GetAlertById(ctx context.Context, query *alertmodels.GetAlertByIdQuery) (res *alertmodels.Alert, err error) {
|
||||||
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
|
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
|
||||||
alert := alertmodels.Alert{}
|
alert := alertmodels.Alert{}
|
||||||
has, err := sess.ID(query.Id).Get(&alert)
|
has, err := sess.ID(query.ID).Get(&alert)
|
||||||
if !has {
|
if !has {
|
||||||
return fmt.Errorf("could not find alert")
|
return fmt.Errorf("could not find alert")
|
||||||
}
|
}
|
||||||
@ -125,7 +125,7 @@ func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *alertmodels.Ge
|
|||||||
FROM alert
|
FROM alert
|
||||||
INNER JOIN dashboard on dashboard.id = alert.dashboard_id `)
|
INNER JOIN dashboard on dashboard.id = alert.dashboard_id `)
|
||||||
|
|
||||||
builder.Write(`WHERE alert.org_id = ?`, query.OrgId)
|
builder.Write(`WHERE alert.org_id = ?`, query.OrgID)
|
||||||
|
|
||||||
if len(strings.TrimSpace(query.Query)) > 0 {
|
if len(strings.TrimSpace(query.Query)) > 0 {
|
||||||
builder.Write(" AND alert.name "+ss.db.GetDialect().LikeStr()+" ?", "%"+query.Query+"%")
|
builder.Write(" AND alert.name "+ss.db.GetDialect().LikeStr()+" ?", "%"+query.Query+"%")
|
||||||
@ -139,8 +139,8 @@ func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *alertmodels.Ge
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if query.PanelId != 0 {
|
if query.PanelID != 0 {
|
||||||
builder.Write(` AND alert.panel_id = ?`, query.PanelId)
|
builder.Write(` AND alert.panel_id = ?`, query.PanelID)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(query.State) > 0 && query.State[0] != "all" {
|
if len(query.State) > 0 && query.State[0] != "all" {
|
||||||
@ -212,9 +212,9 @@ func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*alertmod
|
|||||||
var alertToUpdate *alertmodels.Alert
|
var alertToUpdate *alertmodels.Alert
|
||||||
|
|
||||||
for _, k := range existingAlerts {
|
for _, k := range existingAlerts {
|
||||||
if alert.PanelId == k.PanelId {
|
if alert.PanelID == k.PanelID {
|
||||||
update = true
|
update = true
|
||||||
alert.Id = k.Id
|
alert.ID = k.ID
|
||||||
alertToUpdate = k
|
alertToUpdate = k
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -226,12 +226,12 @@ func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*alertmod
|
|||||||
alert.State = alertToUpdate.State
|
alert.State = alertToUpdate.State
|
||||||
sess.MustCols("message", "for")
|
sess.MustCols("message", "for")
|
||||||
|
|
||||||
_, err := sess.ID(alert.Id).Update(alert)
|
_, err := sess.ID(alert.ID).Update(alert)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug("Alert updated", "name", alert.Name, "id", alert.Id)
|
log.Debug("Alert updated", "name", alert.Name, "id", alert.ID)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
alert.Updated = timeNow()
|
alert.Updated = timeNow()
|
||||||
@ -244,10 +244,10 @@ func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*alertmod
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug("Alert inserted", "name", alert.Name, "id", alert.Id)
|
log.Debug("Alert inserted", "name", alert.Name, "id", alert.ID)
|
||||||
}
|
}
|
||||||
tags := alert.GetTagsFromSettings()
|
tags := alert.GetTagsFromSettings()
|
||||||
if _, err := sess.Exec("DELETE FROM alert_rule_tag WHERE alert_id = ?", alert.Id); err != nil {
|
if _, err := sess.Exec("DELETE FROM alert_rule_tag WHERE alert_id = ?", alert.ID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if tags != nil {
|
if tags != nil {
|
||||||
@ -256,7 +256,7 @@ func (ss *sqlStore) UpdateAlerts(ctx context.Context, existingAlerts []*alertmod
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, tag := range tags {
|
for _, tag := range tags {
|
||||||
if _, err := sess.Exec("INSERT INTO alert_rule_tag (alert_id, tag_id) VALUES(?,?)", alert.Id, tag.Id); err != nil {
|
if _, err := sess.Exec("INSERT INTO alert_rule_tag (alert_id, tag_id) VALUES(?,?)", alert.ID, tag.Id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -271,14 +271,14 @@ func deleteMissingAlerts(alerts []*alertmodels.Alert, existingAlerts []*alertmod
|
|||||||
missing := true
|
missing := true
|
||||||
|
|
||||||
for _, k := range existingAlerts {
|
for _, k := range existingAlerts {
|
||||||
if missingAlert.PanelId == k.PanelId {
|
if missingAlert.PanelID == k.PanelID {
|
||||||
missing = false
|
missing = false
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if missing {
|
if missing {
|
||||||
if err := deleteAlertByIdInternal(missingAlert.Id, "Removed from dashboard", sess, log); err != nil {
|
if err := deleteAlertByIdInternal(missingAlert.ID, "Removed from dashboard", sess, log); err != nil {
|
||||||
// No use trying to delete more, since we're in a transaction and it will be
|
// No use trying to delete more, since we're in a transaction and it will be
|
||||||
// rolled back on error.
|
// rolled back on error.
|
||||||
return err
|
return err
|
||||||
@ -304,7 +304,7 @@ func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *alertmodels.SetAlert
|
|||||||
err = ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
err = ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
||||||
alert := alertmodels.Alert{}
|
alert := alertmodels.Alert{}
|
||||||
|
|
||||||
if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil {
|
if has, err := sess.ID(cmd.AlertID).Get(&alert); err != nil {
|
||||||
return err
|
return err
|
||||||
} else if !has {
|
} else if !has {
|
||||||
return fmt.Errorf("could not find alert")
|
return fmt.Errorf("could not find alert")
|
||||||
@ -329,7 +329,7 @@ func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *alertmodels.SetAlert
|
|||||||
alert.ExecutionError = cmd.Error
|
alert.ExecutionError = cmd.Error
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := sess.ID(alert.Id).Update(&alert)
|
_, err := sess.ID(alert.ID).Update(&alert)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -342,7 +342,7 @@ func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *alertmodels.SetAlert
|
|||||||
|
|
||||||
func (ss *sqlStore) PauseAlert(ctx context.Context, cmd *alertmodels.PauseAlertCommand) error {
|
func (ss *sqlStore) PauseAlert(ctx context.Context, cmd *alertmodels.PauseAlertCommand) error {
|
||||||
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
||||||
if len(cmd.AlertIds) == 0 {
|
if len(cmd.AlertIDs) == 0 {
|
||||||
return fmt.Errorf("command contains no alertids")
|
return fmt.Errorf("command contains no alertids")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -358,8 +358,8 @@ func (ss *sqlStore) PauseAlert(ctx context.Context, cmd *alertmodels.PauseAlertC
|
|||||||
params = append(params, timeNow().UTC())
|
params = append(params, timeNow().UTC())
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer.WriteString(` WHERE id IN (?` + strings.Repeat(",?", len(cmd.AlertIds)-1) + `)`)
|
buffer.WriteString(` WHERE id IN (?` + strings.Repeat(",?", len(cmd.AlertIDs)-1) + `)`)
|
||||||
for _, v := range cmd.AlertIds {
|
for _, v := range cmd.AlertIDs {
|
||||||
params = append(params, v)
|
params = append(params, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -404,7 +404,7 @@ func (ss *sqlStore) GetAlertStatesForDashboard(ctx context.Context, query *alert
|
|||||||
WHERE org_id = ? AND dashboard_id = ?`
|
WHERE org_id = ? AND dashboard_id = ?`
|
||||||
|
|
||||||
res = make([]*alertmodels.AlertStateInfoDTO, 0)
|
res = make([]*alertmodels.AlertStateInfoDTO, 0)
|
||||||
return sess.SQL(rawSQL, query.OrgId, query.DashboardId).Find(&res)
|
return sess.SQL(rawSQL, query.OrgID, query.DashboardID).Find(&res)
|
||||||
})
|
})
|
||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
|
@ -62,9 +62,9 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
items = []*models.Alert{
|
items = []*models.Alert{
|
||||||
{
|
{
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
DashboardId: testDash.ID,
|
DashboardID: testDash.ID,
|
||||||
OrgId: testDash.OrgID,
|
OrgID: testDash.OrgID,
|
||||||
Name: "Alerting title",
|
Name: "Alerting title",
|
||||||
Message: "Alerting message",
|
Message: "Alerting message",
|
||||||
Settings: simplejson.New(),
|
Settings: simplejson.New(),
|
||||||
@ -81,7 +81,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
setup(t)
|
setup(t)
|
||||||
|
|
||||||
// Get alert so we can use its ID in tests
|
// Get alert so we can use its ID in tests
|
||||||
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelID: 1, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
result, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
|
result, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
|
|
||||||
@ -89,7 +89,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("new state ok", func(t *testing.T) {
|
t.Run("new state ok", func(t *testing.T) {
|
||||||
cmd := &models.SetAlertStateCommand{
|
cmd := &models.SetAlertStateCommand{
|
||||||
AlertId: insertedAlert.Id,
|
AlertID: insertedAlert.ID,
|
||||||
State: models.AlertStateOK,
|
State: models.AlertStateOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,7 +97,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
})
|
})
|
||||||
|
|
||||||
alert, _ := getAlertById(t, insertedAlert.Id, store)
|
alert, _ := getAlertById(t, insertedAlert.ID, store)
|
||||||
stateDateBeforePause := alert.NewStateDate
|
stateDateBeforePause := alert.NewStateDate
|
||||||
|
|
||||||
t.Run("can pause all alerts", func(t *testing.T) {
|
t.Run("can pause all alerts", func(t *testing.T) {
|
||||||
@ -106,7 +106,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("cannot updated paused alert", func(t *testing.T) {
|
t.Run("cannot updated paused alert", func(t *testing.T) {
|
||||||
cmd := &models.SetAlertStateCommand{
|
cmd := &models.SetAlertStateCommand{
|
||||||
AlertId: insertedAlert.Id,
|
AlertID: insertedAlert.ID,
|
||||||
State: models.AlertStateOK,
|
State: models.AlertStateOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,13 +115,13 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("alert is paused", func(t *testing.T) {
|
t.Run("alert is paused", func(t *testing.T) {
|
||||||
alert, _ = getAlertById(t, insertedAlert.Id, store)
|
alert, _ = getAlertById(t, insertedAlert.ID, store)
|
||||||
currentState := alert.State
|
currentState := alert.State
|
||||||
require.Equal(t, models.AlertStatePaused, currentState)
|
require.Equal(t, models.AlertStatePaused, currentState)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("pausing alerts should update their NewStateDate", func(t *testing.T) {
|
t.Run("pausing alerts should update their NewStateDate", func(t *testing.T) {
|
||||||
alert, _ = getAlertById(t, insertedAlert.Id, store)
|
alert, _ = getAlertById(t, insertedAlert.ID, store)
|
||||||
stateDateAfterPause := alert.NewStateDate
|
stateDateAfterPause := alert.NewStateDate
|
||||||
require.True(t, stateDateBeforePause.Before(stateDateAfterPause))
|
require.True(t, stateDateBeforePause.Before(stateDateAfterPause))
|
||||||
})
|
})
|
||||||
@ -129,7 +129,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
t.Run("unpausing alerts should update their NewStateDate again", func(t *testing.T) {
|
t.Run("unpausing alerts should update their NewStateDate again", func(t *testing.T) {
|
||||||
err := store.pauseAllAlerts(t, false)
|
err := store.pauseAllAlerts(t, false)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
alert, _ = getAlertById(t, insertedAlert.Id, store)
|
alert, _ = getAlertById(t, insertedAlert.ID, store)
|
||||||
stateDateAfterUnpause := alert.NewStateDate
|
stateDateAfterUnpause := alert.NewStateDate
|
||||||
require.True(t, stateDateBeforePause.Before(stateDateAfterUnpause))
|
require.True(t, stateDateBeforePause.Before(stateDateAfterUnpause))
|
||||||
})
|
})
|
||||||
@ -138,14 +138,14 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Can read properties", func(t *testing.T) {
|
t.Run("Can read properties", func(t *testing.T) {
|
||||||
setup(t)
|
setup(t)
|
||||||
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelID: 1, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
result, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
|
result, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
|
||||||
|
|
||||||
alert := result[0]
|
alert := result[0]
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
require.Greater(t, alert.Id, int64(0))
|
require.Greater(t, alert.ID, int64(0))
|
||||||
require.Equal(t, testDash.ID, alert.DashboardId)
|
require.Equal(t, testDash.ID, alert.DashboardID)
|
||||||
require.Equal(t, int64(1), alert.PanelId)
|
require.Equal(t, int64(1), alert.PanelID)
|
||||||
require.Equal(t, "Alerting title", alert.Name)
|
require.Equal(t, "Alerting title", alert.Name)
|
||||||
require.Equal(t, models.AlertStateUnknown, alert.State)
|
require.Equal(t, models.AlertStateUnknown, alert.State)
|
||||||
require.NotNil(t, alert.NewStateDate)
|
require.NotNil(t, alert.NewStateDate)
|
||||||
@ -153,14 +153,14 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
require.Equal(t, "test", alert.EvalData.Get("test").MustString())
|
require.Equal(t, "test", alert.EvalData.Get("test").MustString())
|
||||||
require.NotNil(t, alert.EvalDate)
|
require.NotNil(t, alert.EvalDate)
|
||||||
require.Equal(t, "", alert.ExecutionError)
|
require.Equal(t, "", alert.ExecutionError)
|
||||||
require.NotNil(t, alert.DashboardUid)
|
require.NotNil(t, alert.DashboardUID)
|
||||||
require.Equal(t, "dashboard-with-alerts", alert.DashboardSlug)
|
require.Equal(t, "dashboard-with-alerts", alert.DashboardSlug)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Viewer can read alerts", func(t *testing.T) {
|
t.Run("Viewer can read alerts", func(t *testing.T) {
|
||||||
setup(t)
|
setup(t)
|
||||||
viewerUser := &user.SignedInUser{OrgRole: org.RoleViewer, OrgID: 1}
|
viewerUser := &user.SignedInUser{OrgRole: org.RoleViewer, OrgID: 1}
|
||||||
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: viewerUser}
|
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelID: 1, OrgID: 1, User: viewerUser}
|
||||||
res, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
|
res, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
|
||||||
|
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
@ -179,7 +179,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Alerts should be updated", func(t *testing.T) {
|
t.Run("Alerts should be updated", func(t *testing.T) {
|
||||||
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
|
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
|
||||||
|
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
@ -201,24 +201,24 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
setup(t)
|
setup(t)
|
||||||
multipleItems := []*models.Alert{
|
multipleItems := []*models.Alert{
|
||||||
{
|
{
|
||||||
DashboardId: testDash.ID,
|
DashboardID: testDash.ID,
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
Name: "1",
|
Name: "1",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Settings: simplejson.New(),
|
Settings: simplejson.New(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
DashboardId: testDash.ID,
|
DashboardID: testDash.ID,
|
||||||
PanelId: 2,
|
PanelID: 2,
|
||||||
Name: "2",
|
Name: "2",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Settings: simplejson.New(),
|
Settings: simplejson.New(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
DashboardId: testDash.ID,
|
DashboardID: testDash.ID,
|
||||||
PanelId: 3,
|
PanelID: 3,
|
||||||
Name: "3",
|
Name: "3",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Settings: simplejson.New(),
|
Settings: simplejson.New(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -228,7 +228,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
t.Run("Should save 3 dashboards", func(t *testing.T) {
|
t.Run("Should save 3 dashboards", func(t *testing.T) {
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
queryForDashboard := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
queryForDashboard := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
res, err2 := store.HandleAlertsQuery(context.Background(), &queryForDashboard)
|
res, err2 := store.HandleAlertsQuery(context.Background(), &queryForDashboard)
|
||||||
|
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
@ -241,7 +241,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
err = store.SaveAlerts(context.Background(), testDash.ID, missingOneAlert)
|
err = store.SaveAlerts(context.Background(), testDash.ID, missingOneAlert)
|
||||||
|
|
||||||
t.Run("should delete the missing alert", func(t *testing.T) {
|
t.Run("should delete the missing alert", func(t *testing.T) {
|
||||||
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
|
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
require.Equal(t, 2, len(res))
|
require.Equal(t, 2, len(res))
|
||||||
@ -253,8 +253,8 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
setup(t)
|
setup(t)
|
||||||
items := []*models.Alert{
|
items := []*models.Alert{
|
||||||
{
|
{
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
DashboardId: testDash.ID,
|
DashboardID: testDash.ID,
|
||||||
Name: "Alerting title",
|
Name: "Alerting title",
|
||||||
Message: "Alerting message",
|
Message: "Alerting message",
|
||||||
},
|
},
|
||||||
@ -271,7 +271,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
|
|||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
t.Run("Alerts should be removed", func(t *testing.T) {
|
t.Run("Alerts should be removed", func(t *testing.T) {
|
||||||
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
|
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
|
||||||
|
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
@ -299,18 +299,18 @@ func TestIntegrationPausingAlerts(t *testing.T) {
|
|||||||
stateDateAfterPause := stateDateBeforePause
|
stateDateAfterPause := stateDateBeforePause
|
||||||
|
|
||||||
// Get alert so we can use its ID in tests
|
// Get alert so we can use its ID in tests
|
||||||
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelID: 1, OrgID: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
|
||||||
res, err2 := sqlStore.HandleAlertsQuery(context.Background(), &alertQuery)
|
res, err2 := sqlStore.HandleAlertsQuery(context.Background(), &alertQuery)
|
||||||
require.Nil(t, err2)
|
require.Nil(t, err2)
|
||||||
|
|
||||||
insertedAlert := res[0]
|
insertedAlert := res[0]
|
||||||
|
|
||||||
t.Run("when paused", func(t *testing.T) {
|
t.Run("when paused", func(t *testing.T) {
|
||||||
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.Id, true)
|
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.ID, true)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
t.Run("the NewStateDate should be updated", func(t *testing.T) {
|
t.Run("the NewStateDate should be updated", func(t *testing.T) {
|
||||||
alert, err := getAlertById(t, insertedAlert.Id, &sqlStore)
|
alert, err := getAlertById(t, insertedAlert.ID, &sqlStore)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
stateDateAfterPause = alert.NewStateDate
|
stateDateAfterPause = alert.NewStateDate
|
||||||
@ -319,11 +319,11 @@ func TestIntegrationPausingAlerts(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("when unpaused", func(t *testing.T) {
|
t.Run("when unpaused", func(t *testing.T) {
|
||||||
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.Id, false)
|
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.ID, false)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
t.Run("the NewStateDate should be updated again", func(t *testing.T) {
|
t.Run("the NewStateDate should be updated again", func(t *testing.T) {
|
||||||
alert, err := getAlertById(t, insertedAlert.Id, &sqlStore)
|
alert, err := getAlertById(t, insertedAlert.ID, &sqlStore)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
stateDateAfterUnpause := alert.NewStateDate
|
stateDateAfterUnpause := alert.NewStateDate
|
||||||
@ -335,8 +335,8 @@ func TestIntegrationPausingAlerts(t *testing.T) {
|
|||||||
|
|
||||||
func (ss *sqlStore) pauseAlert(t *testing.T, orgId int64, alertId int64, pauseState bool) (int64, error) {
|
func (ss *sqlStore) pauseAlert(t *testing.T, orgId int64, alertId int64, pauseState bool) (int64, error) {
|
||||||
cmd := &models.PauseAlertCommand{
|
cmd := &models.PauseAlertCommand{
|
||||||
OrgId: orgId,
|
OrgID: orgId,
|
||||||
AlertIds: []int64{alertId},
|
AlertIDs: []int64{alertId},
|
||||||
Paused: pauseState,
|
Paused: pauseState,
|
||||||
}
|
}
|
||||||
err := ss.PauseAlert(context.Background(), cmd)
|
err := ss.PauseAlert(context.Background(), cmd)
|
||||||
@ -347,9 +347,9 @@ func (ss *sqlStore) pauseAlert(t *testing.T, orgId int64, alertId int64, pauseSt
|
|||||||
func insertTestAlert(title string, message string, orgId int64, dashId int64, settings *simplejson.Json, ss sqlStore) (*models.Alert, error) {
|
func insertTestAlert(title string, message string, orgId int64, dashId int64, settings *simplejson.Json, ss sqlStore) (*models.Alert, error) {
|
||||||
items := []*models.Alert{
|
items := []*models.Alert{
|
||||||
{
|
{
|
||||||
PanelId: 1,
|
PanelID: 1,
|
||||||
DashboardId: dashId,
|
DashboardID: dashId,
|
||||||
OrgId: orgId,
|
OrgID: orgId,
|
||||||
Name: title,
|
Name: title,
|
||||||
Message: message,
|
Message: message,
|
||||||
Settings: settings,
|
Settings: settings,
|
||||||
@ -363,7 +363,7 @@ func insertTestAlert(title string, message string, orgId int64, dashId int64, se
|
|||||||
|
|
||||||
func getAlertById(t *testing.T, id int64, ss *sqlStore) (*models.Alert, error) {
|
func getAlertById(t *testing.T, id int64, ss *sqlStore) (*models.Alert, error) {
|
||||||
q := &models.GetAlertByIdQuery{
|
q := &models.GetAlertByIdQuery{
|
||||||
Id: id,
|
ID: id,
|
||||||
}
|
}
|
||||||
res, err := ss.GetAlertById(context.Background(), q)
|
res, err := ss.GetAlertById(context.Background(), q)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
@ -24,7 +24,7 @@ func (e *AlertEngine) AlertTest(orgID int64, dashboard *simplejson.Json, panelID
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, alert := range alerts {
|
for _, alert := range alerts {
|
||||||
if alert.PanelId != panelID {
|
if alert.PanelID != panelID {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
rule, err := NewRuleFromDBAlert(context.Background(), e.AlertStore, alert, true)
|
rule, err := NewRuleFromDBAlert(context.Background(), e.AlertStore, alert, true)
|
||||||
|
@ -23,8 +23,8 @@ func (s CorrelationsService) createCorrelation(ctx context.Context, cmd CreateCo
|
|||||||
var err error
|
var err error
|
||||||
|
|
||||||
query := &datasources.GetDataSourceQuery{
|
query := &datasources.GetDataSourceQuery{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgId,
|
||||||
Uid: cmd.SourceUID,
|
UID: cmd.SourceUID,
|
||||||
}
|
}
|
||||||
if err = s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
if err = s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
||||||
return ErrSourceDataSourceDoesNotExists
|
return ErrSourceDataSourceDoesNotExists
|
||||||
@ -36,8 +36,8 @@ func (s CorrelationsService) createCorrelation(ctx context.Context, cmd CreateCo
|
|||||||
|
|
||||||
if cmd.TargetUID != nil {
|
if cmd.TargetUID != nil {
|
||||||
if err = s.DataSourceService.GetDataSource(ctx, &datasources.GetDataSourceQuery{
|
if err = s.DataSourceService.GetDataSource(ctx, &datasources.GetDataSourceQuery{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgId,
|
||||||
Uid: *cmd.TargetUID,
|
UID: *cmd.TargetUID,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return ErrTargetDataSourceDoesNotExists
|
return ErrTargetDataSourceDoesNotExists
|
||||||
}
|
}
|
||||||
@ -61,8 +61,8 @@ func (s CorrelationsService) createCorrelation(ctx context.Context, cmd CreateCo
|
|||||||
func (s CorrelationsService) deleteCorrelation(ctx context.Context, cmd DeleteCorrelationCommand) error {
|
func (s CorrelationsService) deleteCorrelation(ctx context.Context, cmd DeleteCorrelationCommand) error {
|
||||||
return s.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
|
return s.SQLStore.WithDbSession(ctx, func(session *db.Session) error {
|
||||||
query := &datasources.GetDataSourceQuery{
|
query := &datasources.GetDataSourceQuery{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgId,
|
||||||
Uid: cmd.SourceUID,
|
UID: cmd.SourceUID,
|
||||||
}
|
}
|
||||||
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
||||||
return ErrSourceDataSourceDoesNotExists
|
return ErrSourceDataSourceDoesNotExists
|
||||||
@ -88,8 +88,8 @@ func (s CorrelationsService) updateCorrelation(ctx context.Context, cmd UpdateCo
|
|||||||
|
|
||||||
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
|
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
|
||||||
query := &datasources.GetDataSourceQuery{
|
query := &datasources.GetDataSourceQuery{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgId,
|
||||||
Uid: cmd.SourceUID,
|
UID: cmd.SourceUID,
|
||||||
}
|
}
|
||||||
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
||||||
return ErrSourceDataSourceDoesNotExists
|
return ErrSourceDataSourceDoesNotExists
|
||||||
@ -150,8 +150,8 @@ func (s CorrelationsService) getCorrelation(ctx context.Context, cmd GetCorrelat
|
|||||||
|
|
||||||
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
|
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
|
||||||
query := &datasources.GetDataSourceQuery{
|
query := &datasources.GetDataSourceQuery{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgId,
|
||||||
Uid: cmd.SourceUID,
|
UID: cmd.SourceUID,
|
||||||
}
|
}
|
||||||
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
||||||
return ErrSourceDataSourceDoesNotExists
|
return ErrSourceDataSourceDoesNotExists
|
||||||
@ -176,8 +176,8 @@ func (s CorrelationsService) getCorrelationsBySourceUID(ctx context.Context, cmd
|
|||||||
|
|
||||||
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
|
err := s.SQLStore.WithTransactionalDbSession(ctx, func(session *db.Session) error {
|
||||||
query := &datasources.GetDataSourceQuery{
|
query := &datasources.GetDataSourceQuery{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgId,
|
||||||
Uid: cmd.SourceUID,
|
UID: cmd.SourceUID,
|
||||||
}
|
}
|
||||||
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
if err := s.DataSourceService.GetDataSource(ctx, query); err != nil {
|
||||||
return ErrSourceDataSourceDoesNotExists
|
return ErrSourceDataSourceDoesNotExists
|
||||||
|
@ -591,9 +591,9 @@ func (d *DashboardStore) updateAlerts(ctx context.Context, existingAlerts []*ale
|
|||||||
var alertToUpdate *alertmodels.Alert
|
var alertToUpdate *alertmodels.Alert
|
||||||
|
|
||||||
for _, k := range existingAlerts {
|
for _, k := range existingAlerts {
|
||||||
if alert.PanelId == k.PanelId {
|
if alert.PanelID == k.PanelID {
|
||||||
update = true
|
update = true
|
||||||
alert.Id = k.Id
|
alert.ID = k.ID
|
||||||
alertToUpdate = k
|
alertToUpdate = k
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -605,12 +605,12 @@ func (d *DashboardStore) updateAlerts(ctx context.Context, existingAlerts []*ale
|
|||||||
alert.State = alertToUpdate.State
|
alert.State = alertToUpdate.State
|
||||||
sess.MustCols("message", "for")
|
sess.MustCols("message", "for")
|
||||||
|
|
||||||
_, err := sess.ID(alert.Id).Update(alert)
|
_, err := sess.ID(alert.ID).Update(alert)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug("Alert updated", "name", alert.Name, "id", alert.Id)
|
log.Debug("Alert updated", "name", alert.Name, "id", alert.ID)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
alert.Updated = time.Now()
|
alert.Updated = time.Now()
|
||||||
@ -623,10 +623,10 @@ func (d *DashboardStore) updateAlerts(ctx context.Context, existingAlerts []*ale
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug("Alert inserted", "name", alert.Name, "id", alert.Id)
|
log.Debug("Alert inserted", "name", alert.Name, "id", alert.ID)
|
||||||
}
|
}
|
||||||
tags := alert.GetTagsFromSettings()
|
tags := alert.GetTagsFromSettings()
|
||||||
if _, err := sess.Exec("DELETE FROM alert_rule_tag WHERE alert_id = ?", alert.Id); err != nil {
|
if _, err := sess.Exec("DELETE FROM alert_rule_tag WHERE alert_id = ?", alert.ID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if tags != nil {
|
if tags != nil {
|
||||||
@ -635,7 +635,7 @@ func (d *DashboardStore) updateAlerts(ctx context.Context, existingAlerts []*ale
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, tag := range tags {
|
for _, tag := range tags {
|
||||||
if _, err := sess.Exec("INSERT INTO alert_rule_tag (alert_id, tag_id) VALUES(?,?)", alert.Id, tag.Id); err != nil {
|
if _, err := sess.Exec("INSERT INTO alert_rule_tag (alert_id, tag_id) VALUES(?,?)", alert.ID, tag.Id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -650,14 +650,14 @@ func (d *DashboardStore) deleteMissingAlerts(alerts []*alertmodels.Alert, existi
|
|||||||
missing := true
|
missing := true
|
||||||
|
|
||||||
for _, k := range existingAlerts {
|
for _, k := range existingAlerts {
|
||||||
if missingAlert.PanelId == k.PanelId {
|
if missingAlert.PanelID == k.PanelID {
|
||||||
missing = false
|
missing = false
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if missing {
|
if missing {
|
||||||
if err := d.deleteAlertByIdInternal(missingAlert.Id, "Removed from dashboard", sess); err != nil {
|
if err := d.deleteAlertByIdInternal(missingAlert.ID, "Removed from dashboard", sess); err != nil {
|
||||||
// No use trying to delete more, since we're in a transaction and it will be
|
// No use trying to delete more, since we're in a transaction and it will be
|
||||||
// rolled back on error.
|
// rolled back on error.
|
||||||
return err
|
return err
|
||||||
@ -856,7 +856,7 @@ func (d *DashboardStore) deleteAlertDefinition(dashboardId int64, sess *db.Sessi
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, alert := range alerts {
|
for _, alert := range alerts {
|
||||||
if err := d.deleteAlertByIdInternal(alert.Id, "Dashboard deleted", sess); err != nil {
|
if err := d.deleteAlertByIdInternal(alert.ID, "Dashboard deleted", sess); err != nil {
|
||||||
// If we return an error, the current transaction gets rolled back, so no use
|
// If we return an error, the current transaction gets rolled back, so no use
|
||||||
// trying to delete more
|
// trying to delete more
|
||||||
return err
|
return err
|
||||||
|
@ -105,7 +105,7 @@ func toAPIError(c *contextmodel.ReqContext, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *DataSourceProxyService) proxyDatasourceRequest(c *contextmodel.ReqContext, ds *datasources.DataSource) {
|
func (p *DataSourceProxyService) proxyDatasourceRequest(c *contextmodel.ReqContext, ds *datasources.DataSource) {
|
||||||
err := p.PluginRequestValidator.Validate(ds.Url, c.Req)
|
err := p.PluginRequestValidator.Validate(ds.URL, c.Req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JsonApiErr(http.StatusForbidden, "Access denied", err)
|
c.JsonApiErr(http.StatusForbidden, "Access denied", err)
|
||||||
return
|
return
|
||||||
@ -123,7 +123,7 @@ func (p *DataSourceProxyService) proxyDatasourceRequest(c *contextmodel.ReqConte
|
|||||||
p.OAuthTokenService, p.DataSourcesService, p.tracer)
|
p.OAuthTokenService, p.DataSourcesService, p.tracer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, datasource.URLValidationError{}) {
|
if errors.Is(err, datasource.URLValidationError{}) {
|
||||||
c.JsonApiErr(http.StatusBadRequest, fmt.Sprintf("Invalid data source URL: %q", ds.Url), err)
|
c.JsonApiErr(http.StatusBadRequest, fmt.Sprintf("Invalid data source URL: %q", ds.URL), err)
|
||||||
} else {
|
} else {
|
||||||
c.JsonApiErr(http.StatusInternalServerError, "Failed creating data source proxy", err)
|
c.JsonApiErr(http.StatusInternalServerError, "Failed creating data source proxy", err)
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ var _ datasources.CacheService = &FakeCacheService{}
|
|||||||
|
|
||||||
func (c *FakeCacheService) GetDatasource(ctx context.Context, datasourceID int64, user *user.SignedInUser, skipCache bool) (*datasources.DataSource, error) {
|
func (c *FakeCacheService) GetDatasource(ctx context.Context, datasourceID int64, user *user.SignedInUser, skipCache bool) (*datasources.DataSource, error) {
|
||||||
for _, datasource := range c.DataSources {
|
for _, datasource := range c.DataSources {
|
||||||
if datasource.Id == datasourceID {
|
if datasource.ID == datasourceID {
|
||||||
return datasource, nil
|
return datasource, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -24,7 +24,7 @@ func (c *FakeCacheService) GetDatasource(ctx context.Context, datasourceID int64
|
|||||||
|
|
||||||
func (c *FakeCacheService) GetDatasourceByUID(ctx context.Context, datasourceUID string, user *user.SignedInUser, skipCache bool) (*datasources.DataSource, error) {
|
func (c *FakeCacheService) GetDatasourceByUID(ctx context.Context, datasourceUID string, user *user.SignedInUser, skipCache bool) (*datasources.DataSource, error) {
|
||||||
for _, datasource := range c.DataSources {
|
for _, datasource := range c.DataSources {
|
||||||
if datasource.Uid == datasourceUID {
|
if datasource.UID == datasourceUID {
|
||||||
return datasource, nil
|
return datasource, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type FakeDataSourceService struct {
|
type FakeDataSourceService struct {
|
||||||
lastId int64
|
lastID int64
|
||||||
DataSources []*datasources.DataSource
|
DataSources []*datasources.DataSource
|
||||||
SimulatePluginFailure bool
|
SimulatePluginFailure bool
|
||||||
}
|
}
|
||||||
@ -20,8 +20,8 @@ var _ datasources.DataSourceService = &FakeDataSourceService{}
|
|||||||
|
|
||||||
func (s *FakeDataSourceService) GetDataSource(ctx context.Context, query *datasources.GetDataSourceQuery) error {
|
func (s *FakeDataSourceService) GetDataSource(ctx context.Context, query *datasources.GetDataSourceQuery) error {
|
||||||
for _, datasource := range s.DataSources {
|
for _, datasource := range s.DataSources {
|
||||||
idMatch := query.Id != 0 && query.Id == datasource.Id
|
idMatch := query.ID != 0 && query.ID == datasource.ID
|
||||||
uidMatch := query.Uid != "" && query.Uid == datasource.Uid
|
uidMatch := query.UID != "" && query.UID == datasource.UID
|
||||||
nameMatch := query.Name != "" && query.Name == datasource.Name
|
nameMatch := query.Name != "" && query.Name == datasource.Name
|
||||||
if idMatch || nameMatch || uidMatch {
|
if idMatch || nameMatch || uidMatch {
|
||||||
query.Result = datasource
|
query.Result = datasource
|
||||||
@ -34,7 +34,7 @@ func (s *FakeDataSourceService) GetDataSource(ctx context.Context, query *dataso
|
|||||||
|
|
||||||
func (s *FakeDataSourceService) GetDataSources(ctx context.Context, query *datasources.GetDataSourcesQuery) error {
|
func (s *FakeDataSourceService) GetDataSources(ctx context.Context, query *datasources.GetDataSourcesQuery) error {
|
||||||
for _, datasource := range s.DataSources {
|
for _, datasource := range s.DataSources {
|
||||||
orgMatch := query.OrgId != 0 && query.OrgId == datasource.OrgId
|
orgMatch := query.OrgID != 0 && query.OrgID == datasource.OrgID
|
||||||
if orgMatch {
|
if orgMatch {
|
||||||
query.Result = append(query.Result, datasource)
|
query.Result = append(query.Result, datasource)
|
||||||
}
|
}
|
||||||
@ -49,7 +49,7 @@ func (s *FakeDataSourceService) GetAllDataSources(ctx context.Context, query *da
|
|||||||
|
|
||||||
func (s *FakeDataSourceService) GetDataSourcesByType(ctx context.Context, query *datasources.GetDataSourcesByTypeQuery) error {
|
func (s *FakeDataSourceService) GetDataSourcesByType(ctx context.Context, query *datasources.GetDataSourcesByTypeQuery) error {
|
||||||
for _, datasource := range s.DataSources {
|
for _, datasource := range s.DataSources {
|
||||||
if query.OrgId > 0 && datasource.OrgId != query.OrgId {
|
if query.OrgID > 0 && datasource.OrgID != query.OrgID {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
typeMatch := query.Type != "" && query.Type == datasource.Type
|
typeMatch := query.Type != "" && query.Type == datasource.Type
|
||||||
@ -61,15 +61,15 @@ func (s *FakeDataSourceService) GetDataSourcesByType(ctx context.Context, query
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *FakeDataSourceService) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) error {
|
func (s *FakeDataSourceService) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) error {
|
||||||
if s.lastId == 0 {
|
if s.lastID == 0 {
|
||||||
s.lastId = int64(len(s.DataSources) - 1)
|
s.lastID = int64(len(s.DataSources) - 1)
|
||||||
}
|
}
|
||||||
cmd.Result = &datasources.DataSource{
|
cmd.Result = &datasources.DataSource{
|
||||||
Id: s.lastId + 1,
|
ID: s.lastID + 1,
|
||||||
Name: cmd.Name,
|
Name: cmd.Name,
|
||||||
Type: cmd.Type,
|
Type: cmd.Type,
|
||||||
Uid: cmd.Uid,
|
UID: cmd.UID,
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgID,
|
||||||
}
|
}
|
||||||
s.DataSources = append(s.DataSources, cmd.Result)
|
s.DataSources = append(s.DataSources, cmd.Result)
|
||||||
return nil
|
return nil
|
||||||
@ -77,8 +77,8 @@ func (s *FakeDataSourceService) AddDataSource(ctx context.Context, cmd *datasour
|
|||||||
|
|
||||||
func (s *FakeDataSourceService) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteDataSourceCommand) error {
|
func (s *FakeDataSourceService) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteDataSourceCommand) error {
|
||||||
for i, datasource := range s.DataSources {
|
for i, datasource := range s.DataSources {
|
||||||
idMatch := cmd.ID != 0 && cmd.ID == datasource.Id
|
idMatch := cmd.ID != 0 && cmd.ID == datasource.ID
|
||||||
uidMatch := cmd.UID != "" && cmd.UID == datasource.Uid
|
uidMatch := cmd.UID != "" && cmd.UID == datasource.UID
|
||||||
nameMatch := cmd.Name != "" && cmd.Name == datasource.Name
|
nameMatch := cmd.Name != "" && cmd.Name == datasource.Name
|
||||||
if idMatch || nameMatch || uidMatch {
|
if idMatch || nameMatch || uidMatch {
|
||||||
s.DataSources = append(s.DataSources[:i], s.DataSources[i+1:]...)
|
s.DataSources = append(s.DataSources[:i], s.DataSources[i+1:]...)
|
||||||
@ -90,8 +90,8 @@ func (s *FakeDataSourceService) DeleteDataSource(ctx context.Context, cmd *datas
|
|||||||
|
|
||||||
func (s *FakeDataSourceService) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateDataSourceCommand) error {
|
func (s *FakeDataSourceService) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateDataSourceCommand) error {
|
||||||
for _, datasource := range s.DataSources {
|
for _, datasource := range s.DataSources {
|
||||||
idMatch := cmd.Id != 0 && cmd.Id == datasource.Id
|
idMatch := cmd.ID != 0 && cmd.ID == datasource.ID
|
||||||
uidMatch := cmd.Uid != "" && cmd.Uid == datasource.Uid
|
uidMatch := cmd.UID != "" && cmd.UID == datasource.UID
|
||||||
nameMatch := cmd.Name != "" && cmd.Name == datasource.Name
|
nameMatch := cmd.Name != "" && cmd.Name == datasource.Name
|
||||||
if idMatch || nameMatch || uidMatch {
|
if idMatch || nameMatch || uidMatch {
|
||||||
if cmd.Name != "" {
|
if cmd.Name != "" {
|
||||||
|
@ -33,14 +33,14 @@ const (
|
|||||||
type DsAccess string
|
type DsAccess string
|
||||||
|
|
||||||
type DataSource struct {
|
type DataSource struct {
|
||||||
Id int64 `json:"id,omitempty"`
|
ID int64 `json:"id,omitempty" xorm:"pk autoincr 'id'"`
|
||||||
OrgId int64 `json:"orgId,omitempty"`
|
OrgID int64 `json:"orgId,omitempty" xorm:"org_id"`
|
||||||
Version int `json:"version,omitempty"`
|
Version int `json:"version,omitempty"`
|
||||||
|
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Access DsAccess `json:"access"`
|
Access DsAccess `json:"access"`
|
||||||
Url string `json:"url"`
|
URL string `json:"url" xorm:"url"`
|
||||||
// swagger:ignore
|
// swagger:ignore
|
||||||
Password string `json:"-"`
|
Password string `json:"-"`
|
||||||
User string `json:"user"`
|
User string `json:"user"`
|
||||||
@ -54,7 +54,7 @@ type DataSource struct {
|
|||||||
JsonData *simplejson.Json `json:"jsonData"`
|
JsonData *simplejson.Json `json:"jsonData"`
|
||||||
SecureJsonData map[string][]byte `json:"secureJsonData"`
|
SecureJsonData map[string][]byte `json:"secureJsonData"`
|
||||||
ReadOnly bool `json:"readOnly"`
|
ReadOnly bool `json:"readOnly"`
|
||||||
Uid string `json:"uid"`
|
UID string `json:"uid" xorm:"uid"`
|
||||||
|
|
||||||
Created time.Time `json:"created,omitempty"`
|
Created time.Time `json:"created,omitempty"`
|
||||||
Updated time.Time `json:"updated,omitempty"`
|
Updated time.Time `json:"updated,omitempty"`
|
||||||
@ -89,7 +89,7 @@ type AddDataSourceCommand struct {
|
|||||||
Name string `json:"name" binding:"Required"`
|
Name string `json:"name" binding:"Required"`
|
||||||
Type string `json:"type" binding:"Required"`
|
Type string `json:"type" binding:"Required"`
|
||||||
Access DsAccess `json:"access" binding:"Required"`
|
Access DsAccess `json:"access" binding:"Required"`
|
||||||
Url string `json:"url"`
|
URL string `json:"url"`
|
||||||
Database string `json:"database"`
|
Database string `json:"database"`
|
||||||
User string `json:"user"`
|
User string `json:"user"`
|
||||||
BasicAuth bool `json:"basicAuth"`
|
BasicAuth bool `json:"basicAuth"`
|
||||||
@ -98,10 +98,10 @@ type AddDataSourceCommand struct {
|
|||||||
IsDefault bool `json:"isDefault"`
|
IsDefault bool `json:"isDefault"`
|
||||||
JsonData *simplejson.Json `json:"jsonData"`
|
JsonData *simplejson.Json `json:"jsonData"`
|
||||||
SecureJsonData map[string]string `json:"secureJsonData"`
|
SecureJsonData map[string]string `json:"secureJsonData"`
|
||||||
Uid string `json:"uid"`
|
UID string `json:"uid"`
|
||||||
|
|
||||||
OrgId int64 `json:"-"`
|
OrgID int64 `json:"-"`
|
||||||
UserId int64 `json:"-"`
|
UserID int64 `json:"-"`
|
||||||
ReadOnly bool `json:"-"`
|
ReadOnly bool `json:"-"`
|
||||||
EncryptedSecureJsonData map[string][]byte `json:"-"`
|
EncryptedSecureJsonData map[string][]byte `json:"-"`
|
||||||
UpdateSecretFn UpdateSecretFn `json:"-"`
|
UpdateSecretFn UpdateSecretFn `json:"-"`
|
||||||
@ -114,7 +114,7 @@ type UpdateDataSourceCommand struct {
|
|||||||
Name string `json:"name" binding:"Required"`
|
Name string `json:"name" binding:"Required"`
|
||||||
Type string `json:"type" binding:"Required"`
|
Type string `json:"type" binding:"Required"`
|
||||||
Access DsAccess `json:"access" binding:"Required"`
|
Access DsAccess `json:"access" binding:"Required"`
|
||||||
Url string `json:"url"`
|
URL string `json:"url"`
|
||||||
User string `json:"user"`
|
User string `json:"user"`
|
||||||
Database string `json:"database"`
|
Database string `json:"database"`
|
||||||
BasicAuth bool `json:"basicAuth"`
|
BasicAuth bool `json:"basicAuth"`
|
||||||
@ -124,10 +124,10 @@ type UpdateDataSourceCommand struct {
|
|||||||
JsonData *simplejson.Json `json:"jsonData"`
|
JsonData *simplejson.Json `json:"jsonData"`
|
||||||
SecureJsonData map[string]string `json:"secureJsonData"`
|
SecureJsonData map[string]string `json:"secureJsonData"`
|
||||||
Version int `json:"version"`
|
Version int `json:"version"`
|
||||||
Uid string `json:"uid"`
|
UID string `json:"uid"`
|
||||||
|
|
||||||
OrgId int64 `json:"-"`
|
OrgID int64 `json:"-"`
|
||||||
Id int64 `json:"-"`
|
ID int64 `json:"-"`
|
||||||
ReadOnly bool `json:"-"`
|
ReadOnly bool `json:"-"`
|
||||||
EncryptedSecureJsonData map[string][]byte `json:"-"`
|
EncryptedSecureJsonData map[string][]byte `json:"-"`
|
||||||
UpdateSecretFn UpdateSecretFn `json:"-"`
|
UpdateSecretFn UpdateSecretFn `json:"-"`
|
||||||
@ -156,7 +156,7 @@ type UpdateSecretFn func() error
|
|||||||
// QUERIES
|
// QUERIES
|
||||||
|
|
||||||
type GetDataSourcesQuery struct {
|
type GetDataSourcesQuery struct {
|
||||||
OrgId int64
|
OrgID int64
|
||||||
DataSourceLimit int
|
DataSourceLimit int
|
||||||
User *user.SignedInUser
|
User *user.SignedInUser
|
||||||
Result []*DataSource
|
Result []*DataSource
|
||||||
@ -167,13 +167,13 @@ type GetAllDataSourcesQuery struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type GetDataSourcesByTypeQuery struct {
|
type GetDataSourcesByTypeQuery struct {
|
||||||
OrgId int64 // optional: filter by org_id
|
OrgID int64 // optional: filter by org_id
|
||||||
Type string
|
Type string
|
||||||
Result []*DataSource
|
Result []*DataSource
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetDefaultDataSourceQuery struct {
|
type GetDefaultDataSourceQuery struct {
|
||||||
OrgId int64
|
OrgID int64
|
||||||
User *user.SignedInUser
|
User *user.SignedInUser
|
||||||
Result *DataSource
|
Result *DataSource
|
||||||
}
|
}
|
||||||
@ -181,11 +181,11 @@ type GetDefaultDataSourceQuery struct {
|
|||||||
// GetDataSourceQuery will get a DataSource based on OrgID as well as the UID (preferred), ID, or Name.
|
// GetDataSourceQuery will get a DataSource based on OrgID as well as the UID (preferred), ID, or Name.
|
||||||
// At least one of the UID, ID, or Name properties must be set in addition to OrgID.
|
// At least one of the UID, ID, or Name properties must be set in addition to OrgID.
|
||||||
type GetDataSourceQuery struct {
|
type GetDataSourceQuery struct {
|
||||||
Id int64
|
ID int64
|
||||||
Uid string
|
UID string
|
||||||
Name string
|
Name string
|
||||||
|
|
||||||
OrgId int64
|
OrgID int64
|
||||||
|
|
||||||
Result *DataSource
|
Result *DataSource
|
||||||
}
|
}
|
||||||
|
@ -43,7 +43,7 @@ func (dc *CacheServiceImpl) GetDatasource(
|
|||||||
if !skipCache {
|
if !skipCache {
|
||||||
if cached, found := dc.CacheService.Get(cacheKey); found {
|
if cached, found := dc.CacheService.Get(cacheKey); found {
|
||||||
ds := cached.(*datasources.DataSource)
|
ds := cached.(*datasources.DataSource)
|
||||||
if ds.OrgId == user.OrgID {
|
if ds.OrgID == user.OrgID {
|
||||||
return ds, nil
|
return ds, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -51,7 +51,7 @@ func (dc *CacheServiceImpl) GetDatasource(
|
|||||||
|
|
||||||
dc.logger.FromContext(ctx).Debug("Querying for data source via SQL store", "id", datasourceID, "orgId", user.OrgID)
|
dc.logger.FromContext(ctx).Debug("Querying for data source via SQL store", "id", datasourceID, "orgId", user.OrgID)
|
||||||
|
|
||||||
query := &datasources.GetDataSourceQuery{Id: datasourceID, OrgId: user.OrgID}
|
query := &datasources.GetDataSourceQuery{ID: datasourceID, OrgID: user.OrgID}
|
||||||
ss := SqlStore{db: dc.SQLStore, logger: dc.logger}
|
ss := SqlStore{db: dc.SQLStore, logger: dc.logger}
|
||||||
err := ss.GetDataSource(ctx, query)
|
err := ss.GetDataSource(ctx, query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -60,8 +60,8 @@ func (dc *CacheServiceImpl) GetDatasource(
|
|||||||
|
|
||||||
ds := query.Result
|
ds := query.Result
|
||||||
|
|
||||||
if ds.Uid != "" {
|
if ds.UID != "" {
|
||||||
dc.CacheService.Set(uidKey(ds.OrgId, ds.Uid), ds, time.Second*5)
|
dc.CacheService.Set(uidKey(ds.OrgID, ds.UID), ds, time.Second*5)
|
||||||
}
|
}
|
||||||
dc.CacheService.Set(cacheKey, ds, dc.cacheTTL)
|
dc.CacheService.Set(cacheKey, ds, dc.cacheTTL)
|
||||||
return ds, nil
|
return ds, nil
|
||||||
@ -84,14 +84,14 @@ func (dc *CacheServiceImpl) GetDatasourceByUID(
|
|||||||
if !skipCache {
|
if !skipCache {
|
||||||
if cached, found := dc.CacheService.Get(uidCacheKey); found {
|
if cached, found := dc.CacheService.Get(uidCacheKey); found {
|
||||||
ds := cached.(*datasources.DataSource)
|
ds := cached.(*datasources.DataSource)
|
||||||
if ds.OrgId == user.OrgID {
|
if ds.OrgID == user.OrgID {
|
||||||
return ds, nil
|
return ds, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dc.logger.FromContext(ctx).Debug("Querying for data source via SQL store", "uid", datasourceUID, "orgId", user.OrgID)
|
dc.logger.FromContext(ctx).Debug("Querying for data source via SQL store", "uid", datasourceUID, "orgId", user.OrgID)
|
||||||
query := &datasources.GetDataSourceQuery{Uid: datasourceUID, OrgId: user.OrgID}
|
query := &datasources.GetDataSourceQuery{UID: datasourceUID, OrgID: user.OrgID}
|
||||||
ss := SqlStore{db: dc.SQLStore, logger: dc.logger}
|
ss := SqlStore{db: dc.SQLStore, logger: dc.logger}
|
||||||
err := ss.GetDataSource(ctx, query)
|
err := ss.GetDataSource(ctx, query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -101,7 +101,7 @@ func (dc *CacheServiceImpl) GetDatasourceByUID(
|
|||||||
ds := query.Result
|
ds := query.Result
|
||||||
|
|
||||||
dc.CacheService.Set(uidCacheKey, ds, dc.cacheTTL)
|
dc.CacheService.Set(uidCacheKey, ds, dc.cacheTTL)
|
||||||
dc.CacheService.Set(idKey(ds.Id), ds, dc.cacheTTL)
|
dc.CacheService.Set(idKey(ds.ID), ds, dc.cacheTTL)
|
||||||
return ds, nil
|
return ds, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -114,12 +114,12 @@ func NewNameScopeResolver(db DataSourceRetriever) (string, accesscontrol.ScopeAt
|
|||||||
return nil, accesscontrol.ErrInvalidScope
|
return nil, accesscontrol.ErrInvalidScope
|
||||||
}
|
}
|
||||||
|
|
||||||
query := datasources.GetDataSourceQuery{Name: dsName, OrgId: orgID}
|
query := datasources.GetDataSourceQuery{Name: dsName, OrgID: orgID}
|
||||||
if err := db.GetDataSource(ctx, &query); err != nil {
|
if err := db.GetDataSource(ctx, &query); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return []string{datasources.ScopeProvider.GetResourceScopeUID(query.Result.Uid)}, nil
|
return []string{datasources.ScopeProvider.GetResourceScopeUID(query.Result.UID)}, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -142,12 +142,12 @@ func NewIDScopeResolver(db DataSourceRetriever) (string, accesscontrol.ScopeAttr
|
|||||||
return nil, accesscontrol.ErrInvalidScope
|
return nil, accesscontrol.ErrInvalidScope
|
||||||
}
|
}
|
||||||
|
|
||||||
query := datasources.GetDataSourceQuery{Id: dsID, OrgId: orgID}
|
query := datasources.GetDataSourceQuery{ID: dsID, OrgID: orgID}
|
||||||
if err := db.GetDataSource(ctx, &query); err != nil {
|
if err := db.GetDataSource(ctx, &query); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return []string{datasources.ScopeProvider.GetResourceScopeUID(query.Result.Uid)}, nil
|
return []string{datasources.ScopeProvider.GetResourceScopeUID(query.Result.UID)}, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -185,7 +185,7 @@ func (s *Service) AddDataSource(ctx context.Context, cmd *datasources.AddDataSou
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.SecretsStore.Set(ctx, cmd.OrgId, cmd.Name, kvstore.DataSourceSecretType, string(secret))
|
return s.SecretsStore.Set(ctx, cmd.OrgID, cmd.Name, kvstore.DataSourceSecretType, string(secret))
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := s.SQLStore.AddDataSource(ctx, cmd); err != nil {
|
if err := s.SQLStore.AddDataSource(ctx, cmd); err != nil {
|
||||||
@ -202,10 +202,10 @@ func (s *Service) AddDataSource(ctx context.Context, cmd *datasources.AddDataSou
|
|||||||
{BuiltinRole: "Viewer", Permission: "Query"},
|
{BuiltinRole: "Viewer", Permission: "Query"},
|
||||||
{BuiltinRole: "Editor", Permission: "Query"},
|
{BuiltinRole: "Editor", Permission: "Query"},
|
||||||
}
|
}
|
||||||
if cmd.UserId != 0 {
|
if cmd.UserID != 0 {
|
||||||
permissions = append(permissions, accesscontrol.SetResourcePermissionCommand{UserID: cmd.UserId, Permission: "Edit"})
|
permissions = append(permissions, accesscontrol.SetResourcePermissionCommand{UserID: cmd.UserID, Permission: "Edit"})
|
||||||
}
|
}
|
||||||
if _, err := s.permissionsService.SetPermissions(ctx, cmd.OrgId, cmd.Result.Uid, permissions...); err != nil {
|
if _, err := s.permissionsService.SetPermissions(ctx, cmd.OrgID, cmd.Result.UID, permissions...); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -229,8 +229,8 @@ func (s *Service) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateD
|
|||||||
var err error
|
var err error
|
||||||
|
|
||||||
query := &datasources.GetDataSourceQuery{
|
query := &datasources.GetDataSourceQuery{
|
||||||
Id: cmd.Id,
|
ID: cmd.ID,
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgID,
|
||||||
}
|
}
|
||||||
err = s.SQLStore.GetDataSource(ctx, query)
|
err = s.SQLStore.GetDataSource(ctx, query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -242,7 +242,7 @@ func (s *Service) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateD
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if cmd.OrgId > 0 && cmd.Name != "" {
|
if cmd.OrgID > 0 && cmd.Name != "" {
|
||||||
cmd.UpdateSecretFn = func() error {
|
cmd.UpdateSecretFn = func() error {
|
||||||
secret, err := json.Marshal(cmd.SecureJsonData)
|
secret, err := json.Marshal(cmd.SecureJsonData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -250,13 +250,13 @@ func (s *Service) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateD
|
|||||||
}
|
}
|
||||||
|
|
||||||
if query.Result.Name != cmd.Name {
|
if query.Result.Name != cmd.Name {
|
||||||
err := s.SecretsStore.Rename(ctx, cmd.OrgId, query.Result.Name, kvstore.DataSourceSecretType, cmd.Name)
|
err := s.SecretsStore.Rename(ctx, cmd.OrgID, query.Result.Name, kvstore.DataSourceSecretType, cmd.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.SecretsStore.Set(ctx, cmd.OrgId, cmd.Name, kvstore.DataSourceSecretType, string(secret))
|
return s.SecretsStore.Set(ctx, cmd.OrgID, cmd.Name, kvstore.DataSourceSecretType, string(secret))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -285,7 +285,7 @@ func (s *Service) GetHTTPTransport(ctx context.Context, ds *datasources.DataSour
|
|||||||
s.ptc.Lock()
|
s.ptc.Lock()
|
||||||
defer s.ptc.Unlock()
|
defer s.ptc.Unlock()
|
||||||
|
|
||||||
if t, present := s.ptc.cache[ds.Id]; present && ds.Updated.Equal(t.updated) {
|
if t, present := s.ptc.cache[ds.ID]; present && ds.Updated.Equal(t.updated) {
|
||||||
return t.roundTripper, nil
|
return t.roundTripper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -301,7 +301,7 @@ func (s *Service) GetHTTPTransport(ctx context.Context, ds *datasources.DataSour
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
s.ptc.cache[ds.Id] = cachedRoundTripper{
|
s.ptc.cache[ds.ID] = cachedRoundTripper{
|
||||||
roundTripper: rt,
|
roundTripper: rt,
|
||||||
updated: ds.Updated,
|
updated: ds.Updated,
|
||||||
}
|
}
|
||||||
@ -319,7 +319,7 @@ func (s *Service) GetTLSConfig(ctx context.Context, ds *datasources.DataSource,
|
|||||||
|
|
||||||
func (s *Service) DecryptedValues(ctx context.Context, ds *datasources.DataSource) (map[string]string, error) {
|
func (s *Service) DecryptedValues(ctx context.Context, ds *datasources.DataSource) (map[string]string, error) {
|
||||||
decryptedValues := make(map[string]string)
|
decryptedValues := make(map[string]string)
|
||||||
secret, exist, err := s.SecretsStore.Get(ctx, ds.OrgId, ds.Name, kvstore.DataSourceSecretType)
|
secret, exist, err := s.SecretsStore.Get(ctx, ds.OrgID, ds.Name, kvstore.DataSourceSecretType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -409,7 +409,7 @@ func (s *Service) httpClientOptions(ctx context.Context, ds *datasources.DataSou
|
|||||||
Labels: map[string]string{
|
Labels: map[string]string{
|
||||||
"datasource_type": ds.Type,
|
"datasource_type": ds.Type,
|
||||||
"datasource_name": ds.Name,
|
"datasource_name": ds.Name,
|
||||||
"datasource_uid": ds.Uid,
|
"datasource_uid": ds.UID,
|
||||||
},
|
},
|
||||||
TLS: &tlsOptions,
|
TLS: &tlsOptions,
|
||||||
}
|
}
|
||||||
|
@ -35,8 +35,8 @@ type dataSourceMockRetriever struct {
|
|||||||
|
|
||||||
func (d *dataSourceMockRetriever) GetDataSource(ctx context.Context, query *datasources.GetDataSourceQuery) error {
|
func (d *dataSourceMockRetriever) GetDataSource(ctx context.Context, query *datasources.GetDataSourceQuery) error {
|
||||||
for _, datasource := range d.res {
|
for _, datasource := range d.res {
|
||||||
idMatch := query.Id != 0 && query.Id == datasource.Id
|
idMatch := query.ID != 0 && query.ID == datasource.ID
|
||||||
uidMatch := query.Uid != "" && query.Uid == datasource.Uid
|
uidMatch := query.UID != "" && query.UID == datasource.UID
|
||||||
nameMatch := query.Name != "" && query.Name == datasource.Name
|
nameMatch := query.Name != "" && query.Name == datasource.Name
|
||||||
if idMatch || nameMatch || uidMatch {
|
if idMatch || nameMatch || uidMatch {
|
||||||
query.Result = datasource
|
query.Result = datasource
|
||||||
@ -49,10 +49,10 @@ func (d *dataSourceMockRetriever) GetDataSource(ctx context.Context, query *data
|
|||||||
|
|
||||||
func TestService_NameScopeResolver(t *testing.T) {
|
func TestService_NameScopeResolver(t *testing.T) {
|
||||||
retriever := &dataSourceMockRetriever{[]*datasources.DataSource{
|
retriever := &dataSourceMockRetriever{[]*datasources.DataSource{
|
||||||
{Name: "test-datasource", Uid: "1"},
|
{Name: "test-datasource", UID: "1"},
|
||||||
{Name: "*", Uid: "2"},
|
{Name: "*", UID: "2"},
|
||||||
{Name: ":/*", Uid: "3"},
|
{Name: ":/*", UID: "3"},
|
||||||
{Name: ":", Uid: "4"},
|
{Name: ":", UID: "4"},
|
||||||
}}
|
}}
|
||||||
|
|
||||||
type testCaseResolver struct {
|
type testCaseResolver struct {
|
||||||
@ -126,7 +126,7 @@ func TestService_NameScopeResolver(t *testing.T) {
|
|||||||
|
|
||||||
func TestService_IDScopeResolver(t *testing.T) {
|
func TestService_IDScopeResolver(t *testing.T) {
|
||||||
retriever := &dataSourceMockRetriever{[]*datasources.DataSource{
|
retriever := &dataSourceMockRetriever{[]*datasources.DataSource{
|
||||||
{Id: 1, Uid: "NnftN9Lnz"},
|
{ID: 1, UID: "NnftN9Lnz"},
|
||||||
}}
|
}}
|
||||||
|
|
||||||
type testCaseResolver struct {
|
type testCaseResolver struct {
|
||||||
@ -259,8 +259,8 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -309,8 +309,8 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
SecureJsonData: map[string][]byte{"tlsCACert": []byte(caCert)},
|
SecureJsonData: map[string][]byte{"tlsCACert": []byte(caCert)},
|
||||||
Updated: time.Now().Add(-2 * time.Minute),
|
Updated: time.Now().Add(-2 * time.Minute),
|
||||||
@ -360,10 +360,10 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: "kubernetes",
|
Name: "kubernetes",
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
JsonData: sjson,
|
JsonData: sjson,
|
||||||
}
|
}
|
||||||
@ -374,7 +374,7 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = secretsStore.Set(context.Background(), ds.OrgId, ds.Name, secretskvs.DataSourceSecretType, string(secureJsonData))
|
err = secretsStore.Set(context.Background(), ds.OrgID, ds.Name, secretskvs.DataSourceSecretType, string(secureJsonData))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
rt, err := dsService.GetHTTPTransport(context.Background(), &ds, provider)
|
rt, err := dsService.GetHTTPTransport(context.Background(), &ds, provider)
|
||||||
@ -408,10 +408,10 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: "kubernetes",
|
Name: "kubernetes",
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
JsonData: sjson,
|
JsonData: sjson,
|
||||||
}
|
}
|
||||||
@ -421,7 +421,7 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = secretsStore.Set(context.Background(), ds.OrgId, ds.Name, secretskvs.DataSourceSecretType, string(secureJsonData))
|
err = secretsStore.Set(context.Background(), ds.OrgID, ds.Name, secretskvs.DataSourceSecretType, string(secureJsonData))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
rt, err := dsService.GetHTTPTransport(context.Background(), &ds, provider)
|
rt, err := dsService.GetHTTPTransport(context.Background(), &ds, provider)
|
||||||
@ -460,8 +460,8 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
JsonData: sjson,
|
JsonData: sjson,
|
||||||
}
|
}
|
||||||
@ -495,10 +495,10 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: "kubernetes",
|
Name: "kubernetes",
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
JsonData: sjson,
|
JsonData: sjson,
|
||||||
}
|
}
|
||||||
@ -508,7 +508,7 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = secretsStore.Set(context.Background(), ds.OrgId, ds.Name, secretskvs.DataSourceSecretType, string(secureJsonData))
|
err = secretsStore.Set(context.Background(), ds.OrgID, ds.Name, secretskvs.DataSourceSecretType, string(secureJsonData))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
headers := dsService.getCustomHeaders(sjson, map[string]string{"httpHeaderValue1": "Bearer xf5yhfkpsnmgo"})
|
headers := dsService.getCustomHeaders(sjson, map[string]string{"httpHeaderValue1": "Bearer xf5yhfkpsnmgo"})
|
||||||
@ -530,7 +530,7 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
defer backend.Close()
|
defer backend.Close()
|
||||||
|
|
||||||
// 2. Get HTTP transport from datasource which uses the test server as backend
|
// 2. Get HTTP transport from datasource which uses the test server as backend
|
||||||
ds.Url = backend.URL
|
ds.URL = backend.URL
|
||||||
rt, err := dsService.GetHTTPTransport(context.Background(), &ds, provider)
|
rt, err := dsService.GetHTTPTransport(context.Background(), &ds, provider)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NotNil(t, rt)
|
require.NotNil(t, rt)
|
||||||
@ -563,8 +563,8 @@ func TestService_GetHttpTransport(t *testing.T) {
|
|||||||
dsService, err := ProvideService(sqlStore, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService(), quotaService)
|
dsService, err := ProvideService(sqlStore, secretsService, secretsStore, cfg, featuremgmt.WithFeatures(), acmock.New(), acmock.NewMockedPermissionsService(), quotaService)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
Url: "http://k8s:8001",
|
URL: "http://k8s:8001",
|
||||||
Type: "Kubernetes",
|
Type: "Kubernetes",
|
||||||
JsonData: sjson,
|
JsonData: sjson,
|
||||||
}
|
}
|
||||||
@ -649,8 +649,8 @@ func TestService_getTimeout(t *testing.T) {
|
|||||||
func TestService_GetDecryptedValues(t *testing.T) {
|
func TestService_GetDecryptedValues(t *testing.T) {
|
||||||
t.Run("should migrate and retrieve values from secure json data", func(t *testing.T) {
|
t.Run("should migrate and retrieve values from secure json data", func(t *testing.T) {
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
Url: "https://api.example.com",
|
URL: "https://api.example.com",
|
||||||
Type: "prometheus",
|
Type: "prometheus",
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -677,8 +677,8 @@ func TestService_GetDecryptedValues(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("should retrieve values from secret store", func(t *testing.T) {
|
t.Run("should retrieve values from secret store", func(t *testing.T) {
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Id: 1,
|
ID: 1,
|
||||||
Url: "https://api.example.com",
|
URL: "https://api.example.com",
|
||||||
Type: "prometheus",
|
Type: "prometheus",
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -695,7 +695,7 @@ func TestService_GetDecryptedValues(t *testing.T) {
|
|||||||
jsonString, err := json.Marshal(jsonData)
|
jsonString, err := json.Marshal(jsonData)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = secretsStore.Set(context.Background(), ds.OrgId, ds.Name, secretskvs.DataSourceSecretType, string(jsonString))
|
err = secretsStore.Set(context.Background(), ds.OrgID, ds.Name, secretskvs.DataSourceSecretType, string(jsonString))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
values, err := dsService.DecryptedValues(context.Background(), ds)
|
values, err := dsService.DecryptedValues(context.Background(), ds)
|
||||||
|
@ -55,15 +55,15 @@ func (ss *SqlStore) GetDataSource(ctx context.Context, query *datasources.GetDat
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ss *SqlStore) getDataSource(ctx context.Context, query *datasources.GetDataSourceQuery, sess *db.Session) error {
|
func (ss *SqlStore) getDataSource(ctx context.Context, query *datasources.GetDataSourceQuery, sess *db.Session) error {
|
||||||
if query.OrgId == 0 || (query.Id == 0 && len(query.Name) == 0 && len(query.Uid) == 0) {
|
if query.OrgID == 0 || (query.ID == 0 && len(query.Name) == 0 && len(query.UID) == 0) {
|
||||||
return datasources.ErrDataSourceIdentifierNotSet
|
return datasources.ErrDataSourceIdentifierNotSet
|
||||||
}
|
}
|
||||||
|
|
||||||
datasource := &datasources.DataSource{Name: query.Name, OrgId: query.OrgId, Id: query.Id, Uid: query.Uid}
|
datasource := &datasources.DataSource{Name: query.Name, OrgID: query.OrgID, ID: query.ID, UID: query.UID}
|
||||||
has, err := sess.Get(datasource)
|
has, err := sess.Get(datasource)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ss.logger.Error("Failed getting data source", "err", err, "uid", query.Uid, "id", query.Id, "name", query.Name, "orgId", query.OrgId)
|
ss.logger.Error("Failed getting data source", "err", err, "uid", query.UID, "id", query.ID, "name", query.Name, "orgId", query.OrgID)
|
||||||
return err
|
return err
|
||||||
} else if !has {
|
} else if !has {
|
||||||
return datasources.ErrDataSourceNotFound
|
return datasources.ErrDataSourceNotFound
|
||||||
@ -78,9 +78,9 @@ func (ss *SqlStore) GetDataSources(ctx context.Context, query *datasources.GetDa
|
|||||||
var sess *xorm.Session
|
var sess *xorm.Session
|
||||||
return ss.db.WithDbSession(ctx, func(dbSess *db.Session) error {
|
return ss.db.WithDbSession(ctx, func(dbSess *db.Session) error {
|
||||||
if query.DataSourceLimit <= 0 {
|
if query.DataSourceLimit <= 0 {
|
||||||
sess = dbSess.Where("org_id=?", query.OrgId).Asc("name")
|
sess = dbSess.Where("org_id=?", query.OrgID).Asc("name")
|
||||||
} else {
|
} else {
|
||||||
sess = dbSess.Limit(query.DataSourceLimit, 0).Where("org_id=?", query.OrgId).Asc("name")
|
sess = dbSess.Limit(query.DataSourceLimit, 0).Where("org_id=?", query.OrgID).Asc("name")
|
||||||
}
|
}
|
||||||
|
|
||||||
query.Result = make([]*datasources.DataSource, 0)
|
query.Result = make([]*datasources.DataSource, 0)
|
||||||
@ -103,8 +103,8 @@ func (ss *SqlStore) GetDataSourcesByType(ctx context.Context, query *datasources
|
|||||||
|
|
||||||
query.Result = make([]*datasources.DataSource, 0)
|
query.Result = make([]*datasources.DataSource, 0)
|
||||||
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
|
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
|
||||||
if query.OrgId > 0 {
|
if query.OrgID > 0 {
|
||||||
return sess.Where("type=? AND org_id=?", query.Type, query.OrgId).Asc("id").Find(&query.Result)
|
return sess.Where("type=? AND org_id=?", query.Type, query.OrgID).Asc("id").Find(&query.Result)
|
||||||
}
|
}
|
||||||
return sess.Where("type=?", query.Type).Asc("id").Find(&query.Result)
|
return sess.Where("type=?", query.Type).Asc("id").Find(&query.Result)
|
||||||
})
|
})
|
||||||
@ -114,7 +114,7 @@ func (ss *SqlStore) GetDataSourcesByType(ctx context.Context, query *datasources
|
|||||||
func (ss *SqlStore) GetDefaultDataSource(ctx context.Context, query *datasources.GetDefaultDataSourceQuery) error {
|
func (ss *SqlStore) GetDefaultDataSource(ctx context.Context, query *datasources.GetDefaultDataSourceQuery) error {
|
||||||
datasource := datasources.DataSource{}
|
datasource := datasources.DataSource{}
|
||||||
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
|
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
|
||||||
exists, err := sess.Where("org_id=? AND is_default=?", query.OrgId, true).Get(&datasource)
|
exists, err := sess.Where("org_id=? AND is_default=?", query.OrgID, true).Get(&datasource)
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
return datasources.ErrDataSourceNotFound
|
return datasources.ErrDataSourceNotFound
|
||||||
@ -129,7 +129,7 @@ func (ss *SqlStore) GetDefaultDataSource(ctx context.Context, query *datasources
|
|||||||
// and is added to the bus. It also removes permissions related to the datasource.
|
// and is added to the bus. It also removes permissions related to the datasource.
|
||||||
func (ss *SqlStore) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteDataSourceCommand) error {
|
func (ss *SqlStore) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteDataSourceCommand) error {
|
||||||
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
||||||
dsQuery := &datasources.GetDataSourceQuery{Id: cmd.ID, Uid: cmd.UID, Name: cmd.Name, OrgId: cmd.OrgID}
|
dsQuery := &datasources.GetDataSourceQuery{ID: cmd.ID, UID: cmd.UID, Name: cmd.Name, OrgID: cmd.OrgID}
|
||||||
errGettingDS := ss.getDataSource(ctx, dsQuery, sess)
|
errGettingDS := ss.getDataSource(ctx, dsQuery, sess)
|
||||||
|
|
||||||
if errGettingDS != nil && !errors.Is(errGettingDS, datasources.ErrDataSourceNotFound) {
|
if errGettingDS != nil && !errors.Is(errGettingDS, datasources.ErrDataSourceNotFound) {
|
||||||
@ -139,7 +139,7 @@ func (ss *SqlStore) DeleteDataSource(ctx context.Context, cmd *datasources.Delet
|
|||||||
ds := dsQuery.Result
|
ds := dsQuery.Result
|
||||||
if ds != nil {
|
if ds != nil {
|
||||||
// Delete the data source
|
// Delete the data source
|
||||||
result, err := sess.Exec("DELETE FROM data_source WHERE org_id=? AND id=?", ds.OrgId, ds.Id)
|
result, err := sess.Exec("DELETE FROM data_source WHERE org_id=? AND id=?", ds.OrgID, ds.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -148,7 +148,7 @@ func (ss *SqlStore) DeleteDataSource(ctx context.Context, cmd *datasources.Delet
|
|||||||
|
|
||||||
// Remove associated AccessControl permissions
|
// Remove associated AccessControl permissions
|
||||||
if _, errDeletingPerms := sess.Exec("DELETE FROM permission WHERE scope=?",
|
if _, errDeletingPerms := sess.Exec("DELETE FROM permission WHERE scope=?",
|
||||||
ac.Scope(datasources.ScopeProvider.GetResourceScope(dsQuery.Result.Uid))); errDeletingPerms != nil {
|
ac.Scope(datasources.ScopeProvider.GetResourceScope(dsQuery.Result.UID))); errDeletingPerms != nil {
|
||||||
return errDeletingPerms
|
return errDeletingPerms
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -165,9 +165,9 @@ func (ss *SqlStore) DeleteDataSource(ctx context.Context, cmd *datasources.Delet
|
|||||||
sess.PublishAfterCommit(&events.DataSourceDeleted{
|
sess.PublishAfterCommit(&events.DataSourceDeleted{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
OrgID: ds.OrgId,
|
OrgID: ds.OrgID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -221,7 +221,7 @@ func (ss *SqlStore) Count(ctx context.Context, scopeParams *quota.ScopeParameter
|
|||||||
|
|
||||||
func (ss *SqlStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) error {
|
func (ss *SqlStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) error {
|
||||||
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
|
||||||
existing := datasources.DataSource{OrgId: cmd.OrgId, Name: cmd.Name}
|
existing := datasources.DataSource{OrgID: cmd.OrgID, Name: cmd.Name}
|
||||||
has, _ := sess.Get(&existing)
|
has, _ := sess.Get(&existing)
|
||||||
|
|
||||||
if has {
|
if has {
|
||||||
@ -232,20 +232,20 @@ func (ss *SqlStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataS
|
|||||||
cmd.JsonData = simplejson.New()
|
cmd.JsonData = simplejson.New()
|
||||||
}
|
}
|
||||||
|
|
||||||
if cmd.Uid == "" {
|
if cmd.UID == "" {
|
||||||
uid, err := generateNewDatasourceUid(sess, cmd.OrgId)
|
uid, err := generateNewDatasourceUid(sess, cmd.OrgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to generate UID for datasource %q: %w", cmd.Name, err)
|
return fmt.Errorf("failed to generate UID for datasource %q: %w", cmd.Name, err)
|
||||||
}
|
}
|
||||||
cmd.Uid = uid
|
cmd.UID = uid
|
||||||
}
|
}
|
||||||
|
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgID,
|
||||||
Name: cmd.Name,
|
Name: cmd.Name,
|
||||||
Type: cmd.Type,
|
Type: cmd.Type,
|
||||||
Access: cmd.Access,
|
Access: cmd.Access,
|
||||||
Url: cmd.Url,
|
URL: cmd.URL,
|
||||||
User: cmd.User,
|
User: cmd.User,
|
||||||
Database: cmd.Database,
|
Database: cmd.Database,
|
||||||
IsDefault: cmd.IsDefault,
|
IsDefault: cmd.IsDefault,
|
||||||
@ -258,7 +258,7 @@ func (ss *SqlStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataS
|
|||||||
Updated: time.Now(),
|
Updated: time.Now(),
|
||||||
Version: 1,
|
Version: 1,
|
||||||
ReadOnly: cmd.ReadOnly,
|
ReadOnly: cmd.ReadOnly,
|
||||||
Uid: cmd.Uid,
|
UID: cmd.UID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := sess.Insert(ds); err != nil {
|
if _, err := sess.Insert(ds); err != nil {
|
||||||
@ -273,7 +273,7 @@ func (ss *SqlStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataS
|
|||||||
|
|
||||||
if cmd.UpdateSecretFn != nil {
|
if cmd.UpdateSecretFn != nil {
|
||||||
if err := cmd.UpdateSecretFn(); err != nil {
|
if err := cmd.UpdateSecretFn(); err != nil {
|
||||||
// ss.logger.Error("Failed to update datasource secrets -- rolling back update", "name", cmd.Name, "type", cmd.Type, "orgId", cmd.OrgId)
|
// ss.logger.Error("Failed to update datasource secrets -- rolling back update", "name", cmd.Name, "type", cmd.Type, "orgId", cmd.OrgID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -283,9 +283,9 @@ func (ss *SqlStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataS
|
|||||||
sess.PublishAfterCommit(&events.DataSourceCreated{
|
sess.PublishAfterCommit(&events.DataSourceCreated{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Name: cmd.Name,
|
Name: cmd.Name,
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
UID: cmd.Uid,
|
UID: cmd.UID,
|
||||||
OrgID: cmd.OrgId,
|
OrgID: cmd.OrgID,
|
||||||
})
|
})
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@ -295,7 +295,7 @@ func updateIsDefaultFlag(ds *datasources.DataSource, sess *db.Session) error {
|
|||||||
// Handle is default flag
|
// Handle is default flag
|
||||||
if ds.IsDefault {
|
if ds.IsDefault {
|
||||||
rawSQL := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
|
rawSQL := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
|
||||||
if _, err := sess.Exec(rawSQL, false, ds.OrgId, ds.Id); err != nil {
|
if _, err := sess.Exec(rawSQL, false, ds.OrgID, ds.ID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -309,12 +309,12 @@ func (ss *SqlStore) UpdateDataSource(ctx context.Context, cmd *datasources.Updat
|
|||||||
}
|
}
|
||||||
|
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Id: cmd.Id,
|
ID: cmd.ID,
|
||||||
OrgId: cmd.OrgId,
|
OrgID: cmd.OrgID,
|
||||||
Name: cmd.Name,
|
Name: cmd.Name,
|
||||||
Type: cmd.Type,
|
Type: cmd.Type,
|
||||||
Access: cmd.Access,
|
Access: cmd.Access,
|
||||||
Url: cmd.Url,
|
URL: cmd.URL,
|
||||||
User: cmd.User,
|
User: cmd.User,
|
||||||
Database: cmd.Database,
|
Database: cmd.Database,
|
||||||
IsDefault: cmd.IsDefault,
|
IsDefault: cmd.IsDefault,
|
||||||
@ -326,7 +326,7 @@ func (ss *SqlStore) UpdateDataSource(ctx context.Context, cmd *datasources.Updat
|
|||||||
Updated: time.Now(),
|
Updated: time.Now(),
|
||||||
ReadOnly: cmd.ReadOnly,
|
ReadOnly: cmd.ReadOnly,
|
||||||
Version: cmd.Version + 1,
|
Version: cmd.Version + 1,
|
||||||
Uid: cmd.Uid,
|
UID: cmd.UID,
|
||||||
}
|
}
|
||||||
|
|
||||||
sess.UseBool("is_default")
|
sess.UseBool("is_default")
|
||||||
@ -349,9 +349,9 @@ func (ss *SqlStore) UpdateDataSource(ctx context.Context, cmd *datasources.Updat
|
|||||||
// the reason we allow cmd.version > db.version is make it possible for people to force
|
// the reason we allow cmd.version > db.version is make it possible for people to force
|
||||||
// updates to datasources using the datasource.yaml file without knowing exactly what version
|
// updates to datasources using the datasource.yaml file without knowing exactly what version
|
||||||
// a datasource have in the db.
|
// a datasource have in the db.
|
||||||
updateSession = sess.Where("id=? and org_id=? and version < ?", ds.Id, ds.OrgId, ds.Version)
|
updateSession = sess.Where("id=? and org_id=? and version < ?", ds.ID, ds.OrgID, ds.Version)
|
||||||
} else {
|
} else {
|
||||||
updateSession = sess.Where("id=? and org_id=?", ds.Id, ds.OrgId)
|
updateSession = sess.Where("id=? and org_id=?", ds.ID, ds.OrgID)
|
||||||
}
|
}
|
||||||
|
|
||||||
affected, err := updateSession.Update(ds)
|
affected, err := updateSession.Update(ds)
|
||||||
@ -367,7 +367,7 @@ func (ss *SqlStore) UpdateDataSource(ctx context.Context, cmd *datasources.Updat
|
|||||||
|
|
||||||
if cmd.UpdateSecretFn != nil {
|
if cmd.UpdateSecretFn != nil {
|
||||||
if err := cmd.UpdateSecretFn(); err != nil {
|
if err := cmd.UpdateSecretFn(); err != nil {
|
||||||
ss.logger.Error("Failed to update datasource secrets -- rolling back update", "UID", cmd.Uid, "name", cmd.Name, "type", cmd.Type, "orgId", cmd.OrgId)
|
ss.logger.Error("Failed to update datasource secrets -- rolling back update", "UID", cmd.UID, "name", cmd.Name, "type", cmd.Type, "orgId", cmd.OrgID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,19 +21,19 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
t.Skip("skipping integration test")
|
t.Skip("skipping integration test")
|
||||||
}
|
}
|
||||||
defaultAddDatasourceCommand := datasources.AddDataSourceCommand{
|
defaultAddDatasourceCommand := datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "nisse",
|
Name: "nisse",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultUpdateDatasourceCommand := datasources.UpdateDataSourceCommand{
|
defaultUpdateDatasourceCommand := datasources.UpdateDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "nisse_updated",
|
Name: "nisse_updated",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
}
|
}
|
||||||
|
|
||||||
initDatasource := func(db db.DB) *datasources.DataSource {
|
initDatasource := func(db db.DB) *datasources.DataSource {
|
||||||
@ -42,7 +42,7 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
err := ss.AddDataSource(context.Background(), &cmd)
|
err := ss.AddDataSource(context.Background(), &cmd)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
err = ss.GetDataSources(context.Background(), &query)
|
err = ss.GetDataSources(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, 1, len(query.Result))
|
require.Equal(t, 1, len(query.Result))
|
||||||
@ -55,24 +55,24 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
db := db.InitTestDB(t)
|
db := db.InitTestDB(t)
|
||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "laban",
|
Name: "laban",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
err = ss.GetDataSources(context.Background(), &query)
|
err = ss.GetDataSources(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
require.Equal(t, 1, len(query.Result))
|
require.Equal(t, 1, len(query.Result))
|
||||||
ds := query.Result[0]
|
ds := query.Result[0]
|
||||||
|
|
||||||
require.EqualValues(t, 10, ds.OrgId)
|
require.EqualValues(t, 10, ds.OrgID)
|
||||||
require.Equal(t, "site", ds.Database)
|
require.Equal(t, "site", ds.Database)
|
||||||
require.True(t, ds.ReadOnly)
|
require.True(t, ds.ReadOnly)
|
||||||
})
|
})
|
||||||
@ -80,7 +80,7 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
t.Run("generates uid if not specified", func(t *testing.T) {
|
t.Run("generates uid if not specified", func(t *testing.T) {
|
||||||
db := db.InitTestDB(t)
|
db := db.InitTestDB(t)
|
||||||
ds := initDatasource(db)
|
ds := initDatasource(db)
|
||||||
require.NotEmpty(t, ds.Uid)
|
require.NotEmpty(t, ds.UID)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("fails to insert ds with same uid", func(t *testing.T) {
|
t.Run("fails to insert ds with same uid", func(t *testing.T) {
|
||||||
@ -88,8 +88,8 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
cmd1 := defaultAddDatasourceCommand
|
cmd1 := defaultAddDatasourceCommand
|
||||||
cmd2 := defaultAddDatasourceCommand
|
cmd2 := defaultAddDatasourceCommand
|
||||||
cmd1.Uid = "test"
|
cmd1.UID = "test"
|
||||||
cmd2.Uid = "test"
|
cmd2.UID = "test"
|
||||||
err := ss.AddDataSource(context.Background(), &cmd1)
|
err := ss.AddDataSource(context.Background(), &cmd1)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
err = ss.AddDataSource(context.Background(), &cmd2)
|
err = ss.AddDataSource(context.Background(), &cmd2)
|
||||||
@ -113,13 +113,13 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
return assert.NotNil(t, created)
|
return assert.NotNil(t, created)
|
||||||
}, time.Second, time.Millisecond)
|
}, time.Second, time.Millisecond)
|
||||||
|
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
err = sqlStore.GetDataSources(context.Background(), &query)
|
err = sqlStore.GetDataSources(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, 1, len(query.Result))
|
require.Equal(t, 1, len(query.Result))
|
||||||
|
|
||||||
require.Equal(t, query.Result[0].Id, created.ID)
|
require.Equal(t, query.Result[0].ID, created.ID)
|
||||||
require.Equal(t, query.Result[0].Uid, created.UID)
|
require.Equal(t, query.Result[0].UID, created.UID)
|
||||||
require.Equal(t, int64(10), created.OrgID)
|
require.Equal(t, int64(10), created.OrgID)
|
||||||
require.Equal(t, "nisse", created.Name)
|
require.Equal(t, "nisse", created.Name)
|
||||||
})
|
})
|
||||||
@ -130,28 +130,28 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
db := db.InitTestDB(t)
|
db := db.InitTestDB(t)
|
||||||
ds := initDatasource(db)
|
ds := initDatasource(db)
|
||||||
cmd := defaultUpdateDatasourceCommand
|
cmd := defaultUpdateDatasourceCommand
|
||||||
cmd.Id = ds.Id
|
cmd.ID = ds.ID
|
||||||
cmd.Version = ds.Version
|
cmd.Version = ds.Version
|
||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
err := ss.UpdateDataSource(context.Background(), &cmd)
|
err := ss.UpdateDataSource(context.Background(), &cmd)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("does not overwrite Uid if not specified", func(t *testing.T) {
|
t.Run("does not overwrite UID if not specified", func(t *testing.T) {
|
||||||
db := db.InitTestDB(t)
|
db := db.InitTestDB(t)
|
||||||
ds := initDatasource(db)
|
ds := initDatasource(db)
|
||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
require.NotEmpty(t, ds.Uid)
|
require.NotEmpty(t, ds.UID)
|
||||||
|
|
||||||
cmd := defaultUpdateDatasourceCommand
|
cmd := defaultUpdateDatasourceCommand
|
||||||
cmd.Id = ds.Id
|
cmd.ID = ds.ID
|
||||||
err := ss.UpdateDataSource(context.Background(), &cmd)
|
err := ss.UpdateDataSource(context.Background(), &cmd)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDataSourceQuery{Id: ds.Id, OrgId: 10}
|
query := datasources.GetDataSourceQuery{ID: ds.ID, OrgID: 10}
|
||||||
err = ss.GetDataSource(context.Background(), &query)
|
err = ss.GetDataSource(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, ds.Uid, query.Result.Uid)
|
require.Equal(t, ds.UID, query.Result.UID)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("prevents update if version changed", func(t *testing.T) {
|
t.Run("prevents update if version changed", func(t *testing.T) {
|
||||||
@ -160,12 +160,12 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
cmd := datasources.UpdateDataSourceCommand{
|
cmd := datasources.UpdateDataSourceCommand{
|
||||||
Id: ds.Id,
|
ID: ds.ID,
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "nisse",
|
Name: "nisse",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Version: ds.Version,
|
Version: ds.Version,
|
||||||
}
|
}
|
||||||
// Make a copy as UpdateDataSource modifies it
|
// Make a copy as UpdateDataSource modifies it
|
||||||
@ -184,12 +184,12 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
cmd := &datasources.UpdateDataSourceCommand{
|
cmd := &datasources.UpdateDataSourceCommand{
|
||||||
Id: ds.Id,
|
ID: ds.ID,
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "nisse",
|
Name: "nisse",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
}
|
}
|
||||||
|
|
||||||
err := ss.UpdateDataSource(context.Background(), cmd)
|
err := ss.UpdateDataSource(context.Background(), cmd)
|
||||||
@ -202,12 +202,12 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
cmd := &datasources.UpdateDataSourceCommand{
|
cmd := &datasources.UpdateDataSourceCommand{
|
||||||
Id: ds.Id,
|
ID: ds.ID,
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "nisse",
|
Name: "nisse",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Version: 90000,
|
Version: 90000,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -222,10 +222,10 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ds := initDatasource(db)
|
ds := initDatasource(db)
|
||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
err := ss.DeleteDataSource(context.Background(), &datasources.DeleteDataSourceCommand{ID: ds.Id, OrgID: ds.OrgId})
|
err := ss.DeleteDataSource(context.Background(), &datasources.DeleteDataSourceCommand{ID: ds.ID, OrgID: ds.OrgID})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
err = ss.GetDataSources(context.Background(), &query)
|
err = ss.GetDataSources(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
@ -238,10 +238,10 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
err := ss.DeleteDataSource(context.Background(),
|
err := ss.DeleteDataSource(context.Background(),
|
||||||
&datasources.DeleteDataSourceCommand{ID: ds.Id, OrgID: 123123})
|
&datasources.DeleteDataSourceCommand{ID: ds.ID, OrgID: 123123})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
err = ss.GetDataSources(context.Background(), &query)
|
err = ss.GetDataSources(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
@ -261,17 +261,17 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
err := ss.DeleteDataSource(context.Background(),
|
err := ss.DeleteDataSource(context.Background(),
|
||||||
&datasources.DeleteDataSourceCommand{ID: ds.Id, UID: ds.Uid, Name: ds.Name, OrgID: ds.OrgId})
|
&datasources.DeleteDataSourceCommand{ID: ds.ID, UID: ds.UID, Name: ds.Name, OrgID: ds.OrgID})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
require.Eventually(t, func() bool {
|
require.Eventually(t, func() bool {
|
||||||
return assert.NotNil(t, deleted)
|
return assert.NotNil(t, deleted)
|
||||||
}, time.Second, time.Millisecond)
|
}, time.Second, time.Millisecond)
|
||||||
|
|
||||||
require.Equal(t, ds.Id, deleted.ID)
|
require.Equal(t, ds.ID, deleted.ID)
|
||||||
require.Equal(t, ds.OrgId, deleted.OrgID)
|
require.Equal(t, ds.OrgID, deleted.OrgID)
|
||||||
require.Equal(t, ds.Name, deleted.Name)
|
require.Equal(t, ds.Name, deleted.Name)
|
||||||
require.Equal(t, ds.Uid, deleted.UID)
|
require.Equal(t, ds.UID, deleted.UID)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("does not fire an event when the datasource is not deleted", func(t *testing.T) {
|
t.Run("does not fire an event when the datasource is not deleted", func(t *testing.T) {
|
||||||
@ -297,9 +297,9 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
db := db.InitTestDB(t)
|
db := db.InitTestDB(t)
|
||||||
ds := initDatasource(db)
|
ds := initDatasource(db)
|
||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
|
|
||||||
err := ss.DeleteDataSource(context.Background(), &datasources.DeleteDataSourceCommand{Name: ds.Name, OrgID: ds.OrgId})
|
err := ss.DeleteDataSource(context.Background(), &datasources.DeleteDataSourceCommand{Name: ds.Name, OrgID: ds.OrgID})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = ss.GetDataSources(context.Background(), &query)
|
err = ss.GetDataSources(context.Background(), &query)
|
||||||
@ -318,17 +318,17 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
_, err := sess.Table("permission").Insert(ac.Permission{
|
_, err := sess.Table("permission").Insert(ac.Permission{
|
||||||
RoleID: 1,
|
RoleID: 1,
|
||||||
Action: "datasources:read",
|
Action: "datasources:read",
|
||||||
Scope: datasources.ScopeProvider.GetResourceScope(ds.Uid),
|
Scope: datasources.ScopeProvider.GetResourceScope(ds.UID),
|
||||||
Updated: time.Now(),
|
Updated: time.Now(),
|
||||||
Created: time.Now(),
|
Created: time.Now(),
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
require.NoError(t, errAddPermissions)
|
require.NoError(t, errAddPermissions)
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
|
|
||||||
errDeletingDS := ss.DeleteDataSource(context.Background(),
|
errDeletingDS := ss.DeleteDataSource(context.Background(),
|
||||||
&datasources.DeleteDataSourceCommand{Name: ds.Name, OrgID: ds.OrgId},
|
&datasources.DeleteDataSourceCommand{Name: ds.Name, OrgID: ds.OrgID},
|
||||||
)
|
)
|
||||||
require.NoError(t, errDeletingDS)
|
require.NoError(t, errDeletingDS)
|
||||||
|
|
||||||
@ -352,17 +352,17 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
datasourceLimit := 6
|
datasourceLimit := 6
|
||||||
for i := 0; i < datasourceLimit+1; i++ {
|
for i := 0; i < datasourceLimit+1; i++ {
|
||||||
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "laban" + strconv.Itoa(i),
|
Name: "laban" + strconv.Itoa(i),
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10, DataSourceLimit: datasourceLimit}
|
query := datasources.GetDataSourcesQuery{OrgID: 10, DataSourceLimit: datasourceLimit}
|
||||||
|
|
||||||
err := ss.GetDataSources(context.Background(), &query)
|
err := ss.GetDataSources(context.Background(), &query)
|
||||||
|
|
||||||
@ -376,17 +376,17 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
numberOfDatasource := 5100
|
numberOfDatasource := 5100
|
||||||
for i := 0; i < numberOfDatasource; i++ {
|
for i := 0; i < numberOfDatasource; i++ {
|
||||||
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "laban" + strconv.Itoa(i),
|
Name: "laban" + strconv.Itoa(i),
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10}
|
query := datasources.GetDataSourcesQuery{OrgID: 10}
|
||||||
|
|
||||||
err := ss.GetDataSources(context.Background(), &query)
|
err := ss.GetDataSources(context.Background(), &query)
|
||||||
|
|
||||||
@ -400,17 +400,17 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
numberOfDatasource := 5100
|
numberOfDatasource := 5100
|
||||||
for i := 0; i < numberOfDatasource; i++ {
|
for i := 0; i < numberOfDatasource; i++ {
|
||||||
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "laban" + strconv.Itoa(i),
|
Name: "laban" + strconv.Itoa(i),
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
query := datasources.GetDataSourcesQuery{OrgId: 10, DataSourceLimit: -1}
|
query := datasources.GetDataSourcesQuery{OrgID: 10, DataSourceLimit: -1}
|
||||||
|
|
||||||
err := ss.GetDataSources(context.Background(), &query)
|
err := ss.GetDataSources(context.Background(), &query)
|
||||||
|
|
||||||
@ -425,22 +425,22 @@ func TestIntegrationDataAccess(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "Elasticsearch",
|
Name: "Elasticsearch",
|
||||||
Type: datasources.DS_ES,
|
Type: datasources.DS_ES,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err = ss.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "Graphite",
|
Name: "Graphite",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
@ -477,17 +477,17 @@ func TestIntegrationGetDefaultDataSource(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
cmd := datasources.AddDataSourceCommand{
|
cmd := datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "nisse",
|
Name: "nisse",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
}
|
}
|
||||||
|
|
||||||
err := ss.AddDataSource(context.Background(), &cmd)
|
err := ss.AddDataSource(context.Background(), &cmd)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDefaultDataSourceQuery{OrgId: 10}
|
query := datasources.GetDefaultDataSourceQuery{OrgID: 10}
|
||||||
err = ss.GetDefaultDataSource(context.Background(), &query)
|
err = ss.GetDefaultDataSource(context.Background(), &query)
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
assert.True(t, errors.Is(err, datasources.ErrDataSourceNotFound))
|
assert.True(t, errors.Is(err, datasources.ErrDataSourceNotFound))
|
||||||
@ -498,18 +498,18 @@ func TestIntegrationGetDefaultDataSource(t *testing.T) {
|
|||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
|
|
||||||
cmd := datasources.AddDataSourceCommand{
|
cmd := datasources.AddDataSourceCommand{
|
||||||
OrgId: 10,
|
OrgID: 10,
|
||||||
Name: "default datasource",
|
Name: "default datasource",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
IsDefault: true,
|
IsDefault: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := ss.AddDataSource(context.Background(), &cmd)
|
err := ss.AddDataSource(context.Background(), &cmd)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
query := datasources.GetDefaultDataSourceQuery{OrgId: 10}
|
query := datasources.GetDefaultDataSourceQuery{OrgID: 10}
|
||||||
err = ss.GetDefaultDataSource(context.Background(), &query)
|
err = ss.GetDefaultDataSource(context.Background(), &query)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, "default datasource", query.Result.Name)
|
assert.Equal(t, "default datasource", query.Result.Name)
|
||||||
@ -518,7 +518,7 @@ func TestIntegrationGetDefaultDataSource(t *testing.T) {
|
|||||||
t.Run("should not return default datasource of other organisation", func(t *testing.T) {
|
t.Run("should not return default datasource of other organisation", func(t *testing.T) {
|
||||||
db := db.InitTestDB(t)
|
db := db.InitTestDB(t)
|
||||||
ss := SqlStore{db: db}
|
ss := SqlStore{db: db}
|
||||||
query := datasources.GetDefaultDataSourceQuery{OrgId: 1}
|
query := datasources.GetDefaultDataSourceQuery{OrgID: 1}
|
||||||
err := ss.GetDefaultDataSource(context.Background(), &query)
|
err := ss.GetDefaultDataSource(context.Background(), &query)
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
assert.True(t, errors.Is(err, datasources.ErrDataSourceNotFound))
|
assert.True(t, errors.Is(err, datasources.ErrDataSourceNotFound))
|
||||||
|
@ -10,7 +10,7 @@ import (
|
|||||||
|
|
||||||
func exportDataSources(helper *commitHelper, job *gitExportJob) error {
|
func exportDataSources(helper *commitHelper, job *gitExportJob) error {
|
||||||
cmd := &datasources.GetDataSourcesQuery{
|
cmd := &datasources.GetDataSourcesQuery{
|
||||||
OrgId: helper.orgID,
|
OrgID: helper.orgID,
|
||||||
}
|
}
|
||||||
err := job.datasourceService.GetDataSources(helper.ctx, cmd)
|
err := job.datasourceService.GetDataSources(helper.ctx, cmd)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -22,7 +22,7 @@ func exportDataSources(helper *commitHelper, job *gitExportJob) error {
|
|||||||
})
|
})
|
||||||
|
|
||||||
for _, ds := range cmd.Result {
|
for _, ds := range cmd.Result {
|
||||||
ds.OrgId = 0
|
ds.OrgID = 0
|
||||||
ds.Version = 0
|
ds.Version = 0
|
||||||
ds.SecureJsonData = map[string][]byte{
|
ds.SecureJsonData = map[string][]byte{
|
||||||
"TODO": []byte("XXX"),
|
"TODO": []byte("XXX"),
|
||||||
@ -31,7 +31,7 @@ func exportDataSources(helper *commitHelper, job *gitExportJob) error {
|
|||||||
err := helper.add(commitOptions{
|
err := helper.add(commitOptions{
|
||||||
body: []commitBody{
|
body: []commitBody{
|
||||||
{
|
{
|
||||||
fpath: filepath.Join(helper.orgDir, "datasources", fmt.Sprintf("%s-ds.json", ds.Uid)),
|
fpath: filepath.Join(helper.orgDir, "datasources", fmt.Sprintf("%s-ds.json", ds.UID)),
|
||||||
body: prettyJSON(ds),
|
body: prettyJSON(ds),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
@ -949,7 +949,7 @@ func (g *GrafanaLive) handleDatasourceScope(ctx context.Context, user *user.Sign
|
|||||||
}
|
}
|
||||||
return features.NewPluginRunner(
|
return features.NewPluginRunner(
|
||||||
ds.Type,
|
ds.Type,
|
||||||
ds.Uid,
|
ds.UID,
|
||||||
g.runStreamManager,
|
g.runStreamManager,
|
||||||
g.contextGetter,
|
g.contextGetter,
|
||||||
streamHandler,
|
streamHandler,
|
||||||
|
@ -118,7 +118,7 @@ func (srv ConfigSrv) RouteDeleteNGalertConfig(c *contextmodel.ReqContext) respon
|
|||||||
func (srv ConfigSrv) externalAlertmanagers(ctx context.Context, orgID int64) ([]string, error) {
|
func (srv ConfigSrv) externalAlertmanagers(ctx context.Context, orgID int64) ([]string, error) {
|
||||||
var alertmanagers []string
|
var alertmanagers []string
|
||||||
query := &datasources.GetDataSourcesByTypeQuery{
|
query := &datasources.GetDataSourcesByTypeQuery{
|
||||||
OrgId: orgID,
|
OrgID: orgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
}
|
}
|
||||||
err := srv.datasourceService.GetDataSourcesByType(ctx, query)
|
err := srv.datasourceService.GetDataSourcesByType(ctx, query)
|
||||||
@ -129,7 +129,7 @@ func (srv ConfigSrv) externalAlertmanagers(ctx context.Context, orgID int64) ([]
|
|||||||
if ds.JsonData.Get(apimodels.HandleGrafanaManagedAlerts).MustBool(false) {
|
if ds.JsonData.Get(apimodels.HandleGrafanaManagedAlerts).MustBool(false) {
|
||||||
// we don't need to build the exact URL as we only need
|
// we don't need to build the exact URL as we only need
|
||||||
// to know if any is set
|
// to know if any is set
|
||||||
alertmanagers = append(alertmanagers, ds.Uid)
|
alertmanagers = append(alertmanagers, ds.UID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return alertmanagers, nil
|
return alertmanagers, nil
|
||||||
|
@ -28,9 +28,9 @@ func TestExternalAlertmanagerChoice(t *testing.T) {
|
|||||||
alertmanagerChoice: definitions.ExternalAlertmanagers,
|
alertmanagerChoice: definitions.ExternalAlertmanagers,
|
||||||
datasources: []*datasources.DataSource{
|
datasources: []*datasources.DataSource{
|
||||||
{
|
{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
Url: "http://localhost:9000",
|
URL: "http://localhost:9000",
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
definitions.HandleGrafanaManagedAlerts: true,
|
definitions.HandleGrafanaManagedAlerts: true,
|
||||||
}),
|
}),
|
||||||
@ -44,9 +44,9 @@ func TestExternalAlertmanagerChoice(t *testing.T) {
|
|||||||
alertmanagerChoice: definitions.ExternalAlertmanagers,
|
alertmanagerChoice: definitions.ExternalAlertmanagers,
|
||||||
datasources: []*datasources.DataSource{
|
datasources: []*datasources.DataSource{
|
||||||
{
|
{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
Url: "http://localhost:9000",
|
URL: "http://localhost:9000",
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{}),
|
JsonData: simplejson.NewFromAny(map[string]interface{}{}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
@ -67,8 +67,8 @@ func TestRouteTestGrafanaRuleConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
||||||
{Uid: data1.DatasourceUID},
|
{UID: data1.DatasourceUID},
|
||||||
{Uid: data2.DatasourceUID},
|
{UID: data2.DatasourceUID},
|
||||||
}}
|
}}
|
||||||
|
|
||||||
var result []eval.Result
|
var result []eval.Result
|
||||||
@ -110,7 +110,7 @@ func TestRouteTestGrafanaRuleConfig(t *testing.T) {
|
|||||||
data1 := models.GenerateAlertQuery()
|
data1 := models.GenerateAlertQuery()
|
||||||
|
|
||||||
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
||||||
{Uid: data1.DatasourceUID},
|
{UID: data1.DatasourceUID},
|
||||||
}}
|
}}
|
||||||
currentTime := time.Now()
|
currentTime := time.Now()
|
||||||
|
|
||||||
@ -193,8 +193,8 @@ func TestRouteEvalQueries(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
||||||
{Uid: data1.DatasourceUID},
|
{UID: data1.DatasourceUID},
|
||||||
{Uid: data2.DatasourceUID},
|
{UID: data2.DatasourceUID},
|
||||||
}}
|
}}
|
||||||
|
|
||||||
evaluator := &eval_mocks.ConditionEvaluatorMock{}
|
evaluator := &eval_mocks.ConditionEvaluatorMock{}
|
||||||
@ -237,7 +237,7 @@ func TestRouteEvalQueries(t *testing.T) {
|
|||||||
data1 := models.GenerateAlertQuery()
|
data1 := models.GenerateAlertQuery()
|
||||||
|
|
||||||
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
ds := &fakes.FakeCacheService{DataSources: []*datasources.DataSource{
|
||||||
{Uid: data1.DatasourceUID},
|
{UID: data1.DatasourceUID},
|
||||||
}}
|
}}
|
||||||
|
|
||||||
currentTime := time.Now()
|
currentTime := time.Now()
|
||||||
|
@ -87,7 +87,7 @@ func (p *LotexProm) getEndpoints(ctx *contextmodel.ReqContext) (*promEndpoints,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if ds.Url == "" {
|
if ds.URL == "" {
|
||||||
return nil, fmt.Errorf("URL for this data source is empty")
|
return nil, fmt.Errorf("URL for this data source is empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -185,7 +185,7 @@ func (r *LotexRuler) validateAndGetPrefix(ctx *contextmodel.ReqContext) (string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate URL
|
// Validate URL
|
||||||
if ds.Url == "" {
|
if ds.URL == "" {
|
||||||
return "", fmt.Errorf("URL for this data source is empty")
|
return "", fmt.Errorf("URL for this data source is empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -206,12 +206,12 @@ func (r *LotexRuler) validateAndGetPrefix(ctx *contextmodel.ReqContext) (string,
|
|||||||
if !ok {
|
if !ok {
|
||||||
r.log.Debug(
|
r.log.Debug(
|
||||||
"Unable to determine prometheus datasource subtype, using default prefix",
|
"Unable to determine prometheus datasource subtype, using default prefix",
|
||||||
"datasource", ds.Uid, "datasourceType", ds.Type, "subtype", subtype, "prefix", prefix)
|
"datasource", ds.UID, "datasourceType", ds.Type, "subtype", subtype, "prefix", prefix)
|
||||||
return prefix, nil
|
return prefix, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
r.log.Debug("Determined prometheus datasource subtype",
|
r.log.Debug("Determined prometheus datasource subtype",
|
||||||
"datasource", ds.Uid, "datasourceType", ds.Type, "subtype", subtype)
|
"datasource", ds.UID, "datasourceType", ds.Type, "subtype", subtype)
|
||||||
return subTypePrefix, nil
|
return subTypePrefix, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -45,46 +45,46 @@ func TestLotexRuler_ValidateAndGetPrefix(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "with an unsupported datasource type",
|
name: "with an unsupported datasource type",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com"}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com"}},
|
||||||
err: errors.New("unexpected datasource type. expecting loki or prometheus"),
|
err: errors.New("unexpected datasource type. expecting loki or prometheus"),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "with a Loki datasource",
|
name: "with a Loki datasource",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com", Type: LokiDatasourceType}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com", Type: LokiDatasourceType}},
|
||||||
expected: "/api/prom/rules",
|
expected: "/api/prom/rules",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "with a Prometheus datasource",
|
name: "with a Prometheus datasource",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com", Type: PrometheusDatasourceType}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com", Type: PrometheusDatasourceType}},
|
||||||
expected: "/rules",
|
expected: "/rules",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "with a Prometheus datasource and subtype of Cortex",
|
name: "with a Prometheus datasource and subtype of Cortex",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
urlParams: "?subtype=cortex",
|
urlParams: "?subtype=cortex",
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com", Type: PrometheusDatasourceType}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com", Type: PrometheusDatasourceType}},
|
||||||
expected: "/rules",
|
expected: "/rules",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "with a Prometheus datasource and subtype of Mimir",
|
name: "with a Prometheus datasource and subtype of Mimir",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
urlParams: "?subtype=mimir",
|
urlParams: "?subtype=mimir",
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com", Type: PrometheusDatasourceType}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com", Type: PrometheusDatasourceType}},
|
||||||
expected: "/config/v1/rules",
|
expected: "/config/v1/rules",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "with a Prometheus datasource and subtype of Prometheus",
|
name: "with a Prometheus datasource and subtype of Prometheus",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
urlParams: "?subtype=prometheus",
|
urlParams: "?subtype=prometheus",
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com", Type: PrometheusDatasourceType}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com", Type: PrometheusDatasourceType}},
|
||||||
expected: "/rules",
|
expected: "/rules",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "with a Prometheus datasource and no subtype",
|
name: "with a Prometheus datasource and no subtype",
|
||||||
namedParams: map[string]string{":DatasourceUID": "d164"},
|
namedParams: map[string]string{":DatasourceUID": "d164"},
|
||||||
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{Url: "http://loki.com", Type: PrometheusDatasourceType}},
|
datasourceCache: fakeCacheService{datasource: &datasources.DataSource{URL: "http://loki.com", Type: PrometheusDatasourceType}},
|
||||||
expected: "/rules",
|
expected: "/rules",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -605,7 +605,7 @@ func (e *evaluatorImpl) Validate(ctx EvaluationContext, condition models.Conditi
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, query := range req.Queries {
|
for _, query := range req.Queries {
|
||||||
if query.DataSource == nil || expr.IsDataSource(query.DataSource.Uid) {
|
if query.DataSource == nil || expr.IsDataSource(query.DataSource.UID) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
p, found := e.pluginsStore.Plugin(ctx.Ctx, query.DataSource.Type)
|
p, found := e.pluginsStore.Plugin(ctx.Ctx, query.DataSource.Type)
|
||||||
|
@ -380,7 +380,7 @@ func TestValidate(t *testing.T) {
|
|||||||
condition: func(services services) models.Condition {
|
condition: func(services services) models.Condition {
|
||||||
dsQuery := models.GenerateAlertQuery()
|
dsQuery := models.GenerateAlertQuery()
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Uid: dsQuery.DatasourceUID,
|
UID: dsQuery.DatasourceUID,
|
||||||
Type: util.GenerateShortUID(),
|
Type: util.GenerateShortUID(),
|
||||||
}
|
}
|
||||||
services.cache.DataSources = append(services.cache.DataSources, ds)
|
services.cache.DataSources = append(services.cache.DataSources, ds)
|
||||||
@ -406,7 +406,7 @@ func TestValidate(t *testing.T) {
|
|||||||
condition: func(services services) models.Condition {
|
condition: func(services services) models.Condition {
|
||||||
dsQuery := models.GenerateAlertQuery()
|
dsQuery := models.GenerateAlertQuery()
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Uid: dsQuery.DatasourceUID,
|
UID: dsQuery.DatasourceUID,
|
||||||
Type: util.GenerateShortUID(),
|
Type: util.GenerateShortUID(),
|
||||||
}
|
}
|
||||||
services.cache.DataSources = append(services.cache.DataSources, ds)
|
services.cache.DataSources = append(services.cache.DataSources, ds)
|
||||||
@ -445,7 +445,7 @@ func TestValidate(t *testing.T) {
|
|||||||
condition: func(services services) models.Condition {
|
condition: func(services services) models.Condition {
|
||||||
dsQuery := models.GenerateAlertQuery()
|
dsQuery := models.GenerateAlertQuery()
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Uid: dsQuery.DatasourceUID,
|
UID: dsQuery.DatasourceUID,
|
||||||
Type: util.GenerateShortUID(),
|
Type: util.GenerateShortUID(),
|
||||||
}
|
}
|
||||||
services.cache.DataSources = append(services.cache.DataSources, ds)
|
services.cache.DataSources = append(services.cache.DataSources, ds)
|
||||||
@ -465,11 +465,11 @@ func TestValidate(t *testing.T) {
|
|||||||
dsQuery1 := models.GenerateAlertQuery()
|
dsQuery1 := models.GenerateAlertQuery()
|
||||||
dsQuery2 := models.GenerateAlertQuery()
|
dsQuery2 := models.GenerateAlertQuery()
|
||||||
ds1 := &datasources.DataSource{
|
ds1 := &datasources.DataSource{
|
||||||
Uid: dsQuery1.DatasourceUID,
|
UID: dsQuery1.DatasourceUID,
|
||||||
Type: util.GenerateShortUID(),
|
Type: util.GenerateShortUID(),
|
||||||
}
|
}
|
||||||
ds2 := &datasources.DataSource{
|
ds2 := &datasources.DataSource{
|
||||||
Uid: dsQuery2.DatasourceUID,
|
UID: dsQuery2.DatasourceUID,
|
||||||
Type: util.GenerateShortUID(),
|
Type: util.GenerateShortUID(),
|
||||||
}
|
}
|
||||||
services.cache.DataSources = append(services.cache.DataSources, ds1, ds2)
|
services.cache.DataSources = append(services.cache.DataSources, ds1, ds2)
|
||||||
@ -500,7 +500,7 @@ func TestValidate(t *testing.T) {
|
|||||||
condition: func(services services) models.Condition {
|
condition: func(services services) models.Condition {
|
||||||
dsQuery := models.GenerateAlertQuery()
|
dsQuery := models.GenerateAlertQuery()
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Uid: dsQuery.DatasourceUID,
|
UID: dsQuery.DatasourceUID,
|
||||||
Type: util.GenerateShortUID(),
|
Type: util.GenerateShortUID(),
|
||||||
}
|
}
|
||||||
services.cache.DataSources = append(services.cache.DataSources, ds)
|
services.cache.DataSources = append(services.cache.DataSources, ds)
|
||||||
|
@ -209,7 +209,7 @@ func (d *AlertsRouter) alertmanagersFromDatasources(orgID int64) ([]string, erro
|
|||||||
// We might have alertmanager datasources that are acting as external
|
// We might have alertmanager datasources that are acting as external
|
||||||
// alertmanager, let's fetch them.
|
// alertmanager, let's fetch them.
|
||||||
query := &datasources.GetDataSourcesByTypeQuery{
|
query := &datasources.GetDataSourcesByTypeQuery{
|
||||||
OrgId: orgID,
|
OrgID: orgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||||
@ -225,8 +225,8 @@ func (d *AlertsRouter) alertmanagersFromDatasources(orgID int64) ([]string, erro
|
|||||||
amURL, err := d.buildExternalURL(ds)
|
amURL, err := d.buildExternalURL(ds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
d.logger.Error("Failed to build external alertmanager URL",
|
d.logger.Error("Failed to build external alertmanager URL",
|
||||||
"org", ds.OrgId,
|
"org", ds.OrgID,
|
||||||
"uid", ds.Uid,
|
"uid", ds.UID,
|
||||||
"error", err)
|
"error", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -238,7 +238,7 @@ func (d *AlertsRouter) alertmanagersFromDatasources(orgID int64) ([]string, erro
|
|||||||
func (d *AlertsRouter) buildExternalURL(ds *datasources.DataSource) (string, error) {
|
func (d *AlertsRouter) buildExternalURL(ds *datasources.DataSource) (string, error) {
|
||||||
// We re-use the same parsing logic as the datasource to make sure it matches whatever output the user received
|
// We re-use the same parsing logic as the datasource to make sure it matches whatever output the user received
|
||||||
// when doing the healthcheck.
|
// when doing the healthcheck.
|
||||||
parsed, err := datasource.ValidateURL(datasources.DS_ALERTMANAGER, ds.Url)
|
parsed, err := datasource.ValidateURL(datasources.DS_ALERTMANAGER, ds.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("failed to parse alertmanager datasource url: %w", err)
|
return "", fmt.Errorf("failed to parse alertmanager datasource url: %w", err)
|
||||||
}
|
}
|
||||||
|
@ -53,8 +53,8 @@ func TestIntegrationSendingToExternalAlertmanager(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ds1 := datasources.DataSource{
|
ds1 := datasources.DataSource{
|
||||||
Url: fakeAM.Server.URL,
|
URL: fakeAM.Server.URL,
|
||||||
OrgId: ruleKey.OrgID,
|
OrgID: ruleKey.OrgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
@ -123,8 +123,8 @@ func TestIntegrationSendingToExternalAlertmanager_WithMultipleOrgs(t *testing.T)
|
|||||||
}
|
}
|
||||||
|
|
||||||
ds1 := datasources.DataSource{
|
ds1 := datasources.DataSource{
|
||||||
Url: fakeAM.Server.URL,
|
URL: fakeAM.Server.URL,
|
||||||
OrgId: ruleKey1.OrgID,
|
OrgID: ruleKey1.OrgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
@ -150,8 +150,8 @@ func TestIntegrationSendingToExternalAlertmanager_WithMultipleOrgs(t *testing.T)
|
|||||||
|
|
||||||
// 1. Now, let's assume a new org comes along.
|
// 1. Now, let's assume a new org comes along.
|
||||||
ds2 := datasources.DataSource{
|
ds2 := datasources.DataSource{
|
||||||
Url: fakeAM.Server.URL,
|
URL: fakeAM.Server.URL,
|
||||||
OrgId: ruleKey2.OrgID,
|
OrgID: ruleKey2.OrgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
@ -196,8 +196,8 @@ func TestIntegrationSendingToExternalAlertmanager_WithMultipleOrgs(t *testing.T)
|
|||||||
// 2. Next, let's modify the configuration of an organization by adding an extra alertmanager.
|
// 2. Next, let's modify the configuration of an organization by adding an extra alertmanager.
|
||||||
fakeAM2 := NewFakeExternalAlertmanager(t)
|
fakeAM2 := NewFakeExternalAlertmanager(t)
|
||||||
ds3 := datasources.DataSource{
|
ds3 := datasources.DataSource{
|
||||||
Url: fakeAM2.Server.URL,
|
URL: fakeAM2.Server.URL,
|
||||||
OrgId: ruleKey2.OrgID,
|
OrgID: ruleKey2.OrgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
@ -225,7 +225,7 @@ func TestIntegrationSendingToExternalAlertmanager_WithMultipleOrgs(t *testing.T)
|
|||||||
assertAlertmanagersStatusForOrg(t, alertsRouter, ruleKey2.OrgID, 2, 0)
|
assertAlertmanagersStatusForOrg(t, alertsRouter, ruleKey2.OrgID, 2, 0)
|
||||||
|
|
||||||
// 3. Now, let's provide a configuration that fails for OrgID = 1.
|
// 3. Now, let's provide a configuration that fails for OrgID = 1.
|
||||||
fakeDs.DataSources[0].Url = "123://invalid.org"
|
fakeDs.DataSources[0].URL = "123://invalid.org"
|
||||||
mockedGetAdminConfigurations.Return([]*models.AdminConfiguration{
|
mockedGetAdminConfigurations.Return([]*models.AdminConfiguration{
|
||||||
{OrgID: ruleKey1.OrgID, SendAlertsTo: models.AllAlertmanagers},
|
{OrgID: ruleKey1.OrgID, SendAlertsTo: models.AllAlertmanagers},
|
||||||
{OrgID: ruleKey2.OrgID},
|
{OrgID: ruleKey2.OrgID},
|
||||||
@ -242,7 +242,7 @@ func TestIntegrationSendingToExternalAlertmanager_WithMultipleOrgs(t *testing.T)
|
|||||||
require.Equal(t, 0, len(alertsRouter.AlertmanagersFor(ruleKey1.OrgID)))
|
require.Equal(t, 0, len(alertsRouter.AlertmanagersFor(ruleKey1.OrgID)))
|
||||||
|
|
||||||
// If we fix it - it should be applied.
|
// If we fix it - it should be applied.
|
||||||
fakeDs.DataSources[0].Url = "notarealalertmanager:3030"
|
fakeDs.DataSources[0].URL = "notarealalertmanager:3030"
|
||||||
mockedGetAdminConfigurations.Return([]*models.AdminConfiguration{
|
mockedGetAdminConfigurations.Return([]*models.AdminConfiguration{
|
||||||
{OrgID: ruleKey1.OrgID, SendAlertsTo: models.AllAlertmanagers},
|
{OrgID: ruleKey1.OrgID, SendAlertsTo: models.AllAlertmanagers},
|
||||||
{OrgID: ruleKey2.OrgID},
|
{OrgID: ruleKey2.OrgID},
|
||||||
@ -283,8 +283,8 @@ func TestChangingAlertmanagersChoice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ds := datasources.DataSource{
|
ds := datasources.DataSource{
|
||||||
Url: fakeAM.Server.URL,
|
URL: fakeAM.Server.URL,
|
||||||
OrgId: ruleKey.OrgID,
|
OrgID: ruleKey.OrgID,
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
@ -437,21 +437,21 @@ func TestBuildExternalURL(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "datasource without auth",
|
name: "datasource without auth",
|
||||||
ds: &datasources.DataSource{
|
ds: &datasources.DataSource{
|
||||||
Url: "https://localhost:9000",
|
URL: "https://localhost:9000",
|
||||||
},
|
},
|
||||||
expectedURL: "https://localhost:9000",
|
expectedURL: "https://localhost:9000",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "datasource without auth and with path",
|
name: "datasource without auth and with path",
|
||||||
ds: &datasources.DataSource{
|
ds: &datasources.DataSource{
|
||||||
Url: "https://localhost:9000/path/to/am",
|
URL: "https://localhost:9000/path/to/am",
|
||||||
},
|
},
|
||||||
expectedURL: "https://localhost:9000/path/to/am",
|
expectedURL: "https://localhost:9000/path/to/am",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "datasource with auth",
|
name: "datasource with auth",
|
||||||
ds: &datasources.DataSource{
|
ds: &datasources.DataSource{
|
||||||
Url: "https://localhost:9000",
|
URL: "https://localhost:9000",
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "johndoe",
|
BasicAuthUser: "johndoe",
|
||||||
SecureJsonData: map[string][]byte{
|
SecureJsonData: map[string][]byte{
|
||||||
@ -463,7 +463,7 @@ func TestBuildExternalURL(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "datasource with auth and path",
|
name: "datasource with auth and path",
|
||||||
ds: &datasources.DataSource{
|
ds: &datasources.DataSource{
|
||||||
Url: "https://localhost:9000/path/to/am",
|
URL: "https://localhost:9000/path/to/am",
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "johndoe",
|
BasicAuthUser: "johndoe",
|
||||||
SecureJsonData: map[string][]byte{
|
SecureJsonData: map[string][]byte{
|
||||||
@ -475,7 +475,7 @@ func TestBuildExternalURL(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "with no scheme specified in the datasource",
|
name: "with no scheme specified in the datasource",
|
||||||
ds: &datasources.DataSource{
|
ds: &datasources.DataSource{
|
||||||
Url: "localhost:9000/path/to/am",
|
URL: "localhost:9000/path/to/am",
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "johndoe",
|
BasicAuthUser: "johndoe",
|
||||||
SecureJsonData: map[string][]byte{
|
SecureJsonData: map[string][]byte{
|
||||||
@ -487,7 +487,7 @@ func TestBuildExternalURL(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "with no scheme specified not auth in the datasource",
|
name: "with no scheme specified not auth in the datasource",
|
||||||
ds: &datasources.DataSource{
|
ds: &datasources.DataSource{
|
||||||
Url: "localhost:9000/path/to/am",
|
URL: "localhost:9000/path/to/am",
|
||||||
},
|
},
|
||||||
expectedURL: "http://localhost:9000/path/to/am",
|
expectedURL: "http://localhost:9000/path/to/am",
|
||||||
},
|
},
|
||||||
|
@ -44,8 +44,8 @@ func (m *CookiesMiddleware) applyCookies(ctx context.Context, pCtx backend.Plugi
|
|||||||
}
|
}
|
||||||
|
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Id: settings.ID,
|
ID: settings.ID,
|
||||||
OrgId: pCtx.OrgID,
|
OrgID: pCtx.OrgID,
|
||||||
JsonData: jsonDataBytes,
|
JsonData: jsonDataBytes,
|
||||||
Updated: settings.Updated,
|
Updated: settings.Updated,
|
||||||
}
|
}
|
||||||
|
@ -48,8 +48,8 @@ func (m *OAuthTokenMiddleware) applyToken(ctx context.Context, pCtx backend.Plug
|
|||||||
}
|
}
|
||||||
|
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
Id: settings.ID,
|
ID: settings.ID,
|
||||||
OrgId: pCtx.OrgID,
|
OrgID: pCtx.OrgID,
|
||||||
JsonData: jsonDataBytes,
|
JsonData: jsonDataBytes,
|
||||||
Updated: settings.Updated,
|
Updated: settings.Updated,
|
||||||
}
|
}
|
||||||
|
@ -44,15 +44,15 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
require.Equal(t, len(store.inserted), 1)
|
require.Equal(t, len(store.inserted), 1)
|
||||||
require.Equal(t, store.inserted[0].OrgId, int64(1))
|
require.Equal(t, store.inserted[0].OrgID, int64(1))
|
||||||
require.Equal(t, store.inserted[0].Access, datasources.DsAccess("proxy"))
|
require.Equal(t, store.inserted[0].Access, datasources.DsAccess("proxy"))
|
||||||
require.Equal(t, store.inserted[0].Name, "My datasource name")
|
require.Equal(t, store.inserted[0].Name, "My datasource name")
|
||||||
require.Equal(t, store.inserted[0].Uid, "P2AD1F727255C56BA")
|
require.Equal(t, store.inserted[0].UID, "P2AD1F727255C56BA")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("when some values missing should not change UID when updates", func(t *testing.T) {
|
t.Run("when some values missing should not change UID when updates", func(t *testing.T) {
|
||||||
store := &spyStore{
|
store := &spyStore{
|
||||||
items: []*datasources.DataSource{{Name: "My datasource name", OrgId: 1, Id: 1, Uid: util.GenerateShortUID()}},
|
items: []*datasources.DataSource{{Name: "My datasource name", OrgID: 1, ID: 1, UID: util.GenerateShortUID()}},
|
||||||
}
|
}
|
||||||
orgFake := &orgtest.FakeOrgService{}
|
orgFake := &orgtest.FakeOrgService{}
|
||||||
correlationsStore := &mockCorrelationsStore{}
|
correlationsStore := &mockCorrelationsStore{}
|
||||||
@ -65,7 +65,7 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
require.Equal(t, len(store.deleted), 0)
|
require.Equal(t, len(store.deleted), 0)
|
||||||
require.Equal(t, len(store.inserted), 0)
|
require.Equal(t, len(store.inserted), 0)
|
||||||
require.Equal(t, len(store.updated), 1)
|
require.Equal(t, len(store.updated), 1)
|
||||||
require.Equal(t, "", store.updated[0].Uid) // XORM will not update the field if its value is default
|
require.Equal(t, "", store.updated[0].UID) // XORM will not update the field if its value is default
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("no datasource in database", func(t *testing.T) {
|
t.Run("no datasource in database", func(t *testing.T) {
|
||||||
@ -84,7 +84,7 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("One datasource in database with same name should update one datasource", func(t *testing.T) {
|
t.Run("One datasource in database with same name should update one datasource", func(t *testing.T) {
|
||||||
store := &spyStore{items: []*datasources.DataSource{{Name: "Graphite", OrgId: 1, Id: 1}}}
|
store := &spyStore{items: []*datasources.DataSource{{Name: "Graphite", OrgID: 1, ID: 1}}}
|
||||||
orgFake := &orgtest.FakeOrgService{}
|
orgFake := &orgtest.FakeOrgService{}
|
||||||
correlationsStore := &mockCorrelationsStore{}
|
correlationsStore := &mockCorrelationsStore{}
|
||||||
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
||||||
@ -116,9 +116,9 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, len(store.inserted), 4)
|
require.Equal(t, len(store.inserted), 4)
|
||||||
require.True(t, store.inserted[0].IsDefault)
|
require.True(t, store.inserted[0].IsDefault)
|
||||||
require.Equal(t, store.inserted[0].OrgId, int64(1))
|
require.Equal(t, store.inserted[0].OrgID, int64(1))
|
||||||
require.True(t, store.inserted[2].IsDefault)
|
require.True(t, store.inserted[2].IsDefault)
|
||||||
require.Equal(t, store.inserted[2].OrgId, int64(2))
|
require.Equal(t, store.inserted[2].OrgID, int64(2))
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Remove one datasource should have removed old datasource", func(t *testing.T) {
|
t.Run("Remove one datasource should have removed old datasource", func(t *testing.T) {
|
||||||
@ -139,7 +139,7 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Two configured datasource and purge others", func(t *testing.T) {
|
t.Run("Two configured datasource and purge others", func(t *testing.T) {
|
||||||
store := &spyStore{items: []*datasources.DataSource{{Name: "old-graphite", OrgId: 1, Id: 1}, {Name: "old-graphite2", OrgId: 1, Id: 2}}}
|
store := &spyStore{items: []*datasources.DataSource{{Name: "old-graphite", OrgID: 1, ID: 1}, {Name: "old-graphite2", OrgID: 1, ID: 2}}}
|
||||||
orgFake := &orgtest.FakeOrgService{}
|
orgFake := &orgtest.FakeOrgService{}
|
||||||
correlationsStore := &mockCorrelationsStore{}
|
correlationsStore := &mockCorrelationsStore{}
|
||||||
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
||||||
@ -154,7 +154,7 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Two configured datasource and purge others = false", func(t *testing.T) {
|
t.Run("Two configured datasource and purge others = false", func(t *testing.T) {
|
||||||
store := &spyStore{items: []*datasources.DataSource{{Name: "Graphite", OrgId: 1, Id: 1}, {Name: "old-graphite2", OrgId: 1, Id: 2}}}
|
store := &spyStore{items: []*datasources.DataSource{{Name: "Graphite", OrgID: 1, ID: 1}, {Name: "old-graphite2", OrgID: 1, ID: 2}}}
|
||||||
orgFake := &orgtest.FakeOrgService{}
|
orgFake := &orgtest.FakeOrgService{}
|
||||||
correlationsStore := &mockCorrelationsStore{}
|
correlationsStore := &mockCorrelationsStore{}
|
||||||
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
||||||
@ -255,7 +255,7 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Updating existing datasource deletes existing correlations and creates two", func(t *testing.T) {
|
t.Run("Updating existing datasource deletes existing correlations and creates two", func(t *testing.T) {
|
||||||
store := &spyStore{items: []*datasources.DataSource{{Name: "Graphite", OrgId: 1, Id: 1}}}
|
store := &spyStore{items: []*datasources.DataSource{{Name: "Graphite", OrgID: 1, ID: 1}}}
|
||||||
orgFake := &orgtest.FakeOrgService{}
|
orgFake := &orgtest.FakeOrgService{}
|
||||||
correlationsStore := &mockCorrelationsStore{}
|
correlationsStore := &mockCorrelationsStore{}
|
||||||
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
dc := newDatasourceProvisioner(logger, store, correlationsStore, orgFake)
|
||||||
@ -270,7 +270,7 @@ func TestDatasourceAsConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Deleting datasource deletes existing correlations", func(t *testing.T) {
|
t.Run("Deleting datasource deletes existing correlations", func(t *testing.T) {
|
||||||
store := &spyStore{items: []*datasources.DataSource{{Name: "old-data-source", OrgId: 1, Id: 1, Uid: "some-uid"}}}
|
store := &spyStore{items: []*datasources.DataSource{{Name: "old-data-source", OrgID: 1, ID: 1, UID: "some-uid"}}}
|
||||||
orgFake := &orgtest.FakeOrgService{}
|
orgFake := &orgtest.FakeOrgService{}
|
||||||
targetUid := "target-uid"
|
targetUid := "target-uid"
|
||||||
correlationsStore := &mockCorrelationsStore{items: []correlations.Correlation{{UID: "some-uid", SourceUID: "some-uid", TargetUID: &targetUid}}}
|
correlationsStore := &mockCorrelationsStore{items: []correlations.Correlation{{UID: "some-uid", SourceUID: "some-uid", TargetUID: &targetUid}}}
|
||||||
@ -369,7 +369,7 @@ type spyStore struct {
|
|||||||
|
|
||||||
func (s *spyStore) GetDataSource(ctx context.Context, query *datasources.GetDataSourceQuery) error {
|
func (s *spyStore) GetDataSource(ctx context.Context, query *datasources.GetDataSourceQuery) error {
|
||||||
for _, v := range s.items {
|
for _, v := range s.items {
|
||||||
if query.Name == v.Name && query.OrgId == v.OrgId {
|
if query.Name == v.Name && query.OrgID == v.OrgID {
|
||||||
query.Result = v
|
query.Result = v
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -380,7 +380,7 @@ func (s *spyStore) GetDataSource(ctx context.Context, query *datasources.GetData
|
|||||||
func (s *spyStore) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteDataSourceCommand) error {
|
func (s *spyStore) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteDataSourceCommand) error {
|
||||||
s.deleted = append(s.deleted, cmd)
|
s.deleted = append(s.deleted, cmd)
|
||||||
for _, v := range s.items {
|
for _, v := range s.items {
|
||||||
if cmd.Name == v.Name && cmd.OrgID == v.OrgId {
|
if cmd.Name == v.Name && cmd.OrgID == v.OrgID {
|
||||||
cmd.DeletedDatasourcesCount = 1
|
cmd.DeletedDatasourcesCount = 1
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -391,7 +391,7 @@ func (s *spyStore) DeleteDataSource(ctx context.Context, cmd *datasources.Delete
|
|||||||
func (s *spyStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) error {
|
func (s *spyStore) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) error {
|
||||||
s.inserted = append(s.inserted, cmd)
|
s.inserted = append(s.inserted, cmd)
|
||||||
cmd.Result = &datasources.DataSource{
|
cmd.Result = &datasources.DataSource{
|
||||||
Uid: cmd.Uid,
|
UID: cmd.UID,
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -65,7 +65,7 @@ func (dc *DatasourceProvisioner) apply(ctx context.Context, cfg *configs) error
|
|||||||
correlationsToInsert := make([]correlations.CreateCorrelationCommand, 0)
|
correlationsToInsert := make([]correlations.CreateCorrelationCommand, 0)
|
||||||
|
|
||||||
for _, ds := range cfg.Datasources {
|
for _, ds := range cfg.Datasources {
|
||||||
cmd := &datasources.GetDataSourceQuery{OrgId: ds.OrgID, Name: ds.Name}
|
cmd := &datasources.GetDataSourceQuery{OrgID: ds.OrgID, Name: ds.Name}
|
||||||
err := dc.store.GetDataSource(ctx, cmd)
|
err := dc.store.GetDataSource(ctx, cmd)
|
||||||
if err != nil && !errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if err != nil && !errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
return err
|
return err
|
||||||
@ -73,13 +73,13 @@ func (dc *DatasourceProvisioner) apply(ctx context.Context, cfg *configs) error
|
|||||||
|
|
||||||
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
insertCmd := createInsertCommand(ds)
|
insertCmd := createInsertCommand(ds)
|
||||||
dc.log.Info("inserting datasource from configuration ", "name", insertCmd.Name, "uid", insertCmd.Uid)
|
dc.log.Info("inserting datasource from configuration ", "name", insertCmd.Name, "uid", insertCmd.UID)
|
||||||
if err := dc.store.AddDataSource(ctx, insertCmd); err != nil {
|
if err := dc.store.AddDataSource(ctx, insertCmd); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, correlation := range ds.Correlations {
|
for _, correlation := range ds.Correlations {
|
||||||
if insertCorrelationCmd, err := makeCreateCorrelationCommand(correlation, insertCmd.Result.Uid, insertCmd.OrgId); err == nil {
|
if insertCorrelationCmd, err := makeCreateCorrelationCommand(correlation, insertCmd.Result.UID, insertCmd.OrgID); err == nil {
|
||||||
correlationsToInsert = append(correlationsToInsert, insertCorrelationCmd)
|
correlationsToInsert = append(correlationsToInsert, insertCorrelationCmd)
|
||||||
} else {
|
} else {
|
||||||
dc.log.Error("failed to parse correlation", "correlation", correlation)
|
dc.log.Error("failed to parse correlation", "correlation", correlation)
|
||||||
@ -87,22 +87,22 @@ func (dc *DatasourceProvisioner) apply(ctx context.Context, cfg *configs) error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
updateCmd := createUpdateCommand(ds, cmd.Result.Id)
|
updateCmd := createUpdateCommand(ds, cmd.Result.ID)
|
||||||
dc.log.Debug("updating datasource from configuration", "name", updateCmd.Name, "uid", updateCmd.Uid)
|
dc.log.Debug("updating datasource from configuration", "name", updateCmd.Name, "uid", updateCmd.UID)
|
||||||
if err := dc.store.UpdateDataSource(ctx, updateCmd); err != nil {
|
if err := dc.store.UpdateDataSource(ctx, updateCmd); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(ds.Correlations) > 0 {
|
if len(ds.Correlations) > 0 {
|
||||||
if err := dc.correlationsStore.DeleteCorrelationsBySourceUID(ctx, correlations.DeleteCorrelationsBySourceUIDCommand{
|
if err := dc.correlationsStore.DeleteCorrelationsBySourceUID(ctx, correlations.DeleteCorrelationsBySourceUIDCommand{
|
||||||
SourceUID: cmd.Result.Uid,
|
SourceUID: cmd.Result.UID,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, correlation := range ds.Correlations {
|
for _, correlation := range ds.Correlations {
|
||||||
if insertCorrelationCmd, err := makeCreateCorrelationCommand(correlation, cmd.Result.Uid, updateCmd.OrgId); err == nil {
|
if insertCorrelationCmd, err := makeCreateCorrelationCommand(correlation, cmd.Result.UID, updateCmd.OrgID); err == nil {
|
||||||
correlationsToInsert = append(correlationsToInsert, insertCorrelationCmd)
|
correlationsToInsert = append(correlationsToInsert, insertCorrelationCmd)
|
||||||
} else {
|
} else {
|
||||||
dc.log.Error("failed to parse correlation", "correlation", correlation)
|
dc.log.Error("failed to parse correlation", "correlation", correlation)
|
||||||
@ -179,7 +179,7 @@ func makeCreateCorrelationCommand(correlation map[string]interface{}, SourceUID
|
|||||||
func (dc *DatasourceProvisioner) deleteDatasources(ctx context.Context, dsToDelete []*deleteDatasourceConfig) error {
|
func (dc *DatasourceProvisioner) deleteDatasources(ctx context.Context, dsToDelete []*deleteDatasourceConfig) error {
|
||||||
for _, ds := range dsToDelete {
|
for _, ds := range dsToDelete {
|
||||||
cmd := &datasources.DeleteDataSourceCommand{OrgID: ds.OrgID, Name: ds.Name}
|
cmd := &datasources.DeleteDataSourceCommand{OrgID: ds.OrgID, Name: ds.Name}
|
||||||
getDsQuery := &datasources.GetDataSourceQuery{Name: ds.Name, OrgId: ds.OrgID}
|
getDsQuery := &datasources.GetDataSourceQuery{Name: ds.Name, OrgID: ds.OrgID}
|
||||||
if err := dc.store.GetDataSource(ctx, getDsQuery); err != nil && !errors.Is(err, datasources.ErrDataSourceNotFound) {
|
if err := dc.store.GetDataSource(ctx, getDsQuery); err != nil && !errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -190,13 +190,13 @@ func (dc *DatasourceProvisioner) deleteDatasources(ctx context.Context, dsToDele
|
|||||||
|
|
||||||
if getDsQuery.Result != nil {
|
if getDsQuery.Result != nil {
|
||||||
if err := dc.correlationsStore.DeleteCorrelationsBySourceUID(ctx, correlations.DeleteCorrelationsBySourceUIDCommand{
|
if err := dc.correlationsStore.DeleteCorrelationsBySourceUID(ctx, correlations.DeleteCorrelationsBySourceUIDCommand{
|
||||||
SourceUID: getDsQuery.Result.Uid,
|
SourceUID: getDsQuery.Result.UID,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := dc.correlationsStore.DeleteCorrelationsByTargetUID(ctx, correlations.DeleteCorrelationsByTargetUIDCommand{
|
if err := dc.correlationsStore.DeleteCorrelationsByTargetUID(ctx, correlations.DeleteCorrelationsByTargetUIDCommand{
|
||||||
TargetUID: getDsQuery.Result.Uid,
|
TargetUID: getDsQuery.Result.UID,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -203,11 +203,11 @@ func createInsertCommand(ds *upsertDataSourceFromConfig) *datasources.AddDataSou
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmd := &datasources.AddDataSourceCommand{
|
cmd := &datasources.AddDataSourceCommand{
|
||||||
OrgId: ds.OrgID,
|
OrgID: ds.OrgID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
Access: datasources.DsAccess(ds.Access),
|
Access: datasources.DsAccess(ds.Access),
|
||||||
Url: ds.URL,
|
URL: ds.URL,
|
||||||
User: ds.User,
|
User: ds.User,
|
||||||
Database: ds.Database,
|
Database: ds.Database,
|
||||||
BasicAuth: ds.BasicAuth,
|
BasicAuth: ds.BasicAuth,
|
||||||
@ -217,11 +217,11 @@ func createInsertCommand(ds *upsertDataSourceFromConfig) *datasources.AddDataSou
|
|||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
SecureJsonData: ds.SecureJSONData,
|
SecureJsonData: ds.SecureJSONData,
|
||||||
ReadOnly: !ds.Editable,
|
ReadOnly: !ds.Editable,
|
||||||
Uid: ds.UID,
|
UID: ds.UID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if cmd.Uid == "" {
|
if cmd.UID == "" {
|
||||||
cmd.Uid = safeUIDFromName(cmd.Name)
|
cmd.UID = safeUIDFromName(cmd.Name)
|
||||||
}
|
}
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
@ -242,13 +242,13 @@ func createUpdateCommand(ds *upsertDataSourceFromConfig, id int64) *datasources.
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &datasources.UpdateDataSourceCommand{
|
return &datasources.UpdateDataSourceCommand{
|
||||||
Id: id,
|
ID: id,
|
||||||
Uid: ds.UID,
|
UID: ds.UID,
|
||||||
OrgId: ds.OrgID,
|
OrgID: ds.OrgID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
Access: datasources.DsAccess(ds.Access),
|
Access: datasources.DsAccess(ds.Access),
|
||||||
Url: ds.URL,
|
URL: ds.URL,
|
||||||
User: ds.User,
|
User: ds.User,
|
||||||
Database: ds.Database,
|
Database: ds.Database,
|
||||||
BasicAuth: ds.BasicAuth,
|
BasicAuth: ds.BasicAuth,
|
||||||
|
@ -268,12 +268,12 @@ func TestIntegrationUnauthenticatedUserCanGetPubdashPanelQueryData(t *testing.T)
|
|||||||
qds := buildQueryDataService(t, cacheService, nil, db)
|
qds := buildQueryDataService(t, cacheService, nil, db)
|
||||||
dsStore := datasourcesService.CreateStore(db, log.New("publicdashboards.test"))
|
dsStore := datasourcesService.CreateStore(db, log.New("publicdashboards.test"))
|
||||||
_ = dsStore.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
_ = dsStore.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
Uid: "ds1",
|
UID: "ds1",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: "laban",
|
Name: "laban",
|
||||||
Type: datasources.DS_MYSQL,
|
Type: datasources.DS_MYSQL,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
Database: "site",
|
Database: "site",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
})
|
})
|
||||||
|
@ -202,14 +202,14 @@ func (s *Service) handleExpressions(ctx context.Context, user *user.SignedInUser
|
|||||||
func (s *Service) handleQuerySingleDatasource(ctx context.Context, user *user.SignedInUser, parsedReq *parsedRequest) (*backend.QueryDataResponse, error) {
|
func (s *Service) handleQuerySingleDatasource(ctx context.Context, user *user.SignedInUser, parsedReq *parsedRequest) (*backend.QueryDataResponse, error) {
|
||||||
queries := parsedReq.getFlattenedQueries()
|
queries := parsedReq.getFlattenedQueries()
|
||||||
ds := queries[0].datasource
|
ds := queries[0].datasource
|
||||||
if err := s.pluginRequestValidator.Validate(ds.Url, nil); err != nil {
|
if err := s.pluginRequestValidator.Validate(ds.URL, nil); err != nil {
|
||||||
return nil, datasources.ErrDataSourceAccessDenied
|
return nil, datasources.ErrDataSourceAccessDenied
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensure that each query passed to this function has the same datasource
|
// ensure that each query passed to this function has the same datasource
|
||||||
for _, pq := range queries {
|
for _, pq := range queries {
|
||||||
if ds.Uid != pq.datasource.Uid {
|
if ds.UID != pq.datasource.UID {
|
||||||
return nil, fmt.Errorf("all queries must have the same datasource - found %s and %s", ds.Uid, pq.datasource.Uid)
|
return nil, fmt.Errorf("all queries must have the same datasource - found %s and %s", ds.UID, pq.datasource.UID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -220,7 +220,7 @@ func (s *Service) handleQuerySingleDatasource(ctx context.Context, user *user.Si
|
|||||||
|
|
||||||
req := &backend.QueryDataRequest{
|
req := &backend.QueryDataRequest{
|
||||||
PluginContext: backend.PluginContext{
|
PluginContext: backend.PluginContext{
|
||||||
OrgID: ds.OrgId,
|
OrgID: ds.OrgID,
|
||||||
PluginID: ds.Type,
|
PluginID: ds.Type,
|
||||||
User: adapters.BackendUserFromSignedInUser(user),
|
User: adapters.BackendUserFromSignedInUser(user),
|
||||||
DataSourceInstanceSettings: instanceSettings,
|
DataSourceInstanceSettings: instanceSettings,
|
||||||
@ -260,15 +260,15 @@ func (s *Service) parseMetricRequest(ctx context.Context, user *user.SignedInUse
|
|||||||
return nil, ErrInvalidDatasourceID
|
return nil, ErrInvalidDatasourceID
|
||||||
}
|
}
|
||||||
|
|
||||||
datasourcesByUid[ds.Uid] = ds
|
datasourcesByUid[ds.UID] = ds
|
||||||
if expr.IsDataSource(ds.Uid) {
|
if expr.IsDataSource(ds.UID) {
|
||||||
req.hasExpression = true
|
req.hasExpression = true
|
||||||
} else {
|
} else {
|
||||||
req.dsTypes[ds.Type] = true
|
req.dsTypes[ds.Type] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := req.parsedQueries[ds.Uid]; !ok {
|
if _, ok := req.parsedQueries[ds.UID]; !ok {
|
||||||
req.parsedQueries[ds.Uid] = []parsedQuery{}
|
req.parsedQueries[ds.UID] = []parsedQuery{}
|
||||||
}
|
}
|
||||||
|
|
||||||
s.log.Debug("Processing metrics query", "query", query)
|
s.log.Debug("Processing metrics query", "query", query)
|
||||||
@ -278,7 +278,7 @@ func (s *Service) parseMetricRequest(ctx context.Context, user *user.SignedInUse
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req.parsedQueries[ds.Uid] = append(req.parsedQueries[ds.Uid], parsedQuery{
|
req.parsedQueries[ds.UID] = append(req.parsedQueries[ds.UID], parsedQuery{
|
||||||
datasource: ds,
|
datasource: ds,
|
||||||
query: backend.DataQuery{
|
query: backend.DataQuery{
|
||||||
TimeRange: backend.TimeRange{
|
TimeRange: backend.TimeRange{
|
||||||
|
@ -483,7 +483,7 @@ func (c *fakeDataSourceCache) GetDatasource(ctx context.Context, datasourceID in
|
|||||||
|
|
||||||
func (c *fakeDataSourceCache) GetDatasourceByUID(ctx context.Context, datasourceUID string, user *user.SignedInUser, skipCache bool) (*datasources.DataSource, error) {
|
func (c *fakeDataSourceCache) GetDatasourceByUID(ctx context.Context, datasourceUID string, user *user.SignedInUser, skipCache bool) (*datasources.DataSource, error) {
|
||||||
return &datasources.DataSource{
|
return &datasources.DataSource{
|
||||||
Uid: datasourceUID,
|
UID: datasourceUID,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -69,9 +69,9 @@ func (s *DataSourceSecretMigrationService) Migrate(ctx context.Context) error {
|
|||||||
// Secrets are set by the update data source function if the SecureJsonData is set in the command
|
// Secrets are set by the update data source function if the SecureJsonData is set in the command
|
||||||
// Secrets are deleted by the update data source function if the disableSecretsCompatibility flag is enabled
|
// Secrets are deleted by the update data source function if the disableSecretsCompatibility flag is enabled
|
||||||
err = s.dataSourcesService.UpdateDataSource(ctx, &datasources.UpdateDataSourceCommand{
|
err = s.dataSourcesService.UpdateDataSource(ctx, &datasources.UpdateDataSourceCommand{
|
||||||
Id: ds.Id,
|
ID: ds.ID,
|
||||||
OrgId: ds.OrgId,
|
OrgID: ds.OrgID,
|
||||||
Uid: ds.Uid,
|
UID: ds.UID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
JsonData: ds.JsonData,
|
JsonData: ds.JsonData,
|
||||||
SecureJsonData: secureJsonData,
|
SecureJsonData: secureJsonData,
|
||||||
|
@ -47,11 +47,11 @@ func TestMigrate(t *testing.T) {
|
|||||||
dataSourceName := "Test"
|
dataSourceName := "Test"
|
||||||
dataSourceOrg := int64(1)
|
dataSourceOrg := int64(1)
|
||||||
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: dataSourceOrg,
|
OrgID: dataSourceOrg,
|
||||||
Name: dataSourceName,
|
Name: dataSourceName,
|
||||||
Type: datasources.DS_MYSQL,
|
Type: datasources.DS_MYSQL,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
EncryptedSecureJsonData: map[string][]byte{
|
EncryptedSecureJsonData: map[string][]byte{
|
||||||
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
||||||
},
|
},
|
||||||
@ -59,7 +59,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secret json data was added
|
// Check if the secret json data was added
|
||||||
query := &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query := &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -82,7 +82,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secure json data was deleted
|
// Check if the secure json data was deleted
|
||||||
query = &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query = &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -113,11 +113,11 @@ func TestMigrate(t *testing.T) {
|
|||||||
|
|
||||||
// Add test data source
|
// Add test data source
|
||||||
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: dataSourceOrg,
|
OrgID: dataSourceOrg,
|
||||||
Name: dataSourceName,
|
Name: dataSourceName,
|
||||||
Type: datasources.DS_MYSQL,
|
Type: datasources.DS_MYSQL,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
EncryptedSecureJsonData: map[string][]byte{
|
EncryptedSecureJsonData: map[string][]byte{
|
||||||
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
||||||
},
|
},
|
||||||
@ -125,7 +125,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secret json data was added
|
// Check if the secret json data was added
|
||||||
query := &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query := &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -148,7 +148,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secure json data was maintained for compatibility
|
// Check if the secure json data was maintained for compatibility
|
||||||
query = &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query = &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -181,11 +181,11 @@ func TestMigrate(t *testing.T) {
|
|||||||
|
|
||||||
// Add test data source
|
// Add test data source
|
||||||
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: dataSourceOrg,
|
OrgID: dataSourceOrg,
|
||||||
Name: dataSourceName,
|
Name: dataSourceName,
|
||||||
Type: datasources.DS_MYSQL,
|
Type: datasources.DS_MYSQL,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
EncryptedSecureJsonData: map[string][]byte{
|
EncryptedSecureJsonData: map[string][]byte{
|
||||||
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
||||||
},
|
},
|
||||||
@ -193,7 +193,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secret json data was added
|
// Check if the secret json data was added
|
||||||
query := &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query := &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -216,7 +216,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secure json data was deleted
|
// Check if the secure json data was deleted
|
||||||
query = &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query = &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -240,7 +240,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secure json data was re-added for compatibility
|
// Check if the secure json data was re-added for compatibility
|
||||||
query = &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query = &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -272,11 +272,11 @@ func TestMigrate(t *testing.T) {
|
|||||||
|
|
||||||
// Add test data source
|
// Add test data source
|
||||||
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
err := ds.AddDataSource(context.Background(), &datasources.AddDataSourceCommand{
|
||||||
OrgId: dataSourceOrg,
|
OrgID: dataSourceOrg,
|
||||||
Name: dataSourceName,
|
Name: dataSourceName,
|
||||||
Type: datasources.DS_MYSQL,
|
Type: datasources.DS_MYSQL,
|
||||||
Access: datasources.DS_ACCESS_DIRECT,
|
Access: datasources.DS_ACCESS_DIRECT,
|
||||||
Url: "http://test",
|
URL: "http://test",
|
||||||
EncryptedSecureJsonData: map[string][]byte{
|
EncryptedSecureJsonData: map[string][]byte{
|
||||||
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
"password": []byte("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
|
||||||
},
|
},
|
||||||
@ -284,7 +284,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secret json data was added
|
// Check if the secret json data was added
|
||||||
query := &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query := &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -307,7 +307,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secure json data was maintained for compatibility
|
// Check if the secure json data was maintained for compatibility
|
||||||
query = &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query = &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
@ -331,7 +331,7 @@ func TestMigrate(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
// Check if the secure json data was deleted
|
// Check if the secure json data was deleted
|
||||||
query = &datasources.GetDataSourceQuery{OrgId: dataSourceOrg, Name: dataSourceName}
|
query = &datasources.GetDataSourceQuery{OrgID: dataSourceOrg, Name: dataSourceName}
|
||||||
err = ds.GetDataSource(context.Background(), query)
|
err = ds.GetDataSource(context.Background(), query)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotNil(t, query.Result)
|
assert.NotNil(t, query.Result)
|
||||||
|
@ -55,14 +55,14 @@ func (e externalAlertmanagerToDatasources) Exec(sess *xorm.Session, mg *migrator
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ds := &datasources.DataSource{
|
ds := &datasources.DataSource{
|
||||||
OrgId: result.OrgID,
|
OrgID: result.OrgID,
|
||||||
Name: fmt.Sprintf("alertmanager-%s", uid),
|
Name: fmt.Sprintf("alertmanager-%s", uid),
|
||||||
Type: "alertmanager",
|
Type: "alertmanager",
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: uri,
|
URL: uri,
|
||||||
Created: time.Unix(result.CreatedAt, 0),
|
Created: time.Unix(result.CreatedAt, 0),
|
||||||
Updated: time.Unix(result.UpdatedAt, 0),
|
Updated: time.Unix(result.UpdatedAt, 0),
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Version: 1,
|
Version: 1,
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
|
@ -656,9 +656,9 @@ func createAlert(t *testing.T, orgId int64, dashboardId int64, panelsId int64, n
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &models.Alert{
|
return &models.Alert{
|
||||||
OrgId: orgId,
|
OrgID: orgId,
|
||||||
DashboardId: dashboardId,
|
DashboardID: dashboardId,
|
||||||
PanelId: panelsId,
|
PanelID: panelsId,
|
||||||
Name: name,
|
Name: name,
|
||||||
Message: "message",
|
Message: "message",
|
||||||
Frequency: int64(60),
|
Frequency: int64(60),
|
||||||
@ -688,9 +688,9 @@ func createDashboard(t *testing.T, id int64, orgId int64, uid string) *dashboard
|
|||||||
func createDatasource(t *testing.T, id int64, orgId int64, uid string) *datasources.DataSource {
|
func createDatasource(t *testing.T, id int64, orgId int64, uid string) *datasources.DataSource {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
return &datasources.DataSource{
|
return &datasources.DataSource{
|
||||||
Id: id,
|
ID: id,
|
||||||
OrgId: orgId,
|
OrgID: orgId,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Created: now,
|
Created: now,
|
||||||
Updated: now,
|
Updated: now,
|
||||||
Name: uid, // Not tested, needed to satisfy contraint.
|
Name: uid, // Not tested, needed to satisfy contraint.
|
||||||
|
@ -50,26 +50,26 @@ func (c *dsCache) refreshCache(ctx context.Context) error {
|
|||||||
|
|
||||||
for _, ds := range q.Result {
|
for _, ds := range q.Result {
|
||||||
val := &dsVal{
|
val := &dsVal{
|
||||||
InternalID: ds.Id,
|
InternalID: ds.ID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
Type: ds.Type,
|
Type: ds.Type,
|
||||||
IsDefault: ds.IsDefault,
|
IsDefault: ds.IsDefault,
|
||||||
}
|
}
|
||||||
_, ok := c.pluginStore.Plugin(ctx, val.Type)
|
_, ok := c.pluginStore.Plugin(ctx, val.Type)
|
||||||
val.PluginExists = ok
|
val.PluginExists = ok
|
||||||
|
|
||||||
orgCache, ok := cache[ds.OrgId]
|
orgCache, ok := cache[ds.OrgID]
|
||||||
if !ok {
|
if !ok {
|
||||||
orgCache = make(map[string]*dsVal, 0)
|
orgCache = make(map[string]*dsVal, 0)
|
||||||
cache[ds.OrgId] = orgCache
|
cache[ds.OrgID] = orgCache
|
||||||
}
|
}
|
||||||
|
|
||||||
orgCache[val.UID] = val
|
orgCache[val.UID] = val
|
||||||
|
|
||||||
// Empty string or
|
// Empty string or
|
||||||
if val.IsDefault {
|
if val.IsDefault {
|
||||||
defaultDS[ds.OrgId] = val
|
defaultDS[ds.OrgID] = val
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -20,17 +20,17 @@ func TestResolver(t *testing.T) {
|
|||||||
ds := &fakeDatasources.FakeDataSourceService{
|
ds := &fakeDatasources.FakeDataSourceService{
|
||||||
DataSources: []*datasources.DataSource{
|
DataSources: []*datasources.DataSource{
|
||||||
{
|
{
|
||||||
Id: 123,
|
ID: 123,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Type: "influx",
|
Type: "influx",
|
||||||
Uid: "influx-uid",
|
UID: "influx-uid",
|
||||||
IsDefault: true,
|
IsDefault: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Id: 234,
|
ID: 234,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Type: "influx",
|
Type: "influx",
|
||||||
Uid: "influx-uid2",
|
UID: "influx-uid2",
|
||||||
Name: "Influx2",
|
Name: "Influx2",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
@ -129,11 +129,11 @@ func TestIntegrationAdminConfiguration_SendingToExternalAlertmanagers(t *testing
|
|||||||
// Add an alertmanager datasource
|
// Add an alertmanager datasource
|
||||||
{
|
{
|
||||||
cmd := datasources.AddDataSourceCommand{
|
cmd := datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: "AM1",
|
Name: "AM1",
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: fakeAM1.URL(),
|
URL: fakeAM1.URL(),
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
"implementation": "prometheus",
|
"implementation": "prometheus",
|
||||||
@ -156,11 +156,11 @@ func TestIntegrationAdminConfiguration_SendingToExternalAlertmanagers(t *testing
|
|||||||
// Add another alertmanager datasource
|
// Add another alertmanager datasource
|
||||||
{
|
{
|
||||||
cmd := datasources.AddDataSourceCommand{
|
cmd := datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Name: "AM2",
|
Name: "AM2",
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: fakeAM2.URL(),
|
URL: fakeAM2.URL(),
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
"implementation": "prometheus",
|
"implementation": "prometheus",
|
||||||
@ -285,11 +285,11 @@ func TestIntegrationAdminConfiguration_SendingToExternalAlertmanagers(t *testing
|
|||||||
// Add an alertmanager datasource fot the other organisation
|
// Add an alertmanager datasource fot the other organisation
|
||||||
{
|
{
|
||||||
cmd := datasources.AddDataSourceCommand{
|
cmd := datasources.AddDataSourceCommand{
|
||||||
OrgId: 2,
|
OrgID: 2,
|
||||||
Name: "AM3",
|
Name: "AM3",
|
||||||
Type: datasources.DS_ALERTMANAGER,
|
Type: datasources.DS_ALERTMANAGER,
|
||||||
Access: "proxy",
|
Access: "proxy",
|
||||||
Url: fakeAM3.URL(),
|
URL: fakeAM3.URL(),
|
||||||
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
JsonData: simplejson.NewFromAny(map[string]interface{}{
|
||||||
"handleGrafanaManagedAlerts": true,
|
"handleGrafanaManagedAlerts": true,
|
||||||
"implementation": "prometheus",
|
"implementation": "prometheus",
|
||||||
|
@ -62,9 +62,9 @@ func TestBacktesting(t *testing.T) {
|
|||||||
Name: "Backtesting-TestDatasource",
|
Name: "Backtesting-TestDatasource",
|
||||||
Type: "testdata",
|
Type: "testdata",
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Uid: query.DatasourceUID,
|
UID: query.DatasourceUID,
|
||||||
UserId: userId,
|
UserID: userId,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
err := env.Server.HTTPServer.DataSourcesService.AddDataSource(context.Background(), dsCmd)
|
err := env.Server.HTTPServer.DataSourcesService.AddDataSource(context.Background(), dsCmd)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
@ -65,12 +65,12 @@ func TestIntegrationAzureMonitor(t *testing.T) {
|
|||||||
|
|
||||||
uid := "azuremonitor"
|
uid := "azuremonitor"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "Azure Monitor",
|
Name: "Azure Monitor",
|
||||||
Type: datasources.DS_AZURE_MONITOR,
|
Type: datasources.DS_AZURE_MONITOR,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
SecureJsonData: secureJSONData,
|
SecureJsonData: secureJSONData,
|
||||||
})
|
})
|
||||||
|
@ -45,18 +45,18 @@ func TestIntegrationCreateCorrelation(t *testing.T) {
|
|||||||
Name: "read-only",
|
Name: "read-only",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
readOnlyDS := createDsCommand.Result.Uid
|
readOnlyDS := createDsCommand.Result.UID
|
||||||
|
|
||||||
createDsCommand = &datasources.AddDataSourceCommand{
|
createDsCommand = &datasources.AddDataSourceCommand{
|
||||||
Name: "writable",
|
Name: "writable",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
writableDs := createDsCommand.Result.Uid
|
writableDs := createDsCommand.Result.UID
|
||||||
|
|
||||||
t.Run("Unauthenticated users shouldn't be able to create correlations", func(t *testing.T) {
|
t.Run("Unauthenticated users shouldn't be able to create correlations", func(t *testing.T) {
|
||||||
res := ctx.Post(PostParams{
|
res := ctx.Post(PostParams{
|
||||||
|
@ -45,19 +45,19 @@ func TestIntegrationDeleteCorrelation(t *testing.T) {
|
|||||||
Name: "read-only",
|
Name: "read-only",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
readOnlyDS := createDsCommand.Result.Uid
|
readOnlyDS := createDsCommand.Result.UID
|
||||||
|
|
||||||
createDsCommand = &datasources.AddDataSourceCommand{
|
createDsCommand = &datasources.AddDataSourceCommand{
|
||||||
Name: "writable",
|
Name: "writable",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
writableDs := createDsCommand.Result.Uid
|
writableDs := createDsCommand.Result.UID
|
||||||
writableDsOrgId := createDsCommand.Result.OrgId
|
writableDsOrgId := createDsCommand.Result.OrgID
|
||||||
|
|
||||||
t.Run("Unauthenticated users shouldn't be able to delete correlations", func(t *testing.T) {
|
t.Run("Unauthenticated users shouldn't be able to delete correlations", func(t *testing.T) {
|
||||||
res := ctx.Delete(DeleteParams{
|
res := ctx.Delete(DeleteParams{
|
||||||
|
@ -68,14 +68,14 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
createDsCommand := &datasources.AddDataSourceCommand{
|
createDsCommand := &datasources.AddDataSourceCommand{
|
||||||
Name: "with-correlations",
|
Name: "with-correlations",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
dsWithCorrelations := createDsCommand.Result
|
dsWithCorrelations := createDsCommand.Result
|
||||||
correlation := ctx.createCorrelation(correlations.CreateCorrelationCommand{
|
correlation := ctx.createCorrelation(correlations.CreateCorrelationCommand{
|
||||||
SourceUID: dsWithCorrelations.Uid,
|
SourceUID: dsWithCorrelations.UID,
|
||||||
TargetUID: &dsWithCorrelations.Uid,
|
TargetUID: &dsWithCorrelations.UID,
|
||||||
OrgId: dsWithCorrelations.OrgId,
|
OrgId: dsWithCorrelations.OrgID,
|
||||||
Config: correlations.CorrelationConfig{
|
Config: correlations.CorrelationConfig{
|
||||||
Type: correlations.ConfigTypeQuery,
|
Type: correlations.ConfigTypeQuery,
|
||||||
Field: "foo",
|
Field: "foo",
|
||||||
@ -86,7 +86,7 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
createDsCommand = &datasources.AddDataSourceCommand{
|
createDsCommand = &datasources.AddDataSourceCommand{
|
||||||
Name: "without-correlations",
|
Name: "without-correlations",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
dsWithoutCorrelations := createDsCommand.Result
|
dsWithoutCorrelations := createDsCommand.Result
|
||||||
@ -99,13 +99,13 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
created, err := sess.InsertMulti(&[]correlations.Correlation{
|
created, err := sess.InsertMulti(&[]correlations.Correlation{
|
||||||
{
|
{
|
||||||
UID: "uid-1",
|
UID: "uid-1",
|
||||||
SourceUID: dsWithoutCorrelations.Uid,
|
SourceUID: dsWithoutCorrelations.UID,
|
||||||
TargetUID: &nonExistingDsUID,
|
TargetUID: &nonExistingDsUID,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
UID: "uid-2",
|
UID: "uid-2",
|
||||||
SourceUID: "THIS-DOES-NOT_EXIST",
|
SourceUID: "THIS-DOES-NOT_EXIST",
|
||||||
TargetUID: &dsWithoutCorrelations.Uid,
|
TargetUID: &dsWithoutCorrelations.UID,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
require.Equal(t, int64(2), created)
|
require.Equal(t, int64(2), created)
|
||||||
@ -215,7 +215,7 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("If no correlation exists it should return 200", func(t *testing.T) {
|
t.Run("If no correlation exists it should return 200", func(t *testing.T) {
|
||||||
res := ctx.Get(GetParams{
|
res := ctx.Get(GetParams{
|
||||||
url: fmt.Sprintf("/api/datasources/uid/%s/correlations", dsWithoutCorrelations.Uid),
|
url: fmt.Sprintf("/api/datasources/uid/%s/correlations", dsWithoutCorrelations.UID),
|
||||||
user: adminUser,
|
user: adminUser,
|
||||||
})
|
})
|
||||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
require.Equal(t, http.StatusOK, res.StatusCode)
|
||||||
@ -234,7 +234,7 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Should correctly return correlations", func(t *testing.T) {
|
t.Run("Should correctly return correlations", func(t *testing.T) {
|
||||||
res := ctx.Get(GetParams{
|
res := ctx.Get(GetParams{
|
||||||
url: fmt.Sprintf("/api/datasources/uid/%s/correlations", dsWithCorrelations.Uid),
|
url: fmt.Sprintf("/api/datasources/uid/%s/correlations", dsWithCorrelations.UID),
|
||||||
user: adminUser,
|
user: adminUser,
|
||||||
})
|
})
|
||||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
require.Equal(t, http.StatusOK, res.StatusCode)
|
||||||
@ -304,7 +304,7 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("If no correlation exists it should return 404", func(t *testing.T) {
|
t.Run("If no correlation exists it should return 404", func(t *testing.T) {
|
||||||
res := ctx.Get(GetParams{
|
res := ctx.Get(GetParams{
|
||||||
url: fmt.Sprintf("/api/datasources/uid/%s/correlations/%s", dsWithoutCorrelations.Uid, "some-correlation-uid"),
|
url: fmt.Sprintf("/api/datasources/uid/%s/correlations/%s", dsWithoutCorrelations.UID, "some-correlation-uid"),
|
||||||
user: adminUser,
|
user: adminUser,
|
||||||
})
|
})
|
||||||
require.Equal(t, http.StatusNotFound, res.StatusCode)
|
require.Equal(t, http.StatusNotFound, res.StatusCode)
|
||||||
@ -323,7 +323,7 @@ func TestIntegrationReadCorrelation(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Should correctly return correlation", func(t *testing.T) {
|
t.Run("Should correctly return correlation", func(t *testing.T) {
|
||||||
res := ctx.Get(GetParams{
|
res := ctx.Get(GetParams{
|
||||||
url: fmt.Sprintf("/api/datasources/uid/%s/correlations/%s", dsWithCorrelations.Uid, correlation.UID),
|
url: fmt.Sprintf("/api/datasources/uid/%s/correlations/%s", dsWithCorrelations.UID, correlation.UID),
|
||||||
user: adminUser,
|
user: adminUser,
|
||||||
})
|
})
|
||||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
require.Equal(t, http.StatusOK, res.StatusCode)
|
||||||
|
@ -45,19 +45,19 @@ func TestIntegrationUpdateCorrelation(t *testing.T) {
|
|||||||
Name: "read-only",
|
Name: "read-only",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
readOnlyDS := createDsCommand.Result.Uid
|
readOnlyDS := createDsCommand.Result.UID
|
||||||
|
|
||||||
createDsCommand = &datasources.AddDataSourceCommand{
|
createDsCommand = &datasources.AddDataSourceCommand{
|
||||||
Name: "writable",
|
Name: "writable",
|
||||||
Type: "loki",
|
Type: "loki",
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
}
|
}
|
||||||
ctx.createDs(createDsCommand)
|
ctx.createDs(createDsCommand)
|
||||||
writableDs := createDsCommand.Result.Uid
|
writableDs := createDsCommand.Result.UID
|
||||||
writableDsOrgId := createDsCommand.Result.OrgId
|
writableDsOrgId := createDsCommand.Result.OrgID
|
||||||
|
|
||||||
t.Run("Unauthenticated users shouldn't be able to update correlations", func(t *testing.T) {
|
t.Run("Unauthenticated users shouldn't be able to update correlations", func(t *testing.T) {
|
||||||
res := ctx.Patch(PatchParams{
|
res := ctx.Patch(PatchParams{
|
||||||
|
@ -57,12 +57,12 @@ func TestIntegrationElasticsearch(t *testing.T) {
|
|||||||
|
|
||||||
uid := "es"
|
uid := "es"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "Elasticsearch",
|
Name: "Elasticsearch",
|
||||||
Type: datasources.DS_ES,
|
Type: datasources.DS_ES,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "basicAuthUser",
|
BasicAuthUser: "basicAuthUser",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
|
@ -55,12 +55,12 @@ func TestIntegrationGraphite(t *testing.T) {
|
|||||||
|
|
||||||
uid := "graphite"
|
uid := "graphite"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "graphite",
|
Name: "graphite",
|
||||||
Type: datasources.DS_GRAPHITE,
|
Type: datasources.DS_GRAPHITE,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "basicAuthUser",
|
BasicAuthUser: "basicAuthUser",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
|
@ -55,12 +55,12 @@ func TestIntegrationInflux(t *testing.T) {
|
|||||||
|
|
||||||
uid := "influxdb"
|
uid := "influxdb"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "InfluxDB",
|
Name: "InfluxDB",
|
||||||
Type: datasources.DS_INFLUXDB,
|
Type: datasources.DS_INFLUXDB,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "basicAuthUser",
|
BasicAuthUser: "basicAuthUser",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
|
@ -55,12 +55,12 @@ func TestIntegrationLoki(t *testing.T) {
|
|||||||
|
|
||||||
uid := "loki"
|
uid := "loki"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "Loki",
|
Name: "Loki",
|
||||||
Type: datasources.DS_LOKI,
|
Type: datasources.DS_LOKI,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "basicAuthUser",
|
BasicAuthUser: "basicAuthUser",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
|
@ -55,12 +55,12 @@ func TestIntegrationOpenTSDB(t *testing.T) {
|
|||||||
|
|
||||||
uid := "influxdb"
|
uid := "influxdb"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "opentsdb",
|
Name: "opentsdb",
|
||||||
Type: datasources.DS_OPENTSDB,
|
Type: datasources.DS_OPENTSDB,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "basicAuthUser",
|
BasicAuthUser: "basicAuthUser",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
|
@ -284,12 +284,12 @@ func newTestScenario(t *testing.T, name string, opts []testScenarioOption, callb
|
|||||||
|
|
||||||
tsCtx.uid = "test-plugin"
|
tsCtx.uid = "test-plugin"
|
||||||
cmd := &datasources.AddDataSourceCommand{
|
cmd := &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "TestPlugin",
|
Name: "TestPlugin",
|
||||||
Type: tsCtx.testPluginID,
|
Type: tsCtx.testPluginID,
|
||||||
Uid: tsCtx.uid,
|
UID: tsCtx.uid,
|
||||||
Url: tsCtx.outgoingServer.URL,
|
URL: tsCtx.outgoingServer.URL,
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
SecureJsonData: secureJSONData,
|
SecureJsonData: secureJSONData,
|
||||||
}
|
}
|
||||||
@ -306,8 +306,8 @@ func newTestScenario(t *testing.T, name string, opts []testScenarioOption, callb
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
getDataSourceQuery := &datasources.GetDataSourceQuery{
|
getDataSourceQuery := &datasources.GetDataSourceQuery{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Uid: tsCtx.uid,
|
UID: tsCtx.uid,
|
||||||
}
|
}
|
||||||
err = testEnv.Server.HTTPServer.DataSourcesService.GetDataSource(ctx, getDataSourceQuery)
|
err = testEnv.Server.HTTPServer.DataSourcesService.GetDataSource(ctx, getDataSourceQuery)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
@ -56,12 +56,12 @@ func TestIntegrationPrometheus(t *testing.T) {
|
|||||||
|
|
||||||
uid := "prometheus"
|
uid := "prometheus"
|
||||||
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
err := testEnv.Server.HTTPServer.DataSourcesService.AddDataSource(ctx, &datasources.AddDataSourceCommand{
|
||||||
OrgId: 1,
|
OrgID: 1,
|
||||||
Access: datasources.DS_ACCESS_PROXY,
|
Access: datasources.DS_ACCESS_PROXY,
|
||||||
Name: "Prometheus",
|
Name: "Prometheus",
|
||||||
Type: datasources.DS_PROMETHEUS,
|
Type: datasources.DS_PROMETHEUS,
|
||||||
Uid: uid,
|
UID: uid,
|
||||||
Url: outgoingServer.URL,
|
URL: outgoingServer.URL,
|
||||||
BasicAuth: true,
|
BasicAuth: true,
|
||||||
BasicAuthUser: "basicAuthUser",
|
BasicAuthUser: "basicAuthUser",
|
||||||
JsonData: jsonData,
|
JsonData: jsonData,
|
||||||
|
@ -74,11 +74,11 @@ type Service struct {
|
|||||||
|
|
||||||
func DataSourceModel(orgId int64) *datasources.DataSource {
|
func DataSourceModel(orgId int64) *datasources.DataSource {
|
||||||
return &datasources.DataSource{
|
return &datasources.DataSource{
|
||||||
Id: DatasourceID,
|
ID: DatasourceID,
|
||||||
Uid: DatasourceUID,
|
UID: DatasourceUID,
|
||||||
Name: DatasourceName,
|
Name: DatasourceName,
|
||||||
Type: "grafana",
|
Type: "grafana",
|
||||||
OrgId: orgId,
|
OrgID: orgId,
|
||||||
JsonData: simplejson.New(),
|
JsonData: simplejson.New(),
|
||||||
SecureJsonData: make(map[string][]byte),
|
SecureJsonData: make(map[string][]byte),
|
||||||
}
|
}
|
||||||
|
@ -79,9 +79,9 @@ func generateRequest(ctx context.Context, ds *datasources.DataSource, decryptedJ
|
|||||||
}
|
}
|
||||||
|
|
||||||
instanceSettings := &backend.DataSourceInstanceSettings{
|
instanceSettings := &backend.DataSourceInstanceSettings{
|
||||||
ID: ds.Id,
|
ID: ds.ID,
|
||||||
Name: ds.Name,
|
Name: ds.Name,
|
||||||
URL: ds.Url,
|
URL: ds.URL,
|
||||||
Database: ds.Database,
|
Database: ds.Database,
|
||||||
User: ds.User,
|
User: ds.User,
|
||||||
BasicAuthEnabled: ds.BasicAuth,
|
BasicAuthEnabled: ds.BasicAuth,
|
||||||
@ -89,7 +89,7 @@ func generateRequest(ctx context.Context, ds *datasources.DataSource, decryptedJ
|
|||||||
JSONData: jsonDataBytes,
|
JSONData: jsonDataBytes,
|
||||||
DecryptedSecureJSONData: decryptedJsonData,
|
DecryptedSecureJSONData: decryptedJsonData,
|
||||||
Updated: ds.Updated,
|
Updated: ds.Updated,
|
||||||
UID: ds.Uid,
|
UID: ds.UID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if query.Headers == nil {
|
if query.Headers == nil {
|
||||||
@ -98,7 +98,7 @@ func generateRequest(ctx context.Context, ds *datasources.DataSource, decryptedJ
|
|||||||
|
|
||||||
req := &backend.QueryDataRequest{
|
req := &backend.QueryDataRequest{
|
||||||
PluginContext: backend.PluginContext{
|
PluginContext: backend.PluginContext{
|
||||||
OrgID: ds.OrgId,
|
OrgID: ds.OrgID,
|
||||||
PluginID: ds.Type,
|
PluginID: ds.Type,
|
||||||
User: adapters.BackendUserFromSignedInUser(query.User),
|
User: adapters.BackendUserFromSignedInUser(query.User),
|
||||||
DataSourceInstanceSettings: instanceSettings,
|
DataSourceInstanceSettings: instanceSettings,
|
||||||
|
@ -40,12 +40,12 @@ func TestHandleRequest(t *testing.T) {
|
|||||||
|
|
||||||
s := ProvideService(client, nil, dsService)
|
s := ProvideService(client, nil, dsService)
|
||||||
|
|
||||||
ds := &datasources.DataSource{Id: 12, Type: "unregisteredType", JsonData: simplejson.New()}
|
ds := &datasources.DataSource{ID: 12, Type: "unregisteredType", JsonData: simplejson.New()}
|
||||||
req := legacydata.DataQuery{
|
req := legacydata.DataQuery{
|
||||||
TimeRange: &legacydata.DataTimeRange{},
|
TimeRange: &legacydata.DataTimeRange{},
|
||||||
Queries: []legacydata.DataSubQuery{
|
Queries: []legacydata.DataSubQuery{
|
||||||
{RefID: "A", DataSource: &datasources.DataSource{Id: 1, Type: "test"}, Model: simplejson.New()},
|
{RefID: "A", DataSource: &datasources.DataSource{ID: 1, Type: "test"}, Model: simplejson.New()},
|
||||||
{RefID: "B", DataSource: &datasources.DataSource{Id: 1, Type: "test"}, Model: simplejson.New()},
|
{RefID: "B", DataSource: &datasources.DataSource{ID: 1, Type: "test"}, Model: simplejson.New()},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
res, err := s.HandleRequest(context.Background(), ds, req)
|
res, err := s.HandleRequest(context.Background(), ds, req)
|
||||||
|
Loading…
Reference in New Issue
Block a user