Alerting: Add UI for imported time intervals

- Add ImportedTimeIntervalAlert component for time intervals imported from external Alertmanager
- Filter imported time intervals (provenance: prometheus_convert) from notification policy selector
- Refactor MuteTimingForm to use provenance prop instead of separate provisioned/imported props
- Add comprehensive tests for MuteTimingsSelector filtering behavior
- Add tests for MuteTimingForm with different provenance values
- Add i18n translations for imported time interval alerts
This commit is contained in:
Sonia Aguilar
2026-01-14 12:02:24 +01:00
parent fd955f90ac
commit f395a749a4
10 changed files with 316 additions and 21 deletions
-10
View File
@@ -1392,11 +1392,6 @@
"count": 2 "count": 2
} }
}, },
"public/app/features/alerting/unified/components/mute-timings/MuteTimingForm.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/mute-timings/MuteTimingTimeInterval.tsx": { "public/app/features/alerting/unified/components/mute-timings/MuteTimingTimeInterval.tsx": {
"no-restricted-syntax": { "no-restricted-syntax": {
"count": 5 "count": 5
@@ -1521,11 +1516,6 @@
"count": 1 "count": 1
} }
}, },
"public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/MuteTimingFields.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/RouteSettings.tsx": { "public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/RouteSettings.tsx": {
"no-restricted-syntax": { "no-restricted-syntax": {
"count": 1 "count": 1
@@ -54,6 +54,24 @@ export const ImportedContactPointAlert = (props: ExtraAlertProps) => {
); );
}; };
export const ImportedTimeIntervalAlert = (props: ExtraAlertProps) => {
return (
<Alert
title={t(
'alerting.provisioning.title-imported-time-interval',
'This time interval was imported and cannot be edited through the UI'
)}
severity="info"
{...props}
>
<Trans i18nKey="alerting.provisioning.body-imported-time-interval">
This time interval was imported from an external Alertmanager and is currently read-only. The time interval will
become editable after the migration process is complete.
</Trans>
</Alert>
);
};
export const ProvisioningBadge = ({ export const ProvisioningBadge = ({
tooltip, tooltip,
provenance, provenance,
@@ -0,0 +1,130 @@
import { render, screen, userEvent } from 'test/test-utils';
import { setupMswServer } from 'app/features/alerting/unified/mockApi';
import { grantUserPermissions } from 'app/features/alerting/unified/mocks';
import { setTimeIntervalsList } from 'app/features/alerting/unified/mocks/server/configure';
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { AccessControlAction } from 'app/types/accessControl';
import MuteTimingsSelector from './MuteTimingsSelector';
const renderWithProvider = (alertManagerSource = GRAFANA_RULES_SOURCE_NAME) => {
return render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName={alertManagerSource}>
<MuteTimingsSelector
alertmanager={alertManagerSource}
selectProps={{
onChange: () => {},
}}
/>
</AlertmanagerProvider>
);
};
setupMswServer();
describe('MuteTimingsSelector', () => {
beforeEach(() => {
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
it('should show all non-imported time intervals', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'regular-interval', provenance: 'none' },
{ name: 'file-provisioned', provenance: 'file' },
{ name: 'another-regular', provenance: 'none' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// All non-imported intervals should be visible
expect(await screen.findByText('regular-interval')).toBeInTheDocument();
expect(screen.getByText('file-provisioned')).toBeInTheDocument();
expect(screen.getByText('another-regular')).toBeInTheDocument();
});
it('should filter out imported time intervals (provenance: prometheus_convert)', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'regular-interval', provenance: 'none' },
{ name: 'imported-interval', provenance: 'prometheus_convert' },
{ name: 'file-provisioned', provenance: 'file' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// Regular and file-provisioned should be visible
expect(await screen.findByText('regular-interval')).toBeInTheDocument();
expect(screen.getByText('file-provisioned')).toBeInTheDocument();
// Imported interval should NOT be in the list
expect(screen.queryByText('imported-interval')).not.toBeInTheDocument();
});
it('should show only non-imported intervals when all types are present', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'normal-1', provenance: 'none' },
{ name: 'imported-1', provenance: 'prometheus_convert' },
{ name: 'normal-2', provenance: 'none' },
{ name: 'imported-2', provenance: 'prometheus_convert' },
{ name: 'file-1', provenance: 'file' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// Non-imported intervals should be visible
expect(await screen.findByText('normal-1')).toBeInTheDocument();
expect(screen.getByText('normal-2')).toBeInTheDocument();
expect(screen.getByText('file-1')).toBeInTheDocument();
// Imported intervals should NOT be visible
expect(screen.queryByText('imported-1')).not.toBeInTheDocument();
expect(screen.queryByText('imported-2')).not.toBeInTheDocument();
});
it('should handle empty list', async () => {
setTimeIntervalsList([]);
renderWithProvider();
// Selector should be present but have no options
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
expect(selector).toBeInTheDocument();
});
it('should handle list with only imported intervals', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'imported-1', provenance: 'prometheus_convert' },
{ name: 'imported-2', provenance: 'prometheus_convert' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// No intervals should be visible
expect(screen.queryByText('imported-1')).not.toBeInTheDocument();
expect(screen.queryByText('imported-2')).not.toBeInTheDocument();
});
});
@@ -1,17 +1,25 @@
import { SelectableValue } from '@grafana/data'; import { SelectableValue } from '@grafana/data';
import { t } from '@grafana/i18n'; import { t } from '@grafana/i18n';
import { MultiSelect, MultiSelectCommonProps } from '@grafana/ui'; import { MultiSelect, MultiSelectCommonProps } from '@grafana/ui';
import { useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings'; import { MuteTiming, useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { BaseAlertmanagerArgs } from 'app/features/alerting/unified/types/hooks'; import { BaseAlertmanagerArgs } from 'app/features/alerting/unified/types/hooks';
import { timeIntervalToString } from 'app/features/alerting/unified/utils/alertmanager'; import { timeIntervalToString } from 'app/features/alerting/unified/utils/alertmanager';
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types'; import { K8sAnnotations } from 'app/features/alerting/unified/utils/k8s/constants';
const mapTimeInterval = ({ name, time_intervals }: MuteTimeInterval): SelectableValue<string> => ({ const PROMETHEUS_CONVERT_PROVENANCE = 'prometheus_convert';
const mapTimeInterval = ({ name, time_intervals }: MuteTiming): SelectableValue<string> => ({
value: name, value: name,
label: name, label: name,
description: time_intervals.map((interval) => timeIntervalToString(interval)).join(', AND '), description: time_intervals.map((interval) => timeIntervalToString(interval)).join(', AND '),
}); });
/** Check if a time interval was imported from an external Alertmanager */
const isImportedTimeInterval = (timing: MuteTiming): boolean => {
const provenance = timing.metadata?.annotations?.[K8sAnnotations.Provenance];
return provenance === PROMETHEUS_CONVERT_PROVENANCE;
};
/** Provides a MultiSelect with available time intervals for the given alertmanager */ /** Provides a MultiSelect with available time intervals for the given alertmanager */
const TimeIntervalSelector = ({ const TimeIntervalSelector = ({
alertmanager, alertmanager,
@@ -19,7 +27,9 @@ const TimeIntervalSelector = ({
}: BaseAlertmanagerArgs & { selectProps: MultiSelectCommonProps<string> }) => { }: BaseAlertmanagerArgs & { selectProps: MultiSelectCommonProps<string> }) => {
const { data } = useMuteTimings({ alertmanager, skip: selectProps.disabled }); const { data } = useMuteTimings({ alertmanager, skip: selectProps.disabled });
const timeIntervalOptions = data?.map((value) => mapTimeInterval(value)) || []; // Filter out imported time intervals (provenance === 'prometheus_convert')
const availableTimings = data?.filter((timing) => !isImportedTimeInterval(timing)) || [];
const timeIntervalOptions = availableTimings.map((value) => mapTimeInterval(value));
return ( return (
<MultiSelect <MultiSelect
@@ -3,6 +3,7 @@ import { Navigate } from 'react-router-dom-v5-compat';
import { t } from '@grafana/i18n'; import { t } from '@grafana/i18n';
import { useGetMuteTiming } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings'; import { useGetMuteTiming } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { useURLSearchParams } from 'app/features/alerting/unified/hooks/useURLSearchParams'; import { useURLSearchParams } from 'app/features/alerting/unified/hooks/useURLSearchParams';
import { K8sAnnotations } from 'app/features/alerting/unified/utils/k8s/constants';
import { useAlertmanager } from '../../state/AlertmanagerContext'; import { useAlertmanager } from '../../state/AlertmanagerContext';
import { withPageErrorBoundary } from '../../withPageErrorBoundary'; import { withPageErrorBoundary } from '../../withPageErrorBoundary';
@@ -28,13 +29,15 @@ const EditTimingRoute = () => {
return <Navigate replace to="/alerting/routes" />; return <Navigate replace to="/alerting/routes" />;
} }
const provenance = timeInterval?.metadata?.annotations?.[K8sAnnotations.Provenance];
return ( return (
<MuteTimingForm <MuteTimingForm
editMode editMode
loading={isLoading} loading={isLoading}
showError={isError} showError={isError}
muteTiming={timeInterval} muteTiming={timeInterval}
provisioned={timeInterval?.provisioned} provenance={provenance}
/> />
); );
}; };
@@ -0,0 +1,103 @@
import { render, screen } from 'test/test-utils';
import { setupMswServer } from 'app/features/alerting/unified/mockApi';
import { grantUserPermissions } from 'app/features/alerting/unified/mocks';
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { AccessControlAction } from 'app/types/accessControl';
import MuteTimingForm from './MuteTimingForm';
import { muteTimeInterval } from './mocks';
const renderWithProvider = (provenance?: string, editMode = false) => {
return render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName={GRAFANA_RULES_SOURCE_NAME}>
<MuteTimingForm
muteTiming={muteTimeInterval}
provenance={provenance}
editMode={editMode}
loading={false}
showError={false}
/>
</AlertmanagerProvider>
);
};
setupMswServer();
describe('MuteTimingForm', () => {
beforeEach(() => {
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
it('should not show any alert when provenance is none', async () => {
renderWithProvider('none');
expect(screen.queryByText(/imported and cannot be edited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/provisioned/i)).not.toBeInTheDocument();
});
it('should not show any alert when provenance is undefined', async () => {
renderWithProvider(undefined);
expect(screen.queryByText(/imported and cannot be edited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/provisioned/i)).not.toBeInTheDocument();
});
it('should show imported alert when provenance is prometheus_convert', async () => {
renderWithProvider('prometheus_convert');
expect(
await screen.findByText(/This time interval was imported and cannot be edited through the UI/i)
).toBeInTheDocument();
expect(
screen.getByText(/This time interval was imported from an external Alertmanager and is currently read-only/i)
).toBeInTheDocument();
});
it('should show provisioning alert when provenance is file', async () => {
renderWithProvider('file');
expect(await screen.findByText(/This time interval cannot be edited through the UI/i)).toBeInTheDocument();
expect(
screen.getByText(/This time interval has been provisioned, that means it was created by config/i)
).toBeInTheDocument();
});
it('should show provisioning alert for other provenance types', async () => {
renderWithProvider('api');
expect(await screen.findByText(/This time interval cannot be edited through the UI/i)).toBeInTheDocument();
});
it('should disable form when provenance is prometheus_convert', async () => {
renderWithProvider('prometheus_convert', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeDisabled();
});
it('should disable form when provenance is file', async () => {
renderWithProvider('file', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeDisabled();
});
it('should enable form when provenance is none', async () => {
renderWithProvider('none', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeEnabled();
});
it('should enable form when provenance is undefined', async () => {
renderWithProvider(undefined, true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeEnabled();
});
});
@@ -14,18 +14,21 @@ import {
import { useAlertmanager } from '../../state/AlertmanagerContext'; import { useAlertmanager } from '../../state/AlertmanagerContext';
import { MuteTimingFields } from '../../types/mute-timing-form'; import { MuteTimingFields } from '../../types/mute-timing-form';
import { PROVENANCE_NONE } from '../../utils/k8s/constants';
import { makeAMLink } from '../../utils/misc'; import { makeAMLink } from '../../utils/misc';
import { createMuteTiming, defaultTimeInterval, isTimeIntervalDisabled } from '../../utils/mute-timings'; import { createMuteTiming, defaultTimeInterval, isTimeIntervalDisabled } from '../../utils/mute-timings';
import { ProvisionedResource, ProvisioningAlert } from '../Provisioning'; import { ImportedTimeIntervalAlert, ProvisionedResource, ProvisioningAlert } from '../Provisioning';
import { MuteTimingTimeInterval } from './MuteTimingTimeInterval'; import { MuteTimingTimeInterval } from './MuteTimingTimeInterval';
const PROMETHEUS_CONVERT_PROVENANCE = 'prometheus_convert';
interface Props { interface Props {
muteTiming?: MuteTiming; muteTiming?: MuteTiming;
showError?: boolean; showError?: boolean;
loading?: boolean; loading?: boolean;
/** Is the current mute timing provisioned? If so, will disable editing via UI */ /** Provenance of the mute timing - indicates how it was created (e.g., 'file', 'prometheus_convert', 'none') */
provisioned?: boolean; provenance?: string;
/** Are we editing an existing time interval? */ /** Are we editing an existing time interval? */
editMode?: boolean; editMode?: boolean;
} }
@@ -56,7 +59,7 @@ const useDefaultValues = (muteTiming?: MuteTiming): MuteTimingFields => {
}; };
}; };
const MuteTimingForm = ({ muteTiming, showError, loading, provisioned, editMode }: Props) => { const MuteTimingForm = ({ muteTiming, showError, loading, provenance, editMode }: Props) => {
const { selectedAlertmanager } = useAlertmanager(); const { selectedAlertmanager } = useAlertmanager();
const hookArgs = { alertmanager: selectedAlertmanager! }; const hookArgs = { alertmanager: selectedAlertmanager! };
@@ -105,14 +108,19 @@ const MuteTimingForm = ({ muteTiming, showError, loading, provisioned, editMode
); );
} }
const isProvisioned = Boolean(provenance && provenance !== PROVENANCE_NONE);
const isImported = provenance === PROMETHEUS_CONVERT_PROVENANCE;
return ( return (
<> <>
{provisioned && <ProvisioningAlert resource={ProvisionedResource.MuteTiming} />} {isProvisioned && isImported && <ImportedTimeIntervalAlert />}
{isProvisioned && !isImported && <ProvisioningAlert resource={ProvisionedResource.MuteTiming} />}
<FormProvider {...formApi}> <FormProvider {...formApi}>
<form onSubmit={formApi.handleSubmit(onSubmit)} data-testid="mute-timing-form"> <form onSubmit={formApi.handleSubmit(onSubmit)} data-testid="mute-timing-form">
<FieldSet disabled={provisioned || updating}> <FieldSet disabled={isProvisioned || updating}>
<Field <Field
required required
noMargin
label={t('alerting.mute-timing-form.label-name', 'Name')} label={t('alerting.mute-timing-form.label-name', 'Name')}
description={t( description={t(
'alerting.time-interval-form.description-unique-time-interval', 'alerting.time-interval-form.description-unique-time-interval',
@@ -27,6 +27,7 @@ export function MuteTimingFields({ alertmanager }: BaseAlertmanagerArgs) {
)} )}
className={styles.muteTimingField} className={styles.muteTimingField}
invalid={!!errors.contactPoints?.[alertmanager]?.muteTimeIntervals} invalid={!!errors.contactPoints?.[alertmanager]?.muteTimeIntervals}
noMargin
> >
<Controller <Controller
render={({ field: { onChange, ref, ...field } }) => ( render={({ field: { onChange, ref, ...field } }) => (
@@ -175,6 +175,36 @@ export const setTimeIntervalsListEmpty = () => {
return handler; return handler;
}; };
interface TimeIntervalConfig {
name: string;
provenance?: string;
}
/**
* Makes the mock server respond with custom time intervals
*/
export const setTimeIntervalsList = (intervals: TimeIntervalConfig[]) => {
const listMuteTimingsPath = listNamespacedTimeIntervalHandler().info.path;
const handler = http.get(listMuteTimingsPath, () => {
const items = intervals.map((interval) => ({
metadata: {
annotations: {
'grafana.com/provenance': interval.provenance ?? 'none',
},
name: interval.name,
uid: `uid-${interval.name}`,
namespace: 'default',
resourceVersion: 'e0270bfced786660',
},
spec: { name: interval.name, time_intervals: [] },
}));
return HttpResponse.json(getK8sResponse('TimeIntervalList', items));
});
server.use(handler);
return handler;
};
export function mimirDataSource() { export function mimirDataSource() {
const dataSource = mockDataSource( const dataSource = mockDataSource(
{ {
+2
View File
@@ -2178,8 +2178,10 @@
"badge-tooltip-provenance": "This resource has been provisioned via {{provenance}} and cannot be edited through the UI", "badge-tooltip-provenance": "This resource has been provisioned via {{provenance}} and cannot be edited through the UI",
"badge-tooltip-standard": "This resource has been provisioned and cannot be edited through the UI", "badge-tooltip-standard": "This resource has been provisioned and cannot be edited through the UI",
"body-imported": "This contact point contains integrations that were imported from an external Alertmanager and is currently read-only. The integrations will become editable after the migration process is complete.", "body-imported": "This contact point contains integrations that were imported from an external Alertmanager and is currently read-only. The integrations will become editable after the migration process is complete.",
"body-imported-time-interval": "This time interval was imported from an external Alertmanager and is currently read-only. The time interval will become editable after the migration process is complete.",
"body-provisioned": "This {{resource}} has been provisioned, that means it was created by config. Please contact your server admin to update this {{resource}}.", "body-provisioned": "This {{resource}} has been provisioned, that means it was created by config. Please contact your server admin to update this {{resource}}.",
"title-imported": "This contact point was imported and cannot be edited through the UI", "title-imported": "This contact point was imported and cannot be edited through the UI",
"title-imported-time-interval": "This time interval was imported and cannot be edited through the UI",
"title-provisioned": "This {{resource}} cannot be edited through the UI" "title-provisioned": "This {{resource}} cannot be edited through the UI"
}, },
"provisioning-badge": { "provisioning-badge": {