Compare commits
11 Commits
ash/react-
...
jacobsonmt
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43e8319ebf | ||
|
|
5a8696cf6b | ||
|
|
78f8acb056 | ||
|
|
589b359fef | ||
|
|
b833a10a0c | ||
|
|
993d2f80e8 | ||
|
|
e01043030c | ||
|
|
38103a2ff0 | ||
|
|
d732af94ff | ||
|
|
0fa9f3a247 | ||
|
|
d220d765b8 |
@@ -1246,4 +1246,9 @@ export interface FeatureToggles {
|
|||||||
* Enable template dashboards
|
* Enable template dashboards
|
||||||
*/
|
*/
|
||||||
dashboardTemplates?: boolean;
|
dashboardTemplates?: boolean;
|
||||||
|
/**
|
||||||
|
* Enables the ability to create multiple alerting policies
|
||||||
|
* @default false
|
||||||
|
*/
|
||||||
|
alertingMultiplePolicies?: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,13 +16,28 @@ import (
|
|||||||
"github.com/grafana/grafana/pkg/services/apiserver/endpoints/request"
|
"github.com/grafana/grafana/pkg/services/apiserver/endpoints/request"
|
||||||
gapiutil "github.com/grafana/grafana/pkg/services/apiserver/utils"
|
gapiutil "github.com/grafana/grafana/pkg/services/apiserver/utils"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/util"
|
"github.com/grafana/grafana/pkg/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ConvertToK8sResource(orgID int64, r definitions.Route, version string, namespacer request.NamespaceMapper) (*model.RoutingTree, error) {
|
func ConvertToK8sResources(orgID int64, routes legacy_storage.ManagedRoutes, namespacer request.NamespaceMapper) (*model.RoutingTreeList, error) {
|
||||||
|
result := &model.RoutingTreeList{
|
||||||
|
Items: make([]model.RoutingTree, 0, len(routes)),
|
||||||
|
}
|
||||||
|
for _, r := range routes {
|
||||||
|
k8sResource, err := ConvertToK8sResource(orgID, r, namespacer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to convert route %q to k8s resource: %w", r.Name, err)
|
||||||
|
}
|
||||||
|
result.Items = append(result.Items, *k8sResource)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConvertToK8sResource(orgID int64, r *legacy_storage.ManagedRoute, namespacer request.NamespaceMapper) (*model.RoutingTree, error) {
|
||||||
spec := model.RoutingTreeSpec{
|
spec := model.RoutingTreeSpec{
|
||||||
Defaults: model.RoutingTreeRouteDefaults{
|
Defaults: model.RoutingTreeRouteDefaults{
|
||||||
GroupBy: r.GroupByStr,
|
GroupBy: r.GroupBy,
|
||||||
GroupWait: optionalPrometheusDurationToString(r.GroupWait),
|
GroupWait: optionalPrometheusDurationToString(r.GroupWait),
|
||||||
GroupInterval: optionalPrometheusDurationToString(r.GroupInterval),
|
GroupInterval: optionalPrometheusDurationToString(r.GroupInterval),
|
||||||
RepeatInterval: optionalPrometheusDurationToString(r.RepeatInterval),
|
RepeatInterval: optionalPrometheusDurationToString(r.RepeatInterval),
|
||||||
@@ -39,9 +54,9 @@ func ConvertToK8sResource(orgID int64, r definitions.Route, version string, name
|
|||||||
|
|
||||||
var result = &model.RoutingTree{
|
var result = &model.RoutingTree{
|
||||||
ObjectMeta: metav1.ObjectMeta{
|
ObjectMeta: metav1.ObjectMeta{
|
||||||
Name: model.UserDefinedRoutingTreeName,
|
Name: r.Name,
|
||||||
Namespace: namespacer(orgID),
|
Namespace: namespacer(orgID),
|
||||||
ResourceVersion: version,
|
ResourceVersion: r.Version,
|
||||||
},
|
},
|
||||||
Spec: spec,
|
Spec: spec,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"github.com/grafana/grafana/pkg/services/apiserver/endpoints/request"
|
"github.com/grafana/grafana/pkg/services/apiserver/endpoints/request"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
alerting_models "github.com/grafana/grafana/pkg/services/ngalert/models"
|
alerting_models "github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -22,9 +23,11 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type RouteService interface {
|
type RouteService interface {
|
||||||
GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error)
|
GetManagedRoutes(ctx context.Context, orgID int64) (legacy_storage.ManagedRoutes, error)
|
||||||
UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p alerting_models.Provenance, version string) (definitions.Route, string, error)
|
GetManagedRoute(ctx context.Context, orgID int64, name string) (legacy_storage.ManagedRoute, error)
|
||||||
ResetPolicyTree(ctx context.Context, orgID int64, p alerting_models.Provenance) (definitions.Route, error)
|
DeleteManagedRoute(ctx context.Context, orgID int64, name string, p alerting_models.Provenance, version string) error
|
||||||
|
CreateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p alerting_models.Provenance) (*legacy_storage.ManagedRoute, error)
|
||||||
|
UpdateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p alerting_models.Provenance, version string) (*legacy_storage.ManagedRoute, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type legacyStorage struct {
|
type legacyStorage struct {
|
||||||
@@ -55,56 +58,76 @@ func (s *legacyStorage) ConvertToTable(ctx context.Context, object runtime.Objec
|
|||||||
return s.tableConverter.ConvertToTable(ctx, object, tableOptions)
|
return s.tableConverter.ConvertToTable(ctx, object, tableOptions)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *legacyStorage) getUserDefinedRoutingTree(ctx context.Context) (*model.RoutingTree, error) {
|
func (s *legacyStorage) List(ctx context.Context, _ *internalversion.ListOptions) (runtime.Object, error) {
|
||||||
orgId, err := request.OrgIDForList(ctx)
|
orgId, err := request.OrgIDForList(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
res, version, err := s.service.GetPolicyTree(ctx, orgId)
|
managedRoutes, err := s.service.GetManagedRoutes(ctx, orgId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return ConvertToK8sResource(orgId, res, version, s.namespacer)
|
return ConvertToK8sResources(orgId, managedRoutes, s.namespacer)
|
||||||
}
|
|
||||||
|
|
||||||
func (s *legacyStorage) List(ctx context.Context, _ *internalversion.ListOptions) (runtime.Object, error) {
|
|
||||||
user, err := s.getUserDefinedRoutingTree(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &model.RoutingTreeList{
|
|
||||||
Items: []model.RoutingTree{
|
|
||||||
*user,
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *legacyStorage) Get(ctx context.Context, name string, _ *metav1.GetOptions) (runtime.Object, error) {
|
func (s *legacyStorage) Get(ctx context.Context, name string, _ *metav1.GetOptions) (runtime.Object, error) {
|
||||||
if name != model.UserDefinedRoutingTreeName {
|
info, err := request.NamespaceInfoFrom(ctx, true)
|
||||||
return nil, errors.NewNotFound(ResourceInfo.GroupResource(), name)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
return s.getUserDefinedRoutingTree(ctx)
|
managedRoute, err := s.service.GetManagedRoute(ctx, info.OrgID, name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ConvertToK8sResource(info.OrgID, &managedRoute, s.namespacer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *legacyStorage) Create(_ context.Context,
|
func (s *legacyStorage) Create(ctx context.Context,
|
||||||
_ runtime.Object,
|
obj runtime.Object,
|
||||||
_ rest.ValidateObjectFunc,
|
createValidation rest.ValidateObjectFunc,
|
||||||
_ *metav1.CreateOptions,
|
_ *metav1.CreateOptions,
|
||||||
) (runtime.Object, error) {
|
) (runtime.Object, error) {
|
||||||
return nil, errors.NewMethodNotSupported(ResourceInfo.GroupResource(), "create")
|
info, err := request.NamespaceInfoFrom(ctx, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if createValidation != nil {
|
||||||
|
if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p, ok := obj.(*model.RoutingTree)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("expected %s but got %s", ResourceInfo.GroupVersionKind(), obj.GetObjectKind().GroupVersionKind())
|
||||||
|
}
|
||||||
|
domainModel, _, err := convertToDomainModel(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
created, err := s.service.CreateManagedRoute(ctx, info.OrgID, p.Name, domainModel, alerting_models.ProvenanceNone)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ConvertToK8sResource(info.OrgID, created, s.namespacer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, _ rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, _ bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
|
func (s *legacyStorage) Update(
|
||||||
if name != model.UserDefinedRoutingTreeName {
|
ctx context.Context,
|
||||||
return nil, false, errors.NewNotFound(ResourceInfo.GroupResource(), name)
|
name string,
|
||||||
}
|
objInfo rest.UpdatedObjectInfo,
|
||||||
|
_ rest.ValidateObjectFunc,
|
||||||
|
updateValidation rest.ValidateObjectUpdateFunc,
|
||||||
|
_ bool,
|
||||||
|
_ *metav1.UpdateOptions,
|
||||||
|
) (runtime.Object, bool, error) {
|
||||||
info, err := request.NamespaceInfoFrom(ctx, true)
|
info, err := request.NamespaceInfoFrom(ctx, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
old, err := s.Get(ctx, model.UserDefinedRoutingTreeName, nil)
|
old, err := s.Get(ctx, name, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return old, false, err
|
return old, false, err
|
||||||
}
|
}
|
||||||
@@ -122,24 +145,26 @@ func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.Up
|
|||||||
return nil, false, fmt.Errorf("expected %s but got %s", ResourceInfo.GroupVersionKind(), obj.GetObjectKind().GroupVersionKind())
|
return nil, false, fmt.Errorf("expected %s but got %s", ResourceInfo.GroupVersionKind(), obj.GetObjectKind().GroupVersionKind())
|
||||||
}
|
}
|
||||||
|
|
||||||
model, version, err := convertToDomainModel(p)
|
domainModel, version, err := convertToDomainModel(p)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
updated, updatedVersion, err := s.service.UpdatePolicyTree(ctx, info.OrgID, model, alerting_models.ProvenanceNone, version)
|
updated, err := s.service.UpdateManagedRoute(ctx, info.OrgID, p.Name, domainModel, alerting_models.ProvenanceNone, version)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
obj, err = ConvertToK8sResource(info.OrgID, updated, updatedVersion, s.namespacer)
|
obj, err = ConvertToK8sResource(info.OrgID, updated, s.namespacer)
|
||||||
return obj, false, err
|
return obj, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete implements rest.GracefulDeleter. It is needed for API server to not crash when it registers DeleteCollection method
|
// Delete implements rest.GracefulDeleter. It is needed for API server to not crash when it registers DeleteCollection method
|
||||||
func (s *legacyStorage) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, opts *metav1.DeleteOptions) (runtime.Object, bool, error) {
|
func (s *legacyStorage) Delete(
|
||||||
if name != model.UserDefinedRoutingTreeName {
|
ctx context.Context,
|
||||||
return nil, false, errors.NewNotFound(ResourceInfo.GroupResource(), name)
|
name string,
|
||||||
}
|
deleteValidation rest.ValidateObjectFunc,
|
||||||
|
options *metav1.DeleteOptions,
|
||||||
|
) (runtime.Object, bool, error) {
|
||||||
info, err := request.NamespaceInfoFrom(ctx, true)
|
info, err := request.NamespaceInfoFrom(ctx, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
@@ -155,10 +180,14 @@ func (s *legacyStorage) Delete(ctx context.Context, name string, deleteValidatio
|
|||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_, err = s.service.ResetPolicyTree(ctx, info.OrgID, alerting_models.ProvenanceNone) // TODO add support for dry-run option
|
version := ""
|
||||||
|
if options.Preconditions != nil && options.Preconditions.ResourceVersion != nil {
|
||||||
|
version = *options.Preconditions.ResourceVersion
|
||||||
|
}
|
||||||
|
err = s.service.DeleteManagedRoute(ctx, info.OrgID, name, alerting_models.ProvenanceNone, version) // TODO add support for dry-run option
|
||||||
return old, false, err
|
return old, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *legacyStorage) DeleteCollection(_ context.Context, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions, _ *internalversion.ListOptions) (runtime.Object, error) {
|
func (s *legacyStorage) DeleteCollection(_ context.Context, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions, _ *internalversion.ListOptions) (runtime.Object, error) {
|
||||||
return nil, errors.NewMethodNotSupported(ResourceInfo.GroupResource(), "delete")
|
return nil, errors.NewMethodNotSupported(ResourceInfo.GroupResource(), "deleteCollection")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package routingtree
|
package routingtree
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||||
"k8s.io/apimachinery/pkg/runtime"
|
"k8s.io/apimachinery/pkg/runtime"
|
||||||
|
|
||||||
model "github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
|
model "github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
|
||||||
@@ -14,5 +16,18 @@ var ResourceInfo = utils.NewResourceInfo(kind.Group(), kind.Version(),
|
|||||||
kind.GroupVersionResource().Resource, strings.ToLower(kind.Kind()), kind.Kind(),
|
kind.GroupVersionResource().Resource, strings.ToLower(kind.Kind()), kind.Kind(),
|
||||||
func() runtime.Object { return kind.ZeroValue() },
|
func() runtime.Object { return kind.ZeroValue() },
|
||||||
func() runtime.Object { return kind.ZeroListValue() },
|
func() runtime.Object { return kind.ZeroListValue() },
|
||||||
utils.TableColumns{},
|
utils.TableColumns{
|
||||||
|
Definition: []metav1.TableColumnDefinition{
|
||||||
|
{Name: "Name", Type: "string", Format: "name"},
|
||||||
|
},
|
||||||
|
Reader: func(obj any) ([]interface{}, error) {
|
||||||
|
r, ok := obj.(*model.RoutingTree)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("expected resource or info")
|
||||||
|
}
|
||||||
|
return []interface{}{
|
||||||
|
r.Name,
|
||||||
|
}, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2158,6 +2158,15 @@ var (
|
|||||||
Owner: grafanaSharingSquad,
|
Owner: grafanaSharingSquad,
|
||||||
FrontendOnly: false,
|
FrontendOnly: false,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "alertingMultiplePolicies",
|
||||||
|
Description: "Enables the ability to create multiple alerting policies",
|
||||||
|
Stage: FeatureStageExperimental,
|
||||||
|
Owner: grafanaAlertingSquad,
|
||||||
|
HideFromAdminPage: true,
|
||||||
|
HideFromDocs: true,
|
||||||
|
Expression: "false",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -277,3 +277,4 @@ pluginStoreServiceLoading,experimental,@grafana/plugins-platform-backend,false,f
|
|||||||
onlyStoreActionSets,GA,@grafana/identity-access-team,false,false,false
|
onlyStoreActionSets,GA,@grafana/identity-access-team,false,false,false
|
||||||
panelTimeSettings,experimental,@grafana/dashboards-squad,false,false,false
|
panelTimeSettings,experimental,@grafana/dashboards-squad,false,false,false
|
||||||
dashboardTemplates,experimental,@grafana/sharing-squad,false,false,false
|
dashboardTemplates,experimental,@grafana/sharing-squad,false,false,false
|
||||||
|
alertingMultiplePolicies,experimental,@grafana/alerting-squad,false,false,false
|
||||||
|
|||||||
|
@@ -1117,4 +1117,8 @@ const (
|
|||||||
// FlagDashboardTemplates
|
// FlagDashboardTemplates
|
||||||
// Enable template dashboards
|
// Enable template dashboards
|
||||||
FlagDashboardTemplates = "dashboardTemplates"
|
FlagDashboardTemplates = "dashboardTemplates"
|
||||||
|
|
||||||
|
// FlagAlertingMultiplePolicies
|
||||||
|
// Enables the ability to create multiple alerting policies
|
||||||
|
FlagAlertingMultiplePolicies = "alertingMultiplePolicies"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -405,6 +405,21 @@
|
|||||||
"expression": "true"
|
"expression": "true"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"metadata": {
|
||||||
|
"name": "alertingMultiplePolicies",
|
||||||
|
"resourceVersion": "1762186293341",
|
||||||
|
"creationTimestamp": "2025-11-03T16:11:33Z"
|
||||||
|
},
|
||||||
|
"spec": {
|
||||||
|
"description": "Enables the ability to create multiple alerting policies",
|
||||||
|
"stage": "experimental",
|
||||||
|
"codeowner": "@grafana/alerting-squad",
|
||||||
|
"hideFromAdminPage": true,
|
||||||
|
"hideFromDocs": true,
|
||||||
|
"expression": "false"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"name": "alertingNotificationHistory",
|
"name": "alertingNotificationHistory",
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/hcl"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/hcl"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
alerting_models "github.com/grafana/grafana/pkg/services/ngalert/models"
|
alerting_models "github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/provisioning"
|
"github.com/grafana/grafana/pkg/services/ngalert/provisioning"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
||||||
"github.com/grafana/grafana/pkg/util"
|
"github.com/grafana/grafana/pkg/util"
|
||||||
@@ -58,6 +59,9 @@ type NotificationPolicyService interface {
|
|||||||
GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error)
|
GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error)
|
||||||
UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p alerting_models.Provenance, version string) (definitions.Route, string, error)
|
UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p alerting_models.Provenance, version string) (definitions.Route, string, error)
|
||||||
ResetPolicyTree(ctx context.Context, orgID int64, provenance alerting_models.Provenance) (definitions.Route, error)
|
ResetPolicyTree(ctx context.Context, orgID int64, provenance alerting_models.Provenance) (definitions.Route, error)
|
||||||
|
|
||||||
|
GetManagedRoute(ctx context.Context, orgID int64, name string) (legacy_storage.ManagedRoute, error)
|
||||||
|
GetManagedRoutes(ctx context.Context, orgID int64) (legacy_storage.ManagedRoutes, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type MuteTimingService interface {
|
type MuteTimingService interface {
|
||||||
@@ -96,19 +100,43 @@ func (srv *ProvisioningSrv) RouteGetPolicyTree(c *contextmodel.ReqContext) respo
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (srv *ProvisioningSrv) RouteGetPolicyTreeExport(c *contextmodel.ReqContext) response.Response {
|
func (srv *ProvisioningSrv) RouteGetPolicyTreeExport(c *contextmodel.ReqContext) response.Response {
|
||||||
policies, _, err := srv.policies.GetPolicyTree(c.Req.Context(), c.GetOrgID())
|
if !srv.featureManager.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) {
|
||||||
if err != nil {
|
// Default to the old behavior of exporting the single user-defined policy tree without a "name" field.
|
||||||
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
|
policy, _, err := srv.policies.GetPolicyTree(c.Req.Context(), c.GetOrgID())
|
||||||
return ErrResp(http.StatusNotFound, err, "")
|
if err != nil {
|
||||||
|
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
|
||||||
|
return ErrResp(http.StatusNotFound, err, "")
|
||||||
|
}
|
||||||
|
return ErrResp(http.StatusInternalServerError, err, "")
|
||||||
}
|
}
|
||||||
return ErrResp(http.StatusInternalServerError, err, "")
|
e, err := AlertingFileExportFromRoute(c.GetOrgID(), policy)
|
||||||
|
if err != nil {
|
||||||
|
return ErrResp(http.StatusInternalServerError, err, "failed to create alerting file export")
|
||||||
|
}
|
||||||
|
return exportResponse(c, e)
|
||||||
}
|
}
|
||||||
|
|
||||||
e, err := AlertingFileExportFromRoute(c.GetOrgID(), policies)
|
routeName := c.Query("routeName")
|
||||||
|
var routesToExport legacy_storage.ManagedRoutes
|
||||||
|
if routeName == "" {
|
||||||
|
// Interpreted as Export All.
|
||||||
|
var err error
|
||||||
|
routesToExport, err = srv.policies.GetManagedRoutes(c.Req.Context(), c.GetOrgID())
|
||||||
|
if err != nil {
|
||||||
|
return response.ErrOrFallback(http.StatusInternalServerError, "failed to export all notification policy trees", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
managedRoute, err := srv.policies.GetManagedRoute(c.Req.Context(), c.GetOrgID(), routeName)
|
||||||
|
if err != nil {
|
||||||
|
return response.ErrOrFallback(http.StatusInternalServerError, "failed to export notification policy tree", err)
|
||||||
|
}
|
||||||
|
routesToExport = legacy_storage.ManagedRoutes{&managedRoute}
|
||||||
|
}
|
||||||
|
|
||||||
|
e, err := AlertingFileExportFromManagedRoutes(c.GetOrgID(), routesToExport)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ErrResp(http.StatusInternalServerError, err, "failed to create alerting file export")
|
return ErrResp(http.StatusInternalServerError, err, "failed to create alerting file export")
|
||||||
}
|
}
|
||||||
|
|
||||||
return exportResponse(c, e)
|
return exportResponse(c, e)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -593,6 +621,9 @@ func escapeAlertingFileExport(body definitions.AlertingFileExport) definitions.A
|
|||||||
}
|
}
|
||||||
|
|
||||||
func escapeRouteExport(r *definitions.RouteExport) {
|
func escapeRouteExport(r *definitions.RouteExport) {
|
||||||
|
if r.Name != nil {
|
||||||
|
r.Name = util.Pointer(addEscapeCharactersToString(*r.Name))
|
||||||
|
}
|
||||||
r.Receiver = addEscapeCharactersToString(r.Receiver)
|
r.Receiver = addEscapeCharactersToString(r.Receiver)
|
||||||
if r.GroupByStr != nil {
|
if r.GroupByStr != nil {
|
||||||
groupByStr := make([]string, len(*r.GroupByStr))
|
groupByStr := make([]string, len(*r.GroupByStr))
|
||||||
|
|||||||
@@ -2248,6 +2248,7 @@ func createTestRequestCtx() contextmodel.ReqContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type fakeNotificationPolicyService struct {
|
type fakeNotificationPolicyService struct {
|
||||||
|
NotificationPolicyService
|
||||||
tree definitions.Route
|
tree definitions.Route
|
||||||
prov models.Provenance
|
prov models.Provenance
|
||||||
}
|
}
|
||||||
@@ -2318,7 +2319,9 @@ func (f *fakeNotificationPolicyService) ResetPolicyTree(ctx context.Context, org
|
|||||||
return f.tree, nil
|
return f.tree, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type fakeFailingNotificationPolicyService struct{}
|
type fakeFailingNotificationPolicyService struct {
|
||||||
|
NotificationPolicyService
|
||||||
|
}
|
||||||
|
|
||||||
func (f *fakeFailingNotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
|
func (f *fakeFailingNotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
|
||||||
return definitions.Route{}, "", fmt.Errorf("something went wrong")
|
return definitions.Route{}, "", fmt.Errorf("something went wrong")
|
||||||
@@ -2332,7 +2335,9 @@ func (f *fakeFailingNotificationPolicyService) ResetPolicyTree(ctx context.Conte
|
|||||||
return definitions.Route{}, fmt.Errorf("something went wrong")
|
return definitions.Route{}, fmt.Errorf("something went wrong")
|
||||||
}
|
}
|
||||||
|
|
||||||
type fakeRejectingNotificationPolicyService struct{}
|
type fakeRejectingNotificationPolicyService struct {
|
||||||
|
NotificationPolicyService
|
||||||
|
}
|
||||||
|
|
||||||
type fakeRejectingNotificationSettingsValidatorProvider struct{}
|
type fakeRejectingNotificationSettingsValidatorProvider struct{}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
|
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/util"
|
"github.com/grafana/grafana/pkg/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -338,6 +339,21 @@ func AlertingFileExportFromRoute(orgID int64, route definitions.Route) (definiti
|
|||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AlertingFileExportFromManagedRoutes creates a definitions.AlertingFileExport DTO from one or more legacy_storage.ManagedRoute.
|
||||||
|
func AlertingFileExportFromManagedRoutes(orgID int64, routes legacy_storage.ManagedRoutes) (definitions.AlertingFileExport, error) {
|
||||||
|
f := definitions.AlertingFileExport{
|
||||||
|
APIVersion: 1,
|
||||||
|
Policies: make([]definitions.NotificationPolicyExport, 0, len(routes)),
|
||||||
|
}
|
||||||
|
for _, route := range routes {
|
||||||
|
f.Policies = append(f.Policies, definitions.NotificationPolicyExport{
|
||||||
|
OrgID: orgID,
|
||||||
|
RouteExport: RouteExportFromManagedRoute(route),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
// RouteExportFromRoute creates a definitions.RouteExport DTO from definitions.Route.
|
// RouteExportFromRoute creates a definitions.RouteExport DTO from definitions.Route.
|
||||||
func RouteExportFromRoute(route *definitions.Route) *definitions.RouteExport {
|
func RouteExportFromRoute(route *definitions.Route) *definitions.RouteExport {
|
||||||
toStringIfNotNil := func(d *model.Duration) *string {
|
toStringIfNotNil := func(d *model.Duration) *string {
|
||||||
@@ -383,6 +399,18 @@ func RouteExportFromRoute(route *definitions.Route) *definitions.RouteExport {
|
|||||||
return &export
|
return &export
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RouteExportFromManagedRoute creates a definitions.RouteExport DTO from legacy_storage.ManagedRoute.
|
||||||
|
func RouteExportFromManagedRoute(route *legacy_storage.ManagedRoute) *definitions.RouteExport {
|
||||||
|
apiRoute := route.AsRoute()
|
||||||
|
export := RouteExportFromRoute(&apiRoute)
|
||||||
|
if route.Name == legacy_storage.UserDefinedRoutingTreeName {
|
||||||
|
export.Name = nil // Functionally this shouldn't matter, aesthetically this prefers an empty name over "user-defined".
|
||||||
|
} else {
|
||||||
|
export.Name = OmitDefault(util.Pointer(route.Name))
|
||||||
|
}
|
||||||
|
return export
|
||||||
|
}
|
||||||
|
|
||||||
// OmitDefault returns nil if the value is the default.
|
// OmitDefault returns nil if the value is the default.
|
||||||
func OmitDefault[T comparable](v *T) *T {
|
func OmitDefault[T comparable](v *T) *T {
|
||||||
var def T
|
var def T
|
||||||
|
|||||||
@@ -775,10 +775,11 @@ func fromPrometheusConfig(prometheusConfig config.Config) PostableApiAlertingCon
|
|||||||
|
|
||||||
// swagger:model
|
// swagger:model
|
||||||
type PostableUserConfig struct {
|
type PostableUserConfig struct {
|
||||||
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
|
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
|
||||||
AlertmanagerConfig PostableApiAlertingConfig `yaml:"alertmanager_config" json:"alertmanager_config"`
|
AlertmanagerConfig PostableApiAlertingConfig `yaml:"alertmanager_config" json:"alertmanager_config"`
|
||||||
ExtraConfigs []ExtraConfiguration `yaml:"extra_config,omitempty" json:"extra_config,omitempty"`
|
ExtraConfigs []ExtraConfiguration `yaml:"extra_config,omitempty" json:"extra_config,omitempty"`
|
||||||
amSimple map[string]interface{} `yaml:"-" json:"-"`
|
ManagedRoutes map[string]*definition.Route `yaml:"managed_routes,omitempty" json:"managed_routes,omitempty"` // TODO: Move to ConfigRevision?
|
||||||
|
amSimple map[string]interface{} `yaml:"-" json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *PostableUserConfig) GetMergedAlertmanagerConfig() (MergeResult, error) {
|
func (c *PostableUserConfig) GetMergedAlertmanagerConfig() (MergeResult, error) {
|
||||||
|
|||||||
@@ -70,7 +70,8 @@ type NotificationPolicyExport struct {
|
|||||||
// RouteExport is the provisioned file export of definitions.Route. This is needed to hide fields that aren't useable in
|
// RouteExport is the provisioned file export of definitions.Route. This is needed to hide fields that aren't useable in
|
||||||
// provisioning file format. An alternative would be to define a custom MarshalJSON and MarshalYAML that excludes them.
|
// provisioning file format. An alternative would be to define a custom MarshalJSON and MarshalYAML that excludes them.
|
||||||
type RouteExport struct {
|
type RouteExport struct {
|
||||||
Receiver string `yaml:"receiver,omitempty" json:"receiver,omitempty" hcl:"contact_point"`
|
Name *string `yaml:"name,omitempty" json:"name,omitempty" hcl:"name,optional"`
|
||||||
|
Receiver string `yaml:"receiver,omitempty" json:"receiver,omitempty" hcl:"contact_point"`
|
||||||
|
|
||||||
GroupByStr *[]string `yaml:"group_by,omitempty" json:"group_by,omitempty" hcl:"group_by"`
|
GroupByStr *[]string `yaml:"group_by,omitempty" json:"group_by,omitempty" hcl:"group_by"`
|
||||||
// Deprecated. Remove before v1.0 release.
|
// Deprecated. Remove before v1.0 release.
|
||||||
|
|||||||
@@ -422,7 +422,7 @@ func (ng *AlertNG) init() error {
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Provisioning
|
// Provisioning
|
||||||
policyService := provisioning.NewNotificationPolicyService(configStore, ng.store, ng.store, ng.Cfg.UnifiedAlerting, ng.Log)
|
policyService := provisioning.NewNotificationPolicyService(configStore, ng.store, ng.store, ng.Cfg.UnifiedAlerting, ng.FeatureToggles, ng.Log)
|
||||||
contactPointService := provisioning.NewContactPointService(configStore, ng.SecretsService, ng.store, ng.store, provisioningReceiverService, ng.Log, ng.store, ng.ResourcePermissions)
|
contactPointService := provisioning.NewContactPointService(configStore, ng.SecretsService, ng.store, ng.store, provisioningReceiverService, ng.Log, ng.store, ng.ResourcePermissions)
|
||||||
templateService := provisioning.NewTemplateService(configStore, ng.store, ng.store, ng.Log)
|
templateService := provisioning.NewTemplateService(configStore, ng.store, ng.store, ng.Log)
|
||||||
muteTimingService := provisioning.NewMuteTimingService(configStore, ng.store, ng.store, ng.Log, ng.store)
|
muteTimingService := provisioning.NewMuteTimingService(configStore, ng.store, ng.store, ng.Log, ng.store)
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import (
|
|||||||
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
|
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
|
||||||
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
|
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
||||||
"github.com/grafana/grafana/pkg/services/notifications"
|
"github.com/grafana/grafana/pkg/services/notifications"
|
||||||
"github.com/grafana/grafana/pkg/setting"
|
"github.com/grafana/grafana/pkg/setting"
|
||||||
@@ -336,6 +337,9 @@ func (am *alertmanager) applyConfig(ctx context.Context, cfg *apimodels.Postable
|
|||||||
return false, fmt.Errorf("failed to decrypt external configurations: %w", err)
|
return false, fmt.Errorf("failed to decrypt external configurations: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add managed routes to the configuration.
|
||||||
|
cfg.AlertmanagerConfig.Route = legacy_storage.WithManagedRoutes(cfg.AlertmanagerConfig.Route, cfg.ManagedRoutes)
|
||||||
|
|
||||||
mergeResult, err := cfg.GetMergedAlertmanagerConfig()
|
mergeResult, err := cfg.GetMergedAlertmanagerConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, fmt.Errorf("failed to get full alertmanager configuration: %w", err)
|
return false, fmt.Errorf("failed to get full alertmanager configuration: %w", err)
|
||||||
|
|||||||
@@ -12,6 +12,12 @@ var (
|
|||||||
"Invalid receiver: '{{ .Public.Reason }}'",
|
"Invalid receiver: '{{ .Public.Reason }}'",
|
||||||
errutil.WithPublic("Invalid receiver: '{{ .Public.Reason }}'"),
|
errutil.WithPublic("Invalid receiver: '{{ .Public.Reason }}'"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
ErrRouteExists = errutil.Conflict("alerting.notifications.routes.exists", errutil.WithPublicMessage("Route with this name already exists. Use a different name or update an existing one."))
|
||||||
|
ErrRouteInvalidFormat = errutil.BadRequest("alerting.notifications.routes.invalidFormat").MustTemplate(
|
||||||
|
"Invalid format of the submitted route.",
|
||||||
|
errutil.WithPublic("Invalid format of the submitted route: {{.Public.Error}}. Correct the payload and try again."),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
func makeErrBadAlertmanagerConfiguration(err error) error {
|
func makeErrBadAlertmanagerConfiguration(err error) error {
|
||||||
@@ -33,3 +39,12 @@ func MakeErrReceiverInvalid(err error) error {
|
|||||||
}
|
}
|
||||||
return ErrReceiverInvalid.Build(data)
|
return ErrReceiverInvalid.Build(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func MakeErrRouteInvalidFormat(err error) error {
|
||||||
|
return ErrRouteInvalidFormat.Build(errutil.TemplateData{
|
||||||
|
Public: map[string]any{
|
||||||
|
"Error": err.Error(),
|
||||||
|
},
|
||||||
|
Error: err,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
380
pkg/services/ngalert/notifier/legacy_storage/routes.go
Normal file
380
pkg/services/ngalert/notifier/legacy_storage/routes.go
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
package legacy_storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"hash"
|
||||||
|
"hash/fnv"
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/grafana/alerting/definition"
|
||||||
|
"github.com/prometheus/alertmanager/dispatch"
|
||||||
|
"github.com/prometheus/alertmanager/pkg/labels"
|
||||||
|
"github.com/prometheus/common/model"
|
||||||
|
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
const UserDefinedRoutingTreeName = "user-defined"
|
||||||
|
const NamedRouteMatcher = "__grafana_managed_route__"
|
||||||
|
|
||||||
|
type ManagedRoute struct {
|
||||||
|
Name string
|
||||||
|
Version string
|
||||||
|
|
||||||
|
Receiver string
|
||||||
|
GroupBy []string
|
||||||
|
GroupWait *model.Duration
|
||||||
|
GroupInterval *model.Duration
|
||||||
|
RepeatInterval *model.Duration
|
||||||
|
Routes []*definition.Route
|
||||||
|
|
||||||
|
Provenance models.Provenance
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ManagedRoute) AsRoute() definition.Route {
|
||||||
|
// Only need to copy the fields that are valid for a root route.
|
||||||
|
return definition.Route{
|
||||||
|
Receiver: r.Receiver,
|
||||||
|
GroupByStr: r.GroupBy,
|
||||||
|
GroupWait: r.GroupWait,
|
||||||
|
GroupInterval: r.GroupInterval,
|
||||||
|
RepeatInterval: r.RepeatInterval,
|
||||||
|
Routes: r.Routes,
|
||||||
|
Provenance: definitions.Provenance(r.Provenance),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ManagedRoute) GeneratedSubRoute() *definition.Route {
|
||||||
|
amRoute := r.AsRoute()
|
||||||
|
|
||||||
|
// It's important that the generated sub-route is fully defined so that they will never rely on the values of the root.
|
||||||
|
defaultOpts := dispatch.DefaultRouteOpts
|
||||||
|
if amRoute.GroupWait == nil {
|
||||||
|
gw := model.Duration(defaultOpts.GroupWait)
|
||||||
|
amRoute.GroupWait = &gw
|
||||||
|
}
|
||||||
|
if amRoute.GroupInterval == nil {
|
||||||
|
gi := model.Duration(defaultOpts.GroupInterval)
|
||||||
|
amRoute.GroupInterval = &gi
|
||||||
|
}
|
||||||
|
if amRoute.RepeatInterval == nil {
|
||||||
|
ri := model.Duration(defaultOpts.RepeatInterval)
|
||||||
|
amRoute.RepeatInterval = &ri
|
||||||
|
}
|
||||||
|
if r.Name != UserDefinedRoutingTreeName {
|
||||||
|
// Set label matcher.
|
||||||
|
amRoute.ObjectMatchers = definitions.ObjectMatchers{managedRouteMatcher(r.Name)}
|
||||||
|
}
|
||||||
|
return &amRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ManagedRoute) ResourceType() string {
|
||||||
|
return (&definition.Route{}).ResourceType()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ManagedRoute) ResourceID() string {
|
||||||
|
if r.Name == UserDefinedRoutingTreeName {
|
||||||
|
// Backwards compatibility with legacy user-defined routing tree.
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return r.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewManagedRoute(name string, r *definition.Route) *ManagedRoute {
|
||||||
|
return &ManagedRoute{
|
||||||
|
Name: name,
|
||||||
|
Version: CalculateRouteFingerprint(*r),
|
||||||
|
|
||||||
|
Receiver: r.Receiver,
|
||||||
|
GroupBy: r.GroupByStr,
|
||||||
|
GroupWait: r.GroupWait,
|
||||||
|
GroupInterval: r.GroupInterval,
|
||||||
|
RepeatInterval: r.RepeatInterval,
|
||||||
|
Routes: r.Routes,
|
||||||
|
|
||||||
|
Provenance: models.Provenance(r.Provenance),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func managedRouteMatcher(name string) *labels.Matcher {
|
||||||
|
return &labels.Matcher{
|
||||||
|
Type: labels.MatchEqual,
|
||||||
|
Name: NamedRouteMatcher,
|
||||||
|
Value: name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ManagedRoutes []*ManagedRoute
|
||||||
|
|
||||||
|
func (m ManagedRoutes) Sort() {
|
||||||
|
// Sort the keys of the map to ensure consistent ordering. Always ensure that the legacy user-defined routing tree is last.
|
||||||
|
slices.SortFunc(m, func(a, b *ManagedRoute) int {
|
||||||
|
if a.Name == UserDefinedRoutingTreeName {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if b.Name == UserDefinedRoutingTreeName {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return strings.Compare(a.Name, b.Name)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithManagedRoutes(root *definitions.Route, managedRoutes map[string]*definition.Route) *definitions.Route {
|
||||||
|
if len(managedRoutes) == 0 {
|
||||||
|
// If there are no managed routes, we just return the original root.
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
newRoot := *root
|
||||||
|
newManagedRoutes := make([]*definition.Route, 0, len(newRoot.Routes)+len(managedRoutes))
|
||||||
|
for _, k := range slices.Sorted(maps.Keys(managedRoutes)) {
|
||||||
|
// On the off chance that the route is nil or invalid managed route with the restricted name, we skip it.
|
||||||
|
if managedRoutes[k] == nil || k == UserDefinedRoutingTreeName {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newManagedRoutes = append(newManagedRoutes, NewManagedRoute(k, managedRoutes[k]).GeneratedSubRoute())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the user-defined routing tree at the end.
|
||||||
|
newManagedRoutes = append(newManagedRoutes, newRoot.Routes...)
|
||||||
|
newRoot.Routes = newManagedRoutes
|
||||||
|
return &newRoot
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) GetManagedRoute(name string) *ManagedRoute {
|
||||||
|
if name == UserDefinedRoutingTreeName {
|
||||||
|
return NewManagedRoute(UserDefinedRoutingTreeName, rev.Config.AlertmanagerConfig.Route)
|
||||||
|
}
|
||||||
|
route, ok := rev.Config.ManagedRoutes[name]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return NewManagedRoute(name, route)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) GetManagedRoutes() ManagedRoutes {
|
||||||
|
managedRoutes := make(ManagedRoutes, 0, len(rev.Config.ManagedRoutes)+1)
|
||||||
|
for _, k := range slices.Sorted(maps.Keys(rev.Config.ManagedRoutes)) {
|
||||||
|
// On the off chance that the route is nil or invalid managed route with the restricted name, we skip it.
|
||||||
|
if rev.Config.ManagedRoutes[k] == nil || k == UserDefinedRoutingTreeName {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
managedRoutes = append(managedRoutes, NewManagedRoute(k, rev.Config.ManagedRoutes[k]))
|
||||||
|
}
|
||||||
|
|
||||||
|
managedRoutes = append(managedRoutes, NewManagedRoute(UserDefinedRoutingTreeName, rev.Config.AlertmanagerConfig.Route))
|
||||||
|
|
||||||
|
return managedRoutes
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) DeleteManagedRoute(name string) {
|
||||||
|
// Intentionally does not consider if name == UserDefinedRoutingTreeName as it should only be Reset via Update.
|
||||||
|
delete(rev.Config.ManagedRoutes, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) CreateManagedRoute(name string, subtree definitions.Route) (*ManagedRoute, error) {
|
||||||
|
if name == "" {
|
||||||
|
return nil, fmt.Errorf("route name is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == UserDefinedRoutingTreeName {
|
||||||
|
return nil, fmt.Errorf("cannot create a managed route with the name %q, this name is reserved for the user-defined routing tree", UserDefinedRoutingTreeName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exists := rev.Config.ManagedRoutes[name]; exists {
|
||||||
|
return nil, ErrRouteExists.Errorf("")
|
||||||
|
}
|
||||||
|
|
||||||
|
managedRoute := NewManagedRoute(name, &subtree)
|
||||||
|
amRoute := managedRoute.AsRoute()
|
||||||
|
|
||||||
|
err := rev.ValidateRoute(amRoute)
|
||||||
|
if err != nil {
|
||||||
|
return nil, MakeErrRouteInvalidFormat(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if rev.Config.ManagedRoutes == nil {
|
||||||
|
rev.Config.ManagedRoutes = make(map[string]*definition.Route, 1)
|
||||||
|
}
|
||||||
|
rev.Config.ManagedRoutes[name] = &amRoute
|
||||||
|
|
||||||
|
return managedRoute, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) UpdateNamedRoute(name string, subtree definitions.Route) (*ManagedRoute, error) {
|
||||||
|
if name == "" {
|
||||||
|
return nil, fmt.Errorf("route name is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
if existing := rev.GetManagedRoute(name); existing == nil {
|
||||||
|
return nil, fmt.Errorf("managed route %q not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
managedRoute := NewManagedRoute(name, &subtree)
|
||||||
|
amRoute := managedRoute.AsRoute()
|
||||||
|
|
||||||
|
err := rev.ValidateRoute(amRoute)
|
||||||
|
if err != nil {
|
||||||
|
return nil, MakeErrRouteInvalidFormat(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == UserDefinedRoutingTreeName {
|
||||||
|
rev.Config.AlertmanagerConfig.Route = &amRoute
|
||||||
|
} else {
|
||||||
|
if rev.Config.ManagedRoutes == nil {
|
||||||
|
rev.Config.ManagedRoutes = make(map[string]*definition.Route, 1)
|
||||||
|
}
|
||||||
|
rev.Config.ManagedRoutes[name] = &amRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
return managedRoute, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) ResetUserDefinedRoute(defaultCfg *definitions.PostableUserConfig) (*ManagedRoute, error) {
|
||||||
|
// Ensure the new default receiver exists and if not, create it.
|
||||||
|
if err := rev.validateReceiverReferences(*defaultCfg.AlertmanagerConfig.Route); err != nil {
|
||||||
|
// Default receiver doesn't exist, create it.
|
||||||
|
var defaultRcv *definitions.PostableApiReceiver
|
||||||
|
for _, rcv := range defaultCfg.AlertmanagerConfig.Receivers {
|
||||||
|
if rcv.Name == defaultCfg.AlertmanagerConfig.Route.Receiver {
|
||||||
|
defaultRcv = rcv
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if defaultRcv == nil {
|
||||||
|
return nil, fmt.Errorf("inconsistent default configuration: default receiver %q not found", defaultCfg.AlertmanagerConfig.Route.Receiver)
|
||||||
|
}
|
||||||
|
rev.Config.AlertmanagerConfig.Receivers = append(rev.Config.AlertmanagerConfig.Receivers, defaultRcv)
|
||||||
|
}
|
||||||
|
|
||||||
|
return rev.UpdateNamedRoute(UserDefinedRoutingTreeName, *defaultCfg.AlertmanagerConfig.Route)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) ValidateRoute(route definitions.Route) error {
|
||||||
|
err := route.Validate()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = rev.validateReceiverReferences(route)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = rev.validateTimeIntervalReferences(route)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) validateReceiverReferences(route definitions.Route) error {
|
||||||
|
receivers := rev.GetReceiversNames()
|
||||||
|
receivers[""] = struct{}{} // Allow empty receiver (inheriting from parent)
|
||||||
|
return route.ValidateReceivers(receivers)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rev *ConfigRevision) validateTimeIntervalReferences(route definitions.Route) error {
|
||||||
|
timeIntervals := map[string]struct{}{}
|
||||||
|
for _, mt := range rev.Config.AlertmanagerConfig.MuteTimeIntervals {
|
||||||
|
timeIntervals[mt.Name] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, mt := range rev.Config.AlertmanagerConfig.TimeIntervals {
|
||||||
|
timeIntervals[mt.Name] = struct{}{}
|
||||||
|
}
|
||||||
|
return route.ValidateTimeIntervals(timeIntervals)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CalculateRouteFingerprint(route definitions.Route) string {
|
||||||
|
sum := fnv.New64a()
|
||||||
|
writeToHash(sum, &route)
|
||||||
|
return fmt.Sprintf("%016x", sum.Sum64())
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeToHash(sum hash.Hash, r *definitions.Route) {
|
||||||
|
writeBytes := func(b []byte) {
|
||||||
|
_, _ = sum.Write(b)
|
||||||
|
// add a byte sequence that cannot happen in UTF-8 strings.
|
||||||
|
_, _ = sum.Write([]byte{255})
|
||||||
|
}
|
||||||
|
writeString := func(s string) {
|
||||||
|
if len(s) == 0 {
|
||||||
|
writeBytes(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// #nosec G103
|
||||||
|
// avoid allocation when converting string to byte slice
|
||||||
|
writeBytes(unsafe.Slice(unsafe.StringData(s), len(s)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// this temp slice is used to convert ints to bytes.
|
||||||
|
tmp := make([]byte, 8)
|
||||||
|
writeInt := func(u int64) {
|
||||||
|
binary.LittleEndian.PutUint64(tmp, uint64(u))
|
||||||
|
writeBytes(tmp)
|
||||||
|
}
|
||||||
|
writeBool := func(b bool) {
|
||||||
|
if b {
|
||||||
|
writeInt(1)
|
||||||
|
} else {
|
||||||
|
writeInt(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeDuration := func(d *model.Duration) {
|
||||||
|
if d == nil {
|
||||||
|
_, _ = sum.Write([]byte{255})
|
||||||
|
} else {
|
||||||
|
binary.LittleEndian.PutUint64(tmp, uint64(*d))
|
||||||
|
_, _ = sum.Write(tmp)
|
||||||
|
_, _ = sum.Write([]byte{255})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writeString(r.Receiver)
|
||||||
|
for _, s := range r.GroupByStr {
|
||||||
|
writeString(s)
|
||||||
|
}
|
||||||
|
for _, labelName := range r.GroupBy {
|
||||||
|
writeString(string(labelName))
|
||||||
|
}
|
||||||
|
writeBool(r.GroupByAll)
|
||||||
|
if len(r.Match) > 0 {
|
||||||
|
for _, key := range slices.Sorted(maps.Keys(r.Match)) {
|
||||||
|
writeString(key)
|
||||||
|
writeString(r.Match[key])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(r.MatchRE) > 0 {
|
||||||
|
for _, key := range slices.Sorted(maps.Keys(r.MatchRE)) {
|
||||||
|
writeString(key)
|
||||||
|
str, err := r.MatchRE[key].MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
writeString(fmt.Sprintf("%+v", r.MatchRE))
|
||||||
|
}
|
||||||
|
writeBytes(str)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, matcher := range r.Matchers {
|
||||||
|
writeString(matcher.String())
|
||||||
|
}
|
||||||
|
for _, matcher := range r.ObjectMatchers {
|
||||||
|
writeString(matcher.String())
|
||||||
|
}
|
||||||
|
for _, timeInterval := range r.MuteTimeIntervals {
|
||||||
|
writeString(timeInterval)
|
||||||
|
}
|
||||||
|
for _, timeInterval := range r.ActiveTimeIntervals {
|
||||||
|
writeString(timeInterval)
|
||||||
|
}
|
||||||
|
writeBool(r.Continue)
|
||||||
|
writeDuration(r.GroupWait)
|
||||||
|
writeDuration(r.GroupInterval)
|
||||||
|
writeDuration(r.RepeatInterval)
|
||||||
|
for _, route := range r.Routes {
|
||||||
|
writeToHash(sum, route)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,6 +41,8 @@ var (
|
|||||||
ErrRouteConflictingMatchers = errutil.BadRequest("alerting.notifications.routes.conflictingMatchers").MustTemplate("Routing tree conflicts with the external configuration",
|
ErrRouteConflictingMatchers = errutil.BadRequest("alerting.notifications.routes.conflictingMatchers").MustTemplate("Routing tree conflicts with the external configuration",
|
||||||
errutil.WithPublic("Cannot add\\update route: matchers conflict with an external routing tree merging matchers {{ .Public.Matchers }}, making the added\\updated route unreachable."),
|
errutil.WithPublic("Cannot add\\update route: matchers conflict with an external routing tree merging matchers {{ .Public.Matchers }}, making the added\\updated route unreachable."),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
ErrRouteNotFound = errutil.NotFound("alerting.notifications.routes.notFound", errutil.WithPublicMessage("Route not found"))
|
||||||
)
|
)
|
||||||
|
|
||||||
// MakeErrTimeIntervalInvalid creates an error with the ErrTimeIntervalInvalid template
|
// MakeErrTimeIntervalInvalid creates an error with the ErrTimeIntervalInvalid template
|
||||||
|
|||||||
@@ -2,19 +2,13 @@ package provisioning
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash"
|
|
||||||
"hash/fnv"
|
|
||||||
"slices"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/grafana/alerting/definition"
|
"github.com/grafana/alerting/definition"
|
||||||
"github.com/prometheus/common/model"
|
|
||||||
"golang.org/x/exp/maps"
|
|
||||||
|
|
||||||
"github.com/grafana/grafana/pkg/infra/log"
|
"github.com/grafana/grafana/pkg/infra/log"
|
||||||
|
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
@@ -29,92 +23,138 @@ type NotificationPolicyService struct {
|
|||||||
log log.Logger
|
log log.Logger
|
||||||
settings setting.UnifiedAlertingSettings
|
settings setting.UnifiedAlertingSettings
|
||||||
validator validation.ProvenanceStatusTransitionValidator
|
validator validation.ProvenanceStatusTransitionValidator
|
||||||
|
FeatureToggles featuremgmt.FeatureToggles
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNotificationPolicyService(am alertmanagerConfigStore, prov ProvisioningStore,
|
func NewNotificationPolicyService(
|
||||||
xact TransactionManager, settings setting.UnifiedAlertingSettings, log log.Logger) *NotificationPolicyService {
|
am alertmanagerConfigStore,
|
||||||
|
prov ProvisioningStore,
|
||||||
|
xact TransactionManager,
|
||||||
|
settings setting.UnifiedAlertingSettings,
|
||||||
|
features featuremgmt.FeatureToggles,
|
||||||
|
log log.Logger,
|
||||||
|
) *NotificationPolicyService {
|
||||||
return &NotificationPolicyService{
|
return &NotificationPolicyService{
|
||||||
configStore: am,
|
configStore: am,
|
||||||
provenanceStore: prov,
|
provenanceStore: prov,
|
||||||
xact: xact,
|
xact: xact,
|
||||||
log: log,
|
log: log,
|
||||||
settings: settings,
|
settings: settings,
|
||||||
|
FeatureToggles: features,
|
||||||
validator: validation.ValidateProvenanceRelaxed,
|
validator: validation.ValidateProvenanceRelaxed,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nps *NotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
|
func (nps *NotificationPolicyService) GetManagedRoute(ctx context.Context, orgID int64, name string) (legacy_storage.ManagedRoute, error) {
|
||||||
|
// TODO: Keep this?
|
||||||
|
if name == "" {
|
||||||
|
name = legacy_storage.UserDefinedRoutingTreeName
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backwards compatibility when managed routes FF is disabled. Only allow the default route.
|
||||||
|
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) && name != legacy_storage.UserDefinedRoutingTreeName {
|
||||||
|
return legacy_storage.ManagedRoute{}, ErrRouteNotFound.Errorf("route %q not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
rev, err := nps.configStore.Get(ctx, orgID)
|
rev, err := nps.configStore.Get(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", err
|
return legacy_storage.ManagedRoute{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if rev.Config.AlertmanagerConfig.Route == nil {
|
route := rev.GetManagedRoute(name)
|
||||||
return definitions.Route{}, "", fmt.Errorf("no route present in current alertmanager config")
|
if route == nil {
|
||||||
|
return legacy_storage.ManagedRoute{}, ErrRouteNotFound.Errorf("route %q not found", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
provenance, err := nps.provenanceStore.GetProvenance(ctx, rev.Config.AlertmanagerConfig.Route, orgID)
|
provenance, err := nps.provenanceStore.GetProvenance(ctx, route, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", err
|
return legacy_storage.ManagedRoute{}, err
|
||||||
}
|
}
|
||||||
result := *rev.Config.AlertmanagerConfig.Route
|
route.Provenance = provenance
|
||||||
result.Provenance = definitions.Provenance(provenance)
|
|
||||||
version := calculateRouteFingerprint(result)
|
return *route, nil
|
||||||
return result, version, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nps *NotificationPolicyService) UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p models.Provenance, version string) (definitions.Route, string, error) {
|
func (nps *NotificationPolicyService) GetManagedRoutes(ctx context.Context, orgID int64) (legacy_storage.ManagedRoutes, error) {
|
||||||
err := tree.Validate()
|
rev, err := nps.configStore.Get(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", MakeErrRouteInvalidFormat(err)
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
provenances, err := nps.provenanceStore.GetProvenances(ctx, orgID, (&legacy_storage.ManagedRoute{}).ResourceType())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
managedRoutesDisabled := !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies)
|
||||||
|
managedRoutes := rev.GetManagedRoutes()
|
||||||
|
for _, mr := range managedRoutes {
|
||||||
|
// Backwards compatibility when managed routes FF is disabled. Don't include any custom managed routes.
|
||||||
|
if managedRoutesDisabled && mr.Name != legacy_storage.UserDefinedRoutingTreeName {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
provenance, ok := provenances[mr.ResourceID()]
|
||||||
|
if !ok {
|
||||||
|
provenance = models.ProvenanceNone
|
||||||
|
}
|
||||||
|
mr.Provenance = provenance
|
||||||
|
}
|
||||||
|
managedRoutes.Sort()
|
||||||
|
return managedRoutes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (nps *NotificationPolicyService) UpdateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p models.Provenance, version string) (*legacy_storage.ManagedRoute, error) {
|
||||||
|
// TODO: Keep this?
|
||||||
|
if name == "" {
|
||||||
|
name = legacy_storage.UserDefinedRoutingTreeName
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backwards compatibility when managed routes FF is disabled. Only allow the default route.
|
||||||
|
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) && name != legacy_storage.UserDefinedRoutingTreeName {
|
||||||
|
return nil, ErrRouteNotFound.Errorf("route %q not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := subtree.Validate()
|
||||||
|
if err != nil {
|
||||||
|
return nil, MakeErrRouteInvalidFormat(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
revision, err := nps.configStore.Get(ctx, orgID)
|
revision, err := nps.configStore.Get(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = nps.checkOptimisticConcurrency(*revision.Config.AlertmanagerConfig.Route, p, version, "update")
|
existing := revision.GetManagedRoute(name)
|
||||||
|
if existing == nil {
|
||||||
|
return nil, ErrRouteNotFound.Errorf("route %q not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = nps.checkOptimisticConcurrency(existing, p, version, "update")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// check that provenance is not changed in an invalid way
|
// check that provenance is not changed in an invalid way
|
||||||
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, &tree, orgID)
|
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, existing, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := nps.validator(storedProvenance, p); err != nil {
|
if err := nps.validator(storedProvenance, p); err != nil {
|
||||||
return definitions.Route{}, "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
receivers := revision.GetReceiversNames()
|
updated, err := revision.UpdateNamedRoute(name, subtree)
|
||||||
receivers[""] = struct{}{} // Allow empty receiver (inheriting from parent)
|
|
||||||
|
|
||||||
err = tree.ValidateReceivers(receivers)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", MakeErrRouteInvalidFormat(err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
updated.Provenance = storedProvenance
|
||||||
timeIntervals := map[string]struct{}{}
|
|
||||||
for _, mt := range revision.Config.AlertmanagerConfig.MuteTimeIntervals {
|
|
||||||
timeIntervals[mt.Name] = struct{}{}
|
|
||||||
}
|
|
||||||
for _, mt := range revision.Config.AlertmanagerConfig.TimeIntervals {
|
|
||||||
timeIntervals[mt.Name] = struct{}{}
|
|
||||||
}
|
|
||||||
err = tree.ValidateTimeIntervals(timeIntervals)
|
|
||||||
if err != nil {
|
|
||||||
return definitions.Route{}, "", MakeErrRouteInvalidFormat(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
revision.Config.AlertmanagerConfig.Route = &tree
|
|
||||||
|
|
||||||
_, err = revision.Config.GetMergedAlertmanagerConfig()
|
_, err = revision.Config.GetMergedAlertmanagerConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, definition.ErrSubtreeMatchersConflict) {
|
if errors.Is(err, definition.ErrSubtreeMatchersConflict) {
|
||||||
// TODO temporarily get the conflicting matchers
|
// TODO temporarily get the conflicting matchers
|
||||||
return definitions.Route{}, "", MakeErrRouteConflictingMatchers(fmt.Sprintf("%s", revision.Config.ExtraConfigs[0].MergeMatchers))
|
return nil, MakeErrRouteConflictingMatchers(fmt.Sprintf("%s", revision.Config.ExtraConfigs[0].MergeMatchers))
|
||||||
}
|
}
|
||||||
nps.log.Warn("Unable to validate the combined routing tree because of an error during merging. This could be a sign of broken external configuration. Skipping", "error", err)
|
nps.log.Warn("Unable to validate the combined routing tree because of an error during merging. This could be a sign of broken external configuration. Skipping", "error", err)
|
||||||
}
|
}
|
||||||
@@ -123,169 +163,147 @@ func (nps *NotificationPolicyService) UpdatePolicyTree(ctx context.Context, orgI
|
|||||||
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
|
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nps.provenanceStore.SetProvenance(ctx, &tree, orgID, p)
|
return nps.provenanceStore.SetProvenance(ctx, updated, orgID, p)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, "", err
|
return nil, err
|
||||||
}
|
}
|
||||||
return tree, calculateRouteFingerprint(tree), nil
|
return updated, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nps *NotificationPolicyService) ResetPolicyTree(ctx context.Context, orgID int64, provenance models.Provenance) (definitions.Route, error) {
|
func (nps *NotificationPolicyService) DeleteManagedRoute(ctx context.Context, orgID int64, name string, p models.Provenance, version string) error {
|
||||||
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, &definitions.Route{}, orgID)
|
// TODO: Keep this?
|
||||||
if err != nil {
|
if name == "" {
|
||||||
return definitions.Route{}, err
|
name = legacy_storage.UserDefinedRoutingTreeName
|
||||||
}
|
|
||||||
if err := nps.validator(storedProvenance, provenance); err != nil {
|
|
||||||
return definitions.Route{}, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultCfg, err := legacy_storage.DeserializeAlertmanagerConfig([]byte(nps.settings.DefaultConfiguration))
|
// Backwards compatibility when managed routes FF is disabled. Only allow the default route.
|
||||||
if err != nil {
|
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) && name != legacy_storage.UserDefinedRoutingTreeName {
|
||||||
nps.log.Error("Failed to parse default alertmanager config: %w", err)
|
return ErrRouteNotFound.Errorf("route %q not found", name)
|
||||||
return definitions.Route{}, fmt.Errorf("failed to parse default alertmanager config: %w", err)
|
|
||||||
}
|
}
|
||||||
route := defaultCfg.AlertmanagerConfig.Route
|
|
||||||
|
|
||||||
revision, err := nps.configStore.Get(ctx, orgID)
|
revision, err := nps.configStore.Get(ctx, orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, err
|
return err
|
||||||
}
|
}
|
||||||
revision.Config.AlertmanagerConfig.Route = route
|
|
||||||
err = nps.ensureDefaultReceiverExists(revision.Config, defaultCfg)
|
existing := revision.GetManagedRoute(name)
|
||||||
|
if existing == nil {
|
||||||
|
return ErrRouteNotFound.Errorf("route %q not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = nps.checkOptimisticConcurrency(existing, p, version, "delete")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, err
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, existing, orgID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := nps.validator(storedProvenance, p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == legacy_storage.UserDefinedRoutingTreeName {
|
||||||
|
defaultCfg, err := legacy_storage.DeserializeAlertmanagerConfig([]byte(nps.settings.DefaultConfiguration))
|
||||||
|
if err != nil {
|
||||||
|
nps.log.Error("Failed to parse default alertmanager config: %w", err)
|
||||||
|
return fmt.Errorf("failed to parse default alertmanager config: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = revision.ResetUserDefinedRoute(defaultCfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
revision.DeleteManagedRoute(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = revision.Config.GetMergedAlertmanagerConfig()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("new routing tree is not compatible with extra configuration: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nps.xact.InTransaction(ctx, func(ctx context.Context) error {
|
||||||
|
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nps.provenanceStore.DeleteProvenance(ctx, existing, orgID)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (nps *NotificationPolicyService) CreateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p models.Provenance) (*legacy_storage.ManagedRoute, error) {
|
||||||
|
// Backwards compatibility when managed routes FF is disabled. This is not allowed.
|
||||||
|
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) {
|
||||||
|
return nil, fmt.Errorf("managed routes are not enabled, see feature toggle %s", featuremgmt.FlagAlertingMultiplePolicies)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := subtree.Validate()
|
||||||
|
if err != nil {
|
||||||
|
return nil, MakeErrRouteInvalidFormat(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
revision, err := nps.configStore.Get(ctx, orgID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := revision.CreateManagedRoute(name, subtree)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = revision.Config.GetMergedAlertmanagerConfig()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new routing tree is not compatible with extra configuration: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = nps.xact.InTransaction(ctx, func(ctx context.Context) error {
|
err = nps.xact.InTransaction(ctx, func(ctx context.Context) error {
|
||||||
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
|
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nps.provenanceStore.DeleteProvenance(ctx, route, orgID)
|
return nps.provenanceStore.SetProvenance(ctx, created, orgID, p)
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return definitions.Route{}, nil
|
return nil, err
|
||||||
} // TODO should be error?
|
}
|
||||||
|
return created, nil
|
||||||
return *route, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nps *NotificationPolicyService) ensureDefaultReceiverExists(cfg *definitions.PostableUserConfig, defaultCfg *definitions.PostableUserConfig) error {
|
// TODO: Remove this method once the all callers support named routes.
|
||||||
defaultRcv := cfg.AlertmanagerConfig.Route.Receiver
|
func (nps *NotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
|
||||||
|
r, err := nps.GetManagedRoute(ctx, orgID, legacy_storage.UserDefinedRoutingTreeName)
|
||||||
for _, rcv := range cfg.AlertmanagerConfig.Receivers {
|
if err != nil {
|
||||||
if rcv.Name == defaultRcv {
|
return definitions.Route{}, "", err
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return r.AsRoute(), r.Version, nil
|
||||||
for _, rcv := range defaultCfg.AlertmanagerConfig.Receivers {
|
|
||||||
if rcv.Name == defaultRcv {
|
|
||||||
cfg.AlertmanagerConfig.Receivers = append(cfg.AlertmanagerConfig.Receivers, rcv)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
nps.log.Error("Grafana Alerting has been configured with a default configuration that is internally inconsistent! The default configuration's notification policy must have a corresponding receiver.")
|
|
||||||
return fmt.Errorf("inconsistent default configuration")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func calculateRouteFingerprint(route definitions.Route) string {
|
// TODO: Remove this method once the all callers support named routes.
|
||||||
sum := fnv.New64a()
|
func (nps *NotificationPolicyService) UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p models.Provenance, version string) (definitions.Route, string, error) {
|
||||||
writeToHash(sum, &route)
|
r, err := nps.UpdateManagedRoute(ctx, orgID, legacy_storage.UserDefinedRoutingTreeName, tree, p, version)
|
||||||
return fmt.Sprintf("%016x", sum.Sum64())
|
if err != nil {
|
||||||
|
return definitions.Route{}, "", err
|
||||||
|
}
|
||||||
|
return r.AsRoute(), r.Version, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeToHash(sum hash.Hash, r *definitions.Route) {
|
// TODO: Remove this method once the all callers support named routes.
|
||||||
writeBytes := func(b []byte) {
|
func (nps *NotificationPolicyService) ResetPolicyTree(ctx context.Context, orgID int64, provenance models.Provenance) (definitions.Route, error) {
|
||||||
_, _ = sum.Write(b)
|
err := nps.DeleteManagedRoute(ctx, orgID, legacy_storage.UserDefinedRoutingTreeName, provenance, "")
|
||||||
// add a byte sequence that cannot happen in UTF-8 strings.
|
if err != nil {
|
||||||
_, _ = sum.Write([]byte{255})
|
return definitions.Route{}, err
|
||||||
}
|
}
|
||||||
writeString := func(s string) {
|
defaultCfg, err := legacy_storage.DeserializeAlertmanagerConfig([]byte(nps.settings.DefaultConfiguration))
|
||||||
if len(s) == 0 {
|
if err != nil {
|
||||||
writeBytes(nil)
|
nps.log.Error("Failed to parse default alertmanager config: %w", err)
|
||||||
return
|
return definitions.Route{}, fmt.Errorf("failed to parse default alertmanager config: %w", err)
|
||||||
}
|
|
||||||
// #nosec G103
|
|
||||||
// avoid allocation when converting string to byte slice
|
|
||||||
writeBytes(unsafe.Slice(unsafe.StringData(s), len(s)))
|
|
||||||
}
|
|
||||||
|
|
||||||
// this temp slice is used to convert ints to bytes.
|
|
||||||
tmp := make([]byte, 8)
|
|
||||||
writeInt := func(u int64) {
|
|
||||||
binary.LittleEndian.PutUint64(tmp, uint64(u))
|
|
||||||
writeBytes(tmp)
|
|
||||||
}
|
|
||||||
writeBool := func(b bool) {
|
|
||||||
if b {
|
|
||||||
writeInt(1)
|
|
||||||
} else {
|
|
||||||
writeInt(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
writeDuration := func(d *model.Duration) {
|
|
||||||
if d == nil {
|
|
||||||
_, _ = sum.Write([]byte{255})
|
|
||||||
} else {
|
|
||||||
binary.LittleEndian.PutUint64(tmp, uint64(*d))
|
|
||||||
_, _ = sum.Write(tmp)
|
|
||||||
_, _ = sum.Write([]byte{255})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
writeString(r.Receiver)
|
|
||||||
for _, s := range r.GroupByStr {
|
|
||||||
writeString(s)
|
|
||||||
}
|
|
||||||
for _, labelName := range r.GroupBy {
|
|
||||||
writeString(string(labelName))
|
|
||||||
}
|
|
||||||
writeBool(r.GroupByAll)
|
|
||||||
if len(r.Match) > 0 {
|
|
||||||
keys := maps.Keys(r.Match)
|
|
||||||
slices.Sort(keys)
|
|
||||||
for _, key := range keys {
|
|
||||||
writeString(key)
|
|
||||||
writeString(r.Match[key])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(r.MatchRE) > 0 {
|
|
||||||
keys := maps.Keys(r.MatchRE)
|
|
||||||
slices.Sort(keys)
|
|
||||||
for _, key := range keys {
|
|
||||||
writeString(key)
|
|
||||||
str, err := r.MatchRE[key].MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
writeString(fmt.Sprintf("%+v", r.MatchRE))
|
|
||||||
}
|
|
||||||
writeBytes(str)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, matcher := range r.Matchers {
|
|
||||||
writeString(matcher.String())
|
|
||||||
}
|
|
||||||
for _, matcher := range r.ObjectMatchers {
|
|
||||||
writeString(matcher.String())
|
|
||||||
}
|
|
||||||
for _, timeInterval := range r.MuteTimeIntervals {
|
|
||||||
writeString(timeInterval)
|
|
||||||
}
|
|
||||||
for _, timeInterval := range r.ActiveTimeIntervals {
|
|
||||||
writeString(timeInterval)
|
|
||||||
}
|
|
||||||
writeBool(r.Continue)
|
|
||||||
writeDuration(r.GroupWait)
|
|
||||||
writeDuration(r.GroupInterval)
|
|
||||||
writeDuration(r.RepeatInterval)
|
|
||||||
for _, route := range r.Routes {
|
|
||||||
writeToHash(sum, route)
|
|
||||||
}
|
}
|
||||||
|
return *defaultCfg.AlertmanagerConfig.Route, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nps *NotificationPolicyService) checkOptimisticConcurrency(current definitions.Route, provenance models.Provenance, desiredVersion string, action string) error {
|
func (nps *NotificationPolicyService) checkOptimisticConcurrency(current *legacy_storage.ManagedRoute, provenance models.Provenance, desiredVersion string, action string) error {
|
||||||
if desiredVersion == "" {
|
if desiredVersion == "" {
|
||||||
if provenance != models.ProvenanceFile {
|
if provenance != models.ProvenanceFile {
|
||||||
// if version is not specified and it's not a file provisioning, emit a log message to reflect that optimistic concurrency is disabled for this request
|
// if version is not specified and it's not a file provisioning, emit a log message to reflect that optimistic concurrency is disabled for this request
|
||||||
@@ -293,9 +311,8 @@ func (nps *NotificationPolicyService) checkOptimisticConcurrency(current definit
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
currentVersion := calculateRouteFingerprint(current)
|
if current.Version != desiredVersion {
|
||||||
if currentVersion != desiredVersion {
|
return ErrVersionConflict.Errorf("provided version %s of routing tree does not match current version %s", desiredVersion, current.Version)
|
||||||
return ErrVersionConflict.Errorf("provided version %s of routing tree does not match current version %s", desiredVersion, currentVersion)
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
"github.com/grafana/grafana/pkg/infra/log"
|
"github.com/grafana/grafana/pkg/infra/log"
|
||||||
|
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
@@ -29,7 +30,7 @@ func TestGetPolicyTree(t *testing.T) {
|
|||||||
rev := getDefaultConfigRevision()
|
rev := getDefaultConfigRevision()
|
||||||
expectedRoute := *rev.Config.AlertmanagerConfig.Route
|
expectedRoute := *rev.Config.AlertmanagerConfig.Route
|
||||||
expectedRoute.Provenance = definitions.Provenance(models.ProvenanceAPI)
|
expectedRoute.Provenance = definitions.Provenance(models.ProvenanceAPI)
|
||||||
expectedVersion := calculateRouteFingerprint(expectedRoute)
|
expectedVersion := legacy_storage.CalculateRouteFingerprint(expectedRoute)
|
||||||
|
|
||||||
sut, store, prov := createNotificationPolicyServiceSut()
|
sut, store, prov := createNotificationPolicyServiceSut()
|
||||||
store.GetFn = func(ctx context.Context, orgID int64) (*legacy_storage.ConfigRevision, error) {
|
store.GetFn = func(ctx context.Context, orgID int64) (*legacy_storage.ConfigRevision, error) {
|
||||||
@@ -52,7 +53,7 @@ func TestGetPolicyTree(t *testing.T) {
|
|||||||
|
|
||||||
assert.Len(t, prov.Calls, 1)
|
assert.Len(t, prov.Calls, 1)
|
||||||
assert.Equal(t, "GetProvenance", prov.Calls[0].MethodName)
|
assert.Equal(t, "GetProvenance", prov.Calls[0].MethodName)
|
||||||
assert.IsType(t, &definitions.Route{}, prov.Calls[0].Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), prov.Calls[0].Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, prov.Calls[0].Arguments[2])
|
assert.Equal(t, orgID, prov.Calls[0].Arguments[2])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,7 +61,7 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
orgID := int64(1)
|
orgID := int64(1)
|
||||||
rev := getDefaultConfigRevision()
|
rev := getDefaultConfigRevision()
|
||||||
|
|
||||||
defaultVersion := calculateRouteFingerprint(*rev.Config.AlertmanagerConfig.Route)
|
defaultVersion := legacy_storage.CalculateRouteFingerprint(*rev.Config.AlertmanagerConfig.Route)
|
||||||
|
|
||||||
newRoute := definitions.Route{
|
newRoute := definitions.Route{
|
||||||
Receiver: rev.Config.AlertmanagerConfig.Receivers[0].Name,
|
Receiver: rev.Config.AlertmanagerConfig.Receivers[0].Name,
|
||||||
@@ -185,7 +186,7 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
|
|
||||||
assert.Len(t, prov.Calls, 1)
|
assert.Len(t, prov.Calls, 1)
|
||||||
assert.Equal(t, "GetProvenance", prov.Calls[0].MethodName)
|
assert.Equal(t, "GetProvenance", prov.Calls[0].MethodName)
|
||||||
assert.IsType(t, &definitions.Route{}, prov.Calls[0].Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), prov.Calls[0].Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, prov.Calls[0].Arguments[2].(int64))
|
assert.Equal(t, orgID, prov.Calls[0].Arguments[2].(int64))
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -273,7 +274,7 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, route, models.ProvenanceAPI, defaultVersion)
|
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, route, models.ProvenanceAPI, defaultVersion)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, route, result)
|
assert.Equal(t, route, result)
|
||||||
assert.Equal(t, calculateRouteFingerprint(route), version)
|
assert.Equal(t, legacy_storage.CalculateRouteFingerprint(route), version)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("updates Route and sets provenance in transaction if route is valid and version matches", func(t *testing.T) {
|
t.Run("updates Route and sets provenance in transaction if route is valid and version matches", func(t *testing.T) {
|
||||||
@@ -289,7 +290,7 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, newRoute, models.ProvenanceAPI, defaultVersion)
|
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, newRoute, models.ProvenanceAPI, defaultVersion)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, newRoute, result)
|
assert.Equal(t, newRoute, result)
|
||||||
assert.Equal(t, calculateRouteFingerprint(newRoute), version)
|
assert.Equal(t, legacy_storage.CalculateRouteFingerprint(newRoute), version)
|
||||||
|
|
||||||
assert.Len(t, store.Calls, 2)
|
assert.Len(t, store.Calls, 2)
|
||||||
assert.Equal(t, "Save", store.Calls[1].Method)
|
assert.Equal(t, "Save", store.Calls[1].Method)
|
||||||
@@ -298,12 +299,12 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
|
|
||||||
c := prov.Calls[0]
|
c := prov.Calls[0]
|
||||||
assert.Equal(t, "GetProvenance", c.MethodName)
|
assert.Equal(t, "GetProvenance", c.MethodName)
|
||||||
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
||||||
c = prov.Calls[1]
|
c = prov.Calls[1]
|
||||||
assert.Equal(t, "SetProvenance", c.MethodName)
|
assert.Equal(t, "SetProvenance", c.MethodName)
|
||||||
assertInTransaction(t, c.Arguments[0].(context.Context))
|
assertInTransaction(t, c.Arguments[0].(context.Context))
|
||||||
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
||||||
assert.Equal(t, models.ProvenanceAPI, c.Arguments[3].(models.Provenance))
|
assert.Equal(t, models.ProvenanceAPI, c.Arguments[3].(models.Provenance))
|
||||||
})
|
})
|
||||||
@@ -321,7 +322,7 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, newRoute, models.ProvenanceAPI, "")
|
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, newRoute, models.ProvenanceAPI, "")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, newRoute, result)
|
assert.Equal(t, newRoute, result)
|
||||||
assert.Equal(t, calculateRouteFingerprint(newRoute), version)
|
assert.Equal(t, legacy_storage.CalculateRouteFingerprint(newRoute), version)
|
||||||
|
|
||||||
assert.Len(t, store.Calls, 2)
|
assert.Len(t, store.Calls, 2)
|
||||||
assert.Equal(t, "Save", store.Calls[1].Method)
|
assert.Equal(t, "Save", store.Calls[1].Method)
|
||||||
@@ -332,7 +333,7 @@ func TestUpdatePolicyTree(t *testing.T) {
|
|||||||
c := prov.Calls[1]
|
c := prov.Calls[1]
|
||||||
assert.Equal(t, "SetProvenance", c.MethodName)
|
assert.Equal(t, "SetProvenance", c.MethodName)
|
||||||
assertInTransaction(t, c.Arguments[0].(context.Context))
|
assertInTransaction(t, c.Arguments[0].(context.Context))
|
||||||
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
||||||
assert.Equal(t, models.ProvenanceAPI, c.Arguments[3].(models.Provenance))
|
assert.Equal(t, models.ProvenanceAPI, c.Arguments[3].(models.Provenance))
|
||||||
})
|
})
|
||||||
@@ -430,12 +431,12 @@ func TestResetPolicyTree(t *testing.T) {
|
|||||||
assert.Len(t, prov.Calls, 2)
|
assert.Len(t, prov.Calls, 2)
|
||||||
c := prov.Calls[0]
|
c := prov.Calls[0]
|
||||||
assert.Equal(t, "GetProvenance", c.MethodName)
|
assert.Equal(t, "GetProvenance", c.MethodName)
|
||||||
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
assert.Equal(t, orgID, c.Arguments[2].(int64))
|
||||||
c = prov.Calls[1]
|
c = prov.Calls[1]
|
||||||
assert.Equal(t, "DeleteProvenance", c.MethodName)
|
assert.Equal(t, "DeleteProvenance", c.MethodName)
|
||||||
assertInTransaction(t, c.Arguments[0].(context.Context))
|
assertInTransaction(t, c.Arguments[0].(context.Context))
|
||||||
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
|
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
|
||||||
assert.Equal(t, orgID, c.Arguments[2])
|
assert.Equal(t, orgID, c.Arguments[2])
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -516,10 +517,10 @@ func TestRoute_Fingerprint(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("stable across code changes", func(t *testing.T) {
|
t.Run("stable across code changes", func(t *testing.T) {
|
||||||
expectedFingerprint := "450c06a7f4a66675" // If this is a valid fingerprint generation change, update the expected value.
|
expectedFingerprint := "450c06a7f4a66675" // If this is a valid fingerprint generation change, update the expected value.
|
||||||
assert.Equal(t, expectedFingerprint, calculateRouteFingerprint(baseRouteGen()))
|
assert.Equal(t, expectedFingerprint, legacy_storage.CalculateRouteFingerprint(baseRouteGen()))
|
||||||
})
|
})
|
||||||
t.Run("unstable across field modification", func(t *testing.T) {
|
t.Run("unstable across field modification", func(t *testing.T) {
|
||||||
fingerprint := calculateRouteFingerprint(baseRouteGen())
|
fingerprint := legacy_storage.CalculateRouteFingerprint(baseRouteGen())
|
||||||
excludedFields := map[string]struct{}{
|
excludedFields := map[string]struct{}{
|
||||||
"Routes": {},
|
"Routes": {},
|
||||||
"Provenance": {},
|
"Provenance": {},
|
||||||
@@ -548,7 +549,7 @@ func TestRoute_Fingerprint(t *testing.T) {
|
|||||||
// Set the field to the value of the completelyDifferentRoute.
|
// Set the field to the value of the completelyDifferentRoute.
|
||||||
vf.Set(otherField)
|
vf.Set(otherField)
|
||||||
|
|
||||||
f2 := calculateRouteFingerprint(cp)
|
f2 := legacy_storage.CalculateRouteFingerprint(cp)
|
||||||
assert.NotEqualf(t, fingerprint, f2, "Route field %s does not seem to be used in fingerprint", field)
|
assert.NotEqualf(t, fingerprint, f2, "Route field %s does not seem to be used in fingerprint", field)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -573,6 +574,7 @@ func createNotificationPolicyServiceSut() (*NotificationPolicyService, *legacy_s
|
|||||||
validator: func(from, to models.Provenance) error {
|
validator: func(from, to models.Provenance) error {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
|
FeatureToggles: featuremgmt.WithFeatures(),
|
||||||
}, configStore, prov
|
}, configStore, prov
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package alerting
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/grafana/grafana/pkg/infra/log"
|
"github.com/grafana/grafana/pkg/infra/log"
|
||||||
@@ -31,7 +32,18 @@ func (c *defaultNotificationPolicyProvisioner) Provision(ctx context.Context,
|
|||||||
files []*AlertingFile) error {
|
files []*AlertingFile) error {
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
for _, np := range file.Policies {
|
for _, np := range file.Policies {
|
||||||
_, _, err := c.notificationPolicyService.UpdatePolicyTree(ctx, np.OrgID,
|
if _, err := c.notificationPolicyService.GetManagedRoute(ctx, np.OrgID, np.Name); err != nil {
|
||||||
|
if errors.Is(err, provisioning.ErrRouteNotFound) {
|
||||||
|
_, err := c.notificationPolicyService.CreateManagedRoute(ctx, np.OrgID, np.Name,
|
||||||
|
np.Policy, models.ProvenanceFile)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s: %w", file.Filename, err)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := c.notificationPolicyService.UpdateManagedRoute(ctx, np.OrgID, np.Name,
|
||||||
np.Policy, models.ProvenanceFile, "")
|
np.Policy, models.ProvenanceFile, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", file.Filename, err)
|
return fmt.Errorf("%s: %w", file.Filename, err)
|
||||||
@@ -44,8 +56,8 @@ func (c *defaultNotificationPolicyProvisioner) Provision(ctx context.Context,
|
|||||||
func (c *defaultNotificationPolicyProvisioner) Unprovision(ctx context.Context,
|
func (c *defaultNotificationPolicyProvisioner) Unprovision(ctx context.Context,
|
||||||
files []*AlertingFile) error {
|
files []*AlertingFile) error {
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
for _, orgID := range file.ResetPolicies {
|
for _, deletePolicy := range file.DeletePolicies {
|
||||||
_, err := c.notificationPolicyService.ResetPolicyTree(ctx, int64(orgID), models.ProvenanceFile)
|
err := c.notificationPolicyService.DeleteManagedRoute(ctx, deletePolicy.OrgID, deletePolicy.Name, models.ProvenanceFile, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", file.Filename, err)
|
return fmt.Errorf("%s: %w", file.Filename, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,19 @@ package alerting
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/services/provisioning/values"
|
"github.com/grafana/grafana/pkg/services/provisioning/values"
|
||||||
)
|
)
|
||||||
|
|
||||||
type NotificiationPolicyV1 struct {
|
type NotificiationPolicyV1 struct {
|
||||||
OrgID values.Int64Value `json:"orgId" yaml:"orgId"`
|
OrgID values.Int64Value `json:"orgId" yaml:"orgId"`
|
||||||
// We use JSONValue here, as we want to have interpolation the values.
|
// We use JSONValue here, as we want to have interpolation the values.
|
||||||
Policy values.JSONValue `json:"-" yaml:"-"`
|
Policy values.JSONValue `json:"-" yaml:"-"`
|
||||||
|
Name values.StringValue `json:"name" yaml:"name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v1 *NotificiationPolicyV1) UnmarshalYAML(unmarshal func(any) error) error {
|
func (v1 *NotificiationPolicyV1) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
@@ -30,6 +34,10 @@ func (v1 *NotificiationPolicyV1) mapToModel() (NotificiationPolicy, error) {
|
|||||||
if orgID < 1 {
|
if orgID < 1 {
|
||||||
orgID = 1
|
orgID = 1
|
||||||
}
|
}
|
||||||
|
name := v1.Name.Value()
|
||||||
|
if name == "" {
|
||||||
|
name = legacy_storage.UserDefinedRoutingTreeName
|
||||||
|
}
|
||||||
var route definitions.Route
|
var route definitions.Route
|
||||||
// We need the string json representation, so we marshal the policy back
|
// We need the string json representation, so we marshal the policy back
|
||||||
// as a string and interpolate it at the same time.
|
// as a string and interpolate it at the same time.
|
||||||
@@ -48,10 +56,37 @@ func (v1 *NotificiationPolicyV1) mapToModel() (NotificiationPolicy, error) {
|
|||||||
return NotificiationPolicy{
|
return NotificiationPolicy{
|
||||||
OrgID: orgID,
|
OrgID: orgID,
|
||||||
Policy: route,
|
Policy: route,
|
||||||
|
Name: strings.TrimSpace(name),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type NotificiationPolicy struct {
|
type NotificiationPolicy struct {
|
||||||
OrgID int64
|
OrgID int64
|
||||||
|
Name string
|
||||||
Policy definitions.Route
|
Policy definitions.Route
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DeleteNotificationPolicyV1 struct {
|
||||||
|
OrgID values.Int64Value `json:"orgId" yaml:"orgId"`
|
||||||
|
Name values.StringValue `json:"name" yaml:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v1 DeleteNotificationPolicyV1) mapToModel() (DeleteNotificationPolicy, error) {
|
||||||
|
name := strings.TrimSpace(v1.Name.Value())
|
||||||
|
if name == "" {
|
||||||
|
return DeleteNotificationPolicy{}, errors.New("delete policy missing name")
|
||||||
|
}
|
||||||
|
orgID := v1.OrgID.Value()
|
||||||
|
if orgID < 1 {
|
||||||
|
orgID = 1
|
||||||
|
}
|
||||||
|
return DeleteNotificationPolicy{
|
||||||
|
OrgID: orgID,
|
||||||
|
Name: name,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteNotificationPolicy struct {
|
||||||
|
OrgID int64
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNotificationPolicy(t *testing.T) {
|
func TestNotificationPolicy(t *testing.T) {
|
||||||
@@ -27,6 +29,33 @@ repeat_interval: ${NOTIFIER_EMAIL_REMINDER_FREQUENCY}
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Equal(t, int64(123), np.OrgID)
|
require.Equal(t, int64(123), np.OrgID)
|
||||||
require.Equal(t, "test", np.Policy.Receiver)
|
require.Equal(t, "test", np.Policy.Receiver)
|
||||||
|
require.Equal(t, legacy_storage.UserDefinedRoutingTreeName, np.Name)
|
||||||
|
require.True(t, np.Policy.Continue)
|
||||||
|
require.Equal(t, envValue, np.Policy.RepeatInterval.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNotificationPolicyWithName(t *testing.T) {
|
||||||
|
const (
|
||||||
|
envKey = "NOTIFIER_EMAIL_REMINDER_FREQUENCY"
|
||||||
|
envValue = "4h"
|
||||||
|
)
|
||||||
|
t.Setenv(envKey, envValue)
|
||||||
|
|
||||||
|
data := `orgId: 123
|
||||||
|
receiver: test
|
||||||
|
continue: true
|
||||||
|
name: "test-policy"
|
||||||
|
repeat_interval: ${NOTIFIER_EMAIL_REMINDER_FREQUENCY}
|
||||||
|
`
|
||||||
|
var model NotificiationPolicyV1
|
||||||
|
|
||||||
|
err := yaml.Unmarshal([]byte(data), &model)
|
||||||
|
require.NoError(t, err)
|
||||||
|
np, err := model.mapToModel()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, int64(123), np.OrgID)
|
||||||
|
require.Equal(t, "test", np.Policy.Receiver)
|
||||||
|
require.Equal(t, "test-policy", np.Name)
|
||||||
require.True(t, np.Policy.Continue)
|
require.True(t, np.Policy.Continue)
|
||||||
require.Equal(t, envValue, np.Policy.RepeatInterval.String())
|
require.Equal(t, envValue, np.Policy.RepeatInterval.String())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
"github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/services/provisioning/values"
|
"github.com/grafana/grafana/pkg/services/provisioning/values"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,7 +22,7 @@ type AlertingFile struct {
|
|||||||
ContactPoints []ContactPoint
|
ContactPoints []ContactPoint
|
||||||
DeleteContactPoints []DeleteContactPoint
|
DeleteContactPoints []DeleteContactPoint
|
||||||
Policies []NotificiationPolicy
|
Policies []NotificiationPolicy
|
||||||
ResetPolicies []OrgID
|
DeletePolicies []DeleteNotificationPolicy
|
||||||
MuteTimes []MuteTime
|
MuteTimes []MuteTime
|
||||||
DeleteMuteTimes []DeleteMuteTime
|
DeleteMuteTimes []DeleteMuteTime
|
||||||
Templates []Template
|
Templates []Template
|
||||||
@@ -31,16 +32,17 @@ type AlertingFile struct {
|
|||||||
type AlertingFileV1 struct {
|
type AlertingFileV1 struct {
|
||||||
configVersion
|
configVersion
|
||||||
Filename string
|
Filename string
|
||||||
Groups []AlertRuleGroupV1 `json:"groups" yaml:"groups"`
|
Groups []AlertRuleGroupV1 `json:"groups" yaml:"groups"`
|
||||||
DeleteRules []RuleDeleteV1 `json:"deleteRules" yaml:"deleteRules"`
|
DeleteRules []RuleDeleteV1 `json:"deleteRules" yaml:"deleteRules"`
|
||||||
ContactPoints []ContactPointV1 `json:"contactPoints" yaml:"contactPoints"`
|
ContactPoints []ContactPointV1 `json:"contactPoints" yaml:"contactPoints"`
|
||||||
DeleteContactPoints []DeleteContactPointV1 `json:"deleteContactPoints" yaml:"deleteContactPoints"`
|
DeleteContactPoints []DeleteContactPointV1 `json:"deleteContactPoints" yaml:"deleteContactPoints"`
|
||||||
Policies []NotificiationPolicyV1 `json:"policies" yaml:"policies"`
|
Policies []NotificiationPolicyV1 `json:"policies" yaml:"policies"`
|
||||||
ResetPolicies []values.Int64Value `json:"resetPolicies" yaml:"resetPolicies"`
|
ResetPolicies []values.Int64Value `json:"resetPolicies" yaml:"resetPolicies"` // Legacy field, use DeletePolicies instead.
|
||||||
MuteTimes []MuteTimeV1 `json:"muteTimes" yaml:"muteTimes"`
|
DeletePolicies []DeleteNotificationPolicyV1 `json:"deletePolicies" yaml:"deletePolicies"`
|
||||||
DeleteMuteTimes []DeleteMuteTimeV1 `json:"deleteMuteTimes" yaml:"deleteMuteTimes"`
|
MuteTimes []MuteTimeV1 `json:"muteTimes" yaml:"muteTimes"`
|
||||||
Templates []TemplateV1 `json:"templates" yaml:"templates"`
|
DeleteMuteTimes []DeleteMuteTimeV1 `json:"deleteMuteTimes" yaml:"deleteMuteTimes"`
|
||||||
DeleteTemplates []DeleteTemplateV1 `json:"deleteTemplates" yaml:"deleteTemplates"`
|
Templates []TemplateV1 `json:"templates" yaml:"templates"`
|
||||||
|
DeleteTemplates []DeleteTemplateV1 `json:"deleteTemplates" yaml:"deleteTemplates"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fileV1 *AlertingFileV1) MapToModel() (AlertingFile, error) {
|
func (fileV1 *AlertingFileV1) MapToModel() (AlertingFile, error) {
|
||||||
@@ -101,7 +103,18 @@ func (fileV1 *AlertingFileV1) mapPolicies(alertingFile *AlertingFile) error {
|
|||||||
alertingFile.Policies = append(alertingFile.Policies, np)
|
alertingFile.Policies = append(alertingFile.Policies, np)
|
||||||
}
|
}
|
||||||
for _, orgIDV1 := range fileV1.ResetPolicies {
|
for _, orgIDV1 := range fileV1.ResetPolicies {
|
||||||
alertingFile.ResetPolicies = append(alertingFile.ResetPolicies, OrgID(orgIDV1.Value()))
|
alertingFile.DeletePolicies = append(alertingFile.DeletePolicies, DeleteNotificationPolicy{
|
||||||
|
OrgID: orgIDV1.Value(),
|
||||||
|
Name: legacy_storage.UserDefinedRoutingTreeName,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, deleteV1 := range fileV1.DeletePolicies {
|
||||||
|
delReq, err := deleteV1.mapToModel()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
alertingFile.DeletePolicies = append(alertingFile.DeletePolicies, delReq)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -336,7 +336,7 @@ func (ps *ProvisioningServiceImpl) ProvisionAlerting(ctx context.Context) error
|
|||||||
contactPointService := provisioning.NewContactPointService(configStore, ps.secretService,
|
contactPointService := provisioning.NewContactPointService(configStore, ps.secretService,
|
||||||
ps.alertingStore, ps.SQLStore, receiverSvc, ps.log, ps.alertingStore, ps.resourcePermissions)
|
ps.alertingStore, ps.SQLStore, receiverSvc, ps.log, ps.alertingStore, ps.resourcePermissions)
|
||||||
notificationPolicyService := provisioning.NewNotificationPolicyService(configStore,
|
notificationPolicyService := provisioning.NewNotificationPolicyService(configStore,
|
||||||
ps.alertingStore, ps.SQLStore, ps.Cfg.UnifiedAlerting, ps.log)
|
ps.alertingStore, ps.SQLStore, ps.Cfg.UnifiedAlerting, ps.alertingStore.FeatureToggles, ps.log)
|
||||||
mutetimingsService := provisioning.NewMuteTimingService(configStore, ps.alertingStore, ps.alertingStore, ps.log, ps.alertingStore)
|
mutetimingsService := provisioning.NewMuteTimingService(configStore, ps.alertingStore, ps.alertingStore, ps.log, ps.alertingStore)
|
||||||
templateService := provisioning.NewTemplateService(configStore, ps.alertingStore, ps.alertingStore, ps.log)
|
templateService := provisioning.NewTemplateService(configStore, ps.alertingStore, ps.alertingStore, ps.log)
|
||||||
cfg := prov_alerting.ProvisionerConfig{
|
cfg := prov_alerting.ProvisionerConfig{
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import (
|
|||||||
"k8s.io/apimachinery/pkg/types"
|
"k8s.io/apimachinery/pkg/types"
|
||||||
|
|
||||||
"github.com/grafana/alerting/notify"
|
"github.com/grafana/alerting/notify"
|
||||||
|
|
||||||
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
|
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
|
||||||
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
|
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
|
||||||
"github.com/grafana/grafana/pkg/bus"
|
"github.com/grafana/grafana/pkg/bus"
|
||||||
@@ -38,6 +37,7 @@ import (
|
|||||||
"github.com/grafana/grafana/pkg/services/ngalert/api"
|
"github.com/grafana/grafana/pkg/services/ngalert/api"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
|
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
||||||
"github.com/grafana/grafana/pkg/services/org"
|
"github.com/grafana/grafana/pkg/services/org"
|
||||||
"github.com/grafana/grafana/pkg/tests/api/alerting"
|
"github.com/grafana/grafana/pkg/tests/api/alerting"
|
||||||
@@ -809,7 +809,9 @@ func TestIntegrationInUseMetadata(t *testing.T) {
|
|||||||
|
|
||||||
// Removing the new extra route should leave only 1.
|
// Removing the new extra route should leave only 1.
|
||||||
amConfig.AlertmanagerConfig.Route.Routes = amConfig.AlertmanagerConfig.Route.Routes[:1]
|
amConfig.AlertmanagerConfig.Route.Routes = amConfig.AlertmanagerConfig.Route.Routes[:1]
|
||||||
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, *amConfig.AlertmanagerConfig.Route, "", func(int64) string { return "default" })
|
managedRoute := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
|
||||||
|
managedRoute.Version = "" // Avoid version conflict.
|
||||||
|
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, managedRoute, func(int64) string { return "default" })
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
routeAdminClient := test_common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
routeAdminClient := test_common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
||||||
_, err = routeAdminClient.Update(ctx, v1Route, v1.UpdateOptions{})
|
_, err = routeAdminClient.Update(ctx, v1Route, v1.UpdateOptions{})
|
||||||
@@ -831,7 +833,9 @@ func TestIntegrationInUseMetadata(t *testing.T) {
|
|||||||
|
|
||||||
// Remove the remaining routes.
|
// Remove the remaining routes.
|
||||||
amConfig.AlertmanagerConfig.Route.Routes = nil
|
amConfig.AlertmanagerConfig.Route.Routes = nil
|
||||||
v1route, err := routingtree.ConvertToK8sResource(1, *amConfig.AlertmanagerConfig.Route, "", func(int64) string { return "default" })
|
managedRoute = legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
|
||||||
|
managedRoute.Version = "" // Avoid version conflict.
|
||||||
|
v1route, err := routingtree.ConvertToK8sResource(1, managedRoute, func(int64) string { return "default" })
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_, err = routeAdminClient.Update(ctx, v1route, v1.UpdateOptions{})
|
_, err = routeAdminClient.Update(ctx, v1route, v1.UpdateOptions{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -1139,9 +1143,15 @@ func TestIntegrationReferentialIntegrity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
updatedRoute := legacyCli.GetRoute(t)
|
updatedRoute := legacyCli.GetRoute(t)
|
||||||
for _, route := range updatedRoute.Routes {
|
// Sanity check to make sure at least some titles updated.
|
||||||
assert.Equalf(t, expectedTitle, route.Receiver, "time receiver in routes should have been renamed but it did not")
|
assert.Error(t, updatedRoute.ValidateReceivers(map[string]struct{}{
|
||||||
}
|
"grafana-default-email": {},
|
||||||
|
}))
|
||||||
|
// Make sure all references are either to the default receiver or the renamed one.
|
||||||
|
assert.NoError(t, updatedRoute.ValidateReceivers(map[string]struct{}{
|
||||||
|
"grafana-default-email": {},
|
||||||
|
expectedTitle: {},
|
||||||
|
}))
|
||||||
|
|
||||||
actual, err = adminClient.Get(ctx, actual.Name, v1.GetOptions{})
|
actual, err = adminClient.Get(ctx, actual.Name, v1.GetOptions{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -1498,7 +1508,9 @@ func persistInitialConfig(t *testing.T, amConfig definitions.PostableUserConfig)
|
|||||||
nsMapper := func(_ int64) string { return "default" }
|
nsMapper := func(_ int64) string { return "default" }
|
||||||
|
|
||||||
routeClient := test_common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
routeClient := test_common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
||||||
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, *amConfig.AlertmanagerConfig.Route, "", nsMapper)
|
managedRoute := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
|
||||||
|
managedRoute.Version = "" // Avoid version conflict.
|
||||||
|
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, managedRoute, nsMapper)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_, err = routeClient.Update(ctx, v1route, v1.UpdateOptions{})
|
_, err = routeClient.Update(ctx, v1route, v1.UpdateOptions{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import (
|
|||||||
|
|
||||||
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
|
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
|
||||||
"github.com/grafana/grafana/pkg/registry/apps/alerting/notifications/routingtree"
|
"github.com/grafana/grafana/pkg/registry/apps/alerting/notifications/routingtree"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
|
|
||||||
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1/fakes"
|
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1/fakes"
|
||||||
"github.com/grafana/grafana/pkg/bus"
|
"github.com/grafana/grafana/pkg/bus"
|
||||||
@@ -48,6 +49,8 @@ func getTestHelper(t *testing.T) *apis.K8sTestHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestIntegrationNotAllowedMethods(t *testing.T) {
|
func TestIntegrationNotAllowedMethods(t *testing.T) {
|
||||||
|
// TODO: Add more tests.
|
||||||
|
t.Skip("No longer applies, need real tests.")
|
||||||
testutil.SkipIntegrationTestInShortMode(t)
|
testutil.SkipIntegrationTestInShortMode(t)
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -387,7 +390,9 @@ func TestIntegrationDataConsistency(t *testing.T) {
|
|||||||
createRoute := func(t *testing.T, route definitions.Route) {
|
createRoute := func(t *testing.T, route definitions.Route) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
routeClient := common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
routeClient := common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
||||||
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), route, "", func(int64) string { return "default" })
|
managedRoute := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, &route)
|
||||||
|
managedRoute.Version = "" // Avoid version conflict.
|
||||||
|
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), managedRoute, func(int64) string { return "default" })
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_, err = routeClient.Update(ctx, v1Route, v1.UpdateOptions{})
|
_, err = routeClient.Update(ctx, v1Route, v1.UpdateOptions{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import (
|
|||||||
"github.com/grafana/grafana/pkg/services/folder/foldertest"
|
"github.com/grafana/grafana/pkg/services/folder/foldertest"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
|
||||||
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
|
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
|
||||||
|
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
|
||||||
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
"github.com/grafana/grafana/pkg/services/ngalert/store"
|
||||||
"github.com/grafana/grafana/pkg/services/org"
|
"github.com/grafana/grafana/pkg/services/org"
|
||||||
"github.com/grafana/grafana/pkg/tests/api/alerting"
|
"github.com/grafana/grafana/pkg/tests/api/alerting"
|
||||||
@@ -656,7 +657,9 @@ func TestIntegrationTimeIntervalReferentialIntegrity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
routeClient := common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
routeClient := common.NewRoutingTreeClient(t, helper.Org1.Admin)
|
||||||
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), *amConfig.AlertmanagerConfig.Route, "", func(int64) string { return "default" })
|
route := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
|
||||||
|
route.Version = "" // Avoid version conflict.
|
||||||
|
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), route, func(int64) string { return "default" })
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
_, err = routeClient.Update(ctx, v1route, v1.UpdateOptions{})
|
_, err = routeClient.Update(ctx, v1route, v1.UpdateOptions{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|||||||
@@ -85,6 +85,21 @@ export function getAlertingRoutes(cfg = config): RouteDescriptor[] {
|
|||||||
)
|
)
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/alerting/notifications/routes/:name/edit',
|
||||||
|
roles: evaluateAccess([
|
||||||
|
AccessControlAction.AlertingNotificationsRead,
|
||||||
|
AccessControlAction.AlertingNotificationsExternalRead,
|
||||||
|
...PERMISSIONS_NOTIFICATION_POLICIES_READ,
|
||||||
|
...PERMISSIONS_NOTIFICATION_POLICIES_MODIFY,
|
||||||
|
]),
|
||||||
|
component: importAlertingComponent(
|
||||||
|
() =>
|
||||||
|
import(
|
||||||
|
/* webpackChunkName: "EditRoutingTreePage" */ 'app/features/alerting/unified/components/notification-policies/EditRoutingTreePage'
|
||||||
|
)
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/alerting/silences',
|
path: '/alerting/silences',
|
||||||
roles: evaluateAccess([
|
roles: evaluateAccess([
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ import {
|
|||||||
import { AccessControlAction } from 'app/types/accessControl';
|
import { AccessControlAction } from 'app/types/accessControl';
|
||||||
|
|
||||||
import NotificationPolicies from './NotificationPoliciesPage';
|
import NotificationPolicies from './NotificationPoliciesPage';
|
||||||
import { findRoutesMatchingFilters } from './components/notification-policies/NotificationPoliciesList';
|
import { findRoutesMatchingFilters } from './components/notification-policies/NotificationPoliciesTree';
|
||||||
import {
|
import {
|
||||||
grantUserPermissions,
|
grantUserPermissions,
|
||||||
mockDataSource,
|
mockDataSource,
|
||||||
|
|||||||
@@ -1,19 +1,63 @@
|
|||||||
import { css } from '@emotion/css';
|
import { css } from '@emotion/css';
|
||||||
import { useState } from 'react';
|
import { Fragment, useState } from 'react';
|
||||||
|
|
||||||
import { GrafanaTheme2, UrlQueryMap } from '@grafana/data';
|
import { GrafanaTheme2, UrlQueryMap } from '@grafana/data';
|
||||||
import { t } from '@grafana/i18n';
|
import { t } from '@grafana/i18n';
|
||||||
import { Tab, TabContent, TabsBar, useStyles2 } from '@grafana/ui';
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Dropdown,
|
||||||
|
EmptyState,
|
||||||
|
LinkButton,
|
||||||
|
LoadingPlaceholder,
|
||||||
|
Menu,
|
||||||
|
Pagination,
|
||||||
|
Stack,
|
||||||
|
Tab,
|
||||||
|
TabContent,
|
||||||
|
TabsBar,
|
||||||
|
Text,
|
||||||
|
Tooltip,
|
||||||
|
useStyles2,
|
||||||
|
} from '@grafana/ui';
|
||||||
import { useQueryParams } from 'app/core/hooks/useQueryParams';
|
import { useQueryParams } from 'app/core/hooks/useQueryParams';
|
||||||
import { useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
|
import { useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
|
||||||
import { NotificationPoliciesList } from 'app/features/alerting/unified/components/notification-policies/NotificationPoliciesList';
|
import { NotificationPoliciesTree } from 'app/features/alerting/unified/components/notification-policies/NotificationPoliciesTree';
|
||||||
import { AlertmanagerAction, useAlertmanagerAbility } from 'app/features/alerting/unified/hooks/useAbilities';
|
import { MetadataRow } from 'app/features/alerting/unified/components/notification-policies/Policy';
|
||||||
|
import {
|
||||||
|
AlertmanagerAction,
|
||||||
|
useAlertmanagerAbilities,
|
||||||
|
useAlertmanagerAbility,
|
||||||
|
} from 'app/features/alerting/unified/hooks/useAbilities';
|
||||||
|
|
||||||
import { AlertmanagerPageWrapper } from './components/AlertingPageWrapper';
|
import { AlertmanagerPageWrapper } from './components/AlertingPageWrapper';
|
||||||
import { GrafanaAlertmanagerWarning } from './components/GrafanaAlertmanagerWarning';
|
import { GrafanaAlertmanagerWarning } from './components/GrafanaAlertmanagerWarning';
|
||||||
import { TimeIntervalsTable } from './components/mute-timings/MuteTimingsTable';
|
import { TimeIntervalsTable } from './components/mute-timings/MuteTimingsTable';
|
||||||
import { useAlertmanager } from './state/AlertmanagerContext';
|
import { useAlertmanager } from './state/AlertmanagerContext';
|
||||||
import { withPageErrorBoundary } from './withPageErrorBoundary';
|
import { withPageErrorBoundary } from './withPageErrorBoundary';
|
||||||
|
import { AlertmanagerGroup, Receiver, Route, ROUTES_META_SYMBOL } from '../../../plugins/datasource/alertmanager/types';
|
||||||
|
import { stringifyErrorLike } from './utils/misc';
|
||||||
|
import {
|
||||||
|
useCreateRoutingTree,
|
||||||
|
useDeleteRoutingTree,
|
||||||
|
useListNotificationPolicyRoutes,
|
||||||
|
useRootRouteSearch,
|
||||||
|
} from './components/notification-policies/useNotificationPolicyRoute';
|
||||||
|
import { useURLSearchParams } from './hooks/useURLSearchParams';
|
||||||
|
import { usePagination } from './hooks/usePagination';
|
||||||
|
import { useCreateRoutingTreeModal, useDeleteRoutingTreeModal } from './components/notification-policies/components/Modals';
|
||||||
|
import { ALL_ROUTING_TREES, useExportRoutingTree } from './components/notification-policies/useExportRoutingTree';
|
||||||
|
import { K8sAnnotations, ROOT_ROUTE_NAME } from './utils/k8s/constants';
|
||||||
|
import ConditionalWrap from './components/ConditionalWrap';
|
||||||
|
import { ProvisioningBadge } from './components/Provisioning';
|
||||||
|
import { getAnnotation } from './utils/k8s/utils';
|
||||||
|
import { Spacer } from './components/Spacer';
|
||||||
|
import MoreButton from './components/MoreButton';
|
||||||
|
import { useGrafanaContactPoints } from './components/contact-points/useContactPoints';
|
||||||
|
import { useAlertGroupsModal } from './components/notification-policies/Modals';
|
||||||
|
import { normalizeMatchers } from './utils/matchers';
|
||||||
|
import { RoutingTreeFilter } from './components/notification-policies/components/RoutingTreeFilter';
|
||||||
|
import {config} from '@grafana/runtime';
|
||||||
|
|
||||||
enum ActiveTab {
|
enum ActiveTab {
|
||||||
NotificationPolicies = 'notification_policies',
|
NotificationPolicies = 'notification_policies',
|
||||||
@@ -73,17 +117,360 @@ const NotificationPoliciesTabs = () => {
|
|||||||
)}
|
)}
|
||||||
</TabsBar>
|
</TabsBar>
|
||||||
<TabContent className={styles.tabContent}>
|
<TabContent className={styles.tabContent}>
|
||||||
{policyTreeTabActive && <NotificationPoliciesList />}
|
{policyTreeTabActive && <PolicyTreeTab />}
|
||||||
{muteTimingsTabActive && <TimeIntervalsTable />}
|
{muteTimingsTabActive && <TimeIntervalsTable />}
|
||||||
</TabContent>
|
</TabContent>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const PolicyTreeTab = () => {
|
||||||
|
const { isGrafanaAlertmanager } = useAlertmanager();
|
||||||
|
|
||||||
|
const useMultiplePoliciesView = config.featureToggles.alertingMultiplePolicies;
|
||||||
|
|
||||||
|
if (!isGrafanaAlertmanager || !useMultiplePoliciesView) {
|
||||||
|
return <NotificationPoliciesTree />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Stack direction="column">
|
||||||
|
<PolicyTreeTabContents />
|
||||||
|
</Stack>
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_PAGE_SIZE = 10;
|
||||||
|
|
||||||
|
const PolicyTreeTabContents = () => {
|
||||||
|
const [queryParams] = useURLSearchParams();
|
||||||
|
|
||||||
|
const [[createPoliciesSupported, createPoliciesAllowed], [exportPoliciesSupported, exportPoliciesAllowed]] =
|
||||||
|
useAlertmanagerAbilities([
|
||||||
|
AlertmanagerAction.CreateNotificationPolicy,
|
||||||
|
AlertmanagerAction.ExportNotificationPolicies,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const {
|
||||||
|
currentData: allPolicies,
|
||||||
|
isLoading,
|
||||||
|
error: fetchPoliciesError,
|
||||||
|
} = useListNotificationPolicyRoutes();
|
||||||
|
|
||||||
|
const [ExportDrawer, showExportDrawer] = useExportRoutingTree();
|
||||||
|
|
||||||
|
const [createTrigger] = useCreateRoutingTree();
|
||||||
|
const [CreateModal, showCreateModal] = useCreateRoutingTreeModal(createTrigger.execute);
|
||||||
|
|
||||||
|
const search = queryParams.get('search');
|
||||||
|
|
||||||
|
const [contactPointsSupported, canSeeContactPoints] = useAlertmanagerAbility(AlertmanagerAction.ViewContactPoint);
|
||||||
|
const shouldFetchContactPoints = contactPointsSupported && canSeeContactPoints;
|
||||||
|
const { contactPoints: receivers } = useGrafanaContactPoints({
|
||||||
|
skip: !shouldFetchContactPoints,
|
||||||
|
fetchStatuses: false,
|
||||||
|
fetchPolicies: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <LoadingPlaceholder text={'Loading...'} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* TODO we can add some additional info here with a ToggleTip */}
|
||||||
|
<Stack direction="row" alignItems="end" justifyContent="space-between">
|
||||||
|
<RoutingTreeFilter />
|
||||||
|
|
||||||
|
<Stack direction="row" gap={1}>
|
||||||
|
{createPoliciesSupported && (
|
||||||
|
<Button
|
||||||
|
icon="plus"
|
||||||
|
aria-label={'add policy'}
|
||||||
|
variant="primary"
|
||||||
|
disabled={!createPoliciesAllowed}
|
||||||
|
onClick={() => showCreateModal()}
|
||||||
|
>
|
||||||
|
Create policy
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{exportPoliciesSupported && (
|
||||||
|
<Button
|
||||||
|
icon="download-alt"
|
||||||
|
variant="secondary"
|
||||||
|
aria-label={'export all'}
|
||||||
|
disabled={!exportPoliciesAllowed}
|
||||||
|
onClick={() => showExportDrawer(ALL_ROUTING_TREES)}
|
||||||
|
>
|
||||||
|
Export all
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
{fetchPoliciesError ? (
|
||||||
|
<Alert title={'Failed to fetch policies'}>{stringifyErrorLike(fetchPoliciesError)}</Alert>
|
||||||
|
) : (
|
||||||
|
<RoutingTreeList
|
||||||
|
policies={allPolicies ?? []}
|
||||||
|
search={search}
|
||||||
|
pageSize={DEFAULT_PAGE_SIZE}
|
||||||
|
receivers={receivers}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{CreateModal}
|
||||||
|
{ExportDrawer}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
interface RoutingTreeListProps {
|
||||||
|
policies: Route[];
|
||||||
|
search?: string | null;
|
||||||
|
pageSize: number;
|
||||||
|
receivers?: Receiver[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const RoutingTreeList = ({ policies, search, pageSize = DEFAULT_PAGE_SIZE, receivers }: RoutingTreeListProps) => {
|
||||||
|
const searchResults = useRootRouteSearch(policies, search);
|
||||||
|
const { page, pageItems, numberOfPages, onPageChange } = usePagination(searchResults, 1, pageSize);
|
||||||
|
|
||||||
|
if (pageItems.length === 0) {
|
||||||
|
return <EmptyState variant="not-found" message={'No policies found'} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{pageItems.map((policy, index) => {
|
||||||
|
const key = `${policy.name}-${index}`;
|
||||||
|
return <RoutingTree key={key} route={policy} receivers={receivers} />;
|
||||||
|
})}
|
||||||
|
<Pagination currentPage={page} numberOfPages={numberOfPages} onNavigate={onPageChange} hideWhenSinglePage />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
interface RoutingTreeProps {
|
||||||
|
route: Route;
|
||||||
|
receivers?: Receiver[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RoutingTree = ({ route, receivers }: RoutingTreeProps) => {
|
||||||
|
const styles = useStyles2(getStyles);
|
||||||
|
const { selectedAlertmanager } = useAlertmanager();
|
||||||
|
|
||||||
|
const [deleteTrigger] = useDeleteRoutingTree();
|
||||||
|
const [DeleteModal, showDeleteModal] = useDeleteRoutingTreeModal(deleteTrigger.execute);
|
||||||
|
const [alertInstancesModal, showAlertGroupsModal] = useAlertGroupsModal(selectedAlertmanager ?? '');
|
||||||
|
|
||||||
|
const matchingInstancesPreview = { enabled: false }; // Placeholder for matching instances preview logic
|
||||||
|
const numberOfAlertInstances = undefined; // Placeholder for number of alert instances logic
|
||||||
|
const matchingAlertGroups: AlertmanagerGroup[] | undefined = []; // Placeholder for matching alert groups logic
|
||||||
|
const matchers = normalizeMatchers(route);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.routingTreeWrapper} data-testid="contact-point">
|
||||||
|
<Stack direction="column" gap={0}>
|
||||||
|
<RoutingTreeHeader
|
||||||
|
route={route}
|
||||||
|
onDelete={(routeToDelete) =>
|
||||||
|
showDeleteModal({
|
||||||
|
name: routeToDelete[ROUTES_META_SYMBOL]?.name ?? '',
|
||||||
|
resourceVersion: routeToDelete[ROUTES_META_SYMBOL]?.resourceVersion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className={styles.routingTreeMetadataWrapper}>
|
||||||
|
<Stack direction="column" gap={0.5}>
|
||||||
|
<MetadataRow
|
||||||
|
matchingInstancesPreview={matchingInstancesPreview}
|
||||||
|
numberOfAlertInstances={numberOfAlertInstances}
|
||||||
|
contactPoint={route.receiver ?? undefined}
|
||||||
|
groupBy={route.group_by ?? []}
|
||||||
|
muteTimings={route.mute_time_intervals ?? []}
|
||||||
|
activeTimings={route.active_time_intervals ?? []}
|
||||||
|
timingOptions={{
|
||||||
|
group_wait: route.group_wait,
|
||||||
|
group_interval: route.group_interval,
|
||||||
|
repeat_interval: route.repeat_interval,
|
||||||
|
}}
|
||||||
|
alertManagerSourceName={selectedAlertmanager ?? ''}
|
||||||
|
receivers={receivers ?? []}
|
||||||
|
matchingAlertGroups={matchingAlertGroups}
|
||||||
|
matchers={matchers}
|
||||||
|
isDefaultPolicy={true}
|
||||||
|
onShowAlertInstances={showAlertGroupsModal}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</div>
|
||||||
|
</Stack>
|
||||||
|
{DeleteModal}
|
||||||
|
{alertInstancesModal}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
interface RoutingTreeHeaderProps {
|
||||||
|
route: Route;
|
||||||
|
onDelete: (route: Route) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RoutingTreeHeader = ({ route, onDelete }: RoutingTreeHeaderProps) => {
|
||||||
|
const provisioned = route[ROUTES_META_SYMBOL]?.provisioned ?? false;
|
||||||
|
const styles = useStyles2(getStyles);
|
||||||
|
|
||||||
|
const [
|
||||||
|
[updatePoliciesSupported, updatePoliciesAllowed],
|
||||||
|
[deletePoliciesSupported, deletePoliciesAllowed],
|
||||||
|
[exportPoliciesSupported, exportPoliciesAllowed],
|
||||||
|
] = useAlertmanagerAbilities([
|
||||||
|
AlertmanagerAction.UpdateNotificationPolicyTree,
|
||||||
|
AlertmanagerAction.DeleteNotificationPolicy,
|
||||||
|
AlertmanagerAction.ExportNotificationPolicies,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const canEdit = updatePoliciesSupported && updatePoliciesAllowed && !provisioned;
|
||||||
|
|
||||||
|
const [ExportDrawer, showExportDrawer] = useExportRoutingTree();
|
||||||
|
|
||||||
|
const menuActions: JSX.Element[] = [];
|
||||||
|
if (exportPoliciesSupported) {
|
||||||
|
menuActions.push(
|
||||||
|
<Fragment key="export-contact-point">
|
||||||
|
<Menu.Item
|
||||||
|
icon="download-alt"
|
||||||
|
label={t('alerting.use-create-dropdown-menu-actions.label-export', 'Export')}
|
||||||
|
ariaLabel="export"
|
||||||
|
disabled={!exportPoliciesAllowed}
|
||||||
|
data-testid="export"
|
||||||
|
onClick={() => showExportDrawer(route.name ?? '')}
|
||||||
|
/>
|
||||||
|
<Menu.Divider />
|
||||||
|
</Fragment>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deletePoliciesSupported) {
|
||||||
|
const canBeDeleted = deletePoliciesAllowed && !provisioned;
|
||||||
|
const isDefaultPolicy = route.name === ROOT_ROUTE_NAME;
|
||||||
|
|
||||||
|
const cannotDeleteNoPermissions = `You do not have the required permission to ${isDefaultPolicy ? 'reset' : 'delete'} this routing tree`;
|
||||||
|
const cannotDeleteProvisioned = `Routing tree is provisioned and cannot be ${isDefaultPolicy ? 'reset' : 'deleted'} via the UI`;
|
||||||
|
|
||||||
|
const reasonsDeleteIsDisabled = [
|
||||||
|
!deletePoliciesAllowed ? cannotDeleteNoPermissions : '',
|
||||||
|
provisioned ? cannotDeleteProvisioned : '',
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
const deleteTooltipContent = (
|
||||||
|
<>
|
||||||
|
{`Routing tree cannot be ${isDefaultPolicy ? 'reset' : 'deleted'} for the following reasons:`}
|
||||||
|
<br />
|
||||||
|
{reasonsDeleteIsDisabled.map((reason) => (
|
||||||
|
<li key={reason}>{reason}</li>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
menuActions.push(
|
||||||
|
<ConditionalWrap
|
||||||
|
key="delete-routing-tree"
|
||||||
|
shouldWrap={!canBeDeleted}
|
||||||
|
wrap={(children) => (
|
||||||
|
<Tooltip content={deleteTooltipContent} placement="top">
|
||||||
|
<span>{children}</span>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Menu.Item
|
||||||
|
label={route.name === ROOT_ROUTE_NAME ? "Reset" : t('alerting.use-create-dropdown-menu-actions.label-delete', 'Delete')}
|
||||||
|
ariaLabel="delete"
|
||||||
|
icon="trash-alt"
|
||||||
|
destructive
|
||||||
|
disabled={!canBeDeleted}
|
||||||
|
onClick={() => onDelete(route)}
|
||||||
|
/>
|
||||||
|
</ConditionalWrap>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const routeName = route.name === ROOT_ROUTE_NAME || !route.name ? 'Default Policy' : route.name;
|
||||||
|
const numberOfPolicies = countPolicies(route);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.headerWrapper}>
|
||||||
|
<Stack direction="row" alignItems="center" gap={1}>
|
||||||
|
<Stack alignItems="center" gap={1} minWidth={0}>
|
||||||
|
<Text element="h2" variant="body" weight="medium" truncate>
|
||||||
|
{routeName}
|
||||||
|
</Text>
|
||||||
|
</Stack>
|
||||||
|
{numberOfPolicies > 0 && <>{`Contains ${numberOfPolicies} polic${numberOfPolicies > 1 ? 'ies' : 'y'}`}</>}
|
||||||
|
{provisioned && (
|
||||||
|
<ProvisioningBadge
|
||||||
|
tooltip
|
||||||
|
provenance={getAnnotation(route[ROUTES_META_SYMBOL] ?? {}, K8sAnnotations.Provenance)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Spacer />
|
||||||
|
<LinkButton
|
||||||
|
tooltipPlacement="top"
|
||||||
|
tooltip={provisioned ? 'Provisioned routing trees cannot be edited in the UI' : undefined}
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
icon={canEdit ? 'pen' : 'eye'}
|
||||||
|
type="button"
|
||||||
|
data-testid={`${canEdit ? 'edit' : 'view'}-action`}
|
||||||
|
href={`/alerting/notifications/routes/${encodeURIComponent(route.name ?? '')}/edit`}
|
||||||
|
>
|
||||||
|
{canEdit ? 'Edit' : 'View'}
|
||||||
|
</LinkButton>
|
||||||
|
{menuActions.length > 0 && (
|
||||||
|
<Dropdown overlay={<Menu>{menuActions}</Menu>}>
|
||||||
|
<MoreButton aria-label={`More actions for routing tree "${route.name ?? ''}"`} />
|
||||||
|
</Dropdown>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
{ExportDrawer}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
function countPolicies(route: Route): number {
|
||||||
|
let count = 0;
|
||||||
|
if (route.routes) {
|
||||||
|
count += route.routes.length;
|
||||||
|
route.routes.forEach((subRoute) => {
|
||||||
|
count += countPolicies(subRoute);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
const getStyles = (theme: GrafanaTheme2) => ({
|
const getStyles = (theme: GrafanaTheme2) => ({
|
||||||
tabContent: css({
|
tabContent: css({
|
||||||
marginTop: theme.spacing(2),
|
marginTop: theme.spacing(2),
|
||||||
}),
|
}),
|
||||||
|
routingTreeWrapper: css({
|
||||||
|
borderRadius: theme.shape.radius.default,
|
||||||
|
border: `solid 1px ${theme.colors.border.weak}`,
|
||||||
|
borderBottom: 'none',
|
||||||
|
}),
|
||||||
|
headerWrapper: css({
|
||||||
|
background: `${theme.colors.background.secondary}`,
|
||||||
|
padding: `${theme.spacing(1)} ${theme.spacing(1.5)}`,
|
||||||
|
|
||||||
|
borderBottom: `solid 1px ${theme.colors.border.weak}`,
|
||||||
|
borderTopLeftRadius: `${theme.shape.radius.default}`,
|
||||||
|
borderTopRightRadius: `${theme.shape.radius.default}`,
|
||||||
|
}),
|
||||||
|
routingTreeMetadataWrapper: css({
|
||||||
|
position: 'relative',
|
||||||
|
|
||||||
|
background: `${theme.colors.background.primary}`,
|
||||||
|
padding: `${theme.spacing(1)} ${theme.spacing(1.5)}`,
|
||||||
|
|
||||||
|
borderBottom: `solid 1px ${theme.colors.border.weak}`,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
interface QueryParamValues {
|
interface QueryParamValues {
|
||||||
|
|||||||
@@ -402,10 +402,10 @@ export const alertRuleApi = alertingApi.injectEndpoints({
|
|||||||
}),
|
}),
|
||||||
keepUnusedDataFor: 0,
|
keepUnusedDataFor: 0,
|
||||||
}),
|
}),
|
||||||
exportPolicies: build.query<string, { format: ExportFormats }>({
|
exportPolicies: build.query<string, { routeName?: string, format: ExportFormats }>({
|
||||||
query: ({ format }) => ({
|
query: ({ routeName, format }) => ({
|
||||||
url: `/api/v1/provisioning/policies/export/`,
|
url: `/api/v1/provisioning/policies/export/`,
|
||||||
params: { format: format },
|
params: { format: format, routeName: routeName },
|
||||||
responseType: 'text',
|
responseType: 'text',
|
||||||
}),
|
}),
|
||||||
keepUnusedDataFor: 0,
|
keepUnusedDataFor: 0,
|
||||||
|
|||||||
@@ -9,12 +9,14 @@ import { FileExportPreview } from './FileExportPreview';
|
|||||||
import { GrafanaExportDrawer } from './GrafanaExportDrawer';
|
import { GrafanaExportDrawer } from './GrafanaExportDrawer';
|
||||||
import { ExportFormats, allGrafanaExportProviders } from './providers';
|
import { ExportFormats, allGrafanaExportProviders } from './providers';
|
||||||
interface GrafanaPoliciesPreviewProps {
|
interface GrafanaPoliciesPreviewProps {
|
||||||
|
routeName?: string;
|
||||||
exportFormat: ExportFormats;
|
exportFormat: ExportFormats;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const GrafanaPoliciesExporterPreview = ({ exportFormat, onClose }: GrafanaPoliciesPreviewProps) => {
|
const GrafanaPoliciesExporterPreview = ({ routeName = '', exportFormat, onClose }: GrafanaPoliciesPreviewProps) => {
|
||||||
const { currentData: policiesDefinition = '', isFetching } = alertRuleApi.useExportPoliciesQuery({
|
const { currentData: policiesDefinition = '', isFetching } = alertRuleApi.useExportPoliciesQuery({
|
||||||
|
routeName: routeName,
|
||||||
format: exportFormat,
|
format: exportFormat,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -35,10 +37,11 @@ const GrafanaPoliciesExporterPreview = ({ exportFormat, onClose }: GrafanaPolici
|
|||||||
};
|
};
|
||||||
|
|
||||||
interface GrafanaPoliciesExporterProps {
|
interface GrafanaPoliciesExporterProps {
|
||||||
|
routeName?: string;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GrafanaPoliciesExporter = ({ onClose }: GrafanaPoliciesExporterProps) => {
|
export const GrafanaPoliciesExporter = ({ routeName = '', onClose }: GrafanaPoliciesExporterProps) => {
|
||||||
const [activeTab, setActiveTab] = useState<ExportFormats>('yaml');
|
const [activeTab, setActiveTab] = useState<ExportFormats>('yaml');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -48,7 +51,7 @@ export const GrafanaPoliciesExporter = ({ onClose }: GrafanaPoliciesExporterProp
|
|||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
formatProviders={Object.values(allGrafanaExportProviders)}
|
formatProviders={Object.values(allGrafanaExportProviders)}
|
||||||
>
|
>
|
||||||
<GrafanaPoliciesExporterPreview exportFormat={activeTab} onClose={onClose} />
|
<GrafanaPoliciesExporterPreview exportFormat={activeTab} onClose={onClose} routeName={routeName}/>
|
||||||
</GrafanaExportDrawer>
|
</GrafanaExportDrawer>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Controller, useForm } from 'react-hook-form';
|
|||||||
|
|
||||||
import { ContactPointSelector as GrafanaManagedContactPointSelector } from '@grafana/alerting/unstable';
|
import { ContactPointSelector as GrafanaManagedContactPointSelector } from '@grafana/alerting/unstable';
|
||||||
import { Trans, t } from '@grafana/i18n';
|
import { Trans, t } from '@grafana/i18n';
|
||||||
import { Collapse, Field, Link, MultiSelect, useStyles2 } from '@grafana/ui';
|
import { Collapse, Field, Input, Link, MultiSelect, useStyles2 } from '@grafana/ui';
|
||||||
import { ExternalAlertmanagerContactPointSelector } from 'app/features/alerting/unified/components/notification-policies/ContactPointSelector';
|
import { ExternalAlertmanagerContactPointSelector } from 'app/features/alerting/unified/components/notification-policies/ContactPointSelector';
|
||||||
import { handleContactPointSelect } from 'app/features/alerting/unified/components/notification-policies/utils';
|
import { handleContactPointSelect } from 'app/features/alerting/unified/components/notification-policies/utils';
|
||||||
import { RouteWithID } from 'app/plugins/datasource/alertmanager/types';
|
import { RouteWithID } from 'app/plugins/datasource/alertmanager/types';
|
||||||
@@ -30,9 +30,10 @@ export interface AmRootRouteFormProps {
|
|||||||
actionButtons: ReactNode;
|
actionButtons: ReactNode;
|
||||||
onSubmit: (route: Partial<FormAmRoute>) => void;
|
onSubmit: (route: Partial<FormAmRoute>) => void;
|
||||||
route: RouteWithID;
|
route: RouteWithID;
|
||||||
|
showNameField?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AmRootRouteForm = ({ actionButtons, alertManagerSourceName, onSubmit, route }: AmRootRouteFormProps) => {
|
export const AmRootRouteForm = ({ actionButtons, alertManagerSourceName, onSubmit, route, showNameField }: AmRootRouteFormProps) => {
|
||||||
const styles = useStyles2(getFormStyles);
|
const styles = useStyles2(getFormStyles);
|
||||||
const [isTimingOptionsExpanded, setIsTimingOptionsExpanded] = useState(false);
|
const [isTimingOptionsExpanded, setIsTimingOptionsExpanded] = useState(false);
|
||||||
const { isGrafanaAlertmanager } = useAlertmanager();
|
const { isGrafanaAlertmanager } = useAlertmanager();
|
||||||
@@ -55,6 +56,30 @@ export const AmRootRouteForm = ({ actionButtons, alertManagerSourceName, onSubmi
|
|||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit(onSubmit)}>
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
{showNameField && (<Field
|
||||||
|
required
|
||||||
|
label={t('alerting.am-root-route-form.name', 'Name')}
|
||||||
|
description={t(
|
||||||
|
'alerting.am-root-route-form.description-unique-route',
|
||||||
|
'A unique name for the routing tree'
|
||||||
|
)}
|
||||||
|
invalid={!!errors.name}
|
||||||
|
error={errors.name?.message}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
{...register('name', {
|
||||||
|
required: true,
|
||||||
|
validate: (value) => {
|
||||||
|
if (!value || value.trim().length === 0) {
|
||||||
|
return 'Name is required';
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
})}
|
||||||
|
className={styles.input}
|
||||||
|
data-testid="routing-tree-name"
|
||||||
|
/>
|
||||||
|
</Field>)}
|
||||||
<Field
|
<Field
|
||||||
label={t('alerting.am-root-route-form.label-default-contact-point', 'Default contact point')}
|
label={t('alerting.am-root-route-form.label-default-contact-point', 'Default contact point')}
|
||||||
invalid={Boolean(errors.receiver) ? true : undefined}
|
invalid={Boolean(errors.receiver) ? true : undefined}
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { useParams } from 'react-router-dom-v5-compat';
|
||||||
|
|
||||||
|
import { Alert } from '@grafana/ui';
|
||||||
|
import { withPageErrorBoundary } from '../../withPageErrorBoundary';
|
||||||
|
import { AlertmanagerPageWrapper } from '../AlertingPageWrapper';
|
||||||
|
import { NotificationPoliciesTree } from './NotificationPoliciesTree';
|
||||||
|
import { ROOT_ROUTE_NAME } from '../../utils/k8s/constants';
|
||||||
|
|
||||||
|
const EditRoutingTree = () => {
|
||||||
|
const { name = '' } = useParams();
|
||||||
|
|
||||||
|
const routeName = decodeURIComponent(name);
|
||||||
|
|
||||||
|
if (!routeName) {
|
||||||
|
return (
|
||||||
|
<Alert severity="error" title={'Routing tree not found'}>
|
||||||
|
{'Sorry, this routing tree does not seem to exist.'}
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <NotificationPoliciesTree routeName={routeName} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
function EditRoutingTreePage() {
|
||||||
|
const { name = '' } = useParams();
|
||||||
|
const routeName = name === ROOT_ROUTE_NAME ? "Default Policy" : decodeURIComponent(name);
|
||||||
|
|
||||||
|
const pageNav = {
|
||||||
|
text: routeName,
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<AlertmanagerPageWrapper navId="am-routes" pageNav={pageNav} accessType="notification">
|
||||||
|
<EditRoutingTree />
|
||||||
|
</AlertmanagerPageWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withPageErrorBoundary(EditRoutingTreePage);
|
||||||
@@ -298,10 +298,10 @@ const useAlertGroupsModal = (
|
|||||||
return [modalElement, handleShow, handleDismiss];
|
return [modalElement, handleShow, handleDismiss];
|
||||||
};
|
};
|
||||||
|
|
||||||
const UpdatingModal: FC<Pick<ModalProps, 'isOpen'>> = ({ isOpen }) => (
|
export const UpdatingModal: FC<Pick<ModalProps, 'isOpen' | 'onDismiss'>> = ({ isOpen, onDismiss = () => {}} ) => (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={isOpen}
|
isOpen={isOpen}
|
||||||
onDismiss={() => {}}
|
onDismiss={onDismiss}
|
||||||
closeOnBackdropClick={false}
|
closeOnBackdropClick={false}
|
||||||
closeOnEscape={false}
|
closeOnEscape={false}
|
||||||
ariaLabel={t('alerting.policies.update.updating', 'Updating...')}
|
ariaLabel={t('alerting.policies.update.updating', 'Updating...')}
|
||||||
|
|||||||
@@ -33,7 +33,11 @@ import {
|
|||||||
useUpdateExistingNotificationPolicy,
|
useUpdateExistingNotificationPolicy,
|
||||||
} from './useNotificationPolicyRoute';
|
} from './useNotificationPolicyRoute';
|
||||||
|
|
||||||
export const NotificationPoliciesList = () => {
|
interface NotificationPoliciesTreeProps {
|
||||||
|
routeName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const NotificationPoliciesTree = ({ routeName }: NotificationPoliciesTreeProps) => {
|
||||||
const appNotification = useAppNotification();
|
const appNotification = useAppNotification();
|
||||||
const [contactPointsSupported, canSeeContactPoints] = useAlertmanagerAbility(AlertmanagerAction.ViewContactPoint);
|
const [contactPointsSupported, canSeeContactPoints] = useAlertmanagerAbility(AlertmanagerAction.ViewContactPoint);
|
||||||
|
|
||||||
@@ -53,16 +57,11 @@ export const NotificationPoliciesList = () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
currentData,
|
currentData: defaultPolicy,
|
||||||
isLoading,
|
isLoading,
|
||||||
error: fetchPoliciesError,
|
error: fetchPoliciesError,
|
||||||
refetch: refetchNotificationPolicyRoute,
|
refetch: refetchNotificationPolicyRoute,
|
||||||
} = useNotificationPolicyRoute({ alertmanager: selectedAlertmanager ?? '' });
|
} = useNotificationPolicyRoute({ alertmanager: selectedAlertmanager ?? '' }, routeName);
|
||||||
|
|
||||||
// We make the assumption that the first policy is the default one
|
|
||||||
// At the time of writing, this will be always the case for the AM config response, and the K8S API
|
|
||||||
// TODO in the future: Generalise the component to support any number of "root" policies
|
|
||||||
const [defaultPolicy] = currentData ?? [];
|
|
||||||
|
|
||||||
// deleting policies
|
// deleting policies
|
||||||
const [deleteNotificationPolicy, deleteNotificationPolicyState] = useDeleteNotificationPolicy({
|
const [deleteNotificationPolicy, deleteNotificationPolicyState] = useDeleteNotificationPolicy({
|
||||||
@@ -140,7 +139,7 @@ export const NotificationPoliciesList = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleDelete(route: RouteWithID) {
|
async function handleDelete(route: RouteWithID) {
|
||||||
await deleteNotificationPolicy.execute(route.id);
|
await deleteNotificationPolicy.execute(route);
|
||||||
handleActionResult({ error: deleteNotificationPolicyState.error });
|
handleActionResult({ error: deleteNotificationPolicyState.error });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,7 +150,7 @@ export const NotificationPoliciesList = () => {
|
|||||||
) {
|
) {
|
||||||
await addNotificationPolicy.execute({
|
await addNotificationPolicy.execute({
|
||||||
partialRoute,
|
partialRoute,
|
||||||
referenceRouteIdentifier: referenceRoute.id,
|
referenceRoute: referenceRoute,
|
||||||
insertPosition,
|
insertPosition,
|
||||||
});
|
});
|
||||||
handleActionResult({ error: addNotificationPolicyState.error });
|
handleActionResult({ error: addNotificationPolicyState.error });
|
||||||
@@ -49,8 +49,9 @@ import { Spacer } from '../Spacer';
|
|||||||
import { GrafanaPoliciesExporter } from '../export/GrafanaPoliciesExporter';
|
import { GrafanaPoliciesExporter } from '../export/GrafanaPoliciesExporter';
|
||||||
|
|
||||||
import { Matchers } from './Matchers';
|
import { Matchers } from './Matchers';
|
||||||
import { RoutesMatchingFilters } from './NotificationPoliciesList';
|
import { RoutesMatchingFilters } from './NotificationPoliciesTree';
|
||||||
import { TimingOptions } from './timingOptions';
|
import { TimingOptions } from './timingOptions';
|
||||||
|
import { ROOT_ROUTE_NAME } from '../../utils/k8s/constants';
|
||||||
|
|
||||||
const POLICIES_PER_PAGE = 20;
|
const POLICIES_PER_PAGE = 20;
|
||||||
|
|
||||||
@@ -81,6 +82,7 @@ interface PolicyComponentProps {
|
|||||||
) => void;
|
) => void;
|
||||||
isAutoGenerated?: boolean;
|
isAutoGenerated?: boolean;
|
||||||
isDefaultPolicy?: boolean;
|
isDefaultPolicy?: boolean;
|
||||||
|
hideChildren? : boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Policy = (props: PolicyComponentProps) => {
|
const Policy = (props: PolicyComponentProps) => {
|
||||||
@@ -103,6 +105,7 @@ const Policy = (props: PolicyComponentProps) => {
|
|||||||
onShowAlertInstances,
|
onShowAlertInstances,
|
||||||
isAutoGenerated = false,
|
isAutoGenerated = false,
|
||||||
isDefaultPolicy = false,
|
isDefaultPolicy = false,
|
||||||
|
hideChildren = false,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const styles = useStyles2(getStyles);
|
const styles = useStyles2(getStyles);
|
||||||
@@ -134,7 +137,7 @@ const Policy = (props: PolicyComponentProps) => {
|
|||||||
const actualContactPoint = contactPoint ?? inheritedProperties?.receiver ?? '';
|
const actualContactPoint = contactPoint ?? inheritedProperties?.receiver ?? '';
|
||||||
const contactPointErrors = contactPointsState ? getContactPointErrors(actualContactPoint, contactPointsState) : [];
|
const contactPointErrors = contactPointsState ? getContactPointErrors(actualContactPoint, contactPointsState) : [];
|
||||||
|
|
||||||
const allChildPolicies = currentRoute.routes ?? [];
|
const allChildPolicies = hideChildren ? []: currentRoute.routes ?? [];
|
||||||
|
|
||||||
// filter child policies that match
|
// filter child policies that match
|
||||||
const childPolicies = filtersApplied
|
const childPolicies = filtersApplied
|
||||||
@@ -239,7 +242,7 @@ const Policy = (props: PolicyComponentProps) => {
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{isImmutablePolicy && (
|
{isImmutablePolicy && (
|
||||||
<>{isAutogeneratedPolicyRoot ? <AutogeneratedRootIndicator /> : <DefaultPolicyIndicator />}</>
|
<>{isAutogeneratedPolicyRoot ? <AutogeneratedRootIndicator /> : <DefaultPolicyIndicator route={currentRoute} />}</>
|
||||||
)}
|
)}
|
||||||
{!isImmutablePolicy && (
|
{!isImmutablePolicy && (
|
||||||
<>
|
<>
|
||||||
@@ -395,7 +398,7 @@ const Policy = (props: PolicyComponentProps) => {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{showExportDrawer && <GrafanaPoliciesExporter onClose={toggleShowExportDrawer} />}
|
{showExportDrawer && <GrafanaPoliciesExporter routeName={currentRoute.name == ROOT_ROUTE_NAME || !currentRoute.name ? "" : currentRoute.name} onClose={toggleShowExportDrawer} />}
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -421,7 +424,7 @@ interface MetadataRowProps {
|
|||||||
) => void;
|
) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MetadataRow({
|
export function MetadataRow({
|
||||||
numberOfAlertInstances,
|
numberOfAlertInstances,
|
||||||
isDefaultPolicy,
|
isDefaultPolicy,
|
||||||
timingOptions,
|
timingOptions,
|
||||||
@@ -691,17 +694,23 @@ const AllMatchesIndicator: FC = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export function DefaultPolicyIndicator() {
|
type DefaultPolicyIndicatorProps = { route?: RouteWithID };
|
||||||
|
|
||||||
|
export const DefaultPolicyIndicator: FC<DefaultPolicyIndicatorProps> = ({route={}}) => {
|
||||||
const styles = useStyles2(getStyles);
|
const styles = useStyles2(getStyles);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Text element="h2" variant="body" weight="medium">
|
<Text element="h2" variant="body" weight="medium">
|
||||||
<Trans i18nKey="alerting.policies.default-policy.title">Default policy</Trans>
|
{ route.name == ROOT_ROUTE_NAME || !route.name ?
|
||||||
|
<Trans i18nKey="alerting.policies.default-policy.title">Default policy</Trans> :
|
||||||
|
`Default policy for '${route.name}'`
|
||||||
|
}
|
||||||
</Text>
|
</Text>
|
||||||
<span className={styles.metadata}>
|
<span className={styles.metadata}>
|
||||||
<Trans i18nKey="alerting.policies.default-policy.description">
|
{ route.name == ROOT_ROUTE_NAME || !route.name ?
|
||||||
All alert instances will be handled by the default policy if no other matching policies are found.
|
<Trans i18nKey="alerting.policies.default-policy.description">All alert instances will be handled by the default policy if no other matching policies are found.</Trans> :
|
||||||
</Trans>
|
"All alert instances associated with this Route will be handled by this default policy if no other matching policies are found."
|
||||||
|
}
|
||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,192 @@
|
|||||||
|
import { useCallback, useMemo, useState } from 'react';
|
||||||
|
|
||||||
|
import { Trans, t } from '@grafana/i18n';
|
||||||
|
import { Button, Modal, ModalProps, useStyles2 } from '@grafana/ui';
|
||||||
|
|
||||||
|
import { stringifyErrorLike } from '../../../utils/misc';
|
||||||
|
import { FormAmRoute } from '../../../types/amroutes';
|
||||||
|
import { AmRootRouteForm } from '../EditDefaultPolicyForm';
|
||||||
|
import { UpdatingModal } from '../Modals';
|
||||||
|
import { getFormStyles } from '../formStyles';
|
||||||
|
import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
|
||||||
|
import { RouteWithID } from '../../../../../../plugins/datasource/alertmanager/types';
|
||||||
|
import { defaultGroupBy } from '../../../utils/amroutes';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This hook controls the delete modal for routing trees, showing loading and error states when appropriate
|
||||||
|
*/
|
||||||
|
export const useDeleteRoutingTreeModal = (
|
||||||
|
handleDelete: ({ name, resourceVersion }: { name: string; resourceVersion?: string }) => Promise<unknown>
|
||||||
|
) => {
|
||||||
|
const [showModal, setShowModal] = useState(false);
|
||||||
|
const [routingTree, setRoutingTree] = useState<{ name: string; resourceVersion?: string }>();
|
||||||
|
const [error, setError] = useState<unknown | undefined>();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleDismiss = useCallback(() => {
|
||||||
|
if (isLoading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setRoutingTree(undefined);
|
||||||
|
setShowModal(false);
|
||||||
|
setError(undefined);
|
||||||
|
}, [isLoading]);
|
||||||
|
|
||||||
|
const handleShow = useCallback(({ name, resourceVersion }: { name: string; resourceVersion?: string }) => {
|
||||||
|
setRoutingTree({ name, resourceVersion });
|
||||||
|
setShowModal(true);
|
||||||
|
setError(undefined);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(() => {
|
||||||
|
if (routingTree) {
|
||||||
|
setIsLoading(true);
|
||||||
|
handleDelete(routingTree)
|
||||||
|
.then(() => setShowModal(false))
|
||||||
|
.catch(setError)
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [handleDelete, routingTree]);
|
||||||
|
|
||||||
|
const modalElement = useMemo(() => {
|
||||||
|
if (error) {
|
||||||
|
return <ErrorModal isOpen={showModal} onDismiss={handleDismiss} error={error} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={showModal}
|
||||||
|
onDismiss={handleDismiss}
|
||||||
|
closeOnBackdropClick={!isLoading}
|
||||||
|
closeOnEscape={!isLoading}
|
||||||
|
title={'Delete routing tree'}
|
||||||
|
>
|
||||||
|
<p>Deleting this routing tree will permanently remove it.</p>
|
||||||
|
<p>Are you sure you want to delete this routing tree?</p>
|
||||||
|
|
||||||
|
<Modal.ButtonRow>
|
||||||
|
<Button type="button" variant="destructive" onClick={handleSubmit} disabled={isLoading}>
|
||||||
|
{isLoading ? 'Deleting...' : 'Yes, delete routing tree'}
|
||||||
|
</Button>
|
||||||
|
<Button type="button" variant="secondary" onClick={handleDismiss} disabled={isLoading}>
|
||||||
|
<Trans i18nKey="alerting.common.cancel">Cancel</Trans>
|
||||||
|
</Button>
|
||||||
|
</Modal.ButtonRow>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}, [error, handleDismiss, handleSubmit, isLoading, showModal]);
|
||||||
|
|
||||||
|
return [modalElement, handleShow, handleDismiss] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptyRouteWithID = {
|
||||||
|
id: '',
|
||||||
|
name: '',
|
||||||
|
group_by: defaultGroupBy,
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This hook controls the create modal for routing trees, showing loading and error states when appropriate
|
||||||
|
*/
|
||||||
|
export const useCreateRoutingTreeModal = (handleCreate: (route: Partial<FormAmRoute>) => Promise<unknown>) => {
|
||||||
|
const styles = useStyles2(getFormStyles);
|
||||||
|
const [showModal, setShowModal] = useState(false);
|
||||||
|
const [route, setRoute] = useState<RouteWithID>(emptyRouteWithID);
|
||||||
|
const [error, setError] = useState<unknown | undefined>();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleDismiss = useCallback(() => {
|
||||||
|
if (isLoading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setShowModal(false);
|
||||||
|
setError(undefined);
|
||||||
|
setRoute(emptyRouteWithID);
|
||||||
|
}, [isLoading]);
|
||||||
|
|
||||||
|
const handleShow = useCallback(() => {
|
||||||
|
setShowModal(true);
|
||||||
|
setError(undefined);
|
||||||
|
setRoute(emptyRouteWithID);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(
|
||||||
|
(newRoute: Partial<FormAmRoute>) => {
|
||||||
|
if (newRoute) {
|
||||||
|
setIsLoading(true);
|
||||||
|
handleCreate(newRoute)
|
||||||
|
.then(() => setShowModal(false))
|
||||||
|
.catch(setError)
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[handleCreate]
|
||||||
|
);
|
||||||
|
|
||||||
|
const modalElement = useMemo(() => {
|
||||||
|
if (error) {
|
||||||
|
return <ErrorModal isOpen={showModal} onDismiss={handleDismiss} error={error} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <UpdatingModal isOpen={showModal} onDismiss={handleDismiss} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={showModal}
|
||||||
|
onDismiss={handleDismiss}
|
||||||
|
closeOnBackdropClick={true}
|
||||||
|
closeOnEscape={true}
|
||||||
|
title={'Create routing tree'}
|
||||||
|
>
|
||||||
|
<AmRootRouteForm
|
||||||
|
route={route}
|
||||||
|
showNameField={true}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME}
|
||||||
|
actionButtons={
|
||||||
|
<Modal.ButtonRow>
|
||||||
|
<Button type="button" variant="secondary" onClick={handleDismiss} fill="outline">
|
||||||
|
<Trans i18nKey="alerting.common.cancel">Cancel</Trans>
|
||||||
|
</Button>
|
||||||
|
<Button type="submit">
|
||||||
|
<Trans i18nKey="alerting.policies.save-policy">Add routing tree</Trans>
|
||||||
|
</Button>
|
||||||
|
</Modal.ButtonRow>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}, [route, error, handleSubmit, handleDismiss, isLoading, showModal, styles.input]);
|
||||||
|
|
||||||
|
return [modalElement, handleShow, handleDismiss] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface ErrorModalProps extends Pick<ModalProps, 'isOpen' | 'onDismiss'> {
|
||||||
|
error: unknown;
|
||||||
|
}
|
||||||
|
const ErrorModal = ({ isOpen, onDismiss, error }: ErrorModalProps) => {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={isOpen}
|
||||||
|
onDismiss={onDismiss}
|
||||||
|
closeOnBackdropClick={true}
|
||||||
|
closeOnEscape={true}
|
||||||
|
title={t('alerting.error-modal.title-something-went-wrong', 'Something went wrong')}
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
<Trans i18nKey="alerting.error-modal.failed-to-update-your-configuration">
|
||||||
|
Failed to update your configuration:
|
||||||
|
</Trans>
|
||||||
|
</p>
|
||||||
|
<pre>
|
||||||
|
<code>{stringifyErrorLike(error)}</code>
|
||||||
|
</pre>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { css } from '@emotion/css';
|
||||||
|
import { useCallback, useState } from 'react';
|
||||||
|
import { useDebounce } from 'react-use';
|
||||||
|
|
||||||
|
import { Trans, t } from '@grafana/i18n';
|
||||||
|
import { Button, Field, Icon, Input, Stack, useStyles2 } from '@grafana/ui';
|
||||||
|
|
||||||
|
import { useURLSearchParams } from '../../../hooks/useURLSearchParams';
|
||||||
|
|
||||||
|
const RoutingTreeFilter = () => {
|
||||||
|
const styles = useStyles2(getStyles);
|
||||||
|
|
||||||
|
const [searchParams, setSearchParams] = useURLSearchParams();
|
||||||
|
|
||||||
|
const defaultValue = searchParams.get('search') ?? '';
|
||||||
|
const [searchValue, setSearchValue] = useState(defaultValue);
|
||||||
|
|
||||||
|
const [_, cancel] = useDebounce(
|
||||||
|
() => {
|
||||||
|
setSearchParams({ search: searchValue }, true);
|
||||||
|
},
|
||||||
|
300,
|
||||||
|
[setSearchParams, searchValue]
|
||||||
|
);
|
||||||
|
|
||||||
|
const clear = useCallback(() => {
|
||||||
|
cancel();
|
||||||
|
setSearchValue('');
|
||||||
|
setSearchParams({ search: '' }, true);
|
||||||
|
}, [cancel, setSearchParams]);
|
||||||
|
|
||||||
|
const hasInput = Boolean(defaultValue);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack direction="row" alignItems="end" gap={0.5}>
|
||||||
|
<Field
|
||||||
|
className={styles.noBottom}
|
||||||
|
label={'Search by name or receiver'}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
aria-label={'search routing trees'}
|
||||||
|
placeholder={t('alerting.contact-points-filter.placeholder-search', 'Search')}
|
||||||
|
width={46}
|
||||||
|
prefix={<Icon name="search" />}
|
||||||
|
onChange={(event) => {
|
||||||
|
setSearchValue(event.currentTarget.value);
|
||||||
|
}}
|
||||||
|
value={searchValue}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
icon="times"
|
||||||
|
onClick={() => clear()}
|
||||||
|
disabled={!hasInput}
|
||||||
|
aria-label={t('alerting.contact-points-filter.aria-label-clear', 'clear')}
|
||||||
|
>
|
||||||
|
<Trans i18nKey="alerting.contact-points-filter.clear">Clear</Trans>
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStyles = () => ({
|
||||||
|
noBottom: css({
|
||||||
|
marginBottom: 0,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
export { RoutingTreeFilter };
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { useCallback, useMemo, useState } from 'react';
|
||||||
|
import { useToggle } from 'react-use';
|
||||||
|
|
||||||
|
import { GrafanaPoliciesExporter } from '../export/GrafanaPoliciesExporter';
|
||||||
|
|
||||||
|
export const ALL_ROUTING_TREES = Symbol('all routing trees');
|
||||||
|
|
||||||
|
type ExportProps = [JSX.Element | null, (routeName: string | typeof ALL_ROUTING_TREES) => void];
|
||||||
|
|
||||||
|
export const useExportRoutingTree = (): ExportProps => {
|
||||||
|
const [routeName, setRouteName] = useState<string | typeof ALL_ROUTING_TREES | null>(null);
|
||||||
|
const [isExportDrawerOpen, toggleShowExportDrawer] = useToggle(false);
|
||||||
|
|
||||||
|
const handleClose = useCallback(() => {
|
||||||
|
setRouteName(null);
|
||||||
|
toggleShowExportDrawer(false);
|
||||||
|
}, [toggleShowExportDrawer]);
|
||||||
|
|
||||||
|
const handleOpen = (routeName: string | typeof ALL_ROUTING_TREES) => {
|
||||||
|
setRouteName(routeName);
|
||||||
|
toggleShowExportDrawer(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawer = useMemo(() => {
|
||||||
|
if (!routeName || !isExportDrawerOpen) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (routeName === ALL_ROUTING_TREES) {
|
||||||
|
// use this drawer when we want to export all policies
|
||||||
|
return <GrafanaPoliciesExporter onClose={handleClose} />;
|
||||||
|
} else {
|
||||||
|
// use this one for exporting a single policy
|
||||||
|
return <GrafanaPoliciesExporter routeName={routeName} onClose={handleClose} />;
|
||||||
|
}
|
||||||
|
}, [isExportDrawerOpen, handleClose, routeName]);
|
||||||
|
|
||||||
|
return [drawer, handleOpen];
|
||||||
|
};
|
||||||
@@ -24,6 +24,7 @@ test('k8sSubRouteToRoute', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const expected: Route = {
|
const expected: Route = {
|
||||||
|
name: 'test-name',
|
||||||
continue: false,
|
continue: false,
|
||||||
group_by: ['label1'],
|
group_by: ['label1'],
|
||||||
group_interval: '5m',
|
group_interval: '5m',
|
||||||
@@ -35,6 +36,7 @@ test('k8sSubRouteToRoute', () => {
|
|||||||
repeat_interval: '4h',
|
repeat_interval: '4h',
|
||||||
routes: [
|
routes: [
|
||||||
{
|
{
|
||||||
|
name: 'test-name',
|
||||||
receiver: 'receiver2',
|
receiver: 'receiver2',
|
||||||
matchers: undefined,
|
matchers: undefined,
|
||||||
object_matchers: [['label2', MatcherOperator.notEqual, 'value2']],
|
object_matchers: [['label2', MatcherOperator.notEqual, 'value2']],
|
||||||
@@ -43,7 +45,7 @@ test('k8sSubRouteToRoute', () => {
|
|||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
expect(k8sSubRouteToRoute(input)).toStrictEqual(expected);
|
expect(k8sSubRouteToRoute(input, 'test-name')).toStrictEqual(expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('routeToK8sSubRoute', () => {
|
test('routeToK8sSubRoute', () => {
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import { pick } from 'lodash';
|
import { pick, uniq } from 'lodash';
|
||||||
import memoize from 'micro-memoize';
|
import memoize from 'micro-memoize';
|
||||||
|
|
||||||
import { INHERITABLE_KEYS, type InheritableProperties } from '@grafana/alerting/internal';
|
import { INHERITABLE_KEYS, type InheritableProperties } from '@grafana/alerting/internal';
|
||||||
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
|
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
|
||||||
import { MatcherOperator, ROUTES_META_SYMBOL, Route } from 'app/plugins/datasource/alertmanager/types';
|
import { ROUTES_META_SYMBOL, Route, RouteWithID, MatcherOperator } from 'app/plugins/datasource/alertmanager/types';
|
||||||
|
|
||||||
import { getAPINamespace } from '../../../../../api/utils';
|
import { getAPINamespace } from '../../../../../api/utils';
|
||||||
import { alertmanagerApi } from '../../api/alertmanagerApi';
|
import { alertmanagerApi } from '../../api/alertmanagerApi';
|
||||||
import { useAsync } from '../../hooks/useAsync';
|
import { useAsync } from '../../hooks/useAsync';
|
||||||
import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig';
|
import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig';
|
||||||
import {
|
import {
|
||||||
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
|
|
||||||
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults,
|
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults,
|
||||||
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
|
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
|
||||||
|
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
|
||||||
generatedRoutesApi as routingTreeApi,
|
generatedRoutesApi as routingTreeApi,
|
||||||
} from '../../openapi/routesApi.gen';
|
} from '../../openapi/routesApi.gen';
|
||||||
import {
|
import {
|
||||||
@@ -32,30 +32,47 @@ import {
|
|||||||
mergePartialAmRouteWithRouteTree,
|
mergePartialAmRouteWithRouteTree,
|
||||||
omitRouteFromRouteTree,
|
omitRouteFromRouteTree,
|
||||||
} from '../../utils/routeTree';
|
} from '../../utils/routeTree';
|
||||||
|
import uFuzzy from '@leeoniya/ufuzzy';
|
||||||
const k8sRoutesToRoutesMemoized = memoize(k8sRoutesToRoutes, { maxSize: 1 });
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
useCreateNamespacedRoutingTreeMutation,
|
||||||
|
useDeleteNamespacedRoutingTreeMutation,
|
||||||
useListNamespacedRoutingTreeQuery,
|
useListNamespacedRoutingTreeQuery,
|
||||||
useReplaceNamespacedRoutingTreeMutation,
|
useReplaceNamespacedRoutingTreeMutation,
|
||||||
useLazyListNamespacedRoutingTreeQuery,
|
useLazyReadNamespacedRoutingTreeQuery,
|
||||||
|
useReadNamespacedRoutingTreeQuery,
|
||||||
} = routingTreeApi;
|
} = routingTreeApi;
|
||||||
|
|
||||||
const { useGetAlertmanagerConfigurationQuery } = alertmanagerApi;
|
const { useGetAlertmanagerConfigurationQuery } = alertmanagerApi;
|
||||||
|
|
||||||
export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArgs, { skip }: Skippable = {}) => {
|
export const useNotificationPolicyRoute = (
|
||||||
|
{ alertmanager }: BaseAlertmanagerArgs,
|
||||||
|
routeName: string = ROOT_ROUTE_NAME,
|
||||||
|
{ skip }: Skippable = {}
|
||||||
|
) => {
|
||||||
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
||||||
|
|
||||||
const k8sRouteQuery = useListNamespacedRoutingTreeQuery(
|
const k8sRouteQuery = useReadNamespacedRoutingTreeQuery(
|
||||||
{ namespace: getAPINamespace() },
|
{ namespace: getAPINamespace(), name: routeName },
|
||||||
{
|
{
|
||||||
skip: skip || !k8sApiSupported,
|
skip: skip || !k8sApiSupported,
|
||||||
selectFromResult: (result) => {
|
selectFromResult: (result) => {
|
||||||
return {
|
const { data, currentData, ...rest } = result;
|
||||||
...result,
|
|
||||||
currentData: result.currentData ? k8sRoutesToRoutesMemoized(result.currentData.items) : undefined,
|
const transformed = useMemo(() => {
|
||||||
data: result.data ? k8sRoutesToRoutesMemoized(result.data.items) : undefined,
|
return data ? k8sRouteToRoute(data) : data;
|
||||||
};
|
}, [data]);
|
||||||
|
|
||||||
|
const transformedCurrent = useMemo(() => {
|
||||||
|
return currentData ? k8sRouteToRoute(currentData) : currentData;
|
||||||
|
}, [currentData]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
data: transformed,
|
||||||
|
currentData: transformedCurrent,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -66,10 +83,10 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
|
|||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
currentData: result.currentData?.alertmanager_config?.route
|
currentData: result.currentData?.alertmanager_config?.route
|
||||||
? [parseAmConfigRoute(result.currentData.alertmanager_config.route)]
|
? parseAmConfigRoute(result.currentData.alertmanager_config.route)
|
||||||
: undefined,
|
: undefined,
|
||||||
data: result.data?.alertmanager_config?.route
|
data: result.data?.alertmanager_config?.route
|
||||||
? [parseAmConfigRoute(result.data.alertmanager_config.route)]
|
? parseAmConfigRoute(result.data.alertmanager_config.route)
|
||||||
: undefined,
|
: undefined,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
@@ -78,6 +95,32 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
|
|||||||
return k8sApiSupported ? k8sRouteQuery : amConfigQuery;
|
return k8sApiSupported ? k8sRouteQuery : amConfigQuery;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const useListNotificationPolicyRoutes = ({ skip }: Skippable = {}) => {
|
||||||
|
return useListNamespacedRoutingTreeQuery(
|
||||||
|
{ namespace: getAPINamespace() },
|
||||||
|
{
|
||||||
|
skip: skip,
|
||||||
|
selectFromResult: (result) => {
|
||||||
|
const { data, currentData, ...rest } = result;
|
||||||
|
|
||||||
|
const transformed = useMemo(() => {
|
||||||
|
return data ? data.items.map(k8sRouteToRoute) : data;
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
const transformedCurrent = useMemo(() => {
|
||||||
|
return currentData ? currentData.items.map(k8sRouteToRoute) : currentData;
|
||||||
|
}, [currentData]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
data: transformed,
|
||||||
|
currentData: transformedCurrent,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const parseAmConfigRoute = memoize((route: Route): Route => {
|
const parseAmConfigRoute = memoize((route: Route): Route => {
|
||||||
return {
|
return {
|
||||||
...route,
|
...route,
|
||||||
@@ -91,25 +134,26 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
|
|||||||
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
||||||
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
|
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
|
||||||
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
|
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
|
||||||
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
|
const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
|
||||||
|
|
||||||
const updateUsingK8sApi = useAsync(async (update: Partial<FormAmRoute>) => {
|
const updateUsingK8sApi = useAsync(async (update: Partial<FormAmRoute>) => {
|
||||||
const namespace = getAPINamespace();
|
const namespace = getAPINamespace();
|
||||||
const result = await listNamespacedRoutingTree({ namespace });
|
const name = update.name ?? ROOT_ROUTE_NAME;
|
||||||
|
const result = await readNamespacedRoutingTree({ namespace, name: name });
|
||||||
|
|
||||||
const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
|
const rootTree = result.data;
|
||||||
if (!rootTree) {
|
if (!rootTree) {
|
||||||
throw new Error(`no root route found for namespace ${namespace}`);
|
throw new Error(`no root route found for namespace ${namespace} and name ${name}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
|
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
|
||||||
const newRouteTree = mergePartialAmRouteWithRouteTree(alertmanager, update, rootRouteWithIdentifiers);
|
const newRouteTree = mergePartialAmRouteWithRouteTree(alertmanager, update, rootRouteWithIdentifiers);
|
||||||
|
|
||||||
// Create the K8s route object
|
// Create the K8s route object
|
||||||
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
|
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
|
||||||
|
|
||||||
return updatedNamespacedRoute({
|
return updatedNamespacedRoute({
|
||||||
name: ROOT_ROUTE_NAME,
|
name: name,
|
||||||
namespace,
|
namespace,
|
||||||
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
|
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
@@ -126,33 +170,34 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
|
|||||||
export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
|
export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
|
||||||
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
||||||
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
|
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
|
||||||
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
|
const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
|
||||||
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
|
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
|
||||||
|
|
||||||
const deleteFromK8sApi = useAsync(async (id: string) => {
|
const deleteFromK8sApi = useAsync(async (route: RouteWithID) => {
|
||||||
const namespace = getAPINamespace();
|
const namespace = getAPINamespace();
|
||||||
const result = await listNamespacedRoutingTree({ namespace });
|
const name = route.name ?? ROOT_ROUTE_NAME;
|
||||||
|
const result = await readNamespacedRoutingTree({ namespace, name: name });
|
||||||
|
|
||||||
const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
|
const rootTree = result.data;
|
||||||
if (!rootTree) {
|
if (!rootTree) {
|
||||||
throw new Error(`no root route found for namespace ${namespace}`);
|
throw new Error(`no root route found for namespace ${namespace}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
|
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
|
||||||
const newRouteTree = omitRouteFromRouteTree(id, rootRouteWithIdentifiers);
|
const newRouteTree = omitRouteFromRouteTree(route.id, rootRouteWithIdentifiers);
|
||||||
|
|
||||||
// Create the K8s route object
|
// Create the K8s route object
|
||||||
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
|
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
|
||||||
|
|
||||||
return updatedNamespacedRoute({
|
return updatedNamespacedRoute({
|
||||||
name: ROOT_ROUTE_NAME,
|
name: name,
|
||||||
namespace,
|
namespace,
|
||||||
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: routeObject,
|
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: routeObject,
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
});
|
});
|
||||||
|
|
||||||
const deleteFromAlertmanagerConfiguration = useAsync(async (id: string) => {
|
const deleteFromAlertmanagerConfiguration = useAsync(async (route: RouteWithID) => {
|
||||||
const action = deleteRouteAction({ id });
|
const action = deleteRouteAction({ id: route.id });
|
||||||
return produceNewAlertmanagerConfiguration(action);
|
return produceNewAlertmanagerConfiguration(action);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -162,32 +207,33 @@ export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerAr
|
|||||||
export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
|
export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
|
||||||
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
const k8sApiSupported = shouldUseK8sApi(alertmanager);
|
||||||
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
|
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
|
||||||
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
|
const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
|
||||||
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
|
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
|
||||||
|
|
||||||
const addToK8sApi = useAsync(
|
const addToK8sApi = useAsync(
|
||||||
async ({
|
async ({
|
||||||
partialRoute,
|
partialRoute,
|
||||||
referenceRouteIdentifier,
|
referenceRoute,
|
||||||
insertPosition,
|
insertPosition,
|
||||||
}: {
|
}: {
|
||||||
partialRoute: Partial<FormAmRoute>;
|
partialRoute: Partial<FormAmRoute>;
|
||||||
referenceRouteIdentifier: string;
|
referenceRoute: RouteWithID;
|
||||||
insertPosition: InsertPosition;
|
insertPosition: InsertPosition;
|
||||||
}) => {
|
}) => {
|
||||||
const namespace = getAPINamespace();
|
const namespace = getAPINamespace();
|
||||||
const result = await listNamespacedRoutingTree({ namespace });
|
const name = referenceRoute.name ?? ROOT_ROUTE_NAME;
|
||||||
|
const result = await readNamespacedRoutingTree({ namespace, name: name });
|
||||||
|
|
||||||
const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
|
const rootTree = result.data;
|
||||||
if (!rootTree) {
|
if (!rootTree) {
|
||||||
throw new Error(`no root route found for namespace ${namespace}`);
|
throw new Error(`no root route found for namespace ${namespace}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
|
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
|
||||||
const newRouteTree = addRouteToReferenceRoute(
|
const newRouteTree = addRouteToReferenceRoute(
|
||||||
alertmanager ?? '',
|
alertmanager ?? '',
|
||||||
partialRoute,
|
partialRoute,
|
||||||
referenceRouteIdentifier,
|
referenceRoute.id,
|
||||||
rootRouteWithIdentifiers,
|
rootRouteWithIdentifiers,
|
||||||
insertPosition
|
insertPosition
|
||||||
);
|
);
|
||||||
@@ -196,7 +242,7 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
|
|||||||
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
|
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
|
||||||
|
|
||||||
return updatedNamespacedRoute({
|
return updatedNamespacedRoute({
|
||||||
name: ROOT_ROUTE_NAME,
|
name: name,
|
||||||
namespace,
|
namespace,
|
||||||
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
|
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
@@ -206,16 +252,16 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
|
|||||||
const addToAlertmanagerConfiguration = useAsync(
|
const addToAlertmanagerConfiguration = useAsync(
|
||||||
async ({
|
async ({
|
||||||
partialRoute,
|
partialRoute,
|
||||||
referenceRouteIdentifier,
|
referenceRoute,
|
||||||
insertPosition,
|
insertPosition,
|
||||||
}: {
|
}: {
|
||||||
partialRoute: Partial<FormAmRoute>;
|
partialRoute: Partial<FormAmRoute>;
|
||||||
referenceRouteIdentifier: string;
|
referenceRoute: RouteWithID;
|
||||||
insertPosition: InsertPosition;
|
insertPosition: InsertPosition;
|
||||||
}) => {
|
}) => {
|
||||||
const action = addRouteAction({
|
const action = addRouteAction({
|
||||||
partialRoute,
|
partialRoute,
|
||||||
referenceRouteIdentifier,
|
referenceRouteIdentifier: referenceRoute.id,
|
||||||
insertPosition,
|
insertPosition,
|
||||||
alertmanager,
|
alertmanager,
|
||||||
});
|
});
|
||||||
@@ -226,29 +272,161 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
|
|||||||
return k8sApiSupported ? addToK8sApi : addToAlertmanagerConfiguration;
|
return k8sApiSupported ? addToK8sApi : addToAlertmanagerConfiguration;
|
||||||
}
|
}
|
||||||
|
|
||||||
function k8sRoutesToRoutes(routes: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree[]): Route[] {
|
type DeleteRoutingTreeArgs = { name: string; resourceVersion?: string };
|
||||||
return routes?.map((route) => {
|
export function useDeleteRoutingTree() {
|
||||||
return {
|
const [deleteNamespacedRoutingTree] = useDeleteNamespacedRoutingTreeMutation();
|
||||||
...route.spec.defaults,
|
|
||||||
routes: route.spec.routes?.map(k8sSubRouteToRoute),
|
return useAsync(async ({ name, resourceVersion }: DeleteRoutingTreeArgs) => {
|
||||||
[ROUTES_META_SYMBOL]: {
|
const namespace = getAPINamespace();
|
||||||
provisioned: isK8sEntityProvisioned(route),
|
|
||||||
resourceVersion: route.metadata.resourceVersion,
|
return deleteNamespacedRoutingTree({
|
||||||
name: route.metadata.name,
|
name: name,
|
||||||
},
|
namespace,
|
||||||
};
|
ioK8SApimachineryPkgApisMetaV1DeleteOptions: { preconditions: { resourceVersion } },
|
||||||
|
}).unwrap();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useCreateRoutingTree() {
|
||||||
|
const [createNamespacedRoutingTree] = useCreateNamespacedRoutingTreeMutation();
|
||||||
|
|
||||||
|
return useAsync(async (partialFormRoute: Partial<FormAmRoute>) => {
|
||||||
|
const namespace = getAPINamespace();
|
||||||
|
|
||||||
|
const {
|
||||||
|
name,
|
||||||
|
overrideGrouping,
|
||||||
|
groupBy,
|
||||||
|
overrideTimings,
|
||||||
|
groupWaitValue,
|
||||||
|
groupIntervalValue,
|
||||||
|
repeatIntervalValue,
|
||||||
|
receiver,
|
||||||
|
} = partialFormRoute;
|
||||||
|
|
||||||
|
// This does not "inherit" from any existing route, as this is a new routing tree. If not set, it will use the system
|
||||||
|
// defaults. Currently supported by group_by, group_wait, group_interval, and repeat_interval
|
||||||
|
const USE_DEFAULTS = undefined;
|
||||||
|
|
||||||
|
const newRoute: Route = {
|
||||||
|
name: name,
|
||||||
|
group_by: overrideGrouping ? groupBy : USE_DEFAULTS,
|
||||||
|
group_wait: overrideTimings && groupWaitValue ? groupWaitValue : USE_DEFAULTS,
|
||||||
|
group_interval: overrideTimings && groupIntervalValue ? groupIntervalValue : USE_DEFAULTS,
|
||||||
|
repeat_interval: overrideTimings && repeatIntervalValue ? repeatIntervalValue : USE_DEFAULTS,
|
||||||
|
receiver: receiver,
|
||||||
|
};
|
||||||
|
|
||||||
|
// defaults(newRoute, TIMING_OPTIONS_DEFAULTS)
|
||||||
|
|
||||||
|
// Create the K8s route object
|
||||||
|
const routeObject = createKubernetesRoutingTreeSpec(newRoute);
|
||||||
|
|
||||||
|
return createNamespacedRoutingTree({
|
||||||
|
namespace,
|
||||||
|
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
|
||||||
|
}).unwrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const fuzzyFinder = new uFuzzy({
|
||||||
|
intraMode: 1,
|
||||||
|
intraIns: 1,
|
||||||
|
intraSub: 1,
|
||||||
|
intraDel: 1,
|
||||||
|
intraTrn: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const useRootRouteSearch = (policies: Route[], search?: string | null): Route[] => {
|
||||||
|
const nameHaystack = useMemo(() => {
|
||||||
|
return policies.map((policy) => policy.name ?? '');
|
||||||
|
}, [policies]);
|
||||||
|
|
||||||
|
const receiverHaystack = useMemo(() => {
|
||||||
|
return policies.map((policy) => policy.receiver ?? '');
|
||||||
|
}, [policies]);
|
||||||
|
|
||||||
|
if (!search) {
|
||||||
|
return policies;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nameHits = fuzzyFinder.filter(nameHaystack, search) ?? [];
|
||||||
|
const typeHits = fuzzyFinder.filter(receiverHaystack, search) ?? [];
|
||||||
|
|
||||||
|
const hits = [...nameHits, ...typeHits];
|
||||||
|
|
||||||
|
return uniq(hits).map((id) => policies[id]) ?? [];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Route to K8s compatible format. Make sure we aren't sending any additional properties the API doesn't recognize
|
||||||
|
* because it will reply with excess properties in the HTTP headers
|
||||||
|
*/
|
||||||
|
export function createKubernetesRoutingTreeSpec(
|
||||||
|
rootRoute: Route
|
||||||
|
): ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree {
|
||||||
|
const inheritableDefaultProperties: InheritableProperties = pick(routeAdapter.toPackage(rootRoute), INHERITABLE_KEYS);
|
||||||
|
|
||||||
|
const name = rootRoute.name ?? ROOT_ROUTE_NAME;
|
||||||
|
|
||||||
|
const defaults: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults = {
|
||||||
|
...inheritableDefaultProperties,
|
||||||
|
// TODO: Fix types in k8s API? Fix our types to not allow empty receiver? TBC
|
||||||
|
receiver: rootRoute.receiver ?? '',
|
||||||
|
};
|
||||||
|
|
||||||
|
const routes = rootRoute.routes?.map(routeToK8sSubRoute) ?? [];
|
||||||
|
|
||||||
|
const spec = {
|
||||||
|
defaults,
|
||||||
|
routes,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
spec: spec,
|
||||||
|
metadata: {
|
||||||
|
name: name,
|
||||||
|
resourceVersion: rootRoute[ROUTES_META_SYMBOL]?.resourceVersion,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const NAMED_ROOT_LABEL_NAME = '__grafana_managed_route__';
|
||||||
|
|
||||||
|
function k8sRouteToRoute(route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree): Route {
|
||||||
|
return {
|
||||||
|
...route.spec.defaults,
|
||||||
|
name: route.metadata.name,
|
||||||
|
routes: route.spec.routes?.map((subroute) => k8sSubRouteToRoute(subroute, route.metadata.name)),
|
||||||
|
// This assumes if a `NAMED_ROOT_LABEL_NAME` label exists, it will NOT go to the default route, which is a fair but
|
||||||
|
// not perfect assumption since we don't yet protect the label.
|
||||||
|
object_matchers:
|
||||||
|
route.metadata.name == ROOT_ROUTE_NAME || !route.metadata.name
|
||||||
|
? [[NAMED_ROOT_LABEL_NAME, MatcherOperator.equal, '']]
|
||||||
|
: [[NAMED_ROOT_LABEL_NAME, MatcherOperator.equal, route.metadata.name]],
|
||||||
|
[ROUTES_META_SYMBOL]: {
|
||||||
|
provisioned: isK8sEntityProvisioned(route),
|
||||||
|
resourceVersion: route.metadata.resourceVersion,
|
||||||
|
name: route.metadata.name,
|
||||||
|
metadata: route.metadata,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/** Helper to provide type safety for matcher operators from API */
|
/** Helper to provide type safety for matcher operators from API */
|
||||||
function isValidMatcherOperator(type: string): type is MatcherOperator {
|
function isValidMatcherOperator(type: string): type is MatcherOperator {
|
||||||
return Object.values<string>(MatcherOperator).includes(type);
|
return Object.values<string>(MatcherOperator).includes(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function k8sSubRouteToRoute(route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route): Route {
|
export function k8sSubRouteToRoute(
|
||||||
|
route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
|
||||||
|
rootName?: string
|
||||||
|
): Route {
|
||||||
return {
|
return {
|
||||||
...route,
|
...route,
|
||||||
routes: route.routes?.map(k8sSubRouteToRoute),
|
name: rootName,
|
||||||
|
routes: route.routes?.map((subroute) => k8sSubRouteToRoute(subroute, rootName)),
|
||||||
matchers: undefined,
|
matchers: undefined,
|
||||||
object_matchers: route.matchers?.map(({ label, type, value }) => {
|
object_matchers: route.matchers?.map(({ label, type, value }) => {
|
||||||
if (!isValidMatcherOperator(type)) {
|
if (!isValidMatcherOperator(type)) {
|
||||||
@@ -272,34 +450,3 @@ export function routeToK8sSubRoute(route: Route): ComGithubGrafanaGrafanaPkgApis
|
|||||||
routes: route.routes?.map(routeToK8sSubRoute),
|
routes: route.routes?.map(routeToK8sSubRoute),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert Route to K8s compatible format. Make sure we aren't sending any additional properties the API doesn't recognize
|
|
||||||
* because it will reply with excess properties in the HTTP headers
|
|
||||||
*/
|
|
||||||
export function createKubernetesRoutingTreeSpec(
|
|
||||||
rootRoute: Route
|
|
||||||
): ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree {
|
|
||||||
const inheritableDefaultProperties: InheritableProperties = pick(routeAdapter.toPackage(rootRoute), INHERITABLE_KEYS);
|
|
||||||
|
|
||||||
const defaults: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults = {
|
|
||||||
...inheritableDefaultProperties,
|
|
||||||
// TODO: Fix types in k8s API? Fix our types to not allow empty receiver? TBC
|
|
||||||
receiver: rootRoute.receiver ?? '',
|
|
||||||
};
|
|
||||||
|
|
||||||
const routes = rootRoute.routes?.map(routeToK8sSubRoute) ?? [];
|
|
||||||
|
|
||||||
const spec = {
|
|
||||||
defaults,
|
|
||||||
routes,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
spec: spec,
|
|
||||||
metadata: {
|
|
||||||
name: ROOT_ROUTE_NAME,
|
|
||||||
resourceVersion: rootRoute[ROUTES_META_SYMBOL]?.resourceVersion,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ export function NotificationPolicyDrawer({
|
|||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
<TextLink href={createRelativeUrl('/alerting/routes')} external inline={false}>
|
<TextLink href={createRelativeUrl(`/alerting/notifications/routes/${encodeURIComponent(policyName ?? '')}/edit`)} external inline={false}>
|
||||||
<Trans i18nKey="alerting.notification-policy-drawer.view-notification-policy-tree">
|
<Trans i18nKey="alerting.notification-policy-drawer.view-notification-policy-tree">
|
||||||
View notification policy tree
|
View notification policy tree
|
||||||
</Trans>
|
</Trans>
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { useAsync } from 'react-use';
|
import { useAsync } from 'react-use';
|
||||||
|
|
||||||
import { useNotificationPolicyRoute } from 'app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute';
|
import {
|
||||||
|
NAMED_ROOT_LABEL_NAME,
|
||||||
|
useNotificationPolicyRoute,
|
||||||
|
} from 'app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute';
|
||||||
|
|
||||||
import { Labels } from '../../../../../../types/unified-alerting-dto';
|
import { Labels } from '../../../../../../types/unified-alerting-dto';
|
||||||
import { useRouteGroupsMatcher } from '../../../useRouteGroupsMatcher';
|
import { useRouteGroupsMatcher } from '../../../useRouteGroupsMatcher';
|
||||||
@@ -10,16 +13,21 @@ import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
|
|||||||
import { normalizeRoute } from '../../../utils/notification-policies';
|
import { normalizeRoute } from '../../../utils/notification-policies';
|
||||||
|
|
||||||
export const useAlertmanagerNotificationRoutingPreview = (alertmanager: string, instances: Labels[]) => {
|
export const useAlertmanagerNotificationRoutingPreview = (alertmanager: string, instances: Labels[]) => {
|
||||||
|
// if a NAMED_ROOT_LABEL_NAME label exists, then we only match to that route.
|
||||||
|
const routeName = useMemo(() => {
|
||||||
|
const routeNameLabel = instances.find((instance) => instance[NAMED_ROOT_LABEL_NAME]);
|
||||||
|
return routeNameLabel?.[NAMED_ROOT_LABEL_NAME];
|
||||||
|
}, [instances]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: currentData,
|
data: defaultPolicy,
|
||||||
isLoading: isPoliciesLoading,
|
isLoading: isPoliciesLoading,
|
||||||
error: policiesError,
|
error: policiesError,
|
||||||
} = useNotificationPolicyRoute({ alertmanager });
|
} = useNotificationPolicyRoute({ alertmanager }, routeName);
|
||||||
|
|
||||||
// this function will use a web worker to compute matching routes
|
// this function will use a web worker to compute matching routes
|
||||||
const { matchInstancesToRoutes } = useRouteGroupsMatcher();
|
const { matchInstancesToRoutes } = useRouteGroupsMatcher();
|
||||||
|
|
||||||
const [defaultPolicy] = currentData ?? [];
|
|
||||||
const rootRoute = useMemo(() => {
|
const rootRoute = useMemo(() => {
|
||||||
if (!defaultPolicy) {
|
if (!defaultPolicy) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -25,6 +25,32 @@ const injectedRtkApi = api
|
|||||||
}),
|
}),
|
||||||
providesTags: ['RoutingTree'],
|
providesTags: ['RoutingTree'],
|
||||||
}),
|
}),
|
||||||
|
createNamespacedRoutingTree: build.mutation<
|
||||||
|
CreateNamespacedRoutingTreeApiResponse,
|
||||||
|
CreateNamespacedRoutingTreeApiArg
|
||||||
|
>({
|
||||||
|
query: (queryArg) => ({
|
||||||
|
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees`,
|
||||||
|
method: 'POST',
|
||||||
|
body: queryArg.comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
|
||||||
|
params: {
|
||||||
|
pretty: queryArg.pretty,
|
||||||
|
dryRun: queryArg.dryRun,
|
||||||
|
fieldManager: queryArg.fieldManager,
|
||||||
|
fieldValidation: queryArg.fieldValidation,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
invalidatesTags: ['RoutingTree'],
|
||||||
|
}),
|
||||||
|
readNamespacedRoutingTree: build.query<ReadNamespacedRoutingTreeApiResponse, ReadNamespacedRoutingTreeApiArg>({
|
||||||
|
query: (queryArg) => ({
|
||||||
|
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees/${queryArg.name}`,
|
||||||
|
params: {
|
||||||
|
pretty: queryArg.pretty,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
providesTags: ['RoutingTree'],
|
||||||
|
}),
|
||||||
replaceNamespacedRoutingTree: build.mutation<
|
replaceNamespacedRoutingTree: build.mutation<
|
||||||
ReplaceNamespacedRoutingTreeApiResponse,
|
ReplaceNamespacedRoutingTreeApiResponse,
|
||||||
ReplaceNamespacedRoutingTreeApiArg
|
ReplaceNamespacedRoutingTreeApiArg
|
||||||
@@ -42,6 +68,24 @@ const injectedRtkApi = api
|
|||||||
}),
|
}),
|
||||||
invalidatesTags: ['RoutingTree'],
|
invalidatesTags: ['RoutingTree'],
|
||||||
}),
|
}),
|
||||||
|
deleteNamespacedRoutingTree: build.mutation<
|
||||||
|
DeleteNamespacedRoutingTreeApiResponse,
|
||||||
|
DeleteNamespacedRoutingTreeApiArg
|
||||||
|
>({
|
||||||
|
query: (queryArg) => ({
|
||||||
|
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees/${queryArg.name}`,
|
||||||
|
method: 'DELETE',
|
||||||
|
params: {
|
||||||
|
pretty: queryArg.pretty,
|
||||||
|
dryRun: queryArg.dryRun,
|
||||||
|
gracePeriodSeconds: queryArg.gracePeriodSeconds,
|
||||||
|
ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential,
|
||||||
|
orphanDependents: queryArg.orphanDependents,
|
||||||
|
propagationPolicy: queryArg.propagationPolicy,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
invalidatesTags: ['RoutingTree'],
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
overrideExisting: false,
|
overrideExisting: false,
|
||||||
});
|
});
|
||||||
@@ -94,6 +138,33 @@ export type ListNamespacedRoutingTreeApiArg = {
|
|||||||
/** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */
|
/** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */
|
||||||
watch?: boolean;
|
watch?: boolean;
|
||||||
};
|
};
|
||||||
|
export type CreateNamespacedRoutingTreeApiResponse = /** status 200 OK */
|
||||||
|
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
|
||||||
|
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
|
||||||
|
| /** status 202 Accepted */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
||||||
|
export type CreateNamespacedRoutingTreeApiArg = {
|
||||||
|
/** object name and auth scope, such as for teams and projects */
|
||||||
|
namespace: string;
|
||||||
|
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
|
||||||
|
pretty?: string;
|
||||||
|
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
|
||||||
|
dryRun?: string;
|
||||||
|
/** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */
|
||||||
|
fieldManager?: string;
|
||||||
|
/** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */
|
||||||
|
fieldValidation?: string;
|
||||||
|
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
||||||
|
};
|
||||||
|
export type ReadNamespacedRoutingTreeApiResponse =
|
||||||
|
/** status 200 OK */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
||||||
|
export type ReadNamespacedRoutingTreeApiArg = {
|
||||||
|
/** name of the RoutingTree */
|
||||||
|
name: string;
|
||||||
|
/** object name and auth scope, such as for teams and projects */
|
||||||
|
namespace: string;
|
||||||
|
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
|
||||||
|
pretty?: string;
|
||||||
|
};
|
||||||
export type ReplaceNamespacedRoutingTreeApiResponse = /** status 200 OK */
|
export type ReplaceNamespacedRoutingTreeApiResponse = /** status 200 OK */
|
||||||
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
|
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
|
||||||
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
||||||
@@ -112,6 +183,28 @@ export type ReplaceNamespacedRoutingTreeApiArg = {
|
|||||||
fieldValidation?: string;
|
fieldValidation?: string;
|
||||||
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
|
||||||
};
|
};
|
||||||
|
export type DeleteNamespacedRoutingTreeApiResponse = /** status 200 OK */
|
||||||
|
| IoK8SApimachineryPkgApisMetaV1Status
|
||||||
|
| /** status 202 Accepted */ IoK8SApimachineryPkgApisMetaV1Status;
|
||||||
|
export type DeleteNamespacedRoutingTreeApiArg = {
|
||||||
|
/** name of the RoutingTree */
|
||||||
|
name: string;
|
||||||
|
/** object name and auth scope, such as for teams and projects */
|
||||||
|
namespace: string;
|
||||||
|
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
|
||||||
|
pretty?: string;
|
||||||
|
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
|
||||||
|
dryRun?: string;
|
||||||
|
/** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */
|
||||||
|
gracePeriodSeconds?: number;
|
||||||
|
/** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */
|
||||||
|
ignoreStoreReadErrorWithClusterBreakingPotential?: boolean;
|
||||||
|
/** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */
|
||||||
|
orphanDependents?: boolean;
|
||||||
|
/** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */
|
||||||
|
propagationPolicy?: string;
|
||||||
|
ioK8SApimachineryPkgApisMetaV1DeleteOptions: IoK8SApimachineryPkgApisMetaV1DeleteOptions;
|
||||||
|
};
|
||||||
export type IoK8SApimachineryPkgApisMetaV1Time = string;
|
export type IoK8SApimachineryPkgApisMetaV1Time = string;
|
||||||
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
||||||
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
|
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
|
||||||
@@ -207,6 +300,7 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Matcher =
|
|||||||
value: string;
|
value: string;
|
||||||
};
|
};
|
||||||
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route = {
|
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route = {
|
||||||
|
active_time_intervals?: string[];
|
||||||
continue?: boolean;
|
continue?: boolean;
|
||||||
group_by?: string[];
|
group_by?: string[];
|
||||||
group_interval?: string;
|
group_interval?: string;
|
||||||
@@ -227,6 +321,7 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTr
|
|||||||
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
kind?: string;
|
kind?: string;
|
||||||
metadata: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
|
metadata: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
|
||||||
|
/** Spec is the spec of the RoutingTree */
|
||||||
spec: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTreeSpec;
|
spec: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTreeSpec;
|
||||||
};
|
};
|
||||||
export type IoK8SApimachineryPkgApisMetaV1ListMeta = {
|
export type IoK8SApimachineryPkgApisMetaV1ListMeta = {
|
||||||
@@ -247,3 +342,69 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTr
|
|||||||
kind?: string;
|
kind?: string;
|
||||||
metadata: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
metadata: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
||||||
};
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1StatusCause = {
|
||||||
|
/** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
"name" - the field "name" on the current resource
|
||||||
|
"items[0].name" - the field "name" on the first array entry in "items" */
|
||||||
|
field?: string;
|
||||||
|
/** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */
|
||||||
|
message?: string;
|
||||||
|
/** A machine-readable description of the cause of the error. If this value is empty there is no information available. */
|
||||||
|
reason?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1StatusDetails = {
|
||||||
|
/** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */
|
||||||
|
causes?: IoK8SApimachineryPkgApisMetaV1StatusCause[];
|
||||||
|
/** The group attribute of the resource associated with the status StatusReason. */
|
||||||
|
group?: string;
|
||||||
|
/** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
kind?: string;
|
||||||
|
/** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */
|
||||||
|
name?: string;
|
||||||
|
/** If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. */
|
||||||
|
retryAfterSeconds?: number;
|
||||||
|
/** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
|
||||||
|
uid?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1Status = {
|
||||||
|
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
|
||||||
|
apiVersion?: string;
|
||||||
|
/** Suggested HTTP return code for this status, 0 if not set. */
|
||||||
|
code?: number;
|
||||||
|
/** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */
|
||||||
|
details?: IoK8SApimachineryPkgApisMetaV1StatusDetails;
|
||||||
|
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
kind?: string;
|
||||||
|
/** A human-readable description of the status of this operation. */
|
||||||
|
message?: string;
|
||||||
|
/** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
metadata?: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
||||||
|
/** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */
|
||||||
|
reason?: string;
|
||||||
|
/** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */
|
||||||
|
status?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1Preconditions = {
|
||||||
|
/** Specifies the target ResourceVersion */
|
||||||
|
resourceVersion?: string;
|
||||||
|
/** Specifies the target UID. */
|
||||||
|
uid?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1DeleteOptions = {
|
||||||
|
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
|
||||||
|
apiVersion?: string;
|
||||||
|
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
|
||||||
|
dryRun?: string[];
|
||||||
|
/** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */
|
||||||
|
gracePeriodSeconds?: number;
|
||||||
|
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
kind?: string;
|
||||||
|
/** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */
|
||||||
|
orphanDependents?: boolean;
|
||||||
|
/** Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */
|
||||||
|
preconditions?: IoK8SApimachineryPkgApisMetaV1Preconditions;
|
||||||
|
/** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */
|
||||||
|
propagationPolicy?: string;
|
||||||
|
};
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export const routeGroupsMatcher = {
|
|||||||
.map((matchDetails) => ({
|
.map((matchDetails) => ({
|
||||||
route,
|
route,
|
||||||
routeTree: {
|
routeTree: {
|
||||||
metadata: { name: 'user-defined' },
|
metadata: { name: routeTree.name },
|
||||||
expandedSpec: expandedTree,
|
expandedSpec: expandedTree,
|
||||||
},
|
},
|
||||||
matchDetails,
|
matchDetails,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { MatcherFieldValue } from './silence-form';
|
|||||||
|
|
||||||
export interface FormAmRoute {
|
export interface FormAmRoute {
|
||||||
id: string;
|
id: string;
|
||||||
|
name?: string;
|
||||||
object_matchers: MatcherFieldValue[];
|
object_matchers: MatcherFieldValue[];
|
||||||
continue: boolean;
|
continue: boolean;
|
||||||
receiver: string;
|
receiver: string;
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ export const commonGroupByOptions = [
|
|||||||
|
|
||||||
export const emptyRoute: FormAmRoute = {
|
export const emptyRoute: FormAmRoute = {
|
||||||
id: '',
|
id: '',
|
||||||
|
name: '',
|
||||||
overrideGrouping: false,
|
overrideGrouping: false,
|
||||||
groupBy: defaultGroupBy,
|
groupBy: defaultGroupBy,
|
||||||
object_matchers: [],
|
object_matchers: [],
|
||||||
@@ -63,9 +64,13 @@ export const emptyRoute: FormAmRoute = {
|
|||||||
activeTimeIntervals: [],
|
activeTimeIntervals: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export function addUniqueIdentifierToRoutes(routes: Route[]): RouteWithID[] {
|
||||||
|
return routes.map((policy, index) => addUniqueIdentifierToRoute(policy, policy.name ?? index.toString()));
|
||||||
|
}
|
||||||
|
|
||||||
// add unique identifiers to each route in the route tree, that way we can figure out what route we've edited / deleted
|
// add unique identifiers to each route in the route tree, that way we can figure out what route we've edited / deleted
|
||||||
// ⚠️ make sure this function uses _stable_ identifiers!
|
// ⚠️ make sure this function uses _stable_ identifiers!
|
||||||
export function addUniqueIdentifierToRoute(route: Route, position = '0'): RouteWithID {
|
export function addUniqueIdentifierToRoute(route: Route, position = route.name ?? '0'): RouteWithID {
|
||||||
const routeHash = hashRoute(route);
|
const routeHash = hashRoute(route);
|
||||||
const routes = route.routes ?? [];
|
const routes = route.routes ?? [];
|
||||||
|
|
||||||
@@ -112,6 +117,7 @@ export const amRouteToFormAmRoute = (route: RouteWithID | undefined): FormAmRout
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
name: route.name ?? '',
|
||||||
// Frontend migration to use object_matchers instead of matchers, match, and match_re
|
// Frontend migration to use object_matchers instead of matchers, match, and match_re
|
||||||
object_matchers: [
|
object_matchers: [
|
||||||
...matchers,
|
...matchers,
|
||||||
|
|||||||
@@ -153,13 +153,14 @@ export function findRouteInTree(
|
|||||||
|
|
||||||
export function cleanRouteIDs<
|
export function cleanRouteIDs<
|
||||||
T extends RouteWithID | Route | ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
|
T extends RouteWithID | Route | ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
|
||||||
>(route: T): Omit<T, 'id'> {
|
>(route: T): Omit<T, 'id' | 'name'> {
|
||||||
return omit(
|
return omit(
|
||||||
{
|
{
|
||||||
...route,
|
...route,
|
||||||
routes: route.routes?.map((route) => cleanRouteIDs(route)),
|
routes: route.routes?.map((route) => cleanRouteIDs(route)),
|
||||||
},
|
},
|
||||||
'id'
|
'id',
|
||||||
|
'name'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,6 +199,7 @@ export function hashRoute(route: Route): string {
|
|||||||
*/
|
*/
|
||||||
export function stabilizeRoute(route: Route): Required<Route> {
|
export function stabilizeRoute(route: Route): Required<Route> {
|
||||||
const result: Required<Route> = {
|
const result: Required<Route> = {
|
||||||
|
name: route.name ?? '',
|
||||||
receiver: route.receiver ?? '',
|
receiver: route.receiver ?? '',
|
||||||
group_by: route.group_by ? [...route.group_by].sort() : [],
|
group_by: route.group_by ? [...route.group_by].sort() : [],
|
||||||
continue: route.continue ?? false,
|
continue: route.continue ?? false,
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ function useGetConfigurationForApps() {
|
|||||||
const { data: rootRoute, isLoading: isLoadingDefaultContactPoint } = useNotificationPolicyRoute({
|
const { data: rootRoute, isLoading: isLoadingDefaultContactPoint } = useNotificationPolicyRoute({
|
||||||
alertmanager: GRAFANA_RULES_SOURCE_NAME,
|
alertmanager: GRAFANA_RULES_SOURCE_NAME,
|
||||||
});
|
});
|
||||||
const defaultContactpoint = rootRoute?.[0].receiver || '';
|
const defaultContactpoint = rootRoute?.receiver || '';
|
||||||
const { isDone: isCreateAlertRuleDone, isLoading: isLoadingAlertCreatedDone } = useIsCreateAlertRuleDone();
|
const { isDone: isCreateAlertRuleDone, isLoading: isLoadingAlertCreatedDone } = useIsCreateAlertRuleDone();
|
||||||
// configuration checks for incidents
|
// configuration checks for incidents
|
||||||
const {
|
const {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//DOCS: https://prometheus.io/docs/alerting/latest/configuration/
|
//DOCS: https://prometheus.io/docs/alerting/latest/configuration/
|
||||||
import { DataSourceJsonData, WithAccessControlMetadata } from '@grafana/data';
|
import { DataSourceJsonData, WithAccessControlMetadata } from '@grafana/data';
|
||||||
import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/unified/openapi/receiversApi.gen';
|
import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/unified/openapi/routesApi.gen';
|
||||||
import { ExtraConfiguration } from 'app/features/alerting/unified/utils/alertmanager/extraConfigs';
|
import { ExtraConfiguration } from 'app/features/alerting/unified/utils/alertmanager/extraConfigs';
|
||||||
|
|
||||||
export const ROUTES_META_SYMBOL = Symbol('routes_metadata');
|
export const ROUTES_META_SYMBOL = Symbol('routes_metadata');
|
||||||
@@ -123,6 +123,7 @@ export type Receiver = GrafanaManagedContactPoint | AlertmanagerReceiver;
|
|||||||
export type ObjectMatcher = [name: string, operator: MatcherOperator, value: string];
|
export type ObjectMatcher = [name: string, operator: MatcherOperator, value: string];
|
||||||
|
|
||||||
export type Route = {
|
export type Route = {
|
||||||
|
name?: string;
|
||||||
receiver?: string | null;
|
receiver?: string | null;
|
||||||
group_by?: string[];
|
group_by?: string[];
|
||||||
continue?: boolean;
|
continue?: boolean;
|
||||||
@@ -147,6 +148,7 @@ export type Route = {
|
|||||||
provisioned?: boolean;
|
provisioned?: boolean;
|
||||||
resourceVersion?: string;
|
resourceVersion?: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
|
metadata?: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -67,8 +67,10 @@ const config: ConfigFile = {
|
|||||||
apiImport: 'alertingApi',
|
apiImport: 'alertingApi',
|
||||||
filterEndpoints: [
|
filterEndpoints: [
|
||||||
'listNamespacedRoutingTree',
|
'listNamespacedRoutingTree',
|
||||||
|
'createNamespacedRoutingTree',
|
||||||
|
'readNamespacedRoutingTree',
|
||||||
'replaceNamespacedRoutingTree',
|
'replaceNamespacedRoutingTree',
|
||||||
'deleteCollectionNamespacedRoutingTree',
|
'deleteNamespacedRoutingTree',
|
||||||
],
|
],
|
||||||
exportName: 'generatedRoutesApi',
|
exportName: 'generatedRoutesApi',
|
||||||
flattenArg: false,
|
flattenArg: false,
|
||||||
|
|||||||
Reference in New Issue
Block a user