+
+ );
+};
diff --git a/public/app/features/alerting/unified/components/notification-policies/components/RoutingTreeFilter.tsx b/public/app/features/alerting/unified/components/notification-policies/components/RoutingTreeFilter.tsx
new file mode 100644
index 00000000000..35005165a8d
--- /dev/null
+++ b/public/app/features/alerting/unified/components/notification-policies/components/RoutingTreeFilter.tsx
@@ -0,0 +1,71 @@
+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 (
+
+
+ }
+ onChange={(event) => {
+ setSearchValue(event.currentTarget.value);
+ }}
+ value={searchValue}
+ />
+
+
+
+ );
+};
+
+const getStyles = () => ({
+ noBottom: css({
+ marginBottom: 0,
+ }),
+});
+
+export { RoutingTreeFilter };
diff --git a/public/app/features/alerting/unified/components/notification-policies/useExportRoutingTree.tsx b/public/app/features/alerting/unified/components/notification-policies/useExportRoutingTree.tsx
new file mode 100644
index 00000000000..3fdcc059aa5
--- /dev/null
+++ b/public/app/features/alerting/unified/components/notification-policies/useExportRoutingTree.tsx
@@ -0,0 +1,31 @@
+import { useCallback, useMemo, useState } from 'react';
+import { useToggle } from 'react-use';
+
+import { GrafanaPoliciesExporter } from '../export/GrafanaPoliciesExporter';
+
+type ExportProps = [JSX.Element | null, (routeName: string) => void];
+
+export const useExportRoutingTree = (): ExportProps => {
+ const [routeName, setRouteName] = useState(null);
+ const [isExportDrawerOpen, toggleShowExportDrawer] = useToggle(false);
+
+ const handleClose = useCallback(() => {
+ setRouteName(null);
+ toggleShowExportDrawer(false);
+ }, [toggleShowExportDrawer]);
+
+ const handleOpen = (routeName: string) => {
+ setRouteName(routeName);
+ toggleShowExportDrawer(true);
+ };
+
+ const drawer = useMemo(() => {
+ if (!routeName || !isExportDrawerOpen) {
+ return null;
+ }
+
+ return ;
+ }, [isExportDrawerOpen, handleClose, routeName]);
+
+ return [drawer, handleOpen];
+};
diff --git a/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.test.tsx b/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.test.tsx
index a57886534ff..00082a3404e 100644
--- a/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.test.tsx
+++ b/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.test.tsx
@@ -30,6 +30,7 @@ test('k8sSubRouteToRoute', () => {
};
const expected: Route = {
+ name: 'test-name',
continue: false,
group_by: ['label1'],
group_interval: '5m',
@@ -41,6 +42,7 @@ test('k8sSubRouteToRoute', () => {
repeat_interval: '4h',
routes: [
{
+ name: 'test-name',
receiver: 'receiver2',
matchers: undefined,
object_matchers: [['label2', MatcherOperator.notEqual, 'value2']],
@@ -49,7 +51,7 @@ test('k8sSubRouteToRoute', () => {
],
};
- expect(k8sSubRouteToRoute(input)).toStrictEqual(expected);
+ expect(k8sSubRouteToRoute(input, 'test-name')).toStrictEqual(expected);
});
test('routeToK8sSubRoute', () => {
diff --git a/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts b/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts
index ca9be820463..4c6b315a8a4 100644
--- a/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts
+++ b/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts
@@ -1,9 +1,11 @@
-import { pick } from 'lodash';
+import uFuzzy from '@leeoniya/ufuzzy';
+import { pick, uniq } from 'lodash';
import memoize from 'micro-memoize';
+import { useMemo } from 'react';
import { INHERITABLE_KEYS, type InheritableProperties } from '@grafana/alerting/internal';
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
-import { MatcherOperator, ROUTES_META_SYMBOL, Route } from 'app/plugins/datasource/alertmanager/types';
+import { MatcherOperator, ROUTES_META_SYMBOL, Route, RouteWithID } from 'app/plugins/datasource/alertmanager/types';
import { getAPINamespace } from '../../../../../api/utils';
import { alertmanagerApi } from '../../api/alertmanagerApi';
@@ -38,28 +40,37 @@ export function isRouteProvisioned(route: Route): boolean {
return isProvisionedResource(provenance);
}
-const k8sRoutesToRoutesMemoized = memoize(k8sRoutesToRoutes, { maxSize: 1 });
-
const {
+ useCreateNamespacedRoutingTreeMutation,
+ useDeleteNamespacedRoutingTreeMutation,
useListNamespacedRoutingTreeQuery,
useReplaceNamespacedRoutingTreeMutation,
- useLazyListNamespacedRoutingTreeQuery,
+ useLazyReadNamespacedRoutingTreeQuery,
+ useReadNamespacedRoutingTreeQuery,
} = routingTreeApi;
const { useGetAlertmanagerConfigurationQuery } = alertmanagerApi;
-export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArgs, { skip }: Skippable = {}) => {
+const memoK8sRouteToRoute = memoize(k8sRouteToRoute);
+
+export const useNotificationPolicyRoute = (
+ { alertmanager }: BaseAlertmanagerArgs,
+ routeName: string = ROOT_ROUTE_NAME,
+ { skip }: Skippable = {}
+) => {
const k8sApiSupported = shouldUseK8sApi(alertmanager);
- const k8sRouteQuery = useListNamespacedRoutingTreeQuery(
- { namespace: getAPINamespace() },
+ const k8sRouteQuery = useReadNamespacedRoutingTreeQuery(
+ { namespace: getAPINamespace(), name: routeName },
{
skip: skip || !k8sApiSupported,
selectFromResult: (result) => {
+ const { data, currentData, ...rest } = result;
+
return {
- ...result,
- currentData: result.currentData ? k8sRoutesToRoutesMemoized(result.currentData.items) : undefined,
- data: result.data ? k8sRoutesToRoutesMemoized(result.data.items) : undefined,
+ ...rest,
+ data: data ? memoK8sRouteToRoute(data) : data,
+ currentData: currentData ? memoK8sRouteToRoute(currentData) : currentData,
};
},
}
@@ -71,10 +82,10 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
return {
...result,
currentData: result.currentData?.alertmanager_config?.route
- ? [parseAmConfigRoute(result.currentData.alertmanager_config.route)]
+ ? parseAmConfigRoute(result.currentData.alertmanager_config.route)
: undefined,
data: result.data?.alertmanager_config?.route
- ? [parseAmConfigRoute(result.data.alertmanager_config.route)]
+ ? parseAmConfigRoute(result.data.alertmanager_config.route)
: undefined,
};
},
@@ -83,6 +94,24 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
return k8sApiSupported ? k8sRouteQuery : amConfigQuery;
};
+export const useListNotificationPolicyRoutes = ({ skip }: Skippable = {}) => {
+ return useListNamespacedRoutingTreeQuery(
+ { namespace: getAPINamespace() },
+ {
+ skip: skip,
+ selectFromResult: (result) => {
+ const { data, currentData, ...rest } = result;
+
+ return {
+ ...rest,
+ data: data ? data.items.map(memoK8sRouteToRoute) : data,
+ currentData: currentData ? currentData.items.map(memoK8sRouteToRoute) : currentData,
+ };
+ },
+ }
+ );
+};
+
const parseAmConfigRoute = memoize((route: Route): Route => {
return {
...route,
@@ -96,25 +125,26 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
- const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
+ const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
const updateUsingK8sApi = useAsync(async (update: Partial) => {
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) {
- 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);
// Create the K8s route object
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
return updatedNamespacedRoute({
- name: ROOT_ROUTE_NAME,
+ name: name,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
}).unwrap();
@@ -131,33 +161,34 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
- const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
+ const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
- const deleteFromK8sApi = useAsync(async (id: string) => {
+ const deleteFromK8sApi = useAsync(async (route: RouteWithID) => {
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) {
throw new Error(`no root route found for namespace ${namespace}`);
}
- const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
- const newRouteTree = omitRouteFromRouteTree(id, rootRouteWithIdentifiers);
+ const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
+ const newRouteTree = omitRouteFromRouteTree(route.id, rootRouteWithIdentifiers);
// Create the K8s route object
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
return updatedNamespacedRoute({
- name: ROOT_ROUTE_NAME,
+ name: name,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: routeObject,
}).unwrap();
});
- const deleteFromAlertmanagerConfiguration = useAsync(async (id: string) => {
- const action = deleteRouteAction({ id });
+ const deleteFromAlertmanagerConfiguration = useAsync(async (route: RouteWithID) => {
+ const action = deleteRouteAction({ id: route.id });
return produceNewAlertmanagerConfiguration(action);
});
@@ -167,32 +198,33 @@ export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerAr
export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
- const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
+ const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
const addToK8sApi = useAsync(
async ({
partialRoute,
- referenceRouteIdentifier,
+ referenceRoute,
insertPosition,
}: {
partialRoute: Partial;
- referenceRouteIdentifier: string;
+ referenceRoute: RouteWithID;
insertPosition: InsertPosition;
}) => {
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) {
throw new Error(`no root route found for namespace ${namespace}`);
}
- const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
+ const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
const newRouteTree = addRouteToReferenceRoute(
alertmanager ?? '',
partialRoute,
- referenceRouteIdentifier,
+ referenceRoute.id,
rootRouteWithIdentifiers,
insertPosition
);
@@ -201,7 +233,7 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
return updatedNamespacedRoute({
- name: ROOT_ROUTE_NAME,
+ name: name,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
}).unwrap();
@@ -211,16 +243,16 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
const addToAlertmanagerConfiguration = useAsync(
async ({
partialRoute,
- referenceRouteIdentifier,
+ referenceRoute,
insertPosition,
}: {
partialRoute: Partial;
- referenceRouteIdentifier: string;
+ referenceRoute: RouteWithID;
insertPosition: InsertPosition;
}) => {
const action = addRouteAction({
partialRoute,
- referenceRouteIdentifier,
+ referenceRouteIdentifier: referenceRoute.id,
insertPosition,
alertmanager,
});
@@ -231,30 +263,161 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
return k8sApiSupported ? addToK8sApi : addToAlertmanagerConfiguration;
}
-function k8sRoutesToRoutes(routes: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree[]): Route[] {
- return routes?.map((route) => {
- return {
- ...route.spec.defaults,
- routes: route.spec.routes?.map(k8sSubRouteToRoute),
- [ROUTES_META_SYMBOL]: {
- provenance: getAnnotation(route, K8sAnnotations.Provenance),
- resourceVersion: route.metadata.resourceVersion,
- name: route.metadata.name,
- },
- provenance: getAnnotation(route, K8sAnnotations.Provenance),
- };
+type DeleteRoutingTreeArgs = { name: string; resourceVersion?: string };
+export function useDeleteRoutingTree() {
+ const [deleteNamespacedRoutingTree] = useDeleteNamespacedRoutingTreeMutation();
+
+ return useAsync(async ({ name, resourceVersion }: DeleteRoutingTreeArgs) => {
+ const namespace = getAPINamespace();
+
+ return deleteNamespacedRoutingTree({
+ name: name,
+ namespace,
+ ioK8SApimachineryPkgApisMetaV1DeleteOptions: { preconditions: { resourceVersion } },
+ }).unwrap();
});
}
+export function useCreateRoutingTree() {
+ const [createNamespacedRoutingTree] = useCreateNamespacedRoutingTreeMutation();
+
+ return useAsync(async (partialFormRoute: Partial) => {
+ 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__';
+
+export 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]: {
+ provenance: getAnnotation(route, K8sAnnotations.Provenance),
+ resourceVersion: route.metadata.resourceVersion,
+ name: route.metadata.name,
+ metadata: route.metadata,
+ },
+ provenance: getAnnotation(route, K8sAnnotations.Provenance),
+ };
+}
+
/** Helper to provide type safety for matcher operators from API */
function isValidMatcherOperator(type: string): type is MatcherOperator {
return Object.values(MatcherOperator).includes(type);
}
-export function k8sSubRouteToRoute(route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route): Route {
+export function k8sSubRouteToRoute(
+ route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
+ rootName?: string
+): Route {
return {
...route,
- routes: route.routes?.map(k8sSubRouteToRoute),
+ name: rootName,
+ routes: route.routes?.map((subroute) => k8sSubRouteToRoute(subroute, rootName)),
matchers: undefined,
object_matchers: route.matchers?.map(({ label, type, value }) => {
if (!isValidMatcherOperator(type)) {
@@ -278,34 +441,3 @@ export function routeToK8sSubRoute(route: Route): ComGithubGrafanaGrafanaPkgApis
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,
- },
- };
-}
diff --git a/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/NotificationPolicyDrawer.tsx b/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/NotificationPolicyDrawer.tsx
index 48154eb455b..b24319ef1b8 100644
--- a/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/NotificationPolicyDrawer.tsx
+++ b/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/NotificationPolicyDrawer.tsx
@@ -97,7 +97,11 @@ export function NotificationPolicyDrawer({
)}
-
+
View notification policy tree
diff --git a/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/useAlertmanagerNotificationRoutingPreview.ts b/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/useAlertmanagerNotificationRoutingPreview.ts
index 2f95fe40d52..82271f7a304 100644
--- a/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/useAlertmanagerNotificationRoutingPreview.ts
+++ b/public/app/features/alerting/unified/components/rule-editor/notificaton-preview/useAlertmanagerNotificationRoutingPreview.ts
@@ -1,7 +1,10 @@
import { useMemo } from 'react';
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 { useRouteGroupsMatcher } from '../../../useRouteGroupsMatcher';
@@ -10,16 +13,21 @@ import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
import { normalizeRoute } from '../../../utils/notification-policies';
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 {
- data: currentData,
+ data: defaultPolicy,
isLoading: isPoliciesLoading,
error: policiesError,
- } = useNotificationPolicyRoute({ alertmanager });
+ } = useNotificationPolicyRoute({ alertmanager }, routeName);
// this function will use a web worker to compute matching routes
const { matchInstancesToRoutes } = useRouteGroupsMatcher();
- const [defaultPolicy] = currentData ?? [];
const rootRoute = useMemo(() => {
if (!defaultPolicy) {
return;
diff --git a/public/app/features/alerting/unified/mocks/server/entities/k8s/routingtrees.ts b/public/app/features/alerting/unified/mocks/server/entities/k8s/routingtrees.ts
index 1005267badf..1c526a917b0 100644
--- a/public/app/features/alerting/unified/mocks/server/entities/k8s/routingtrees.ts
+++ b/public/app/features/alerting/unified/mocks/server/entities/k8s/routingtrees.ts
@@ -3,6 +3,7 @@ import {
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Matcher,
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
+ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTreeSpec,
} from 'app/features/alerting/unified/openapi/routesApi.gen';
import { KnownProvenance } from 'app/features/alerting/unified/types/knownProvenance';
import { K8sAnnotations, ROOT_ROUTE_NAME } from 'app/features/alerting/unified/utils/k8s/constants';
@@ -62,26 +63,144 @@ export const getUserDefinedRoutingTree: (
}) || [],
};
- return {
- metadata: {
- name: ROOT_ROUTE_NAME,
- namespace: 'default',
- annotations: {
- [K8sAnnotations.Provenance]: KnownProvenance.None,
- },
- // Resource versions are much shorter than this in reality, but this is an easy way
- // for us to mock the concurrency logic and check if the policies have updated since the last fetch
- resourceVersion: btoa(JSON.stringify(spec)),
- },
- spec,
- };
+ return routingTreeFromSpec(ROOT_ROUTE_NAME, spec);
};
+const routingTreeFromSpec: (
+ routeName: string,
+ spec: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTreeSpec,
+ provenance?: string
+) => ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree = (
+ routeName,
+ spec,
+ provenance = KnownProvenance.None
+) => ({
+ kind: 'RoutingTree',
+ metadata: {
+ name: routeName,
+ namespace: 'default',
+ annotations: {
+ [K8sAnnotations.Provenance]: provenance,
+ },
+ // Resource versions are much shorter than this in reality, but this is an easy way
+ // for us to mock the concurrency logic and check if the policies have updated since the last fetch
+ resourceVersion: btoa(JSON.stringify(spec)),
+ },
+ spec: spec,
+});
+
const getDefaultRoutingTreeMap = () =>
- new Map([[ROOT_ROUTE_NAME, getUserDefinedRoutingTree(grafanaAlertmanagerConfig)]]);
+ new Map([
+ [ROOT_ROUTE_NAME, getUserDefinedRoutingTree(grafanaAlertmanagerConfig)],
+ [
+ 'Managed Policy - Empty Provisioned',
+ routingTreeFromSpec(
+ 'Managed Policy - Empty Provisioned',
+ {
+ defaults: {
+ receiver: grafanaAlertmanagerConfig?.alertmanager_config?.receivers![0].name, // grafana-default-email
+ },
+ routes: [],
+ },
+ 'api'
+ ),
+ ],
+ [
+ 'Managed Policy - Override + Inherit',
+ routingTreeFromSpec('Managed Policy - Override + Inherit', {
+ defaults: {
+ receiver: grafanaAlertmanagerConfig?.alertmanager_config?.receivers![1].name, // provisioned-contact-point
+ group_by: ['alertname'],
+ group_wait: '1s',
+ group_interval: '1m',
+ repeat_interval: '1h',
+ },
+ routes: [
+ {
+ // Override.
+ receiver: grafanaAlertmanagerConfig?.alertmanager_config?.receivers![2].name, // lotsa-emails
+ group_by: ['alertname', 'grafana_folder'],
+ group_wait: '10s',
+ group_interval: '10m',
+ repeat_interval: '10h',
+ continue: true,
+ active_time_intervals: [grafanaAlertmanagerConfig?.alertmanager_config?.time_intervals![0].name], // Some interval
+ mute_time_intervals: [grafanaAlertmanagerConfig?.alertmanager_config?.time_intervals![1].name], // A provisioned interval
+ matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'critical' }],
+ },
+ {
+ // Inherit.
+ matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'warn' }],
+ },
+ ],
+ }),
+ ],
+ [
+ 'Managed Policy - Many Top-Level',
+ routingTreeFromSpec('Managed Policy - Many Top-Level', {
+ defaults: {
+ receiver: grafanaAlertmanagerConfig?.alertmanager_config?.receivers![2].name, // lotsa-emails
+ group_by: ['alertname'],
+ group_wait: '2s',
+ group_interval: '2m',
+ repeat_interval: '2h',
+ },
+ routes: [
+ // Many top-level routes.
+ { matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'warn' }] },
+ { matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'critical' }] },
+ { matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'info' }] },
+ { matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'debug' }] },
+ { matchers: [{ label: 'severity', type: MatcherOperator.equal, value: 'unknown' }] },
+ ],
+ }),
+ ],
+ [
+ 'Managed Policy - Deeply Nested',
+ routingTreeFromSpec('Managed Policy - Deeply Nested', {
+ defaults: {
+ receiver: grafanaAlertmanagerConfig?.alertmanager_config?.receivers![3].name, // Slack with multiple channels
+ group_by: ['...'],
+ group_wait: '3s',
+ group_interval: '3m',
+ repeat_interval: '3h',
+ },
+ routes: [
+ // Deeply nested route.
+ {
+ matchers: [{ label: 'level', type: MatcherOperator.equal, value: 'one' }],
+ routes: [
+ {
+ matchers: [{ label: 'level', type: MatcherOperator.equal, value: 'two' }],
+ routes: [
+ {
+ matchers: [{ label: 'level', type: MatcherOperator.equal, value: 'three' }],
+ routes: [
+ {
+ matchers: [{ label: 'level', type: MatcherOperator.equal, value: 'four' }],
+ routes: [
+ {
+ matchers: [{ label: 'level', type: MatcherOperator.equal, value: 'five' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ ]);
let ROUTING_TREE_MAP = getDefaultRoutingTreeMap();
+export const getRoutingTreeList = () => {
+ return Array.from(ROUTING_TREE_MAP.values());
+};
+
export const getRoutingTree = (treeName: string) => {
return ROUTING_TREE_MAP.get(treeName);
};
@@ -93,6 +212,14 @@ export const setRoutingTree = (
return ROUTING_TREE_MAP.set(treeName, updatedRoutingTree);
};
+export const deleteRoutingTree = (treeName: string) => {
+ return ROUTING_TREE_MAP.delete(treeName);
+};
+
+export const resetDefaultRoutingTree = () => {
+ ROUTING_TREE_MAP.set(ROOT_ROUTE_NAME, getUserDefinedRoutingTree(grafanaAlertmanagerConfig));
+};
+
export const resetRoutingTreeMap = () => {
ROUTING_TREE_MAP = getDefaultRoutingTreeMap();
};
diff --git a/public/app/features/alerting/unified/mocks/server/handlers/k8s/routingtrees.k8s.ts b/public/app/features/alerting/unified/mocks/server/handlers/k8s/routingtrees.k8s.ts
index b0fdc2fd0a6..9ca54c40501 100644
--- a/public/app/features/alerting/unified/mocks/server/handlers/k8s/routingtrees.k8s.ts
+++ b/public/app/features/alerting/unified/mocks/server/handlers/k8s/routingtrees.k8s.ts
@@ -1,26 +1,32 @@
import { HttpResponse, http } from 'msw';
-import { getRoutingTree, setRoutingTree } from 'app/features/alerting/unified/mocks/server/entities/k8s/routingtrees';
+import {
+ deleteRoutingTree,
+ getRoutingTree,
+ getRoutingTreeList,
+ resetDefaultRoutingTree,
+ setRoutingTree,
+} from 'app/features/alerting/unified/mocks/server/entities/k8s/routingtrees';
import { ALERTING_API_SERVER_BASE_URL } from 'app/features/alerting/unified/mocks/server/utils';
import {
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
ListNamespacedRoutingTreeApiResponse,
} from 'app/features/alerting/unified/openapi/routesApi.gen';
-import { ROOT_ROUTE_NAME } from 'app/features/alerting/unified/utils/k8s/constants';
import { ApiMachineryError } from 'app/features/alerting/unified/utils/k8s/errors';
+import { ROOT_ROUTE_NAME } from '../../../../utils/k8s/constants';
+
const wrapRoutingTreeResponse: (
- route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
-) => ListNamespacedRoutingTreeApiResponse = (route) => ({
+ routes: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree[]
+) => ListNamespacedRoutingTreeApiResponse = (routes) => ({
kind: 'RoutingTree',
metadata: {},
- items: [route],
+ items: routes,
});
const listNamespacedRoutingTreesHandler = () =>
http.get<{ namespace: string }>(`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/routingtrees`, () => {
- const userDefinedTree = getRoutingTree(ROOT_ROUTE_NAME)!;
- return HttpResponse.json(wrapRoutingTreeResponse(userDefinedTree));
+ return HttpResponse.json(wrapRoutingTreeResponse(getRoutingTreeList()));
});
const HTTP_RESPONSE_CONFLICT: ApiMachineryError = {
@@ -50,6 +56,52 @@ const updateNamespacedRoutingTreeHandler = () =>
}
);
-const handlers = [listNamespacedRoutingTreesHandler(), updateNamespacedRoutingTreeHandler()];
+const getNamespacedRoutingTreeHandler = () =>
+ http.get<{ namespace: string; name: string }>(
+ `${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/routingtrees/:name`,
+ ({ params: { name } }) => {
+ const routingTree = getRoutingTree(name);
+ if (!routingTree) {
+ return HttpResponse.json({ message: 'NotFound' }, { status: 404 });
+ }
+ return HttpResponse.json(routingTree);
+ }
+ );
+
+const createNamespacedRoutingTreeHandler = () =>
+ http.post<
+ { namespace: string; name: string },
+ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
+ >(`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/routingtrees`, async ({ params: { name }, request }) => {
+ const routingTree = await request.json();
+ setRoutingTree(name, routingTree);
+ return HttpResponse.json(routingTree);
+ });
+
+const deleteNamespacedRoutingTreeHandler = () =>
+ http.delete<{ namespace: string; name: string }>(
+ `${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/routingtrees/:name`,
+ ({ params: { name } }) => {
+ const routingTree = getRoutingTree(name);
+ if (!routingTree) {
+ return HttpResponse.json({ message: 'NotFound' }, { status: 404 });
+ }
+ if (name === ROOT_ROUTE_NAME) {
+ // Reset instead.
+ resetDefaultRoutingTree();
+ } else {
+ deleteRoutingTree(name);
+ }
+ return HttpResponse.json({});
+ }
+ );
+
+const handlers = [
+ listNamespacedRoutingTreesHandler(),
+ updateNamespacedRoutingTreeHandler(),
+ getNamespacedRoutingTreeHandler(),
+ createNamespacedRoutingTreeHandler(),
+ deleteNamespacedRoutingTreeHandler(),
+];
export default handlers;
diff --git a/public/app/features/alerting/unified/openapi/routesApi.gen.ts b/public/app/features/alerting/unified/openapi/routesApi.gen.ts
index d06665f1137..31940119bf4 100644
--- a/public/app/features/alerting/unified/openapi/routesApi.gen.ts
+++ b/public/app/features/alerting/unified/openapi/routesApi.gen.ts
@@ -25,6 +25,32 @@ const injectedRtkApi = api
}),
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({
+ query: (queryArg) => ({
+ url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees/${queryArg.name}`,
+ params: {
+ pretty: queryArg.pretty,
+ },
+ }),
+ providesTags: ['RoutingTree'],
+ }),
replaceNamespacedRoutingTree: build.mutation<
ReplaceNamespacedRoutingTreeApiResponse,
ReplaceNamespacedRoutingTreeApiArg
@@ -42,6 +68,24 @@ const injectedRtkApi = api
}),
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,
});
@@ -56,7 +100,7 @@ export type ListNamespacedRoutingTreeApiArg = {
/** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */
allowWatchBookmarks?: boolean;
/** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key".
-
+
This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */
continue?: string;
/** A selector to restrict the list of returned objects by their fields. Defaults to everything. */
@@ -64,19 +108,19 @@ export type ListNamespacedRoutingTreeApiArg = {
/** A selector to restrict the list of returned objects by their labels. Defaults to everything. */
labelSelector?: string;
/** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
-
+
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */
limit?: number;
/** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
-
+
Defaults to unset */
resourceVersion?: string;
/** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
-
+
Defaults to unset */
resourceVersionMatch?: string;
/** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.
-
+
When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan
is interpreted as "data at least as new as the provided `resourceVersion`"
and the bookmark event is send when the state is synced
@@ -86,7 +130,7 @@ export type ListNamespacedRoutingTreeApiArg = {
when request started being processed.
- `resourceVersionMatch` set to any other value or unset
Invalid error is returned.
-
+
Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */
sendInitialEvents?: boolean;
/** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */
@@ -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?: 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 */
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
@@ -112,6 +183,28 @@ export type ReplaceNamespacedRoutingTreeApiArg = {
fieldValidation?: string;
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 IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
@@ -150,21 +243,21 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = {
[key: string]: string;
};
/** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.
-
+
Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
creationTimestamp?: IoK8SApimachineryPkgApisMetaV1Time;
/** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */
deletionGracePeriodSeconds?: number;
/** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.
-
+
Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
deletionTimestamp?: IoK8SApimachineryPkgApisMetaV1Time;
/** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */
finalizers?: string[];
/** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
-
+
If this field is specified and the generated name exists, the server will return a 409.
-
+
Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */
generateName?: string;
/** A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. */
@@ -178,19 +271,19 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = {
/** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
name?: string;
/** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
-
+
Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */
namespace?: string;
/** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */
ownerReferences?: IoK8SApimachineryPkgApisMetaV1OwnerReference[];
/** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.
-
+
Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
resourceVersion?: string;
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
selfLink?: string;
/** UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.
-
+
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
uid?: string;
};
@@ -207,6 +300,7 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Matcher =
value: string;
};
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route = {
+ active_time_intervals?: string[];
continue?: boolean;
group_by?: 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?: string;
metadata: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
+ /** Spec is the spec of the RoutingTree */
spec: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTreeSpec;
};
export type IoK8SApimachineryPkgApisMetaV1ListMeta = {
@@ -247,3 +342,69 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTr
kind?: string;
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;
+};
diff --git a/public/app/features/alerting/unified/routeGroupsMatcher.ts b/public/app/features/alerting/unified/routeGroupsMatcher.ts
index 5a89fb6623e..09cc5b88abc 100644
--- a/public/app/features/alerting/unified/routeGroupsMatcher.ts
+++ b/public/app/features/alerting/unified/routeGroupsMatcher.ts
@@ -52,7 +52,7 @@ export const routeGroupsMatcher = {
.map((matchDetails) => ({
route,
routeTree: {
- metadata: { name: 'user-defined' },
+ metadata: { name: routeTree.name },
expandedSpec: expandedTree,
},
matchDetails,
diff --git a/public/app/features/alerting/unified/types/amroutes.ts b/public/app/features/alerting/unified/types/amroutes.ts
index bf9f3ef3797..239a2f73a75 100644
--- a/public/app/features/alerting/unified/types/amroutes.ts
+++ b/public/app/features/alerting/unified/types/amroutes.ts
@@ -2,6 +2,7 @@ import { MatcherFieldValue } from './silence-form';
export interface FormAmRoute {
id: string;
+ name?: string;
object_matchers: MatcherFieldValue[];
continue: boolean;
receiver: string;
diff --git a/public/app/features/alerting/unified/utils/amroutes.ts b/public/app/features/alerting/unified/utils/amroutes.ts
index 8b31dce9212..67af2af5605 100644
--- a/public/app/features/alerting/unified/utils/amroutes.ts
+++ b/public/app/features/alerting/unified/utils/amroutes.ts
@@ -49,6 +49,7 @@ export const commonGroupByOptions = [
export const emptyRoute: FormAmRoute = {
id: '',
+ name: '',
overrideGrouping: false,
groupBy: defaultGroupBy,
object_matchers: [],
@@ -63,9 +64,13 @@ export const emptyRoute: FormAmRoute = {
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
// ⚠️ 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 routes = route.routes ?? [];
@@ -112,6 +117,7 @@ export const amRouteToFormAmRoute = (route: RouteWithID | undefined): FormAmRout
return {
id,
+ name: route.name ?? '',
// Frontend migration to use object_matchers instead of matchers, match, and match_re
object_matchers: [
...matchers,
diff --git a/public/app/features/alerting/unified/utils/routeTree.test.ts b/public/app/features/alerting/unified/utils/routeTree.test.ts
index c83f24be8a6..2b085b79b90 100644
--- a/public/app/features/alerting/unified/utils/routeTree.test.ts
+++ b/public/app/features/alerting/unified/utils/routeTree.test.ts
@@ -137,6 +137,7 @@ describe('hashRoute and stabilizeRoute', () => {
};
const expected: Route = {
+ name: '',
active_time_intervals: [],
continue: false,
group_interval: '',
@@ -164,9 +165,9 @@ describe('hashRoute and stabilizeRoute', () => {
expect(stabilizeRoute(route)).toEqual(expected);
// the hash of the route should be stable (so we assert is twice)
- expect(hashRoute(route)).toBe('-1tfmmx');
- expect(hashRoute(route)).toBe('-1tfmmx');
- expect(hashRoute(expected)).toBe('-1tfmmx');
+ expect(hashRoute(route)).toBe('-djke0w');
+ expect(hashRoute(route)).toBe('-djke0w');
+ expect(hashRoute(expected)).toBe('-djke0w');
// the hash of the unstabilized route should be the same as the stabilized route
// because the hash function will stabilize the inputs
diff --git a/public/app/features/alerting/unified/utils/routeTree.ts b/public/app/features/alerting/unified/utils/routeTree.ts
index ba08bfd7526..2803d765ce8 100644
--- a/public/app/features/alerting/unified/utils/routeTree.ts
+++ b/public/app/features/alerting/unified/utils/routeTree.ts
@@ -153,13 +153,14 @@ export function findRouteInTree(
export function cleanRouteIDs<
T extends RouteWithID | Route | ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
->(route: T): Omit {
+>(route: T): Omit {
return omit(
{
...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 {
const result: Required = {
+ name: route.name ?? '',
receiver: route.receiver ?? '',
group_by: route.group_by ? [...route.group_by].sort() : [],
continue: route.continue ?? false,
diff --git a/public/app/features/gops/configuration-tracker/irmHooks.ts b/public/app/features/gops/configuration-tracker/irmHooks.ts
index 761ab573bc0..4be4363dbb3 100644
--- a/public/app/features/gops/configuration-tracker/irmHooks.ts
+++ b/public/app/features/gops/configuration-tracker/irmHooks.ts
@@ -63,7 +63,7 @@ function useGetConfigurationForApps() {
const { data: rootRoute, isLoading: isLoadingDefaultContactPoint } = useNotificationPolicyRoute({
alertmanager: GRAFANA_RULES_SOURCE_NAME,
});
- const defaultContactpoint = rootRoute?.[0].receiver || '';
+ const defaultContactpoint = rootRoute?.receiver || '';
const { isDone: isCreateAlertRuleDone, isLoading: isLoadingAlertCreatedDone } = useIsCreateAlertRuleDone();
// configuration checks for incidents
const {
diff --git a/public/app/plugins/datasource/alertmanager/types.ts b/public/app/plugins/datasource/alertmanager/types.ts
index 1f964e6b664..75acf92ef0c 100644
--- a/public/app/plugins/datasource/alertmanager/types.ts
+++ b/public/app/plugins/datasource/alertmanager/types.ts
@@ -1,6 +1,6 @@
//DOCS: https://prometheus.io/docs/alerting/latest/configuration/
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';
export const ROUTES_META_SYMBOL = Symbol('routes_metadata');
@@ -127,6 +127,7 @@ export type Receiver = GrafanaManagedContactPoint | AlertmanagerReceiver;
export type ObjectMatcher = [name: string, operator: MatcherOperator, value: string];
export type Route = {
+ name?: string;
receiver?: string | null;
group_by?: string[];
continue?: boolean;
@@ -151,6 +152,7 @@ export type Route = {
provenance?: string;
resourceVersion?: string;
name?: string;
+ metadata?: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
};
};
diff --git a/public/locales/en-US/grafana.json b/public/locales/en-US/grafana.json
index d44f97fa30e..da64803d7c6 100644
--- a/public/locales/en-US/grafana.json
+++ b/public/locales/en-US/grafana.json
@@ -663,14 +663,18 @@
"aria-label-group-by": "Group by",
"aria-label-group-interval": "Group interval",
"aria-label-group-wait": "Group wait",
+ "aria-label-name": "Name",
"aria-label-repeat-interval": "Repeat interval",
"create-a-contact-point": "Create a contact point",
+ "description-unique-routing": "A unique name for the routing tree",
"label-default-contact-point": "Default contact point",
+ "label-name": "Name",
"label-timing-options": "Timing options",
"message": {
"required": "Required."
},
- "or": "or"
+ "or": "or",
+ "validate-name": "Name is required"
},
"am-routes-expanded-form": {
"add-matcher": "Add matcher",
@@ -2137,6 +2141,10 @@
"new-policy": "Add new policy",
"no-matchers": "No matchers",
"reload-policies": "Reload policies",
+ "root-policy": {
+ "description": "All alert instances associated with this Route will be handled by this default policy if no other matching policies are found.",
+ "title": "Default policy for '{{routeName}}'"
+ },
"save-policy": "Save policy",
"update": {
"please-wait": "Please wait while we update your notification policies.",
@@ -2154,6 +2162,54 @@
"title": "Failed to add or update notification policy"
}
},
+ "policies-list": {
+ "create": {
+ "aria-label": "add policy",
+ "text": "Create policy"
+ },
+ "delete-reasons": {
+ "no-permissions": "You do not have the required permission to delete this routing tree",
+ "provisioned": "Routing tree is provisioned and cannot be deleted via the UI"
+ },
+ "delete-text": "Routing tree cannot be deleted for the following reasons:",
+ "empty-state": {
+ "message": "No policies found"
+ },
+ "fetch": {
+ "error": "Failed to fetch policies"
+ },
+ "policy-header": {
+ "delete": {
+ "aria-label": "delete",
+ "delete-label": "Delete",
+ "reset-label": "Reset"
+ },
+ "edit": {
+ "text": "Edit"
+ },
+ "export": {
+ "aria-label": "export",
+ "label": "Export"
+ },
+ "more-actions": {
+ "aria-label": "More actions for routing tree \"{{name}}\""
+ },
+ "view": {
+ "provisioned-tooltip": "Provisioned routing trees cannot be edited in the UI",
+ "text": "View"
+ }
+ },
+ "reset-reasons": {
+ "no-permissions": "You do not have the required permission to reset this routing tree",
+ "provisioned": "Routing tree is provisioned and cannot be reset via the UI"
+ },
+ "reset-text": "Routing tree cannot be reset for the following reasons:",
+ "text-loading": "Loading...."
+ },
+ "policies-tree-wrapper": {
+ "sorry-routing-exist": "Sorry, this routing tree does not seem to exist.",
+ "title-routing-tree-not-found": "Routing tree not found"
+ },
"policy": {
"label-new-child-policy": "New child policy",
"label-new-sibling-above": "New sibling above",
@@ -2337,6 +2393,13 @@
"label-override-timings": "Override timings",
"repeat-interval": "Repeat interval: {{repeatIntervalValue}}"
},
+ "routing-tree-filter": {
+ "aria-label-clear": "clear",
+ "aria-label-search-routing-trees": "search routing trees",
+ "clear": "Clear",
+ "label-search-by-name-or-receiver": "Search by name or receiver",
+ "placeholder-search": "Search"
+ },
"rule-actions-buttons": {
"title-edit": "Edit",
"title-view": "View"
@@ -3102,6 +3165,12 @@
"label-edit": "Edit",
"label-export": "Export"
},
+ "use-create-routing-tree-modal": {
+ "modal-element": {
+ "add-routing-tree": "Add routing tree",
+ "title-create-routing-tree": "Create routing tree"
+ }
+ },
"use-delete-contact-point-modal": {
"delete-confirm": "Yes, delete contact point",
"deleting": "Deleting...",
@@ -3121,6 +3190,15 @@
"title-delete-notification-policy": "Delete notification policy"
}
},
+ "use-delete-routing-tree-modal": {
+ "modal-element": {
+ "delete-routing": "Are you sure you want to delete this routing tree?",
+ "delete-yes": "Yes, delete routing tree",
+ "deleting": "Deleting...",
+ "deleting-routing-permanently-remove": "Deleting this routing tree will permanently remove it.",
+ "title-delete-routing-tree": "Delete routing tree"
+ }
+ },
"use-edit-configuration-drawer": {
"drawer": {
"internal-grafana-alertmanager-title": "Grafana built-in Alertmanager",
diff --git a/scripts/generate-alerting-rtk-apis.ts b/scripts/generate-alerting-rtk-apis.ts
index dd2cc9c611d..6ef7fdb0b1b 100644
--- a/scripts/generate-alerting-rtk-apis.ts
+++ b/scripts/generate-alerting-rtk-apis.ts
@@ -67,8 +67,10 @@ const config: ConfigFile = {
apiImport: 'alertingApi',
filterEndpoints: [
'listNamespacedRoutingTree',
+ 'createNamespacedRoutingTree',
+ 'readNamespacedRoutingTree',
'replaceNamespacedRoutingTree',
- 'deleteCollectionNamespacedRoutingTree',
+ 'deleteNamespacedRoutingTree',
],
exportName: 'generatedRoutesApi',
flattenArg: false,