Alerting: Edit, create and delete contact points via k8s API (#91701)

This commit is contained in:
Tom Ratcliffe 2024-08-30 12:10:30 +01:00 committed by GitHub
parent f4a8e0a214
commit 690fbe6077
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
40 changed files with 1091 additions and 623 deletions

View File

@ -1817,9 +1817,6 @@ exports[`better eslint`] = {
"public/app/features/alerting/unified/components/receivers/DuplicateTemplateView.tsx:5381": [
[0, 0, 0, "No untranslated strings. Wrap text with <Trans />", "0"]
],
"public/app/features/alerting/unified/components/receivers/EditReceiverView.tsx:5381": [
[0, 0, 0, "No untranslated strings. Wrap text with <Trans />", "0"]
],
"public/app/features/alerting/unified/components/receivers/EditTemplateView.tsx:5381": [
[0, 0, 0, "No untranslated strings. Wrap text with <Trans />", "0"]
],
@ -5856,8 +5853,7 @@ exports[`better eslint`] = {
],
"public/app/plugins/datasource/alertmanager/types.ts:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"],
[0, 0, 0, "Unexpected any. Specify a different type.", "1"],
[0, 0, 0, "Unexpected any. Specify a different type.", "2"]
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
],
"public/app/plugins/datasource/azuremonitor/azureMetadata/index.ts:5381": [
[0, 0, 0, "Do not use export all (\`export * from ...\`)", "0"],

View File

@ -7,14 +7,14 @@ import { AlertmanagerPageWrapper } from './components/AlertingPageWrapper';
const ContactPointsV2 = SafeDynamicImport(() => import('./components/contact-points/ContactPoints'));
const EditContactPoint = SafeDynamicImport(() => import('./components/contact-points/EditContactPoint'));
const NewContactPoint = SafeDynamicImport(() => import('./components/contact-points/NewContactPoint'));
const NewReceiverView = SafeDynamicImport(() => import('./components/receivers/NewReceiverView'));
const GlobalConfig = SafeDynamicImport(() => import('./components/contact-points/components/GlobalConfig'));
const ContactPoints = (): JSX.Element => (
<AlertmanagerPageWrapper navId="receivers" accessType="notification">
<Switch>
<Route exact={true} path="/alerting/notifications" component={ContactPointsV2} />
<Route exact={true} path="/alerting/notifications/receivers/new" component={NewContactPoint} />
<Route exact={true} path="/alerting/notifications/receivers/new" component={NewReceiverView} />
<Route exact={true} path="/alerting/notifications/receivers/:name/edit" component={EditContactPoint} />
<Route exact={true} path="/alerting/notifications/global-config" component={GlobalConfig} />
</Switch>

View File

@ -113,6 +113,9 @@ export const alertingApi = createApi({
'GrafanaSlo',
'RuleGroup',
'RuleNamespace',
'ContactPoint',
'ContactPointsStatus',
'Receiver',
],
endpoints: () => ({}),
});

View File

@ -47,6 +47,20 @@ interface AlertmanagerAlertsFilter {
matchers?: Matcher[];
}
/**
* List of tags corresponding to entities that are implicitly provided by an alert manager configuration.
*
* i.e. "things that should be fetched fresh if the AM config has changed"
*/
export const ALERTMANAGER_PROVIDED_ENTITY_TAGS = [
'AlertingConfiguration',
'AlertmanagerConfiguration',
'AlertmanagerConnectionStatus',
'ContactPoint',
'ContactPointsStatus',
'Receiver',
] as const;
// Based on https://github.com/prometheus/alertmanager/blob/main/api/v2/openapi.yaml
export const alertmanagerApi = alertingApi.injectEndpoints({
endpoints: (build) => ({
@ -120,7 +134,7 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
data: config,
showSuccessAlert: false,
}),
invalidatesTags: ['AlertingConfiguration', 'AlertmanagerConfiguration', 'AlertmanagerConnectionStatus'],
invalidatesTags: [...ALERTMANAGER_PROVIDED_ENTITY_TAGS],
}),
getAlertmanagerConfigurationHistory: build.query<AlertManagerCortexConfig[], void>({
@ -248,7 +262,7 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
data: config,
showSuccessAlert: false,
}),
invalidatesTags: ['AlertmanagerConfiguration'],
invalidatesTags: ['AlertmanagerConfiguration', 'ContactPoint', 'ContactPointsStatus', 'Receiver'],
}),
// Grafana Managed Alertmanager only
@ -274,12 +288,13 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
}),
}));
},
providesTags: ['ContactPointsStatus'],
}),
// Grafana Managed Alertmanager only
// TODO: Remove as part of migration to k8s API for receivers
getContactPointsList: build.query<GrafanaManagedContactPoint[], void>({
query: () => ({ url: '/api/v1/notifications/receivers' }),
providesTags: ['AlertmanagerConfiguration'],
providesTags: ['ContactPoint'],
}),
getMuteTimingList: build.query<MuteTimeInterval[], void>({
query: () => ({ url: '/api/v1/notifications/time-intervals' }),

View File

@ -1,3 +1,5 @@
/** @deprecated To be deleted - use alertingApiServer API instead */
import { ContactPointsState } from 'app/types';
import { CONTACT_POINTS_STATE_INTERVAL_MS } from '../utils/constants';

View File

@ -0,0 +1,22 @@
import { generatedReceiversApi } from 'app/features/alerting/unified/openapi/receiversApi.gen';
export const receiversApi = generatedReceiversApi.enhanceEndpoints({
endpoints: {
createNamespacedReceiver: {
invalidatesTags: ['Receiver', 'ContactPoint', 'ContactPointsStatus', 'AlertmanagerConfiguration'],
},
// Add the content-type header, as otherwise the inner workings of
// backend_srv will not realise the body is supposed to be JSON
// and will incorrectly serialise the body as URLSearchParams
deleteNamespacedReceiver: (endpoint) => {
const originalQuery = endpoint.query;
endpoint.query = (...args) => {
const baseQuery = originalQuery!(...args);
baseQuery.headers = {
'content-type': 'application/json',
};
return baseQuery;
};
},
},
});

View File

@ -7,6 +7,9 @@ import { Icon, Stack, Text, Tooltip, useStyles2 } from '@grafana/ui';
import { Trans } from 'app/core/internationalization';
import { PrimaryText } from 'app/features/alerting/unified/components/common/TextVariants';
import { ContactPointHeader } from 'app/features/alerting/unified/components/contact-points/ContactPointHeader';
import { useDeleteContactPointModal } from 'app/features/alerting/unified/components/contact-points/components/Modals';
import { useDeleteContactPoint } from 'app/features/alerting/unified/components/contact-points/useContactPoints';
import { useAlertmanager } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { receiverTypeNames } from 'app/plugins/datasource/alertmanager/consts';
import { GrafanaNotifierType, NotifierStatus } from 'app/types/alerting';
@ -16,26 +19,19 @@ import { ReceiverMetadataBadge } from '../receivers/grafanaAppReceivers/Receiver
import { ReceiverPluginMetadata } from '../receivers/grafanaAppReceivers/useReceiversMetadata';
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from './constants';
import { getReceiverDescription, ReceiverConfigWithMetadata, RouteReference } from './utils';
import { ContactPointWithMetadata, getReceiverDescription, ReceiverConfigWithMetadata } from './utils';
interface ContactPointProps {
name: string;
disabled?: boolean;
provisioned?: boolean;
receivers: ReceiverConfigWithMetadata[];
policies?: RouteReference[];
onDelete: (name: string) => void;
contactPoint: ContactPointWithMetadata;
}
export const ContactPoint = ({
name,
disabled = false,
provisioned = false,
receivers,
policies = [],
onDelete,
}: ContactPointProps) => {
export const ContactPoint = ({ disabled = false, contactPoint }: ContactPointProps) => {
const { grafana_managed_receiver_configs: receivers } = contactPoint;
const styles = useStyles2(getStyles);
const { selectedAlertmanager } = useAlertmanager();
const handleDelete = useDeleteContactPoint({ alertmanager: selectedAlertmanager! });
const [DeleteModal, showDeleteModal] = useDeleteContactPointModal(handleDelete);
// TODO probably not the best way to figure out if we want to show either only the summary or full metadata for the receivers?
const showFullMetadata = receivers.some((receiver) => Boolean(receiver[RECEIVER_META_KEY]));
@ -44,11 +40,14 @@ export const ContactPoint = ({
<div className={styles.contactPointWrapper} data-testid="contact-point">
<Stack direction="column" gap={0}>
<ContactPointHeader
name={name}
policies={policies}
provisioned={provisioned}
contactPoint={contactPoint}
disabled={disabled}
onDelete={onDelete}
onDelete={(contactPointToDelete) =>
showDeleteModal({
name: contactPointToDelete.id || contactPointToDelete.name,
resourceVersion: contactPointToDelete.metadata?.resourceVersion,
})
}
/>
{showFullMetadata ? (
<div>
@ -58,7 +57,6 @@ export const ContactPoint = ({
const sendingResolved = !Boolean(receiver.disableResolveMessage);
const pluginMetadata = receiver[RECEIVER_PLUGIN_META_KEY];
const key = metadata.name + index;
return (
<ContactPointReceiver
key={key}
@ -78,6 +76,7 @@ export const ContactPoint = ({
</div>
)}
</Stack>
{DeleteModal}
</div>
);
};

View File

@ -6,6 +6,7 @@ import { Dropdown, LinkButton, Menu, Stack, Text, TextLink, Tooltip, useStyles2
import { t } from 'app/core/internationalization';
import ConditionalWrap from 'app/features/alerting/unified/components/ConditionalWrap';
import { useExportContactPoint } from 'app/features/alerting/unified/components/contact-points/useExportContactPoint';
import { PROVENANCE_ANNOTATION } from 'app/features/alerting/unified/utils/k8s/constants';
import { AlertmanagerAction, useAlertmanagerAbility } from '../../hooks/useAbilities';
import { createRelativeUrl } from '../../utils/url';
@ -14,18 +15,16 @@ import { ProvisioningBadge } from '../Provisioning';
import { Spacer } from '../Spacer';
import { UnusedContactPointBadge } from './components/UnusedBadge';
import { RouteReference } from './utils';
import { ContactPointWithMetadata } from './utils';
interface ContactPointHeaderProps {
name: string;
contactPoint: ContactPointWithMetadata;
disabled?: boolean;
provisioned?: boolean;
policies?: RouteReference[];
onDelete: (name: string) => void;
onDelete: (contactPoint: ContactPointWithMetadata) => void;
}
export const ContactPointHeader = (props: ContactPointHeaderProps) => {
const { name, disabled = false, provisioned = false, policies = [], onDelete } = props;
export const ContactPointHeader = ({ contactPoint, disabled = false, onDelete }: ContactPointHeaderProps) => {
const { name, id, provisioned, policies = [] } = contactPoint;
const styles = useStyles2(getStyles);
const [exportSupported, exportAllowed] = useAlertmanagerAbility(AlertmanagerAction.ExportContactPoint);
@ -76,7 +75,7 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
icon="trash-alt"
destructive
disabled={disabled || !canDelete}
onClick={() => onDelete(name)}
onClick={() => onDelete(contactPoint)}
/>
</ConditionalWrap>
);
@ -86,6 +85,10 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
count: numberOfPolicies,
});
// TOOD: Tidy up/consolidate logic for working out id for contact point. This requires some unravelling of
// existing types so its clearer where the ID has come from
const urlId = id || name;
return (
<div className={styles.headerWrapper}>
<Stack direction="row" alignItems="center" gap={1}>
@ -104,7 +107,9 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
{referencedByPoliciesText}
</TextLink>
)}
{provisioned && <ProvisioningBadge />}
{provisioned && (
<ProvisioningBadge tooltip provenance={contactPoint.metadata?.annotations?.[PROVENANCE_ANNOTATION]} />
)}
{!isReferencedByAnyPolicy && <UnusedContactPointBadge />}
<Spacer />
<LinkButton
@ -117,13 +122,13 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
disabled={disabled}
aria-label={`${canEdit ? 'edit' : 'view'}-action`}
data-testid={`${canEdit ? 'edit' : 'view'}-action`}
href={`/alerting/notifications/receivers/${encodeURIComponent(name)}/edit`}
href={`/alerting/notifications/receivers/${encodeURIComponent(urlId)}/edit`}
>
{canEdit ? 'Edit' : 'View'}
</LinkButton>
{menuActions.length > 0 && (
<Dropdown overlay={<Menu>{menuActions}</Menu>}>
<MoreButton />
<MoreButton aria-label={`More actions for contact point "${contactPoint.name}"`} />
</Dropdown>
)}
</Stack>

View File

@ -1,10 +1,9 @@
import userEvent from '@testing-library/user-event';
import { MemoryHistoryBuildOptions } from 'history';
import { noop } from 'lodash';
import { ComponentProps, ReactNode } from 'react';
import { render, screen, waitFor, waitForElementToBeRemoved } from 'test/test-utils';
import { render, screen, userEvent, waitFor, waitForElementToBeRemoved } from 'test/test-utils';
import { selectors } from '@grafana/e2e-selectors';
import { config } from '@grafana/runtime';
import { AlertManagerDataSourceJsonData, AlertManagerImplementation } from 'app/plugins/datasource/alertmanager/types';
import { AccessControlAction } from 'app/types';
@ -12,7 +11,7 @@ import { setupMswServer } from '../../mockApi';
import { grantUserPermissions, mockDataSource } from '../../mocks';
import { AlertmanagerProvider } from '../../state/AlertmanagerContext';
import { setupDataSources } from '../../testSetup/datasources';
import { DataSourceType } from '../../utils/datasource';
import { DataSourceType, GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
import { ContactPoint } from './ContactPoint';
import ContactPointsPageContents from './ContactPoints';
@ -20,7 +19,7 @@ import setupMimirFlavoredServer, { MIMIR_DATASOURCE_UID } from './__mocks__/mimi
import setupVanillaAlertmanagerFlavoredServer, {
VANILLA_ALERTMANAGER_DATASOURCE_UID,
} from './__mocks__/vanillaAlertmanagerServer';
import { RouteReference } from './utils';
import { ContactPointWithMetadata, RouteReference } from './utils';
/**
* There are lots of ways in which we test our pages and components. Here's my opinionated approach to testing them.
@ -52,6 +51,24 @@ const renderWithProvider = (
{ historyOptions }
);
const basicContactPoint: ContactPointWithMetadata = {
name: 'my-contact-point',
id: 'foo',
grafana_managed_receiver_configs: [],
};
const attemptDeleteContactPoint = async (name: string) => {
const user = userEvent.setup();
const moreActions = await screen.findByRole('button', { name: `More actions for contact point "${name}"` });
await user.click(moreActions);
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
await user.click(deleteButton);
await screen.findByRole('heading', { name: /delete contact point/i });
return user.click(await screen.findByRole('button', { name: /delete contact point/i }));
};
describe('contact points', () => {
describe('Contact points with Grafana managed alertmanager', () => {
beforeEach(() => {
@ -124,7 +141,7 @@ describe('contact points', () => {
it('should disable certain actions if the user has no write permissions', async () => {
grantUserPermissions([AccessControlAction.AlertingNotificationsRead]);
renderWithProvider(<ContactPointsPageContents />);
const { user } = renderWithProvider(<ContactPointsPageContents />);
// wait for loading to be done
await waitForElementToBeRemoved(screen.queryByText('Loading...'));
@ -145,34 +162,33 @@ describe('contact points', () => {
// check if all of the delete buttons are disabled
for await (const button of moreButtons) {
await userEvent.click(button);
await user.click(button);
const deleteButton = screen.queryByRole('menuitem', { name: 'delete' });
expect(deleteButton).toBeDisabled();
// click outside the menu to close it otherwise we can't interact with the rest of the page
await userEvent.click(document.body);
await user.click(document.body);
}
// check buttons in Notification Templates
const notificationTemplatesTab = screen.getByRole('tab', { name: 'Notification Templates' });
await userEvent.click(notificationTemplatesTab);
await user.click(notificationTemplatesTab);
expect(screen.getByRole('link', { name: 'Add notification template' })).toHaveAttribute('aria-disabled', 'true');
});
it('should call delete when clicked and not disabled', async () => {
const onDelete = jest.fn();
renderWithProvider(<ContactPoint name={'my-contact-point'} receivers={[]} onDelete={onDelete} />);
it('allows deleting when not disabled', async () => {
renderWithProvider(
<ContactPointsPageContents />,
{ initialEntries: ['/?tab=contact_points'] },
{ alertmanagerSourceName: GRAFANA_RULES_SOURCE_NAME }
);
const moreActions = screen.getByRole('button', { name: /More/ });
await userEvent.click(moreActions);
await attemptDeleteContactPoint('lotsa-emails');
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
await userEvent.click(deleteButton);
expect(onDelete).toHaveBeenCalledWith('my-contact-point');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('should disable edit button', async () => {
renderWithProvider(<ContactPoint name={'my-contact-point'} disabled={true} receivers={[]} onDelete={noop} />);
renderWithProvider(<ContactPoint contactPoint={basicContactPoint} disabled={true} />);
const moreActions = screen.getByRole('button', { name: /More/ });
expect(moreActions).toBeEnabled();
@ -182,7 +198,7 @@ describe('contact points', () => {
});
it('should disable buttons when provisioned', async () => {
renderWithProvider(<ContactPoint name={'my-contact-point'} provisioned={true} receivers={[]} onDelete={noop} />);
const { user } = renderWithProvider(<ContactPoint contactPoint={{ ...basicContactPoint, provisioned: true }} />);
expect(screen.getByText(/provisioned/i)).toBeInTheDocument();
@ -194,7 +210,7 @@ describe('contact points', () => {
const moreActions = screen.getByRole('button', { name: /More/ });
expect(moreActions).toBeEnabled();
await userEvent.click(moreActions);
await user.click(moreActions);
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
expect(deleteButton).toBeDisabled();
@ -210,12 +226,12 @@ describe('contact points', () => {
},
];
renderWithProvider(<ContactPoint name={'my-contact-point'} receivers={[]} policies={policies} onDelete={noop} />);
const { user } = renderWithProvider(<ContactPoint contactPoint={{ ...basicContactPoint, policies }} />);
expect(screen.getByRole('link', { name: /1 notification policy/ })).toBeInTheDocument();
const moreActions = screen.getByRole('button', { name: /More/ });
await userEvent.click(moreActions);
await user.click(moreActions);
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
expect(deleteButton).toBeDisabled();
@ -231,20 +247,20 @@ describe('contact points', () => {
},
];
renderWithProvider(<ContactPoint name={'my-contact-point'} receivers={[]} policies={policies} onDelete={noop} />);
const { user } = renderWithProvider(<ContactPoint contactPoint={{ ...basicContactPoint, policies }} />);
const moreActions = screen.getByRole('button', { name: /More/ });
await userEvent.click(moreActions);
await user.click(moreActions);
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
expect(deleteButton).toBeEnabled();
});
it('should be able to search', async () => {
renderWithProvider(<ContactPointsPageContents />);
const { user } = renderWithProvider(<ContactPointsPageContents />);
const searchInput = await screen.findByRole('textbox', { name: 'search contact points' });
await userEvent.type(searchInput, 'slack');
await user.type(searchInput, 'slack');
expect(searchInput).toHaveValue('slack');
expect(await screen.findByText('Slack with multiple channels')).toBeInTheDocument();
@ -254,7 +270,7 @@ describe('contact points', () => {
// ⚠️ for some reason, the query params are preserved for all tests so don't forget to clear the input
const clearButton = screen.getByRole('button', { name: 'clear' });
await userEvent.click(clearButton);
await user.click(clearButton);
expect(searchInput).toHaveValue('');
});
});
@ -332,7 +348,7 @@ describe('contact points', () => {
});
it("should not allow any editing because it's not supported", async () => {
renderWithProvider(<ContactPointsPageContents />, undefined, {
const { user } = renderWithProvider(<ContactPointsPageContents />, undefined, {
alertmanagerSourceName: VANILLA_ALERTMANAGER_DATASOURCE_UID,
});
@ -347,8 +363,45 @@ describe('contact points', () => {
// check buttons in Notification Templates
const notificationTemplatesTab = screen.getByRole('tab', { name: 'Notification Templates' });
await userEvent.click(notificationTemplatesTab);
await user.click(notificationTemplatesTab);
expect(screen.queryByRole('link', { name: 'Add notification template' })).not.toBeInTheDocument();
});
});
describe('alertingApiServer enabled', () => {
beforeEach(() => {
config.featureToggles.alertingApiServer = true;
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
const renderGrafanaContactPoints = () =>
renderWithProvider(
<ContactPointsPageContents />,
{ initialEntries: ['/?tab=contact_points'] },
{ alertmanagerSourceName: GRAFANA_RULES_SOURCE_NAME }
);
it('renders list view correctly', async () => {
renderGrafanaContactPoints();
// Check for a specific contact point that we expect to exist in the mock AM config/k8s response
expect(await screen.findByRole('heading', { name: 'lotsa-emails' })).toBeInTheDocument();
});
it('allows deleting', async () => {
renderGrafanaContactPoints();
await attemptDeleteContactPoint('lotsa-emails');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('does not allow deletion of provisioned contact points', async () => {
renderGrafanaContactPoints();
return expect(attemptDeleteContactPoint('provisioned-contact-point')).rejects.toBeTruthy();
});
});
});

View File

@ -25,11 +25,10 @@ import { ContactPoint } from './ContactPoint';
import { NotificationTemplates } from './NotificationTemplates';
import { ContactPointsFilter } from './components/ContactPointsFilter';
import { GlobalConfigAlert } from './components/GlobalConfigAlert';
import { useDeleteContactPointModal } from './components/Modals';
import { useContactPointsWithStatus, useDeleteContactPoint } from './useContactPoints';
import { useContactPointsWithStatus } from './useContactPoints';
import { useContactPointsSearch } from './useContactPointsSearch';
import { ALL_CONTACT_POINTS, useExportContactPoint } from './useExportContactPoint';
import { ContactPointWithMetadata, isProvisioned } from './utils';
import { ContactPointWithMetadata } from './utils';
export enum ActiveTab {
ContactPoints = 'contact_points',
@ -48,7 +47,6 @@ const ContactPointsTab = () => {
fetchStatuses: true,
});
const { deleteTrigger, updateAlertmanagerState } = useDeleteContactPoint(selectedAlertmanager!);
const [addContactPointSupported, addContactPointAllowed] = useAlertmanagerAbility(
AlertmanagerAction.CreateContactPoint
);
@ -56,7 +54,6 @@ const ContactPointsTab = () => {
AlertmanagerAction.ExportContactPoint
);
const [DeleteModal, showDeleteModal] = useDeleteContactPointModal(deleteTrigger, updateAlertmanagerState.isLoading);
const [ExportDrawer, showExportDrawer] = useExportContactPoint();
const search = queryParams.get('search');
@ -102,16 +99,9 @@ const ContactPointsTab = () => {
)}
</Stack>
</Stack>
<ContactPointsList
contactPoints={contactPoints}
search={search}
pageSize={DEFAULT_PAGE_SIZE}
onDelete={(name) => showDeleteModal(name)}
disabled={updateAlertmanagerState.isLoading}
/>
<ContactPointsList contactPoints={contactPoints} search={search} pageSize={DEFAULT_PAGE_SIZE} />
{/* Grafana manager Alertmanager does not support global config, Mimir and Cortex do */}
{!isGrafanaManagedAlertmanager && <GlobalConfigAlert alertManagerName={selectedAlertmanager!} />}
{DeleteModal}
{ExportDrawer}
</>
);
@ -204,7 +194,6 @@ interface ContactPointsListProps {
contactPoints: ContactPointWithMetadata[];
search?: string | null;
disabled?: boolean;
onDelete: (name: string) => void;
pageSize?: number;
}
@ -213,7 +202,6 @@ const ContactPointsList = ({
disabled = false,
search,
pageSize = DEFAULT_PAGE_SIZE,
onDelete,
}: ContactPointsListProps) => {
const searchResults = useContactPointsSearch(contactPoints, search);
const { page, pageItems, numberOfPages, onPageChange } = usePagination(searchResults, 1, pageSize);
@ -221,21 +209,8 @@ const ContactPointsList = ({
return (
<>
{pageItems.map((contactPoint, index) => {
const provisioned = isProvisioned(contactPoint);
const policies = contactPoint.policies ?? [];
const key = `${contactPoint.name}-${index}`;
return (
<ContactPoint
key={key}
name={contactPoint.name}
disabled={disabled}
onDelete={onDelete}
receivers={contactPoint.grafana_managed_receiver_configs}
provisioned={provisioned}
policies={policies}
/>
);
return <ContactPoint key={key} contactPoint={contactPoint} disabled={disabled} />;
})}
<Pagination currentPage={page} numberOfPages={numberOfPages} onNavigate={onPageChange} hideWhenSinglePage />
</>

View File

@ -1,9 +1,9 @@
import { RouteChildrenProps } from 'react-router-dom';
import { Alert } from '@grafana/ui';
import { EntityNotFound } from 'app/core/components/PageNotFound/EntityNotFound';
import { Alert, LoadingPlaceholder } from '@grafana/ui';
import { useGetContactPoint } from 'app/features/alerting/unified/components/contact-points/useContactPoints';
import { stringifyErrorLike } from 'app/features/alerting/unified/utils/misc';
import { useAlertmanagerConfig } from '../../hooks/useAlertmanagerConfig';
import { useAlertmanager } from '../../state/AlertmanagerContext';
import { EditReceiverView } from '../receivers/EditReceiverView';
@ -11,36 +11,35 @@ type Props = RouteChildrenProps<{ name: string }>;
const EditContactPoint = ({ match }: Props) => {
const { selectedAlertmanager } = useAlertmanager();
const { data, isLoading, error } = useAlertmanagerConfig(selectedAlertmanager);
const contactPointName = match?.params.name;
if (!contactPointName) {
return <EntityNotFound entity="Contact point" />;
}
const contactPointName = decodeURIComponent(match?.params.name!);
const {
isLoading,
error,
data: contactPoint,
} = useGetContactPoint({ name: contactPointName, alertmanager: selectedAlertmanager! });
if (isLoading && !data) {
return 'loading...';
if (isLoading) {
return <LoadingPlaceholder text="Loading..." />;
}
if (error) {
return (
<Alert severity="error" title="Failed to fetch contact point">
{String(error)}
{stringifyErrorLike(error)}
</Alert>
);
}
if (!data) {
return null;
if (!contactPoint) {
return (
<Alert severity="error" title="Receiver not found">
{'Sorry, this contact point does not seem to exist.'}
</Alert>
);
}
return (
<EditReceiverView
alertManagerSourceName={selectedAlertmanager!}
config={data}
receiverName={decodeURIComponent(contactPointName)}
/>
);
return <EditReceiverView alertmanagerName={selectedAlertmanager!} contactPoint={contactPoint} />;
};
export default EditContactPoint;

View File

@ -1,102 +0,0 @@
import { render, screen, waitFor, userEvent } from 'test/test-utils';
import { byLabelText, byPlaceholderText, byRole, byTestId } from 'testing-library-selector';
import { AccessControlAction } from 'app/types';
import { setupMswServer } from '../../mockApi';
import { grantUserPermissions } from '../../mocks';
import { AlertmanagerProvider } from '../../state/AlertmanagerContext';
import NewContactPoint from './NewContactPoint';
import { setupSaveEndpointMock, setupTestEndpointMock } from './__mocks__/grafanaManagedServer';
import 'core-js/stable/structured-clone';
const server = setupMswServer();
const user = userEvent.setup();
beforeEach(() => {
grantUserPermissions([AccessControlAction.AlertingNotificationsRead, AccessControlAction.AlertingNotificationsWrite]);
});
it('should be able to test and save a receiver', async () => {
const testMock = setupTestEndpointMock(server);
const saveMock = setupSaveEndpointMock(server);
render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName="grafana">
<NewContactPoint />
</AlertmanagerProvider>
);
// wait for loading to be done
// type in a name for the new receiver
await user.type(await ui.inputs.name.find(), 'my new receiver');
// enter some email
const email = ui.inputs.email.addresses.get();
await user.clear(email);
await user.type(email, 'tester@grafana.com');
// try to test the contact point
await user.click(await ui.testContactPointButton.find());
expect(await ui.testContactPointModal.find()).toBeInTheDocument();
await user.click(ui.customContactPointOption.get());
// enter custom annotations and labels
await user.type(screen.getByPlaceholderText('Enter a description...'), 'Test contact point');
await user.type(ui.contactPointLabelKey(0).get(), 'foo');
await user.type(ui.contactPointLabelValue(0).get(), 'bar');
// click test
await user.click(ui.testContactPoint.get());
// we shouldn't be testing implementation details but when the request is successful
// it can't seem to assert on the success toast
await waitFor(() => {
expect(testMock).toHaveBeenCalled();
});
expect(testMock.mock.lastCall).toMatchSnapshot();
await user.click(ui.saveContactButton.get());
await waitFor(() => {
expect(saveMock).toHaveBeenCalled();
});
expect(saveMock.mock.lastCall).toMatchSnapshot();
});
const ui = {
saveContactButton: byRole('button', { name: /save contact point/i }),
newContactPointIntegrationButton: byRole('button', { name: /add contact point integration/i }),
testContactPointButton: byRole('button', { name: /Test/ }),
testContactPointModal: byRole('heading', { name: /test contact point/i }),
customContactPointOption: byRole('radio', { name: /custom/i }),
contactPointAnnotationSelect: (idx: number) => byTestId(`annotation-key-${idx}`),
contactPointAnnotationValue: (idx: number) => byTestId(`annotation-value-${idx}`),
contactPointLabelKey: (idx: number) => byTestId(`label-key-${idx}`),
contactPointLabelValue: (idx: number) => byTestId(`label-value-${idx}`),
testContactPoint: byRole('button', { name: /send test notification/i }),
cancelButton: byTestId('cancel-button'),
channelFormContainer: byTestId('item-container'),
inputs: {
name: byPlaceholderText('Name'),
email: {
addresses: byLabelText(/Addresses/),
toEmails: byLabelText(/To/),
},
hipchat: {
url: byLabelText('Hip Chat Url'),
apiKey: byLabelText('API Key'),
},
slack: {
webhookURL: byLabelText(/Webhook URL/i),
},
webhook: {
URL: byLabelText(/The endpoint to send HTTP POST requests to/i),
},
},
};

View File

@ -1,30 +0,0 @@
import { Alert } from '@grafana/ui';
import { useAlertmanagerConfig } from '../../hooks/useAlertmanagerConfig';
import { useAlertmanager } from '../../state/AlertmanagerContext';
import { NewReceiverView } from '../receivers/NewReceiverView';
const NewContactPoint = () => {
const { selectedAlertmanager } = useAlertmanager();
const { data, isLoading, error } = useAlertmanagerConfig(selectedAlertmanager);
if (isLoading && !data) {
return 'loading...';
}
if (error) {
return (
<Alert severity="error" title="Failed to fetch contact point">
{String(error)}
</Alert>
);
}
if (!data) {
return null;
}
return <NewReceiverView config={data} alertManagerSourceName={selectedAlertmanager!} />;
};
export default NewContactPoint;

View File

@ -1,46 +0,0 @@
import { http, HttpResponse } from 'msw';
import { SetupServer } from 'msw/node';
/** @deprecated */
export const setupTestEndpointMock = (server: SetupServer) => {
const mock = jest.fn();
server.use(
http.post(
'/api/alertmanager/grafana/config/api/v1/receivers/test',
async ({ request }) => {
const requestBody = await request.json();
mock(requestBody);
return HttpResponse.json({});
},
{
once: true,
}
)
);
return mock;
};
/** @deprecated */
export const setupSaveEndpointMock = (server: SetupServer) => {
const mock = jest.fn();
server.use(
http.post(
'/api/alertmanager/grafana/config/api/v1/alerts',
async ({ request }) => {
const requestBody = await request.json();
mock(requestBody);
return HttpResponse.json({});
},
{
once: true,
}
)
);
return mock;
};

View File

@ -29,6 +29,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "grafana-default-email",
"name": "grafana-default-email",
"policies": [
{
@ -38,6 +39,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
},
},
],
"provisioned": false,
},
{
"grafana_managed_receiver_configs": [
@ -64,8 +66,10 @@ exports[`useContactPoints should return contact points with status 1`] = `
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "lotsa-emails",
"name": "lotsa-emails",
"policies": [],
"provisioned": false,
},
{
"grafana_managed_receiver_configs": [
@ -87,8 +91,10 @@ exports[`useContactPoints should return contact points with status 1`] = `
},
},
],
"id": "OnCall Conctact point",
"name": "OnCall Conctact point",
"policies": [],
"provisioned": false,
},
{
"grafana_managed_receiver_configs": [
@ -116,6 +122,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "provisioned-contact-point",
"name": "provisioned-contact-point",
"policies": [
{
@ -125,6 +132,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
},
},
],
"provisioned": true,
},
{
"grafana_managed_receiver_configs": [
@ -175,8 +183,10 @@ exports[`useContactPoints should return contact points with status 1`] = `
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "Slack with multiple channels",
"name": "Slack with multiple channels",
"policies": [],
"provisioned": false,
},
],
"error": undefined,
@ -213,6 +223,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "grafana-default-email",
"name": "grafana-default-email",
"policies": [
{
@ -222,6 +233,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
},
},
],
"provisioned": false,
},
{
"grafana_managed_receiver_configs": [
@ -248,8 +260,10 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "lotsa-emails",
"name": "lotsa-emails",
"policies": [],
"provisioned": false,
},
{
"grafana_managed_receiver_configs": [
@ -274,8 +288,10 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
},
},
],
"id": "OnCall Conctact point",
"name": "OnCall Conctact point",
"policies": [],
"provisioned": false,
},
{
"grafana_managed_receiver_configs": [
@ -303,6 +319,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "provisioned-contact-point",
"name": "provisioned-contact-point",
"policies": [
{
@ -312,6 +329,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
},
},
],
"provisioned": true,
},
{
"grafana_managed_receiver_configs": [
@ -362,8 +380,10 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
Symbol(receiver_plugin_metadata): undefined,
},
],
"id": "Slack with multiple channels",
"name": "Slack with multiple channels",
"policies": [],
"provisioned": false,
},
],
"error": undefined,

View File

@ -4,40 +4,41 @@ import { Button, Modal, ModalProps } from '@grafana/ui';
import { stringifyErrorLike } from '../../../utils/misc';
type ModalHook<T = undefined> = [JSX.Element, (item: T) => void, () => void];
/**
* This hook controls the delete modal for contact points, showing loading and error states when appropriate
*/
export const useDeleteContactPointModal = (
handleDelete: (name: string) => Promise<void>,
isLoading: boolean
): ModalHook<string> => {
handleDelete: ({ name, resourceVersion }: { name: string; resourceVersion?: string }) => Promise<unknown>
) => {
const [showModal, setShowModal] = useState(false);
const [contactPoint, setContactPoint] = useState<string>();
const [contactPoint, setContactPoint] = useState<{ name: string; resourceVersion?: string }>();
const [error, setError] = useState<unknown | undefined>();
const [isLoading, setIsLoading] = useState(false);
const handleDismiss = useCallback(() => {
if (isLoading) {
return;
}
setContactPoint(undefined);
setShowModal(false);
setError(undefined);
}, [isLoading]);
const handleShow = useCallback((name: string) => {
setContactPoint(name);
const handleShow = useCallback(({ name, resourceVersion }: { name: string; resourceVersion?: string }) => {
setContactPoint({ name, resourceVersion });
setShowModal(true);
setError(undefined);
}, []);
const handleSubmit = useCallback(() => {
if (contactPoint) {
setIsLoading(true);
handleDelete(contactPoint)
.then(() => setShowModal(false))
.catch(setError);
.catch(setError)
.finally(() => {
setIsLoading(false);
});
}
}, [handleDelete, contactPoint]);
@ -69,7 +70,7 @@ export const useDeleteContactPointModal = (
);
}, [error, handleDismiss, handleSubmit, isLoading, showModal]);
return [modalElement, handleShow, handleDismiss];
return [modalElement, handleShow, handleDismiss] as const;
};
interface ErrorModalProps extends Pick<ModalProps, 'isOpen' | 'onDismiss'> {
@ -84,10 +85,8 @@ const ErrorModal = ({ isOpen, onDismiss, error }: ErrorModalProps) => (
title={'Something went wrong'}
>
<p>Failed to update your configuration:</p>
<p>
<pre>
<code>{stringifyErrorLike(error)}</code>
</pre>
</p>
<pre>
<code>{stringifyErrorLike(error)}</code>
</pre>
</Modal>
);

View File

@ -65,10 +65,32 @@ describe('useContactPoints', () => {
expect(snapshot).toMatchSnapshot();
});
it('returns matching responses with and without alertingApiServer', async () => {
it('returns ~matching responses with and without alertingApiServer', async () => {
// Compare the responses between the two implementations, but do not consider:
// - ID: k8s API will return id properties, but the AM config will fall back to the name of the contact point.
// These will be different, so we don't want to compare them
// - Metadata: k8s API includes metadata, AM config does not
const snapshotAmConfig = await getHookResponse(false);
const snapshotAlertingApiServer = await getHookResponse(true);
expect(snapshotAmConfig).toEqual(snapshotAlertingApiServer);
const amContactPoints = snapshotAmConfig.contactPoints.map((receiver) => {
const { id, ...rest } = receiver;
return rest;
});
const k8sContactPoints = snapshotAlertingApiServer.contactPoints.map((receiver) => {
const { id, metadata, ...rest } = receiver;
return rest;
});
expect({
...snapshotAmConfig,
contactPoints: amContactPoints,
}).toEqual({
...snapshotAlertingApiServer,
contactPoints: k8sContactPoints,
});
});
describe('when having oncall plugin installed and no alert manager config data', () => {

View File

@ -7,14 +7,29 @@ import { produce } from 'immer';
import { remove } from 'lodash';
import { useMemo } from 'react';
import { alertingApi } from 'app/features/alerting/unified/api/alertingApi';
import { receiversApi } from 'app/features/alerting/unified/api/receiversK8sApi';
import { useOnCallIntegration } from 'app/features/alerting/unified/components/receivers/grafanaAppReceivers/onCall/useOnCallIntegration';
import {
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver,
generatedReceiversApi,
} from 'app/features/alerting/unified/openapi/receiversApi.gen';
import { updateAlertManagerConfigAction } from 'app/features/alerting/unified/state/actions';
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { cloudNotifierTypes } from 'app/features/alerting/unified/utils/cloud-alertmanager-notifier-types';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { getK8sNamespace, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
import {
getK8sNamespace,
isK8sEntityProvisioned,
shouldUseK8sApi,
} from 'app/features/alerting/unified/utils/k8s/utils';
import { updateConfigWithReceiver } from 'app/features/alerting/unified/utils/receiver-form';
import {
GrafanaManagedContactPoint,
GrafanaManagedReceiverConfig,
Receiver,
} from 'app/plugins/datasource/alertmanager/types';
import { useDispatch } from 'app/types';
import { alertmanagerApi } from '../../api/alertmanagerApi';
import { onCallApi } from '../../api/onCallApi';
@ -42,7 +57,13 @@ const {
useUpdateAlertmanagerConfigurationMutation,
} = alertmanagerApi;
const { useGrafanaOnCallIntegrationsQuery } = onCallApi;
const { useListNamespacedReceiverQuery } = generatedReceiversApi;
const {
useListNamespacedReceiverQuery,
useReadNamespacedReceiverQuery,
useDeleteNamespacedReceiverMutation,
useCreateNamespacedReceiverMutation,
useReplaceNamespacedReceiverMutation,
} = receiversApi;
const defaultOptions = {
refetchOnFocus: true,
@ -71,19 +92,26 @@ const useOnCallIntegrations = ({ skip }: Skippable = {}) => {
type K8sReceiver = ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
// TODO: Make this typed as returning `GrafanaManagedContactPoint` - we can't yet do this as the schema thinks
// its returning integration settings as a `string` rather than `Record<string, any>`
const parseK8sReceiver = (item: K8sReceiver) => {
return { name: item.spec.title, grafana_managed_receiver_configs: item.spec.integrations };
const parseK8sReceiver = (item: K8sReceiver): GrafanaManagedContactPoint => {
return {
id: item.metadata.uid || item.spec.title,
name: item.spec.title,
provisioned: isK8sEntityProvisioned(item),
grafana_managed_receiver_configs: item.spec.integrations,
metadata: item.metadata,
};
};
const useK8sContactPoints = (...[hookParams, queryOptions]: Parameters<typeof useListNamespacedReceiverQuery>) => {
return useListNamespacedReceiverQuery(hookParams, {
...queryOptions,
selectFromResult: ({ data, ...rest }) => {
selectFromResult: (result) => {
const data = result.data?.items.map((item) => parseK8sReceiver(item));
return {
...rest,
data: data?.items.map((item) => parseK8sReceiver(item)),
...result,
data,
currentData: data,
};
},
});
@ -97,7 +125,21 @@ const useFetchGrafanaContactPoints = ({ skip }: Skippable = {}) => {
const namespace = getK8sNamespace();
const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);
const grafanaResponse = useGetContactPointsListQuery(undefined, { skip: skip || useK8sApi });
const grafanaResponse = useGetContactPointsListQuery(undefined, {
skip: skip || useK8sApi,
selectFromResult: (result) => {
const data = result.data?.map((item) => ({
...item,
provisioned: item.grafana_managed_receiver_configs?.some((item) => item.provenance),
}));
return {
...result,
data,
currentData: data,
};
},
});
const k8sResponse = useK8sContactPoints({ namespace }, { skip: skip || !useK8sApi });
return useK8sApi ? k8sResponse : grafanaResponse;
@ -115,7 +157,7 @@ type GrafanaFetchOptions = {
};
/**
* Fetch contact points from separate endpoint (i.e. not the Alertmanager config) and combine with
* Fetch list of contact points from separate endpoint (i.e. not the Alertmanager config) and combine with
* OnCall integrations and any additional metadata from list of notifiers
* (e.g. hydrate with additional names/descriptions)
*/
@ -173,6 +215,71 @@ export const useGrafanaContactPoints = ({
]);
};
/**
* Fetch single contact point via the alertmanager config
*/
const useGetAlertmanagerContactPoint = (
{ alertmanager, name }: BaseAlertmanagerArgs & { name: string },
queryOptions?: Parameters<typeof useGetAlertmanagerConfigurationQuery>[1]
) => {
return useGetAlertmanagerConfigurationQuery(alertmanager, {
...queryOptions,
selectFromResult: (result) => {
const matchedContactPoint = result.data?.alertmanager_config.receivers?.find(
(receiver) => receiver.name === name
);
return {
...result,
data: matchedContactPoint,
currentData: matchedContactPoint,
};
},
});
};
/**
* Fetch single contact point via the k8s API, or the alertmanager config
*/
const useGetGrafanaContactPoint = (
{ name }: { name: string },
queryOptions?: Parameters<typeof useReadNamespacedReceiverQuery>[1]
) => {
const namespace = getK8sNamespace();
const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);
const k8sResponse = useReadNamespacedReceiverQuery(
{ namespace, name },
{
...queryOptions,
selectFromResult: (result) => {
const data = result.data ? parseK8sReceiver(result.data) : undefined;
return {
...result,
data,
currentData: data,
};
},
skip: queryOptions?.skip || !useK8sApi,
}
);
const grafanaResponse = useGetAlertmanagerContactPoint(
{ alertmanager: GRAFANA_RULES_SOURCE_NAME, name },
{ skip: queryOptions?.skip || useK8sApi }
);
return useK8sApi ? k8sResponse : grafanaResponse;
};
export const useGetContactPoint = ({ alertmanager, name }: { alertmanager: string; name: string }) => {
const isGrafana = alertmanager === GRAFANA_RULES_SOURCE_NAME;
const grafanaResponse = useGetGrafanaContactPoint({ name }, { skip: !isGrafana });
const alertmanagerResponse = useGetAlertmanagerContactPoint({ alertmanager, name }, { skip: isGrafana });
return isGrafana ? grafanaResponse : alertmanagerResponse;
};
export function useContactPointsWithStatus({
alertmanager,
fetchStatuses,
@ -203,30 +310,182 @@ export function useContactPointsWithStatus({
return isGrafanaAlertmanager ? grafanaResponse : alertmanagerConfigResponse;
}
export function useDeleteContactPoint(selectedAlertmanager: string) {
export function useDeleteContactPoint({ alertmanager }: BaseAlertmanagerArgs) {
const [fetchAlertmanagerConfig] = useLazyGetAlertmanagerConfigurationQuery();
const [updateAlertManager, updateAlertmanagerState] = useUpdateAlertmanagerConfigurationMutation();
const [updateAlertManager] = useUpdateAlertmanagerConfigurationMutation();
const [deleteReceiver] = useDeleteNamespacedReceiverMutation();
const deleteTrigger = (contactPointName: string) => {
return fetchAlertmanagerConfig(selectedAlertmanager).then(({ data }) => {
if (!data) {
return;
}
const useK8sApi = shouldUseK8sApi(alertmanager);
const newConfig = produce(data, (draft) => {
remove(draft?.alertmanager_config?.receivers ?? [], (receiver) => receiver.name === contactPointName);
return draft;
});
return updateAlertManager({
selectedAlertmanager,
config: newConfig,
return async ({ name, resourceVersion }: { name: string; resourceVersion?: string }) => {
if (useK8sApi) {
const namespace = getK8sNamespace();
return deleteReceiver({
name,
namespace,
ioK8SApimachineryPkgApisMetaV1DeleteOptions: { preconditions: { resourceVersion } },
}).unwrap();
});
};
}
const config = await fetchAlertmanagerConfig(alertmanager).unwrap();
return {
deleteTrigger,
updateAlertmanagerState,
const newConfig = produce(config, (draft) => {
remove(draft?.alertmanager_config?.receivers ?? [], (receiver) => receiver.name === name);
return draft;
});
return updateAlertManager({
selectedAlertmanager: alertmanager,
config: newConfig,
}).unwrap();
};
}
const mapIntegrationSettings = (integration: GrafanaManagedReceiverConfig): GrafanaManagedReceiverConfig => {
return {
...integration,
settings: { ...integration.settings, ...integration.secureSettings },
};
};
const grafanaContactPointToK8sReceiver = (
contactPoint: GrafanaManagedContactPoint,
id?: string,
resourceVersion?: string
): K8sReceiver => {
return {
metadata: {
...(id && { name: id }),
resourceVersion,
},
spec: {
title: contactPoint.name,
integrations: (contactPoint.grafana_managed_receiver_configs || []).map(mapIntegrationSettings),
},
};
};
type ContactPointOperationArgs = {
contactPoint: Receiver;
};
type CreateContactPointArgs = ContactPointOperationArgs;
type UpdateContactPointArgs = ContactPointOperationArgs & {
/** ID of existing contact point to update - used when updating via k8s API */
id?: string;
resourceVersion?: string;
/** Name of the existing contact point - used for checking uniqueness of name when not using k8s API*/
originalName?: string;
};
export const useCreateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) => {
const isGrafanaAlertmanager = alertmanager === GRAFANA_RULES_SOURCE_NAME;
const useK8sApi = shouldUseK8sApi(alertmanager);
const { createOnCallIntegrations } = useOnCallIntegration();
const [getAlertmanagerConfig] = useLazyGetAlertmanagerConfigurationQuery();
const [createGrafanaContactPoint] = useCreateNamespacedReceiverMutation();
const dispatch = useDispatch();
return async ({ contactPoint }: CreateContactPointArgs) => {
const receiverWithPotentialOnCall = isGrafanaAlertmanager
? await createOnCallIntegrations(contactPoint)
: contactPoint;
if (useK8sApi) {
const namespace = getK8sNamespace();
const contactPointToUse = grafanaContactPointToK8sReceiver(receiverWithPotentialOnCall);
return createGrafanaContactPoint({
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver: contactPointToUse,
}).unwrap();
}
const config = await getAlertmanagerConfig(alertmanager).unwrap();
const newConfig = updateConfigWithReceiver(config, receiverWithPotentialOnCall);
return await dispatch(
updateAlertManagerConfigAction({
newConfig: newConfig,
oldConfig: config,
alertManagerSourceName: alertmanager,
})
).then(() => {
dispatch(alertingApi.util.invalidateTags(['AlertmanagerConfiguration', 'ContactPoint', 'ContactPointsStatus']));
dispatch(generatedReceiversApi.util.invalidateTags(['Receiver']));
});
};
};
export const useUpdateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) => {
const isGrafanaAlertmanager = alertmanager === GRAFANA_RULES_SOURCE_NAME;
const useK8sApi = shouldUseK8sApi(alertmanager);
const { createOnCallIntegrations } = useOnCallIntegration();
const [getAlertmanagerConfig] = useLazyGetAlertmanagerConfigurationQuery();
const [replaceGrafanaContactPoint] = useReplaceNamespacedReceiverMutation();
const dispatch = useDispatch();
return async ({ contactPoint, id, originalName, resourceVersion }: UpdateContactPointArgs) => {
const receiverWithPotentialOnCall = isGrafanaAlertmanager
? await createOnCallIntegrations(contactPoint)
: contactPoint;
if (useK8sApi && id) {
const namespace = getK8sNamespace();
const contactPointToUse = grafanaContactPointToK8sReceiver(receiverWithPotentialOnCall, id, resourceVersion);
return replaceGrafanaContactPoint({
name: id,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver: contactPointToUse,
}).unwrap();
}
const config = await getAlertmanagerConfig(alertmanager).unwrap();
const newConfig = updateConfigWithReceiver(config, receiverWithPotentialOnCall, originalName);
return dispatch(
updateAlertManagerConfigAction({
newConfig: newConfig,
oldConfig: config,
alertManagerSourceName: alertmanager,
})
)
.unwrap()
.then(() => {
dispatch(alertingApi.util.invalidateTags(['AlertmanagerConfiguration', 'ContactPoint', 'ContactPointsStatus']));
dispatch(generatedReceiversApi.util.invalidateTags(['Receiver']));
});
};
};
export const useValidateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) => {
const useK8sApi = shouldUseK8sApi(alertmanager);
const [getConfig] = useLazyGetAlertmanagerConfigurationQuery();
// If we're using the kubernetes API, then we let the API response handle the validation instead
// as we don't expect to be able to fetch the intervals via the AM config
if (useK8sApi) {
return () => undefined;
}
return async (value: string, existingValue?: string) => {
// If we've been given an existing value, and the name has not changed,
// we can skip validation
// (as we don't want to incorrectly flag the existing name as matching itself)
if (existingValue && value === existingValue) {
return;
}
return getConfig(alertmanager)
.unwrap()
.then((config) => {
const { alertmanager_config } = config;
const duplicated = Boolean(alertmanager_config.receivers?.find((contactPoint) => contactPoint.name === value));
return duplicated ? `Contact point already exists with name "${value}"` : undefined;
});
};
};

View File

@ -1,5 +1,3 @@
import { GrafanaManagedContactPoint } from 'app/plugins/datasource/alertmanager/types';
import { ReceiverTypes } from '../receivers/grafanaAppReceivers/onCall/onCall';
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from './constants';
@ -7,34 +5,9 @@ import {
ReceiverConfigWithMetadata,
getReceiverDescription,
isAutoGeneratedPolicy,
isProvisioned,
summarizeEmailAddresses,
} from './utils';
describe('isProvisioned', () => {
it('should return true when at least one receiver is provisioned', () => {
const contactPoint: GrafanaManagedContactPoint = {
name: 'my-contact-point',
grafana_managed_receiver_configs: [
{ name: 'email', provenance: 'api', type: 'email', disableResolveMessage: false, settings: {} },
],
};
expect(isProvisioned(contactPoint)).toBe(true);
});
it('should return false when no receiver was provisioned', () => {
const contactPoint: GrafanaManagedContactPoint = {
name: 'my-contact-point',
grafana_managed_receiver_configs: [
{ name: 'email', provenance: undefined, type: 'email', disableResolveMessage: false, settings: {} },
],
};
expect(isProvisioned(contactPoint)).toBe(false);
});
});
describe('isAutoGeneratedPolicy', () => {
it('should return false when not enabled', () => {
expect(isAutoGeneratedPolicy({})).toBe(false);

View File

@ -22,13 +22,6 @@ import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from
const AUTOGENERATED_RECEIVER_POLICY_MATCHER_KEY = '__grafana_receiver__';
export function isProvisioned(contactPoint: GrafanaManagedContactPoint) {
// for some reason the provenance is on the receiver and not the entire contact point
const provenance = contactPoint.grafana_managed_receiver_configs?.find((receiver) => receiver.provenance)?.provenance;
return Boolean(provenance);
}
// TODO we should really add some type information to these receiver settings...
export function getReceiverDescription(receiver: ReceiverConfigWithMetadata): ReactNode | undefined {
if (!receiver.settings) {
@ -98,6 +91,7 @@ export interface ReceiverConfigWithMetadata extends GrafanaManagedReceiverConfig
}
export interface ContactPointWithMetadata extends GrafanaManagedContactPoint {
id: string;
policies?: RouteReference[]; // now is optional as we don't have the data from the read-only endpoint
grafana_managed_receiver_configs: ReceiverConfigWithMetadata[];
}
@ -134,8 +128,11 @@ export function enhanceContactPointsWithMetadata({
const receivers = extractReceivers(contactPoint);
const statusForReceiver = status.find((status) => status.name === contactPoint.name);
const id = 'id' in contactPoint && contactPoint.id ? contactPoint.id : contactPoint.name;
return {
...contactPoint,
id,
policies:
alertmanagerConfiguration && usedContactPointsByName && (usedContactPointsByName[contactPoint.name] ?? []),
grafana_managed_receiver_configs: receivers.map((receiver, index) => {

View File

@ -9,8 +9,12 @@ import {
} from 'app/features/alerting/unified/openapi/timeIntervalsApi.gen';
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { PROVENANCE_ANNOTATION, PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
import { getK8sNamespace, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
import { PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
import {
getK8sNamespace,
isK8sEntityProvisioned,
shouldUseK8sApi,
} from 'app/features/alerting/unified/utils/k8s/utils';
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
import { useAsync } from '../../hooks/useAsync';
@ -48,7 +52,7 @@ const parseK8sTimeInterval: (item: TimeIntervalV0Alpha1) => MuteTiming = (item)
...spec,
id: spec.name,
metadata,
provisioned: metadata.annotations?.[PROVENANCE_ANNOTATION] !== PROVENANCE_NONE,
provisioned: isK8sEntityProvisioned(item),
};
};

View File

@ -1,5 +1,4 @@
import { Alert } from '@grafana/ui';
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
import { GrafanaManagedContactPoint, Receiver } from 'app/plugins/datasource/alertmanager/types';
import { AlertmanagerAction, useAlertmanagerAbility } from '../../hooks/useAbilities';
import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
@ -8,41 +7,25 @@ import { CloudReceiverForm } from './form/CloudReceiverForm';
import { GrafanaReceiverForm } from './form/GrafanaReceiverForm';
interface Props {
receiverName: string;
config: AlertManagerCortexConfig;
alertManagerSourceName: string;
alertmanagerName: string;
contactPoint: GrafanaManagedContactPoint | Receiver;
}
export const EditReceiverView = ({ config, receiverName, alertManagerSourceName }: Props) => {
export const EditReceiverView = ({ contactPoint, alertmanagerName }: Props) => {
const [editSupported, editAllowed] = useAlertmanagerAbility(AlertmanagerAction.UpdateContactPoint);
const receiver = config.alertmanager_config.receivers?.find(({ name }) => name === receiverName);
if (!receiver) {
return (
<Alert severity="error" title="Receiver not found">
Sorry, this receiver does not seem to exist.
</Alert>
);
}
const readOnly = !editSupported || !editAllowed;
if (alertManagerSourceName === GRAFANA_RULES_SOURCE_NAME) {
return (
<GrafanaReceiverForm
config={config}
alertManagerSourceName={alertManagerSourceName}
existing={receiver}
readOnly={readOnly}
/>
);
if (alertmanagerName === GRAFANA_RULES_SOURCE_NAME) {
console.log(contactPoint);
return <GrafanaReceiverForm contactPoint={contactPoint} readOnly={readOnly} editMode />;
} else {
return (
<CloudReceiverForm
config={config}
alertManagerSourceName={alertManagerSourceName}
existing={receiver}
alertManagerSourceName={alertmanagerName}
contactPoint={contactPoint}
readOnly={readOnly}
editMode
/>
);
}

View File

@ -0,0 +1,126 @@
import 'core-js/stable/structured-clone';
import { Route } from 'react-router';
import { render, screen } from 'test/test-utils';
import { byLabelText, byPlaceholderText, byRole, byTestId } from 'testing-library-selector';
import { config } from '@grafana/runtime';
import { captureRequests } from 'app/features/alerting/unified/mocks/server/events';
import { AccessControlAction } from 'app/types';
import { setupMswServer } from '../../mockApi';
import { grantUserPermissions } from '../../mocks';
import { AlertmanagerProvider } from '../../state/AlertmanagerContext';
import NewReceiverView from './NewReceiverView';
setupMswServer();
const renderForm = () =>
render(
<AlertmanagerProvider accessType="notification" alertmanagerSourceName="grafana">
<Route path="/alerting/notifications/new" exact>
<NewReceiverView />
</Route>
<Route path="/alerting/notifications" exact>
redirected
</Route>
</AlertmanagerProvider>,
{
historyOptions: { initialEntries: ['/alerting/notifications/new'] },
}
);
beforeEach(() => {
grantUserPermissions([AccessControlAction.AlertingNotificationsRead, AccessControlAction.AlertingNotificationsWrite]);
});
describe('alerting API server enabled', () => {
beforeEach(() => {
config.featureToggles.alertingApiServer = true;
});
it('can create a receiver', async () => {
const { user } = renderForm();
expect(await ui.inputs.name.find()).toBeEnabled();
await user.type(await ui.inputs.name.find(), 'my new receiver');
// enter some email
const email = ui.inputs.email.addresses.get();
await user.clear(email);
await user.type(email, 'tester@grafana.com');
await user.click(ui.saveContactButton.get());
expect(await screen.findByText(/redirected/i)).toBeInTheDocument();
});
});
describe('alerting API server disabled', () => {
beforeEach(() => {
config.featureToggles.alertingApiServer = false;
});
it('should be able to test and save a receiver', async () => {
const capture = captureRequests();
const { user } = renderForm();
// wait for loading to be done
// type in a name for the new receiver
await user.type(await ui.inputs.name.find(), 'my new receiver');
// enter some email
const email = ui.inputs.email.addresses.get();
await user.clear(email);
await user.type(email, 'tester@grafana.com');
// try to test the contact point
await user.click(await ui.testContactPointButton.find());
expect(await ui.testContactPointModal.find()).toBeInTheDocument();
await user.click(ui.customContactPointOption.get());
// enter custom annotations and labels
await user.type(screen.getByPlaceholderText('Enter a description...'), 'Test contact point');
await user.type(ui.contactPointLabelKey(0).get(), 'foo');
await user.type(ui.contactPointLabelValue(0).get(), 'bar');
// click test
await user.click(ui.testContactPoint.get());
// we shouldn't be testing implementation details but when the request is successful
// it can't seem to assert on the success toast
await user.click(ui.saveContactButton.get());
const requests = await capture;
const testRequest = requests.find((r) => r.url.endsWith('/config/api/v1/receivers/test'));
const saveRequest = requests.find(
(r) => r.url.endsWith('/api/alertmanager/grafana/config/api/v1/alerts') && r.method === 'POST'
);
const testBody = await testRequest?.json();
const saveBody = await saveRequest?.json();
expect([testBody]).toMatchSnapshot();
expect([saveBody]).toMatchSnapshot();
});
});
const ui = {
saveContactButton: byRole('button', { name: /save contact point/i }),
testContactPointButton: byRole('button', { name: /Test/ }),
testContactPointModal: byRole('heading', { name: /test contact point/i }),
customContactPointOption: byRole('radio', { name: /custom/i }),
contactPointLabelKey: (idx: number) => byTestId(`label-key-${idx}`),
contactPointLabelValue: (idx: number) => byTestId(`label-value-${idx}`),
testContactPoint: byRole('button', { name: /send test notification/i }),
inputs: {
name: byPlaceholderText('Name'),
email: {
addresses: byLabelText(/Addresses/),
},
},
};

View File

@ -1,19 +1,17 @@
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
import { useAlertmanager } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
import { CloudReceiverForm } from './form/CloudReceiverForm';
import { GrafanaReceiverForm } from './form/GrafanaReceiverForm';
interface Props {
config: AlertManagerCortexConfig;
alertManagerSourceName: string;
}
export const NewReceiverView = ({ alertManagerSourceName, config }: Props) => {
if (alertManagerSourceName === GRAFANA_RULES_SOURCE_NAME) {
return <GrafanaReceiverForm alertManagerSourceName={alertManagerSourceName} config={config} />;
const NewReceiverView = () => {
const { selectedAlertmanager } = useAlertmanager();
if (selectedAlertmanager === GRAFANA_RULES_SOURCE_NAME) {
return <GrafanaReceiverForm />;
} else {
return <CloudReceiverForm alertManagerSourceName={alertManagerSourceName} config={config} />;
return <CloudReceiverForm alertManagerSourceName={selectedAlertmanager!} />;
}
};
export default NewReceiverView;

View File

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`should be able to test and save a receiver 1`] = `
exports[`alerting API server disabled should be able to test and save a receiver 1`] = `
[
{
"alert": {
@ -32,7 +32,7 @@ exports[`should be able to test and save a receiver 1`] = `
]
`;
exports[`should be able to test and save a receiver 2`] = `
exports[`alerting API server disabled should be able to test and save a receiver 2`] = `
[
{
"alertmanager_config": {

View File

@ -1,19 +1,18 @@
import { useMemo } from 'react';
import { locationService } from '@grafana/runtime';
import { Alert } from '@grafana/ui';
import { AlertManagerCortexConfig, Receiver } from 'app/plugins/datasource/alertmanager/types';
import { useDispatch } from 'app/types';
import { alertmanagerApi } from 'app/features/alerting/unified/api/alertmanagerApi';
import {
useCreateContactPoint,
useUpdateContactPoint,
} from 'app/features/alerting/unified/components/contact-points/useContactPoints';
import { Receiver } from 'app/plugins/datasource/alertmanager/types';
import { alertmanagerApi } from '../../../api/alertmanagerApi';
import { updateAlertManagerConfigAction } from '../../../state/actions';
import { CloudChannelValues, ReceiverFormValues, CloudChannelMap } from '../../../types/receiver-form';
import { cloudNotifierTypes } from '../../../utils/cloud-alertmanager-notifier-types';
import { isVanillaPrometheusAlertManagerDataSource } from '../../../utils/datasource';
import {
cloudReceiverToFormValues,
formValuesToCloudReceiver,
updateConfigWithReceiver,
} from '../../../utils/receiver-form';
import { cloudReceiverToFormValues, formValuesToCloudReceiver } from '../../../utils/receiver-form';
import { CloudCommonChannelSettings } from './CloudCommonChannelSettings';
import { ReceiverForm } from './ReceiverForm';
@ -21,9 +20,9 @@ import { Notifier } from './notifiers';
interface Props {
alertManagerSourceName: string;
config: AlertManagerCortexConfig;
existing?: Receiver;
contactPoint?: Receiver;
readOnly?: boolean;
editMode?: boolean;
}
const defaultChannelValues: CloudChannelValues = Object.freeze({
@ -36,39 +35,33 @@ const defaultChannelValues: CloudChannelValues = Object.freeze({
});
const cloudNotifiers = cloudNotifierTypes.map<Notifier>((n) => ({ dto: n }));
const { useGetAlertmanagerConfigurationQuery } = alertmanagerApi;
export const CloudReceiverForm = ({ contactPoint, alertManagerSourceName, readOnly = false, editMode }: Props) => {
const { isLoading, data: config } = useGetAlertmanagerConfigurationQuery(alertManagerSourceName);
export const CloudReceiverForm = ({ existing, alertManagerSourceName, config, readOnly = false }: Props) => {
const dispatch = useDispatch();
const isVanillaAM = isVanillaPrometheusAlertManagerDataSource(alertManagerSourceName);
const createContactPoint = useCreateContactPoint({ alertmanager: alertManagerSourceName });
const updateContactPoint = useUpdateContactPoint({ alertmanager: alertManagerSourceName });
// transform receiver DTO to form values
const [existingValue] = useMemo((): [ReceiverFormValues<CloudChannelValues> | undefined, CloudChannelMap] => {
if (!existing) {
if (!contactPoint) {
return [undefined, {}];
}
return cloudReceiverToFormValues(existing, cloudNotifierTypes);
}, [existing]);
return cloudReceiverToFormValues(contactPoint, cloudNotifierTypes);
}, [contactPoint]);
const onSubmit = async (values: ReceiverFormValues<CloudChannelValues>) => {
const newReceiver = formValuesToCloudReceiver(values, defaultChannelValues);
await dispatch(
updateAlertManagerConfigAction({
newConfig: updateConfigWithReceiver(config, newReceiver, existing?.name),
oldConfig: config,
alertManagerSourceName,
successMessage: existing ? 'Contact point updated.' : 'Contact point created.',
redirectPath: '/alerting/notifications',
})
).then(() => {
dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration']));
});
if (editMode) {
await updateContactPoint({ contactPoint: newReceiver, originalName: contactPoint!.name });
} else {
await createContactPoint({ contactPoint: newReceiver });
}
locationService.push('/alerting/notifications');
};
const takenReceiverNames = useMemo(
() => config.alertmanager_config.receivers?.map(({ name }) => name).filter((name) => name !== existing?.name) ?? [],
[config, existing]
);
// this basically checks if we can manage the selected alert manager data source, either because it's a Grafana Managed one
// or a Mimir-based AlertManager
const isManageableAlertManagerDataSource =
@ -82,15 +75,14 @@ export const CloudReceiverForm = ({ existing, alertManagerSourceName, config, re
</Alert>
)}
<ReceiverForm<CloudChannelValues>
showDefaultRouteWarning={!isLoading && !config?.alertmanager_config.route}
isEditable={isManageableAlertManagerDataSource}
isTestable={isManageableAlertManagerDataSource}
config={config}
onSubmit={onSubmit}
initialValues={existingValue}
notifiers={cloudNotifiers}
alertManagerSourceName={alertManagerSourceName}
defaultItem={defaultChannelValues}
takenReceiverNames={takenReceiverNames}
commonSettingsComponent={CloudCommonChannelSettings}
/>
</>

View File

@ -1,5 +1,5 @@
import { clickSelectOption } from 'test/helpers/selectOptionInTest';
import { render, waitFor, userEvent } from 'test/test-utils';
import { render, waitFor } from 'test/test-utils';
import { byLabelText, byRole, byTestId, byText } from 'testing-library-selector';
import { disablePlugin } from 'app/features/alerting/unified/mocks/server/configure';
@ -8,11 +8,9 @@ import {
setOnCallIntegrations,
} from 'app/features/alerting/unified/mocks/server/handlers/plugins/configure-plugins';
import { SupportedPlugin } from 'app/features/alerting/unified/types/pluginBridges';
import { clearPluginSettingsCache } from 'app/features/plugins/pluginSettings';
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
import { AlertmanagerConfigBuilder, setupMswServer } from '../../../mockApi';
import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
import { GrafanaReceiverForm } from './GrafanaReceiverForm';
@ -35,17 +33,11 @@ const ui = {
};
describe('GrafanaReceiverForm', () => {
beforeEach(() => {
clearPluginSettingsCache();
});
describe('OnCall contact point', () => {
it('OnCall contact point should be disabled if OnCall integration is not enabled', async () => {
disablePlugin(SupportedPlugin.OnCall);
const amConfig = getAmCortexConfig((_) => {});
render(<GrafanaReceiverForm alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME} config={amConfig} />);
render(<GrafanaReceiverForm />);
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
@ -65,11 +57,7 @@ describe('GrafanaReceiverForm', () => {
{ display_name: 'apac-oncall', value: 'apac-oncall', integration_url: 'https://apac.oncall.example.com' },
]);
const amConfig = getAmCortexConfig((_) => {});
const user = userEvent.setup();
render(<GrafanaReceiverForm alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME} config={amConfig} />);
const { user } = render(<GrafanaReceiverForm />);
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
@ -121,13 +109,7 @@ describe('GrafanaReceiverForm', () => {
)
);
render(
<GrafanaReceiverForm
alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME}
config={amConfig}
existing={amConfig.alertmanager_config.receivers![0]}
/>
);
render(<GrafanaReceiverForm contactPoint={amConfig.alertmanager_config.receivers![0]} />);
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());

View File

@ -1,8 +1,14 @@
import { useMemo, useState } from 'react';
import { locationService } from '@grafana/runtime';
import { Alert, LoadingPlaceholder } from '@grafana/ui';
import {
AlertManagerCortexConfig,
useCreateContactPoint,
useUpdateContactPoint,
} from 'app/features/alerting/unified/components/contact-points/useContactPoints';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
import {
GrafanaManagedContactPoint,
GrafanaManagedReceiverConfig,
TestReceiversAlert,
@ -10,14 +16,12 @@ import {
import { useDispatch } from 'app/types';
import { alertmanagerApi } from '../../../api/alertmanagerApi';
import { testReceiversAction, updateAlertManagerConfigAction } from '../../../state/actions';
import { testReceiversAction } from '../../../state/actions';
import { GrafanaChannelValues, ReceiverFormValues } from '../../../types/receiver-form';
import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
import {
formChannelValuesToGrafanaChannelConfig,
formValuesToGrafanaReceiver,
grafanaReceiverToFormValues,
updateConfigWithReceiver,
} from '../../../utils/receiver-form';
import { ProvisionedResource, ProvisioningAlert } from '../../Provisioning';
import { ReceiverTypes } from '../grafanaAppReceivers/onCall/onCall';
@ -28,13 +32,6 @@ import { ReceiverForm } from './ReceiverForm';
import { TestContactPointModal } from './TestContactPointModal';
import { Notifier } from './notifiers';
interface Props {
alertManagerSourceName: string;
config: AlertManagerCortexConfig;
existing?: GrafanaManagedContactPoint;
readOnly?: boolean;
}
const defaultChannelValues: GrafanaChannelValues = Object.freeze({
__id: '',
secureSettings: {},
@ -44,20 +41,28 @@ const defaultChannelValues: GrafanaChannelValues = Object.freeze({
type: 'email',
});
export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config, readOnly = false }: Props) => {
interface Props {
contactPoint?: GrafanaManagedContactPoint;
readOnly?: boolean;
editMode?: boolean;
}
const { useGrafanaNotifiersQuery } = alertmanagerApi;
export const GrafanaReceiverForm = ({ contactPoint, readOnly = false, editMode }: Props) => {
const dispatch = useDispatch();
const createContactPoint = useCreateContactPoint({ alertmanager: GRAFANA_RULES_SOURCE_NAME });
const updateContactPoint = useUpdateContactPoint({ alertmanager: GRAFANA_RULES_SOURCE_NAME });
const {
onCallNotifierMeta,
extendOnCallNotifierFeatures,
extendOnCallReceivers,
onCallFormValidators,
createOnCallIntegrations,
isLoadingOnCallIntegration,
hasOnCallError,
} = useOnCallIntegration();
const { useGrafanaNotifiersQuery } = alertmanagerApi;
const { data: grafanaNotifiers = [], isLoading: isLoadingNotifiers } = useGrafanaNotifiersQuery();
const [testChannelValues, setTestChannelValues] = useState<GrafanaChannelValues>();
@ -67,29 +72,26 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
ReceiverFormValues<GrafanaChannelValues> | undefined,
Record<string, GrafanaManagedReceiverConfig>,
] => {
if (!existing || isLoadingNotifiers || isLoadingOnCallIntegration) {
if (!contactPoint || isLoadingNotifiers || isLoadingOnCallIntegration) {
return [undefined, {}];
}
return grafanaReceiverToFormValues(extendOnCallReceivers(existing), grafanaNotifiers);
}, [existing, isLoadingNotifiers, grafanaNotifiers, extendOnCallReceivers, isLoadingOnCallIntegration]);
return grafanaReceiverToFormValues(extendOnCallReceivers(contactPoint), grafanaNotifiers);
}, [contactPoint, isLoadingNotifiers, grafanaNotifiers, extendOnCallReceivers, isLoadingOnCallIntegration]);
const onSubmit = async (values: ReceiverFormValues<GrafanaChannelValues>) => {
const newReceiver = formValuesToGrafanaReceiver(values, id2original, defaultChannelValues, grafanaNotifiers);
const receiverWithOnCall = await createOnCallIntegrations(newReceiver);
const newConfig = updateConfigWithReceiver(config, receiverWithOnCall, existing?.name);
await dispatch(
updateAlertManagerConfigAction({
newConfig: newConfig,
oldConfig: config,
alertManagerSourceName: GRAFANA_RULES_SOURCE_NAME,
successMessage: existing ? 'Contact point updated.' : 'Contact point created',
redirectPath: '/alerting/notifications',
})
).then(() => {
dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration']));
});
if (editMode) {
await updateContactPoint({
contactPoint: newReceiver,
id: contactPoint!.id,
resourceVersion: contactPoint?.metadata?.resourceVersion,
originalName: contactPoint?.name,
});
} else {
await createContactPoint({ contactPoint: newReceiver });
}
locationService.push('/alerting/notifications');
};
const onTestChannel = (values: GrafanaChannelValues) => {
@ -102,7 +104,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
const chan = formChannelValuesToGrafanaChannelConfig(testChannelValues, defaultChannelValues, 'test', existing);
const payload = {
alertManagerSourceName,
alertManagerSourceName: GRAFANA_RULES_SOURCE_NAME,
receivers: [
{
name: 'test',
@ -116,17 +118,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
}
};
const takenReceiverNames = useMemo(
() => config.alertmanager_config.receivers?.map(({ name }) => name).filter((name) => name !== existing?.name) ?? [],
[config, existing]
);
// if any receivers in the contact point have a "provenance", the entire contact point should be readOnly
const hasProvisionedItems = existing
? (existing.grafana_managed_receiver_configs ?? []).some((item) => Boolean(item.provenance))
: false;
const isEditable = !readOnly && !hasProvisionedItems;
const isEditable = !readOnly && !contactPoint?.provisioned;
const isTestable = !readOnly;
if (isLoadingNotifiers || isLoadingOnCallIntegration) {
@ -134,7 +126,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
}
const notifiers: Notifier[] = grafanaNotifiers.map((n) => {
if (n.type === 'oncall') {
if (n.type === ReceiverTypes.OnCall) {
return {
dto: extendOnCallNotifierFeatures(n),
meta: onCallNotifierMeta,
@ -143,7 +135,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
return { dto: n };
});
const disableEditTitle = editMode && shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);
return (
<>
{hasOnCallError && (
@ -153,19 +145,18 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
</Alert>
)}
{hasProvisionedItems && <ProvisioningAlert resource={ProvisionedResource.ContactPoint} />}
{contactPoint?.provisioned && <ProvisioningAlert resource={ProvisionedResource.ContactPoint} />}
<ReceiverForm<GrafanaChannelValues>
disableEditTitle={disableEditTitle}
isEditable={isEditable}
isTestable={isTestable}
config={config}
onSubmit={onSubmit}
initialValues={existingValue}
onTestChannel={onTestChannel}
notifiers={notifiers}
alertManagerSourceName={alertManagerSourceName}
alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME}
defaultItem={{ ...defaultChannelValues }}
takenReceiverNames={takenReceiverNames}
commonSettingsComponent={GrafanaCommonChannelSettings}
customValidators={{ [ReceiverTypes.OnCall]: onCallFormValidators }}
/>

View File

@ -1,14 +1,13 @@
import { css } from '@emotion/css';
import { useCallback } from 'react';
import * as React from 'react';
import { FieldErrors, FormProvider, SubmitErrorHandler, useForm, Validate } from 'react-hook-form';
import { FieldErrors, FormProvider, SubmitErrorHandler, useForm } from 'react-hook-form';
import { GrafanaTheme2 } from '@grafana/data';
import { isFetchError } from '@grafana/runtime';
import { Alert, Button, Field, Input, LinkButton, useStyles2 } from '@grafana/ui';
import { useAppNotification } from 'app/core/copy/appNotification';
import { useCleanup } from 'app/core/hooks/useCleanup';
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
import { useValidateContactPoint } from 'app/features/alerting/unified/components/contact-points/useContactPoints';
import { getMessageFromError } from '../../../../../../core/utils/errors';
import { logError } from '../../../Analytics';
@ -24,36 +23,45 @@ import { Notifier } from './notifiers';
import { normalizeFormValues } from './util';
interface Props<R extends ChannelValues> {
config: AlertManagerCortexConfig;
notifiers: Notifier[];
defaultItem: R;
alertManagerSourceName: string;
onTestChannel?: (channel: R) => void;
onSubmit: (values: ReceiverFormValues<R>) => Promise<void>;
takenReceiverNames: string[]; // will validate that user entered receiver name is not one of these
commonSettingsComponent: CommonSettingsComponentType;
initialValues?: ReceiverFormValues<R>;
isEditable: boolean;
isTestable?: boolean;
customValidators?: Record<string, React.ComponentProps<typeof ChannelSubForm>['customValidators']>;
/**
* Should we show a warning that there is no default policy set,
* and that contact point being created will be set as the default?
*/
showDefaultRouteWarning?: boolean;
/**
* Should we disable the title editing? Required when we're using the API server,
* as at the time of writing this is not possible
*/
disableEditTitle?: boolean;
}
export function ReceiverForm<R extends ChannelValues>({
config,
initialValues,
defaultItem,
notifiers,
alertManagerSourceName,
onSubmit,
onTestChannel,
takenReceiverNames,
commonSettingsComponent,
isEditable,
isTestable,
customValidators,
}: Props<R>): JSX.Element {
showDefaultRouteWarning,
disableEditTitle,
}: Props<R>) {
const notifyApp = useAppNotification();
const styles = useStyles2(getStyles);
const validateContactPointName = useValidateContactPoint({ alertmanager: alertManagerSourceName });
// normalize deprecated and new config values
const normalizedConfig = normalizeFormValues(initialValues);
@ -84,14 +92,6 @@ export function ReceiverForm<R extends ChannelValues>({
const { fields, append, remove } = useControlledFieldArray<R>({ name: 'items', formAPI, softDelete: true });
const validateNameIsAvailable: Validate<string, ReceiverFormValues<R>> = useCallback(
(name: string) =>
takenReceiverNames.map((name) => name.trim().toLowerCase()).includes(name.trim().toLowerCase())
? 'Another receiver with this name already exists.'
: true,
[takenReceiverNames]
);
const submitCallback = async (values: ReceiverFormValues<R>) => {
try {
await onSubmit({
@ -116,7 +116,7 @@ export function ReceiverForm<R extends ChannelValues>({
return (
<FormProvider {...formAPI}>
{!config.alertmanager_config.route && (
{showDefaultRouteWarning && (
<Alert severity="warning" title="Attention">
Because there is no default policy configured yet, this contact point will automatically be set as default.
</Alert>
@ -127,11 +127,15 @@ export function ReceiverForm<R extends ChannelValues>({
</h4>
<Field label="Name" invalid={!!errors.name} error={errors.name && errors.name.message} required>
<Input
disabled={disableEditTitle}
readOnly={!isEditable}
id="name"
{...register('name', {
required: 'Name is required',
validate: { nameIsAvailable: validateNameIsAvailable },
validate: async (value) => {
const existingValue = initialValues?.name;
return validateContactPointName(value, existingValue);
},
})}
width={39}
placeholder="Name"
@ -198,7 +202,7 @@ export function ReceiverForm<R extends ChannelValues>({
disabled={isSubmitting}
variant="secondary"
data-testid="cancel-button"
href={makeAMLink('alerting/notifications', alertManagerSourceName)}
href={makeAMLink('/alerting/notifications', alertManagerSourceName)}
>
Cancel
</LinkButton>

View File

@ -35,6 +35,7 @@ export const OptionField: FC<Props> = ({
customValidator,
}) => {
const optionPath = `${pathPrefix}${pathSuffix}`;
const isSecure = pathSuffix === 'secureSettings.';
if (option.element === 'subform') {
return (
@ -75,12 +76,13 @@ export const OptionField: FC<Props> = ({
readOnly={readOnly}
pathIndex={pathPrefix}
customValidator={customValidator}
isSecure={isSecure}
/>
</Field>
);
};
const OptionInput: FC<Props & { id: string; pathIndex?: string }> = ({
const OptionInput: FC<Props & { id: string; pathIndex?: string; isSecure?: boolean }> = ({
option,
invalid,
id,
@ -88,11 +90,19 @@ const OptionInput: FC<Props & { id: string; pathIndex?: string }> = ({
pathIndex = '',
readOnly = false,
customValidator,
isSecure,
}) => {
const styles = useStyles2(getStyles);
const { control, register, unregister, getValues, setValue } = useFormContext();
const name = `${pathPrefix}${option.propertyName}`;
useEffect(() => {
// Remove the value of secure fields so it doesn't show the incorrect value when clearing the field
if (isSecure) {
setValue(name, null);
}
}, [isSecure, name, setValue]);
// workaround for https://github.com/react-hook-form/react-hook-form/issues/4993#issuecomment-829012506
useEffect(
() => () => {

View File

@ -142,7 +142,8 @@ export function useOnCallIntegration() {
return receiver;
}
const onCallIntegrations = receiver.grafana_managed_receiver_configs?.filter((c) => c.type === 'oncall') ?? [];
const onCallIntegrations =
receiver.grafana_managed_receiver_configs?.filter((c) => c.type === ReceiverTypes.OnCall) ?? [];
const newOnCallIntegrations = onCallIntegrations.filter(
(c) => c.settings[OnCallIntegrationSetting.IntegrationType] === OnCallIntegrationType.NewIntegration
);

View File

@ -95,6 +95,12 @@ const getReceiversHandler = () =>
return HttpResponse.json({ message: 'Not found.' }, { status: 404 });
});
const testReceiversHandler = () =>
http.post('/api/alertmanager/grafana/config/api/v1/receivers/test', () => {
// TODO: scaffold out response as needed by tests
return HttpResponse.json({});
});
const getGroupsHandler = () =>
http.get<{ datasourceUid: string }>('/api/alertmanager/:datasourceUid/api/v2/alerts/groups', () =>
// TODO: Scaffold out response with better data as required by tests
@ -110,6 +116,7 @@ const handlers = [
updateAlertmanagerConfigHandler(),
getGrafanaAlertmanagerTemplatePreview(),
getReceiversHandler(),
testReceiversHandler(),
getGroupsHandler(),
];
export default handlers;

View File

@ -1,3 +1,4 @@
import { camelCase } from 'lodash';
import { HttpResponse, http } from 'msw';
import alertmanagerConfig from 'app/features/alerting/unified/components/contact-points/__mocks__/alertmanager.config.mock.json';
@ -16,7 +17,11 @@ const mappedReceivers =
return integration.provenance;
})?.provenance || PROVENANCE_NONE;
return {
metadata: { annotations: { [PROVENANCE_ANNOTATION]: provenance } },
metadata: {
// This isn't exactly accurate, but its the cleanest way to use the same data for AM config and K8S responses
uid: camelCase(contactPoint.name),
annotations: { [PROVENANCE_ANNOTATION]: provenance },
},
spec: {
title: contactPoint.name,
integrations: contactPoint.grafana_managed_receiver_configs || [],
@ -34,5 +39,31 @@ const listNamespacedReceiverHandler = () =>
return HttpResponse.json(parsedReceivers);
});
const handlers = [listNamespacedReceiverHandler()];
const createNamespacedReceiverHandler = () =>
http.post<{ namespace: string }>(
`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/receivers`,
async ({ request }) => {
const body = await request.json();
return HttpResponse.json(body);
}
);
const deleteNamespacedReceiverHandler = () =>
http.delete<{ namespace: string; name: string }>(
`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/receivers/:name`,
({ params }) => {
const { name } = params;
const matchedReceiver = parsedReceivers.items.find((receiver) => receiver.metadata.uid === name);
if (matchedReceiver) {
return HttpResponse.json(parsedReceivers);
}
return HttpResponse.json({}, { status: 404 });
}
);
const handlers = [
listNamespacedReceiverHandler(),
createNamespacedReceiverHandler(),
deleteNamespacedReceiverHandler(),
];
export default handlers;

View File

@ -25,6 +25,56 @@ const injectedRtkApi = api
}),
providesTags: ['Receiver'],
}),
createNamespacedReceiver: build.mutation<CreateNamespacedReceiverApiResponse, CreateNamespacedReceiverApiArg>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/receivers`,
method: 'POST',
body: queryArg.comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
},
}),
invalidatesTags: ['Receiver'],
}),
readNamespacedReceiver: build.query<ReadNamespacedReceiverApiResponse, ReadNamespacedReceiverApiArg>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/receivers/${queryArg.name}`,
params: { pretty: queryArg.pretty },
}),
providesTags: ['Receiver'],
}),
replaceNamespacedReceiver: build.mutation<ReplaceNamespacedReceiverApiResponse, ReplaceNamespacedReceiverApiArg>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/receivers/${queryArg.name}`,
method: 'PUT',
body: queryArg.comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
},
}),
invalidatesTags: ['Receiver'],
}),
deleteNamespacedReceiver: build.mutation<DeleteNamespacedReceiverApiResponse, DeleteNamespacedReceiverApiArg>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/receivers/${queryArg.name}`,
method: 'DELETE',
body: queryArg.ioK8SApimachineryPkgApisMetaV1DeleteOptions,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
gracePeriodSeconds: queryArg.gracePeriodSeconds,
orphanDependents: queryArg.orphanDependents,
propagationPolicy: queryArg.propagationPolicy,
},
}),
invalidatesTags: ['Receiver'],
}),
}),
overrideExisting: false,
});
@ -39,7 +89,7 @@ export type ListNamespacedReceiverApiArg = {
/** 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. */
@ -47,19 +97,19 @@ export type ListNamespacedReceiverApiArg = {
/** 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
@ -69,7 +119,7 @@ export type ListNamespacedReceiverApiArg = {
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. */
@ -77,6 +127,71 @@ export type ListNamespacedReceiverApiArg = {
/** 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 CreateNamespacedReceiverApiResponse = /** status 200 OK */
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver
| /** status 202 Accepted */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
export type CreateNamespacedReceiverApiArg = {
/** 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;
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
};
export type ReadNamespacedReceiverApiResponse =
/** status 200 OK */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
export type ReadNamespacedReceiverApiArg = {
/** name of the Receiver */
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 ReplaceNamespacedReceiverApiResponse = /** status 200 OK */
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
export type ReplaceNamespacedReceiverApiArg = {
/** name of the Receiver */
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;
/** 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;
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
};
export type DeleteNamespacedReceiverApiResponse = /** status 200 OK */
| IoK8SApimachineryPkgApisMetaV1Status
| /** status 202 Accepted */ IoK8SApimachineryPkgApisMetaV1Status;
export type DeleteNamespacedReceiverApiArg = {
/** name of the Receiver */
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;
/** 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 = {
@ -115,21 +230,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. */
@ -143,28 +258,29 @@ 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;
};
export type ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured = {
[key: string]: any;
};
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Integration = {
SecureFields?: {
[key: string]: boolean;
};
SecureFields?: ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured;
disableResolveMessage?: boolean;
settings: string;
settings: ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured;
type: string;
uid?: string;
};
@ -198,3 +314,69 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1ReceiverL
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;
};

View File

@ -77,24 +77,6 @@ const injectedRtkApi = api
}),
invalidatesTags: ['TimeInterval'],
}),
patchNamespacedTimeInterval: build.mutation<
PatchNamespacedTimeIntervalApiResponse,
PatchNamespacedTimeIntervalApiArg
>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/timeintervals/${queryArg.name}`,
method: 'PATCH',
body: queryArg.ioK8SApimachineryPkgApisMetaV1Patch,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
force: queryArg.force,
},
}),
invalidatesTags: ['TimeInterval'],
}),
}),
overrideExisting: false,
});
@ -202,26 +184,6 @@ export type DeleteNamespacedTimeIntervalApiArg = {
propagationPolicy?: string;
ioK8SApimachineryPkgApisMetaV1DeleteOptions: IoK8SApimachineryPkgApisMetaV1DeleteOptions;
};
export type PatchNamespacedTimeIntervalApiResponse = /** status 200 OK */
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TimeInterval
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TimeInterval;
export type PatchNamespacedTimeIntervalApiArg = {
/** name of the TimeInterval */
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;
/** 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. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */
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;
/** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */
force?: boolean;
ioK8SApimachineryPkgApisMetaV1Patch: IoK8SApimachineryPkgApisMetaV1Patch;
};
export type IoK8SApimachineryPkgApisMetaV1Time = string;
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
@ -412,4 +374,3 @@ export type IoK8SApimachineryPkgApisMetaV1DeleteOptions = {
/** 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;
};
export type IoK8SApimachineryPkgApisMetaV1Patch = object;

View File

@ -331,7 +331,14 @@ export const updateAlertManagerConfigAction = createAsyncThunk<void, UpdateAlert
);
}
await updateAlertManagerConfig(alertManagerSourceName, addDefaultsToAlertmanagerConfig(newConfig));
thunkAPI.dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration']));
thunkAPI.dispatch(
alertmanagerApi.util.invalidateTags([
'AlertmanagerConfiguration',
'ContactPoint',
'ContactPointsStatus',
'Receiver',
])
);
if (redirectPath) {
const options = new URLSearchParams(redirectSearch ?? '');
locationService.push(makeAMLink(redirectPath, alertManagerSourceName, options));

View File

@ -1,5 +1,6 @@
import { config } from '@grafana/runtime';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { PROVENANCE_ANNOTATION, PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
/**
* Get the correct namespace to use when using the K8S API.
@ -16,3 +17,16 @@ export const shouldUseK8sApi = (alertmanager?: string) => {
const featureToggleEnabled = config.featureToggles.alertingApiServer;
return featureToggleEnabled && alertmanager === GRAFANA_RULES_SOURCE_NAME;
};
type Entity = {
metadata: {
annotations?: Record<string, string>;
};
};
/**
* Check the metadata of a kubernetes entity and check if has the necessary annotations
* that denote it as provisioned
*/
export const isK8sEntityProvisioned = (item: Entity) =>
item.metadata.annotations?.[PROVENANCE_ANNOTATION] !== PROVENANCE_NONE;

View File

@ -125,38 +125,39 @@ export function formValuesToCloudReceiver(
export function updateConfigWithReceiver(
config: AlertManagerCortexConfig,
receiver: Receiver,
replaceReceiverName?: string
existingReceiverName?: string
): AlertManagerCortexConfig {
const oldReceivers = config.alertmanager_config.receivers ?? [];
const existingReceivers = config.alertmanager_config.receivers ?? [];
const receiverWasRenamed = existingReceiverName && receiver.name !== existingReceiverName;
// sanity check that name is not duplicated
if (receiver.name !== replaceReceiverName && !!oldReceivers.find(({ name }) => name === receiver.name)) {
if (!existingReceiverName && !!existingReceivers.find(({ name }) => name === receiver.name)) {
throw new Error(`Duplicate receiver name ${receiver.name}`);
}
// sanity check that existing receiver exists
if (replaceReceiverName && !oldReceivers.find(({ name }) => name === replaceReceiverName)) {
throw new Error(`Expected receiver ${replaceReceiverName} to exist, but did not find it in the config`);
if (existingReceiverName && !existingReceivers.find(({ name }) => name === existingReceiverName)) {
throw new Error(`Expected receiver ${existingReceiverName} to exist, but did not find it in the config`);
}
const updated: AlertManagerCortexConfig = {
...config,
alertmanager_config: {
// @todo rename receiver on routes as necessary
...config.alertmanager_config,
receivers: replaceReceiverName
? oldReceivers.map((existingReceiver) =>
existingReceiver.name === replaceReceiverName ? receiver : existingReceiver
receivers: existingReceiverName
? existingReceivers.map((existingReceiver) =>
existingReceiver.name === existingReceiverName ? receiver : existingReceiver
)
: [...oldReceivers, receiver],
: [...existingReceivers, receiver],
},
};
// if receiver was renamed, rename it in routes as well
if (updated.alertmanager_config.route && replaceReceiverName && receiver.name !== replaceReceiverName) {
if (updated.alertmanager_config.route && receiverWasRenamed) {
updated.alertmanager_config.route = renameReceiverInRoute(
updated.alertmanager_config.route,
replaceReceiverName,
existingReceiverName,
receiver.name
);
}

View File

@ -1,5 +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';
export type AlertManagerCortexConfig = {
template_files: Record<string, string>;
@ -65,12 +66,15 @@ export type WebhookConfig = {
max_alerts?: number;
};
type GrafanaManagedReceiverConfigSettings<T = any> = Record<string, T>;
export type GrafanaManagedReceiverConfig = {
uid?: string;
disableResolveMessage?: boolean;
secureFields?: Record<string, boolean>;
secureSettings?: Record<string, any>;
settings?: Record<string, any>; // sometimes settings are optional for security reasons (RBAC)
secureSettings?: GrafanaManagedReceiverConfigSettings;
/** If retrieved from k8s API, SecureSettings property name is different */
// SecureSettings?: GrafanaManagedReceiverConfigSettings<boolean>;
settings: GrafanaManagedReceiverConfigSettings;
type: string;
/**
* Name of the _receiver_, which in most cases will be the
@ -88,6 +92,10 @@ export type GrafanaManagedReceiverConfig = {
export interface GrafanaManagedContactPoint {
name: string;
/** If parsed from k8s API, we'll have an ID property */
id?: string;
metadata?: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
provisioned?: boolean;
grafana_managed_receiver_configs?: GrafanaManagedReceiverConfig[];
}

View File

@ -32,7 +32,6 @@ const config: ConfigFile = {
'listNamespacedTimeInterval',
'createNamespacedTimeInterval',
'deleteNamespacedTimeInterval',
'patchNamespacedTimeInterval',
'replaceNamespacedTimeInterval',
],
exportName: 'generatedTimeIntervalsApi',
@ -41,7 +40,13 @@ const config: ConfigFile = {
'../public/app/features/alerting/unified/openapi/receiversApi.gen.ts': {
apiFile: '../public/app/features/alerting/unified/api/alertingApi.ts',
apiImport: 'alertingApi',
filterEndpoints: ['listNamespacedReceiver'],
filterEndpoints: [
'listNamespacedReceiver',
'createNamespacedReceiver',
'readNamespacedReceiver',
'deleteNamespacedReceiver',
'replaceNamespacedReceiver',
],
exportName: 'generatedReceiversApi',
flattenArg: false,
},