Alerting: Allow administrators delete rules permanently via UI (#101974)

* add query parameter to existing APIs to control the permanent deletion of rules
* add GUID to gettable rule
* add new endpoint /ruler/grafana/api/v1/trash/rule/guid/{RuleGUID} to delete rules from trash permanently

---------

Signed-off-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
This commit is contained in:
Yuri Tseretyan
2025-03-14 22:14:06 +02:00
committed by GitHub
parent e30034a42a
commit 309a2eb4e9
25 changed files with 585 additions and 115 deletions
+32 -4
View File
@@ -78,6 +78,14 @@ var ignoreFieldsForValidate = [...]string{"RuleGroupIndex"}
// Returns http.StatusForbidden if user does not have access to any of the rules that match the filter.
// Returns http.StatusBadRequest if all rules that match the filter and the user is authorized to delete are provisioned.
func (srv RulerSrv) RouteDeleteAlertRules(c *contextmodel.ReqContext, namespaceUID string, group string) response.Response {
var permanently bool
if c.QueryBool("deletePermanently") {
if !c.SignedInUser.HasRole(identity.RoleAdmin) {
return ErrResp(http.StatusForbidden, errors.New("only administrators can delete rules permanently"), "")
}
permanently = true
}
namespace, err := srv.store.GetNamespaceByUID(c.Req.Context(), namespaceUID, c.SignedInUser.GetOrgID(), c.SignedInUser)
if err != nil {
return toNamespaceErrorResponse(err)
@@ -161,7 +169,7 @@ func (srv RulerSrv) RouteDeleteAlertRules(c *contextmodel.ReqContext, namespaceU
rulesToDelete = append(rulesToDelete, uid...)
}
if len(rulesToDelete) > 0 {
err := srv.store.DeleteAlertRulesByUID(ctx, c.SignedInUser.GetOrgID(), ngmodels.NewUserUID(c.SignedInUser), rulesToDelete...)
err := srv.store.DeleteAlertRulesByUID(ctx, c.SignedInUser.GetOrgID(), ngmodels.NewUserUID(c.SignedInUser), permanently, rulesToDelete...)
if err != nil {
return err
}
@@ -385,6 +393,14 @@ func (srv RulerSrv) RouteGetRuleVersionsByUID(c *contextmodel.ReqContext, ruleUI
}
func (srv RulerSrv) RoutePostNameRulesConfig(c *contextmodel.ReqContext, ruleGroupConfig apimodels.PostableRuleGroupConfig, namespaceUID string) response.Response {
var deletePermanently bool
if c.QueryBool("deletePermanently") {
if !c.SignedInUser.HasRole(identity.RoleAdmin) {
return ErrResp(http.StatusForbidden, errors.New("only administrators can delete rules permanently"), "")
}
deletePermanently = true
}
namespace, err := srv.store.GetNamespaceByUID(c.Req.Context(), namespaceUID, c.SignedInUser.GetOrgID(), c.SignedInUser)
if err != nil {
return toNamespaceErrorResponse(err)
@@ -405,7 +421,18 @@ func (srv RulerSrv) RoutePostNameRulesConfig(c *contextmodel.ReqContext, ruleGro
RuleGroup: ruleGroupConfig.Name,
}
return srv.updateAlertRulesInGroup(c, groupKey, rules)
return srv.updateAlertRulesInGroup(c, groupKey, rules, deletePermanently)
}
func (srv RulerSrv) RouteDeleteAlertRuleFromTrashByGUID(ctx *contextmodel.ReqContext, guid string) response.Response {
deleted, err := srv.store.DeleteRuleFromTrashByGUID(ctx.Req.Context(), ctx.SignedInUser.GetOrgID(), guid)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to delete rule from trash")
}
if deleted == 0 {
return response.Empty(http.StatusNotFound)
}
return response.Empty(http.StatusOK)
}
func (srv RulerSrv) checkGroupLimits(group apimodels.PostableRuleGroupConfig) error {
@@ -424,7 +451,7 @@ func (srv RulerSrv) checkGroupLimits(group apimodels.PostableRuleGroupConfig) er
// All operations are performed in a single transaction
//
//nolint:gocyclo
func (srv RulerSrv) updateAlertRulesInGroup(c *contextmodel.ReqContext, groupKey ngmodels.AlertRuleGroupKey, rules []*ngmodels.AlertRuleWithOptionals) response.Response {
func (srv RulerSrv) updateAlertRulesInGroup(c *contextmodel.ReqContext, groupKey ngmodels.AlertRuleGroupKey, rules []*ngmodels.AlertRuleWithOptionals, deletePermanently bool) response.Response {
var finalChanges *store.GroupDelta
var dbConfig *ngmodels.AlertConfiguration
err := srv.xactManager.InTransaction(c.Req.Context(), func(tranCtx context.Context) error {
@@ -485,7 +512,7 @@ func (srv RulerSrv) updateAlertRulesInGroup(c *contextmodel.ReqContext, groupKey
UIDs = append(UIDs, rule.UID)
}
if err = srv.store.DeleteAlertRulesByUID(tranCtx, c.SignedInUser.GetOrgID(), ngmodels.NewUserUID(c.SignedInUser), UIDs...); err != nil {
if err = srv.store.DeleteAlertRulesByUID(tranCtx, c.SignedInUser.GetOrgID(), ngmodels.NewUserUID(c.SignedInUser), deletePermanently, UIDs...); err != nil {
return fmt.Errorf("failed to delete rules: %w", err)
}
}
@@ -631,6 +658,7 @@ func toGettableExtendedRuleNode(r ngmodels.AlertRule, provenanceRecords map[stri
NotificationSettings: AlertRuleNotificationSettingsFromNotificationSettings(r.NotificationSettings),
Record: ApiRecordFromModelRecord(r.Record),
Metadata: AlertRuleMetadataFromModelMetadata(r.Metadata),
GUID: r.GUID,
},
}
forDuration := model.Duration(r.For)
+1 -1
View File
@@ -60,7 +60,7 @@ func TestRouteDeleteAlertRules(t *testing.T) {
deleteCommands := getRecordedCommand(ruleStore)
require.Len(t, deleteCommands, 1)
cmd := deleteCommands[0]
actualUIDs := cmd.Params[2].([]string)
actualUIDs := cmd.Params[3].([]string)
require.Len(t, actualUIDs, len(expectedRules))
for _, rule := range expectedRules {
require.Containsf(t, actualUIDs, rule.UID, "Rule %s was expected to be deleted but it wasn't", rule.UID)
@@ -65,6 +65,8 @@ func (api *API) authorize(method, path string) web.Handler {
ac.EvalPermission(ac.ActionAlertingRuleDelete, scope),
),
)
case http.MethodDelete + "/api/ruler/grafana/api/v1/trash/rule/guid/{RuleGUID}":
return middleware.ReqOrgAdmin
// Grafana rule state history paths
case http.MethodGet + "/api/v1/rules/history":
@@ -41,7 +41,7 @@ func TestAuthorize(t *testing.T) {
}
paths[p] = methods
}
require.Len(t, paths, 66)
require.Len(t, paths, 67)
ac := acmock.New()
api := &API{AccessControl: ac, FeatureManager: featuremgmt.WithFeatures()}
@@ -128,3 +128,7 @@ func (f *RulerApiHandler) getService(ctx *contextmodel.ReqContext) (*LotexRuler,
func (f *RulerApiHandler) handleRouteGetRuleVersionsByUID(ctx *contextmodel.ReqContext, ruleUID string) response.Response {
return f.GrafanaRuler.RouteGetRuleVersionsByUID(ctx, ruleUID)
}
func (f *RulerApiHandler) handleRouteDeleteRuleFromTrashByGUID(ctx *contextmodel.ReqContext, ruleGUID string) response.Response {
return f.GrafanaRuler.RouteDeleteAlertRuleFromTrashByGUID(ctx, ruleGUID)
}
@@ -23,6 +23,7 @@ type RulerApi interface {
RouteDeleteGrafanaRuleGroupConfig(*contextmodel.ReqContext) response.Response
RouteDeleteNamespaceGrafanaRulesConfig(*contextmodel.ReqContext) response.Response
RouteDeleteNamespaceRulesConfig(*contextmodel.ReqContext) response.Response
RouteDeleteRuleFromTrashByGUID(*contextmodel.ReqContext) response.Response
RouteDeleteRuleGroupConfig(*contextmodel.ReqContext) response.Response
RouteGetGrafanaRuleGroupConfig(*contextmodel.ReqContext) response.Response
RouteGetGrafanaRulesConfig(*contextmodel.ReqContext) response.Response
@@ -55,6 +56,11 @@ func (f *RulerApiHandler) RouteDeleteNamespaceRulesConfig(ctx *contextmodel.ReqC
namespaceParam := web.Params(ctx.Req)[":Namespace"]
return f.handleRouteDeleteNamespaceRulesConfig(ctx, datasourceUIDParam, namespaceParam)
}
func (f *RulerApiHandler) RouteDeleteRuleFromTrashByGUID(ctx *contextmodel.ReqContext) response.Response {
// Parse Path Parameters
ruleGUIDParam := web.Params(ctx.Req)[":RuleGUID"]
return f.handleRouteDeleteRuleFromTrashByGUID(ctx, ruleGUIDParam)
}
func (f *RulerApiHandler) RouteDeleteRuleGroupConfig(ctx *contextmodel.ReqContext) response.Response {
// Parse Path Parameters
datasourceUIDParam := web.Params(ctx.Req)[":DatasourceUID"]
@@ -177,6 +183,18 @@ func (api *API) RegisterRulerApiEndpoints(srv RulerApi, m *metrics.API) {
m,
),
)
group.Delete(
toMacaronPath("/api/ruler/grafana/api/v1/trash/rule/guid/{RuleGUID}"),
requestmeta.SetOwner(requestmeta.TeamAlerting),
requestmeta.SetSLOGroup(requestmeta.SLOGroupHighSlow),
api.authorize(http.MethodDelete, "/api/ruler/grafana/api/v1/trash/rule/guid/{RuleGUID}"),
metrics.Instrument(
http.MethodDelete,
"/api/ruler/grafana/api/v1/trash/rule/guid/{RuleGUID}",
api.Hooks.Wrap(srv.RouteDeleteRuleFromTrashByGUID),
m,
),
)
group.Delete(
toMacaronPath("/api/ruler/{DatasourceUID}/api/v1/rules/{Namespace}/{Groupname}"),
requestmeta.SetOwner(requestmeta.TeamAlerting),
+2 -1
View File
@@ -29,7 +29,8 @@ type RuleStore interface {
// and return the map of uuid to id.
InsertAlertRules(ctx context.Context, user *ngmodels.UserUID, rules []ngmodels.AlertRule) ([]ngmodels.AlertRuleKeyWithId, error)
UpdateAlertRules(ctx context.Context, user *ngmodels.UserUID, rules []ngmodels.UpdateRule) error
DeleteAlertRulesByUID(ctx context.Context, orgID int64, user *ngmodels.UserUID, ruleUID ...string) error
DeleteAlertRulesByUID(ctx context.Context, orgID int64, user *ngmodels.UserUID, permanently bool, ruleUID ...string) error
DeleteRuleFromTrashByGUID(ctx context.Context, orgID int64, ruleGUID string) (int64, error)
// IncreaseVersionForAllRulesInNamespaces Increases version for all rules that have specified namespace uids
IncreaseVersionForAllRulesInNamespaces(ctx context.Context, orgID int64, namespaceUIDs []string) ([]ngmodels.AlertRuleKeyWithVersion, error)
+23 -1
View File
@@ -396,6 +396,9 @@
},
"metric": {
"type": "string"
},
"targetDatasourceUid": {
"type": "string"
}
},
"title": "Record is the provisioned export of models.Record.",
@@ -1607,6 +1610,9 @@
],
"type": "string"
},
"guid": {
"type": "string"
},
"intervalSeconds": {
"format": "int64",
"type": "integer"
@@ -3492,6 +3498,11 @@
"description": "Name of the recorded metric.",
"example": "grafana_alerts_ratio",
"type": "string"
},
"target_datasource_uid": {
"description": "Which data source should be used to write the output of the recording rule, specified by UID.",
"example": "my-prom",
"type": "string"
}
},
"required": [
@@ -4355,6 +4366,15 @@
"description": "Name of the associated template definition for this result.",
"type": "string"
},
"scope": {
"description": "Scope that was successfully used to interpolate the template. If the root scope \".\" fails, more specific\nscopes will be tried, such as \".Alerts', or \".Alert\".",
"enum": [
".",
".Alerts",
".Alert"
],
"type": "string"
},
"text": {
"description": "Interpolated value of the template.",
"type": "string"
@@ -4493,6 +4513,7 @@
"type": "object"
},
"URL": {
"description": "The general form represented is:\n\n[scheme:][//[userinfo@]host][/]path[?query][#fragment]\n\nURLs that do not start with a slash after the scheme are interpreted as:\n\nscheme:opaque[?query][#fragment]\n\nThe Host field contains the host and port subcomponents of the URL.\nWhen the port is present, it is separated from the host with a colon.\nWhen the host is an IPv6 address, it must be enclosed in square brackets:\n\"[fe80::1]:80\". The [net.JoinHostPort] function combines a host and port\ninto a string suitable for the Host field, adding square brackets to\nthe host when necessary.\n\nNote that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.\nA consequence is that it is impossible to tell which slashes in the Path were\nslashes in the raw URL and which were %2f. This distinction is rarely important,\nbut when it is, the code should use the [URL.EscapedPath] method, which preserves\nthe original encoding of Path.\n\nThe RawPath field is an optional field which is only set when the default\nencoding of Path is different from the escaped path. See the EscapedPath method\nfor more details.\n\nURL's String method uses the EscapedPath method to obtain the path.",
"properties": {
"ForceQuery": {
"type": "boolean"
@@ -4528,7 +4549,7 @@
"$ref": "#/definitions/Userinfo"
}
},
"title": "URL is a custom URL type that allows validation at configuration load time.",
"title": "A URL represents a parsed URL (technically, a URI reference).",
"type": "object"
},
"UpdateRuleGroupResponse": {
@@ -5056,6 +5077,7 @@
"type": "object"
},
"gettableSilences": {
"description": "GettableSilences gettable silences",
"items": {
"$ref": "#/definitions/gettableSilence",
"type": "object"
@@ -20,6 +20,18 @@ import (
// 403: ForbiddenError
// 404: description: Not found.
// swagger:route Delete /ruler/grafana/api/v1/trash/rule/guid/{RuleGUID} ruler RouteDeleteRuleFromTrashByGUID
//
// Permanently delete a rule from trash by GUID
//
// Produces:
// - application/json
//
// Responses:
// 202: Ack
// 403: ForbiddenError
// 404: description: Not found.
// swagger:route Get /ruler/grafana/api/v1/rule/{RuleUID}/versions ruler RouteGetRuleVersionsByUID
//
// Get rule versions by UID
@@ -237,6 +249,12 @@ type PathGetRuleByUIDParams struct {
RuleUID string
}
// swagger:parameters RouteDeleteRuleFromTrashByGUID
type PathDeleteRuleFromTrashByGUIDParams struct {
// in: path
RuleGUID string
}
// swagger:model
type RuleGroupConfigResponse struct {
GettableRuleGroupConfig
@@ -572,6 +590,7 @@ type GettableGrafanaRule struct {
NotificationSettings *AlertRuleNotificationSettings `json:"notification_settings,omitempty" yaml:"notification_settings,omitempty"`
Record *Record `json:"record,omitempty" yaml:"record,omitempty"`
Metadata *AlertRuleMetadata `json:"metadata,omitempty" yaml:"metadata,omitempty"`
GUID string `json:"guid" yaml:"guid"`
}
// UserInfo represents user-related information, including a unique identifier and a name.
+58 -3
View File
@@ -396,6 +396,9 @@
},
"metric": {
"type": "string"
},
"targetDatasourceUid": {
"type": "string"
}
},
"title": "Record is the provisioned export of models.Record.",
@@ -1607,6 +1610,9 @@
],
"type": "string"
},
"guid": {
"type": "string"
},
"intervalSeconds": {
"format": "int64",
"type": "integer"
@@ -3492,6 +3498,11 @@
"description": "Name of the recorded metric.",
"example": "grafana_alerts_ratio",
"type": "string"
},
"target_datasource_uid": {
"description": "Which data source should be used to write the output of the recording rule, specified by UID.",
"example": "my-prom",
"type": "string"
}
},
"required": [
@@ -4355,6 +4366,15 @@
"description": "Name of the associated template definition for this result.",
"type": "string"
},
"scope": {
"description": "Scope that was successfully used to interpolate the template. If the root scope \".\" fails, more specific\nscopes will be tried, such as \".Alerts', or \".Alert\".",
"enum": [
".",
".Alerts",
".Alert"
],
"type": "string"
},
"text": {
"description": "Interpolated value of the template.",
"type": "string"
@@ -4493,7 +4513,6 @@
"type": "object"
},
"URL": {
"description": "The general form represented is:\n\n[scheme:][//[userinfo@]host][/]path[?query][#fragment]\n\nURLs that do not start with a slash after the scheme are interpreted as:\n\nscheme:opaque[?query][#fragment]\n\nThe Host field contains the host and port subcomponents of the URL.\nWhen the port is present, it is separated from the host with a colon.\nWhen the host is an IPv6 address, it must be enclosed in square brackets:\n\"[fe80::1]:80\". The [net.JoinHostPort] function combines a host and port\ninto a string suitable for the Host field, adding square brackets to\nthe host when necessary.\n\nNote that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.\nA consequence is that it is impossible to tell which slashes in the Path were\nslashes in the raw URL and which were %2f. This distinction is rarely important,\nbut when it is, the code should use the [URL.EscapedPath] method, which preserves\nthe original encoding of Path.\n\nThe RawPath field is an optional field which is only set when the default\nencoding of Path is different from the escaped path. See the EscapedPath method\nfor more details.\n\nURL's String method uses the EscapedPath method to obtain the path.",
"properties": {
"ForceQuery": {
"type": "boolean"
@@ -4529,7 +4548,7 @@
"$ref": "#/definitions/Userinfo"
}
},
"title": "A URL represents a parsed URL (technically, a URI reference).",
"title": "URL is a custom URL type that allows validation at configuration load time.",
"type": "object"
},
"UpdateRuleGroupResponse": {
@@ -5058,7 +5077,6 @@
"type": "object"
},
"gettableSilences": {
"description": "GettableSilences gettable silences",
"items": {
"$ref": "#/definitions/gettableSilence",
"type": "object"
@@ -7472,6 +7490,43 @@
]
}
},
"/ruler/grafana/api/v1/trash/rule/guid/{RuleGUID}": {
"delete": {
"description": "Permanently delete a rule from trash by GUID",
"operationId": "RouteDeleteRuleFromTrashByGUID",
"parameters": [
{
"in": "path",
"name": "RuleGUID",
"required": true,
"type": "string"
}
],
"produces": [
"application/json"
],
"responses": {
"202": {
"description": "Ack",
"schema": {
"$ref": "#/definitions/Ack"
}
},
"403": {
"description": "ForbiddenError",
"schema": {
"$ref": "#/definitions/ForbiddenError"
}
},
"404": {
"description": " Not found."
}
},
"tags": [
"ruler"
]
}
},
"/ruler/{DatasourceUID}/api/v1/rules": {
"get": {
"description": "List rule groups",
+58 -3
View File
@@ -2173,6 +2173,43 @@
}
}
},
"/ruler/grafana/api/v1/trash/rule/guid/{RuleGUID}": {
"delete": {
"description": "Permanently delete a rule from trash by GUID",
"produces": [
"application/json"
],
"tags": [
"ruler"
],
"operationId": "RouteDeleteRuleFromTrashByGUID",
"parameters": [
{
"type": "string",
"name": "RuleGUID",
"in": "path",
"required": true
}
],
"responses": {
"202": {
"description": "Ack",
"schema": {
"$ref": "#/definitions/Ack"
}
},
"403": {
"description": "ForbiddenError",
"schema": {
"$ref": "#/definitions/ForbiddenError"
}
},
"404": {
"description": " Not found."
}
}
}
},
"/ruler/{DatasourceUID}/api/v1/rules": {
"get": {
"description": "List rule groups",
@@ -4584,6 +4621,9 @@
},
"metric": {
"type": "string"
},
"targetDatasourceUid": {
"type": "string"
}
}
},
@@ -5795,6 +5835,9 @@
"Error"
]
},
"guid": {
"type": "string"
},
"intervalSeconds": {
"type": "integer",
"format": "int64"
@@ -7685,6 +7728,11 @@
"description": "Name of the recorded metric.",
"type": "string",
"example": "grafana_alerts_ratio"
},
"target_datasource_uid": {
"description": "Which data source should be used to write the output of the recording rule, specified by UID.",
"type": "string",
"example": "my-prom"
}
}
},
@@ -8544,6 +8592,15 @@
"description": "Name of the associated template definition for this result.",
"type": "string"
},
"scope": {
"description": "Scope that was successfully used to interpolate the template. If the root scope \".\" fails, more specific\nscopes will be tried, such as \".Alerts', or \".Alert\".",
"type": "string",
"enum": [
".",
".Alerts",
".Alert"
]
},
"text": {
"description": "Interpolated value of the template.",
"type": "string"
@@ -8681,9 +8738,8 @@
}
},
"URL": {
"description": "The general form represented is:\n\n[scheme:][//[userinfo@]host][/]path[?query][#fragment]\n\nURLs that do not start with a slash after the scheme are interpreted as:\n\nscheme:opaque[?query][#fragment]\n\nThe Host field contains the host and port subcomponents of the URL.\nWhen the port is present, it is separated from the host with a colon.\nWhen the host is an IPv6 address, it must be enclosed in square brackets:\n\"[fe80::1]:80\". The [net.JoinHostPort] function combines a host and port\ninto a string suitable for the Host field, adding square brackets to\nthe host when necessary.\n\nNote that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.\nA consequence is that it is impossible to tell which slashes in the Path were\nslashes in the raw URL and which were %2f. This distinction is rarely important,\nbut when it is, the code should use the [URL.EscapedPath] method, which preserves\nthe original encoding of Path.\n\nThe RawPath field is an optional field which is only set when the default\nencoding of Path is different from the escaped path. See the EscapedPath method\nfor more details.\n\nURL's String method uses the EscapedPath method to obtain the path.",
"type": "object",
"title": "A URL represents a parsed URL (technically, a URI reference).",
"title": "URL is a custom URL type that allows validation at configuration load time.",
"properties": {
"ForceQuery": {
"type": "boolean"
@@ -9246,7 +9302,6 @@
}
},
"gettableSilences": {
"description": "GettableSilences gettable silences",
"type": "array",
"items": {
"type": "object",