mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Alerting: Edit, create and delete contact points via k8s API (#91701)
This commit is contained in:
parent
f4a8e0a214
commit
690fbe6077
@ -1817,9 +1817,6 @@ exports[`better eslint`] = {
|
|||||||
"public/app/features/alerting/unified/components/receivers/DuplicateTemplateView.tsx:5381": [
|
"public/app/features/alerting/unified/components/receivers/DuplicateTemplateView.tsx:5381": [
|
||||||
[0, 0, 0, "No untranslated strings. Wrap text with <Trans />", "0"]
|
[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": [
|
"public/app/features/alerting/unified/components/receivers/EditTemplateView.tsx:5381": [
|
||||||
[0, 0, 0, "No untranslated strings. Wrap text with <Trans />", "0"]
|
[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": [
|
"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.", "0"],
|
||||||
[0, 0, 0, "Unexpected any. Specify a different type.", "1"],
|
[0, 0, 0, "Unexpected any. Specify a different type.", "1"]
|
||||||
[0, 0, 0, "Unexpected any. Specify a different type.", "2"]
|
|
||||||
],
|
],
|
||||||
"public/app/plugins/datasource/azuremonitor/azureMetadata/index.ts:5381": [
|
"public/app/plugins/datasource/azuremonitor/azureMetadata/index.ts:5381": [
|
||||||
[0, 0, 0, "Do not use export all (\`export * from ...\`)", "0"],
|
[0, 0, 0, "Do not use export all (\`export * from ...\`)", "0"],
|
||||||
|
@ -7,14 +7,14 @@ import { AlertmanagerPageWrapper } from './components/AlertingPageWrapper';
|
|||||||
|
|
||||||
const ContactPointsV2 = SafeDynamicImport(() => import('./components/contact-points/ContactPoints'));
|
const ContactPointsV2 = SafeDynamicImport(() => import('./components/contact-points/ContactPoints'));
|
||||||
const EditContactPoint = SafeDynamicImport(() => import('./components/contact-points/EditContactPoint'));
|
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 GlobalConfig = SafeDynamicImport(() => import('./components/contact-points/components/GlobalConfig'));
|
||||||
|
|
||||||
const ContactPoints = (): JSX.Element => (
|
const ContactPoints = (): JSX.Element => (
|
||||||
<AlertmanagerPageWrapper navId="receivers" accessType="notification">
|
<AlertmanagerPageWrapper navId="receivers" accessType="notification">
|
||||||
<Switch>
|
<Switch>
|
||||||
<Route exact={true} path="/alerting/notifications" component={ContactPointsV2} />
|
<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/receivers/:name/edit" component={EditContactPoint} />
|
||||||
<Route exact={true} path="/alerting/notifications/global-config" component={GlobalConfig} />
|
<Route exact={true} path="/alerting/notifications/global-config" component={GlobalConfig} />
|
||||||
</Switch>
|
</Switch>
|
||||||
|
@ -113,6 +113,9 @@ export const alertingApi = createApi({
|
|||||||
'GrafanaSlo',
|
'GrafanaSlo',
|
||||||
'RuleGroup',
|
'RuleGroup',
|
||||||
'RuleNamespace',
|
'RuleNamespace',
|
||||||
|
'ContactPoint',
|
||||||
|
'ContactPointsStatus',
|
||||||
|
'Receiver',
|
||||||
],
|
],
|
||||||
endpoints: () => ({}),
|
endpoints: () => ({}),
|
||||||
});
|
});
|
||||||
|
@ -47,6 +47,20 @@ interface AlertmanagerAlertsFilter {
|
|||||||
matchers?: Matcher[];
|
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
|
// Based on https://github.com/prometheus/alertmanager/blob/main/api/v2/openapi.yaml
|
||||||
export const alertmanagerApi = alertingApi.injectEndpoints({
|
export const alertmanagerApi = alertingApi.injectEndpoints({
|
||||||
endpoints: (build) => ({
|
endpoints: (build) => ({
|
||||||
@ -120,7 +134,7 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
|
|||||||
data: config,
|
data: config,
|
||||||
showSuccessAlert: false,
|
showSuccessAlert: false,
|
||||||
}),
|
}),
|
||||||
invalidatesTags: ['AlertingConfiguration', 'AlertmanagerConfiguration', 'AlertmanagerConnectionStatus'],
|
invalidatesTags: [...ALERTMANAGER_PROVIDED_ENTITY_TAGS],
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getAlertmanagerConfigurationHistory: build.query<AlertManagerCortexConfig[], void>({
|
getAlertmanagerConfigurationHistory: build.query<AlertManagerCortexConfig[], void>({
|
||||||
@ -248,7 +262,7 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
|
|||||||
data: config,
|
data: config,
|
||||||
showSuccessAlert: false,
|
showSuccessAlert: false,
|
||||||
}),
|
}),
|
||||||
invalidatesTags: ['AlertmanagerConfiguration'],
|
invalidatesTags: ['AlertmanagerConfiguration', 'ContactPoint', 'ContactPointsStatus', 'Receiver'],
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// Grafana Managed Alertmanager only
|
// Grafana Managed Alertmanager only
|
||||||
@ -274,12 +288,13 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
|
|||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
},
|
},
|
||||||
|
providesTags: ['ContactPointsStatus'],
|
||||||
}),
|
}),
|
||||||
// Grafana Managed Alertmanager only
|
// Grafana Managed Alertmanager only
|
||||||
// TODO: Remove as part of migration to k8s API for receivers
|
// TODO: Remove as part of migration to k8s API for receivers
|
||||||
getContactPointsList: build.query<GrafanaManagedContactPoint[], void>({
|
getContactPointsList: build.query<GrafanaManagedContactPoint[], void>({
|
||||||
query: () => ({ url: '/api/v1/notifications/receivers' }),
|
query: () => ({ url: '/api/v1/notifications/receivers' }),
|
||||||
providesTags: ['AlertmanagerConfiguration'],
|
providesTags: ['ContactPoint'],
|
||||||
}),
|
}),
|
||||||
getMuteTimingList: build.query<MuteTimeInterval[], void>({
|
getMuteTimingList: build.query<MuteTimeInterval[], void>({
|
||||||
query: () => ({ url: '/api/v1/notifications/time-intervals' }),
|
query: () => ({ url: '/api/v1/notifications/time-intervals' }),
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
/** @deprecated To be deleted - use alertingApiServer API instead */
|
||||||
|
|
||||||
import { ContactPointsState } from 'app/types';
|
import { ContactPointsState } from 'app/types';
|
||||||
|
|
||||||
import { CONTACT_POINTS_STATE_INTERVAL_MS } from '../utils/constants';
|
import { CONTACT_POINTS_STATE_INTERVAL_MS } from '../utils/constants';
|
||||||
|
22
public/app/features/alerting/unified/api/receiversK8sApi.ts
Normal file
22
public/app/features/alerting/unified/api/receiversK8sApi.ts
Normal 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;
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
@ -7,6 +7,9 @@ import { Icon, Stack, Text, Tooltip, useStyles2 } from '@grafana/ui';
|
|||||||
import { Trans } from 'app/core/internationalization';
|
import { Trans } from 'app/core/internationalization';
|
||||||
import { PrimaryText } from 'app/features/alerting/unified/components/common/TextVariants';
|
import { PrimaryText } from 'app/features/alerting/unified/components/common/TextVariants';
|
||||||
import { ContactPointHeader } from 'app/features/alerting/unified/components/contact-points/ContactPointHeader';
|
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 { receiverTypeNames } from 'app/plugins/datasource/alertmanager/consts';
|
||||||
import { GrafanaNotifierType, NotifierStatus } from 'app/types/alerting';
|
import { GrafanaNotifierType, NotifierStatus } from 'app/types/alerting';
|
||||||
|
|
||||||
@ -16,26 +19,19 @@ import { ReceiverMetadataBadge } from '../receivers/grafanaAppReceivers/Receiver
|
|||||||
import { ReceiverPluginMetadata } from '../receivers/grafanaAppReceivers/useReceiversMetadata';
|
import { ReceiverPluginMetadata } from '../receivers/grafanaAppReceivers/useReceiversMetadata';
|
||||||
|
|
||||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from './constants';
|
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 {
|
interface ContactPointProps {
|
||||||
name: string;
|
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
provisioned?: boolean;
|
contactPoint: ContactPointWithMetadata;
|
||||||
receivers: ReceiverConfigWithMetadata[];
|
|
||||||
policies?: RouteReference[];
|
|
||||||
onDelete: (name: string) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ContactPoint = ({
|
export const ContactPoint = ({ disabled = false, contactPoint }: ContactPointProps) => {
|
||||||
name,
|
const { grafana_managed_receiver_configs: receivers } = contactPoint;
|
||||||
disabled = false,
|
|
||||||
provisioned = false,
|
|
||||||
receivers,
|
|
||||||
policies = [],
|
|
||||||
onDelete,
|
|
||||||
}: ContactPointProps) => {
|
|
||||||
const styles = useStyles2(getStyles);
|
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?
|
// 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]));
|
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">
|
<div className={styles.contactPointWrapper} data-testid="contact-point">
|
||||||
<Stack direction="column" gap={0}>
|
<Stack direction="column" gap={0}>
|
||||||
<ContactPointHeader
|
<ContactPointHeader
|
||||||
name={name}
|
contactPoint={contactPoint}
|
||||||
policies={policies}
|
|
||||||
provisioned={provisioned}
|
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onDelete={onDelete}
|
onDelete={(contactPointToDelete) =>
|
||||||
|
showDeleteModal({
|
||||||
|
name: contactPointToDelete.id || contactPointToDelete.name,
|
||||||
|
resourceVersion: contactPointToDelete.metadata?.resourceVersion,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
{showFullMetadata ? (
|
{showFullMetadata ? (
|
||||||
<div>
|
<div>
|
||||||
@ -58,7 +57,6 @@ export const ContactPoint = ({
|
|||||||
const sendingResolved = !Boolean(receiver.disableResolveMessage);
|
const sendingResolved = !Boolean(receiver.disableResolveMessage);
|
||||||
const pluginMetadata = receiver[RECEIVER_PLUGIN_META_KEY];
|
const pluginMetadata = receiver[RECEIVER_PLUGIN_META_KEY];
|
||||||
const key = metadata.name + index;
|
const key = metadata.name + index;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ContactPointReceiver
|
<ContactPointReceiver
|
||||||
key={key}
|
key={key}
|
||||||
@ -78,6 +76,7 @@ export const ContactPoint = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
{DeleteModal}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@ -6,6 +6,7 @@ import { Dropdown, LinkButton, Menu, Stack, Text, TextLink, Tooltip, useStyles2
|
|||||||
import { t } from 'app/core/internationalization';
|
import { t } from 'app/core/internationalization';
|
||||||
import ConditionalWrap from 'app/features/alerting/unified/components/ConditionalWrap';
|
import ConditionalWrap from 'app/features/alerting/unified/components/ConditionalWrap';
|
||||||
import { useExportContactPoint } from 'app/features/alerting/unified/components/contact-points/useExportContactPoint';
|
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 { AlertmanagerAction, useAlertmanagerAbility } from '../../hooks/useAbilities';
|
||||||
import { createRelativeUrl } from '../../utils/url';
|
import { createRelativeUrl } from '../../utils/url';
|
||||||
@ -14,18 +15,16 @@ import { ProvisioningBadge } from '../Provisioning';
|
|||||||
import { Spacer } from '../Spacer';
|
import { Spacer } from '../Spacer';
|
||||||
|
|
||||||
import { UnusedContactPointBadge } from './components/UnusedBadge';
|
import { UnusedContactPointBadge } from './components/UnusedBadge';
|
||||||
import { RouteReference } from './utils';
|
import { ContactPointWithMetadata } from './utils';
|
||||||
|
|
||||||
interface ContactPointHeaderProps {
|
interface ContactPointHeaderProps {
|
||||||
name: string;
|
contactPoint: ContactPointWithMetadata;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
provisioned?: boolean;
|
onDelete: (contactPoint: ContactPointWithMetadata) => void;
|
||||||
policies?: RouteReference[];
|
|
||||||
onDelete: (name: string) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ContactPointHeader = (props: ContactPointHeaderProps) => {
|
export const ContactPointHeader = ({ contactPoint, disabled = false, onDelete }: ContactPointHeaderProps) => {
|
||||||
const { name, disabled = false, provisioned = false, policies = [], onDelete } = props;
|
const { name, id, provisioned, policies = [] } = contactPoint;
|
||||||
const styles = useStyles2(getStyles);
|
const styles = useStyles2(getStyles);
|
||||||
|
|
||||||
const [exportSupported, exportAllowed] = useAlertmanagerAbility(AlertmanagerAction.ExportContactPoint);
|
const [exportSupported, exportAllowed] = useAlertmanagerAbility(AlertmanagerAction.ExportContactPoint);
|
||||||
@ -76,7 +75,7 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
|
|||||||
icon="trash-alt"
|
icon="trash-alt"
|
||||||
destructive
|
destructive
|
||||||
disabled={disabled || !canDelete}
|
disabled={disabled || !canDelete}
|
||||||
onClick={() => onDelete(name)}
|
onClick={() => onDelete(contactPoint)}
|
||||||
/>
|
/>
|
||||||
</ConditionalWrap>
|
</ConditionalWrap>
|
||||||
);
|
);
|
||||||
@ -86,6 +85,10 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
|
|||||||
count: numberOfPolicies,
|
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 (
|
return (
|
||||||
<div className={styles.headerWrapper}>
|
<div className={styles.headerWrapper}>
|
||||||
<Stack direction="row" alignItems="center" gap={1}>
|
<Stack direction="row" alignItems="center" gap={1}>
|
||||||
@ -104,7 +107,9 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
|
|||||||
{referencedByPoliciesText}
|
{referencedByPoliciesText}
|
||||||
</TextLink>
|
</TextLink>
|
||||||
)}
|
)}
|
||||||
{provisioned && <ProvisioningBadge />}
|
{provisioned && (
|
||||||
|
<ProvisioningBadge tooltip provenance={contactPoint.metadata?.annotations?.[PROVENANCE_ANNOTATION]} />
|
||||||
|
)}
|
||||||
{!isReferencedByAnyPolicy && <UnusedContactPointBadge />}
|
{!isReferencedByAnyPolicy && <UnusedContactPointBadge />}
|
||||||
<Spacer />
|
<Spacer />
|
||||||
<LinkButton
|
<LinkButton
|
||||||
@ -117,13 +122,13 @@ export const ContactPointHeader = (props: ContactPointHeaderProps) => {
|
|||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
aria-label={`${canEdit ? 'edit' : 'view'}-action`}
|
aria-label={`${canEdit ? 'edit' : 'view'}-action`}
|
||||||
data-testid={`${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'}
|
{canEdit ? 'Edit' : 'View'}
|
||||||
</LinkButton>
|
</LinkButton>
|
||||||
{menuActions.length > 0 && (
|
{menuActions.length > 0 && (
|
||||||
<Dropdown overlay={<Menu>{menuActions}</Menu>}>
|
<Dropdown overlay={<Menu>{menuActions}</Menu>}>
|
||||||
<MoreButton />
|
<MoreButton aria-label={`More actions for contact point "${contactPoint.name}"`} />
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
@ -1,10 +1,9 @@
|
|||||||
import userEvent from '@testing-library/user-event';
|
|
||||||
import { MemoryHistoryBuildOptions } from 'history';
|
import { MemoryHistoryBuildOptions } from 'history';
|
||||||
import { noop } from 'lodash';
|
|
||||||
import { ComponentProps, ReactNode } from 'react';
|
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 { selectors } from '@grafana/e2e-selectors';
|
||||||
|
import { config } from '@grafana/runtime';
|
||||||
import { AlertManagerDataSourceJsonData, AlertManagerImplementation } from 'app/plugins/datasource/alertmanager/types';
|
import { AlertManagerDataSourceJsonData, AlertManagerImplementation } from 'app/plugins/datasource/alertmanager/types';
|
||||||
import { AccessControlAction } from 'app/types';
|
import { AccessControlAction } from 'app/types';
|
||||||
|
|
||||||
@ -12,7 +11,7 @@ import { setupMswServer } from '../../mockApi';
|
|||||||
import { grantUserPermissions, mockDataSource } from '../../mocks';
|
import { grantUserPermissions, mockDataSource } from '../../mocks';
|
||||||
import { AlertmanagerProvider } from '../../state/AlertmanagerContext';
|
import { AlertmanagerProvider } from '../../state/AlertmanagerContext';
|
||||||
import { setupDataSources } from '../../testSetup/datasources';
|
import { setupDataSources } from '../../testSetup/datasources';
|
||||||
import { DataSourceType } from '../../utils/datasource';
|
import { DataSourceType, GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
|
||||||
|
|
||||||
import { ContactPoint } from './ContactPoint';
|
import { ContactPoint } from './ContactPoint';
|
||||||
import ContactPointsPageContents from './ContactPoints';
|
import ContactPointsPageContents from './ContactPoints';
|
||||||
@ -20,7 +19,7 @@ import setupMimirFlavoredServer, { MIMIR_DATASOURCE_UID } from './__mocks__/mimi
|
|||||||
import setupVanillaAlertmanagerFlavoredServer, {
|
import setupVanillaAlertmanagerFlavoredServer, {
|
||||||
VANILLA_ALERTMANAGER_DATASOURCE_UID,
|
VANILLA_ALERTMANAGER_DATASOURCE_UID,
|
||||||
} from './__mocks__/vanillaAlertmanagerServer';
|
} 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.
|
* 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 }
|
{ 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', () => {
|
||||||
describe('Contact points with Grafana managed alertmanager', () => {
|
describe('Contact points with Grafana managed alertmanager', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@ -124,7 +141,7 @@ describe('contact points', () => {
|
|||||||
it('should disable certain actions if the user has no write permissions', async () => {
|
it('should disable certain actions if the user has no write permissions', async () => {
|
||||||
grantUserPermissions([AccessControlAction.AlertingNotificationsRead]);
|
grantUserPermissions([AccessControlAction.AlertingNotificationsRead]);
|
||||||
|
|
||||||
renderWithProvider(<ContactPointsPageContents />);
|
const { user } = renderWithProvider(<ContactPointsPageContents />);
|
||||||
|
|
||||||
// wait for loading to be done
|
// wait for loading to be done
|
||||||
await waitForElementToBeRemoved(screen.queryByText('Loading...'));
|
await waitForElementToBeRemoved(screen.queryByText('Loading...'));
|
||||||
@ -145,34 +162,33 @@ describe('contact points', () => {
|
|||||||
|
|
||||||
// check if all of the delete buttons are disabled
|
// check if all of the delete buttons are disabled
|
||||||
for await (const button of moreButtons) {
|
for await (const button of moreButtons) {
|
||||||
await userEvent.click(button);
|
await user.click(button);
|
||||||
const deleteButton = screen.queryByRole('menuitem', { name: 'delete' });
|
const deleteButton = screen.queryByRole('menuitem', { name: 'delete' });
|
||||||
expect(deleteButton).toBeDisabled();
|
expect(deleteButton).toBeDisabled();
|
||||||
// click outside the menu to close it otherwise we can't interact with the rest of the page
|
// 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
|
// check buttons in Notification Templates
|
||||||
const notificationTemplatesTab = screen.getByRole('tab', { name: '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');
|
expect(screen.getByRole('link', { name: 'Add notification template' })).toHaveAttribute('aria-disabled', 'true');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should call delete when clicked and not disabled', async () => {
|
it('allows deleting when not disabled', async () => {
|
||||||
const onDelete = jest.fn();
|
renderWithProvider(
|
||||||
renderWithProvider(<ContactPoint name={'my-contact-point'} receivers={[]} onDelete={onDelete} />);
|
<ContactPointsPageContents />,
|
||||||
|
{ initialEntries: ['/?tab=contact_points'] },
|
||||||
|
{ alertmanagerSourceName: GRAFANA_RULES_SOURCE_NAME }
|
||||||
|
);
|
||||||
|
|
||||||
const moreActions = screen.getByRole('button', { name: /More/ });
|
await attemptDeleteContactPoint('lotsa-emails');
|
||||||
await userEvent.click(moreActions);
|
|
||||||
|
|
||||||
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
await userEvent.click(deleteButton);
|
|
||||||
|
|
||||||
expect(onDelete).toHaveBeenCalledWith('my-contact-point');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should disable edit button', async () => {
|
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/ });
|
const moreActions = screen.getByRole('button', { name: /More/ });
|
||||||
expect(moreActions).toBeEnabled();
|
expect(moreActions).toBeEnabled();
|
||||||
@ -182,7 +198,7 @@ describe('contact points', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should disable buttons when provisioned', async () => {
|
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();
|
expect(screen.getByText(/provisioned/i)).toBeInTheDocument();
|
||||||
|
|
||||||
@ -194,7 +210,7 @@ describe('contact points', () => {
|
|||||||
|
|
||||||
const moreActions = screen.getByRole('button', { name: /More/ });
|
const moreActions = screen.getByRole('button', { name: /More/ });
|
||||||
expect(moreActions).toBeEnabled();
|
expect(moreActions).toBeEnabled();
|
||||||
await userEvent.click(moreActions);
|
await user.click(moreActions);
|
||||||
|
|
||||||
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
||||||
expect(deleteButton).toBeDisabled();
|
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();
|
expect(screen.getByRole('link', { name: /1 notification policy/ })).toBeInTheDocument();
|
||||||
|
|
||||||
const moreActions = screen.getByRole('button', { name: /More/ });
|
const moreActions = screen.getByRole('button', { name: /More/ });
|
||||||
await userEvent.click(moreActions);
|
await user.click(moreActions);
|
||||||
|
|
||||||
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
||||||
expect(deleteButton).toBeDisabled();
|
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/ });
|
const moreActions = screen.getByRole('button', { name: /More/ });
|
||||||
await userEvent.click(moreActions);
|
await user.click(moreActions);
|
||||||
|
|
||||||
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
const deleteButton = screen.getByRole('menuitem', { name: /delete/i });
|
||||||
expect(deleteButton).toBeEnabled();
|
expect(deleteButton).toBeEnabled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to search', async () => {
|
it('should be able to search', async () => {
|
||||||
renderWithProvider(<ContactPointsPageContents />);
|
const { user } = renderWithProvider(<ContactPointsPageContents />);
|
||||||
|
|
||||||
const searchInput = await screen.findByRole('textbox', { name: 'search contact points' });
|
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(searchInput).toHaveValue('slack');
|
||||||
|
|
||||||
expect(await screen.findByText('Slack with multiple channels')).toBeInTheDocument();
|
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
|
// ⚠️ 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' });
|
const clearButton = screen.getByRole('button', { name: 'clear' });
|
||||||
await userEvent.click(clearButton);
|
await user.click(clearButton);
|
||||||
expect(searchInput).toHaveValue('');
|
expect(searchInput).toHaveValue('');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -332,7 +348,7 @@ describe('contact points', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should not allow any editing because it's not supported", async () => {
|
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,
|
alertmanagerSourceName: VANILLA_ALERTMANAGER_DATASOURCE_UID,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -347,8 +363,45 @@ describe('contact points', () => {
|
|||||||
|
|
||||||
// check buttons in Notification Templates
|
// check buttons in Notification Templates
|
||||||
const notificationTemplatesTab = screen.getByRole('tab', { name: '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();
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
@ -25,11 +25,10 @@ import { ContactPoint } from './ContactPoint';
|
|||||||
import { NotificationTemplates } from './NotificationTemplates';
|
import { NotificationTemplates } from './NotificationTemplates';
|
||||||
import { ContactPointsFilter } from './components/ContactPointsFilter';
|
import { ContactPointsFilter } from './components/ContactPointsFilter';
|
||||||
import { GlobalConfigAlert } from './components/GlobalConfigAlert';
|
import { GlobalConfigAlert } from './components/GlobalConfigAlert';
|
||||||
import { useDeleteContactPointModal } from './components/Modals';
|
import { useContactPointsWithStatus } from './useContactPoints';
|
||||||
import { useContactPointsWithStatus, useDeleteContactPoint } from './useContactPoints';
|
|
||||||
import { useContactPointsSearch } from './useContactPointsSearch';
|
import { useContactPointsSearch } from './useContactPointsSearch';
|
||||||
import { ALL_CONTACT_POINTS, useExportContactPoint } from './useExportContactPoint';
|
import { ALL_CONTACT_POINTS, useExportContactPoint } from './useExportContactPoint';
|
||||||
import { ContactPointWithMetadata, isProvisioned } from './utils';
|
import { ContactPointWithMetadata } from './utils';
|
||||||
|
|
||||||
export enum ActiveTab {
|
export enum ActiveTab {
|
||||||
ContactPoints = 'contact_points',
|
ContactPoints = 'contact_points',
|
||||||
@ -48,7 +47,6 @@ const ContactPointsTab = () => {
|
|||||||
fetchStatuses: true,
|
fetchStatuses: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { deleteTrigger, updateAlertmanagerState } = useDeleteContactPoint(selectedAlertmanager!);
|
|
||||||
const [addContactPointSupported, addContactPointAllowed] = useAlertmanagerAbility(
|
const [addContactPointSupported, addContactPointAllowed] = useAlertmanagerAbility(
|
||||||
AlertmanagerAction.CreateContactPoint
|
AlertmanagerAction.CreateContactPoint
|
||||||
);
|
);
|
||||||
@ -56,7 +54,6 @@ const ContactPointsTab = () => {
|
|||||||
AlertmanagerAction.ExportContactPoint
|
AlertmanagerAction.ExportContactPoint
|
||||||
);
|
);
|
||||||
|
|
||||||
const [DeleteModal, showDeleteModal] = useDeleteContactPointModal(deleteTrigger, updateAlertmanagerState.isLoading);
|
|
||||||
const [ExportDrawer, showExportDrawer] = useExportContactPoint();
|
const [ExportDrawer, showExportDrawer] = useExportContactPoint();
|
||||||
|
|
||||||
const search = queryParams.get('search');
|
const search = queryParams.get('search');
|
||||||
@ -102,16 +99,9 @@ const ContactPointsTab = () => {
|
|||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
</Stack>
|
</Stack>
|
||||||
<ContactPointsList
|
<ContactPointsList contactPoints={contactPoints} search={search} pageSize={DEFAULT_PAGE_SIZE} />
|
||||||
contactPoints={contactPoints}
|
|
||||||
search={search}
|
|
||||||
pageSize={DEFAULT_PAGE_SIZE}
|
|
||||||
onDelete={(name) => showDeleteModal(name)}
|
|
||||||
disabled={updateAlertmanagerState.isLoading}
|
|
||||||
/>
|
|
||||||
{/* Grafana manager Alertmanager does not support global config, Mimir and Cortex do */}
|
{/* Grafana manager Alertmanager does not support global config, Mimir and Cortex do */}
|
||||||
{!isGrafanaManagedAlertmanager && <GlobalConfigAlert alertManagerName={selectedAlertmanager!} />}
|
{!isGrafanaManagedAlertmanager && <GlobalConfigAlert alertManagerName={selectedAlertmanager!} />}
|
||||||
{DeleteModal}
|
|
||||||
{ExportDrawer}
|
{ExportDrawer}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@ -204,7 +194,6 @@ interface ContactPointsListProps {
|
|||||||
contactPoints: ContactPointWithMetadata[];
|
contactPoints: ContactPointWithMetadata[];
|
||||||
search?: string | null;
|
search?: string | null;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
onDelete: (name: string) => void;
|
|
||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -213,7 +202,6 @@ const ContactPointsList = ({
|
|||||||
disabled = false,
|
disabled = false,
|
||||||
search,
|
search,
|
||||||
pageSize = DEFAULT_PAGE_SIZE,
|
pageSize = DEFAULT_PAGE_SIZE,
|
||||||
onDelete,
|
|
||||||
}: ContactPointsListProps) => {
|
}: ContactPointsListProps) => {
|
||||||
const searchResults = useContactPointsSearch(contactPoints, search);
|
const searchResults = useContactPointsSearch(contactPoints, search);
|
||||||
const { page, pageItems, numberOfPages, onPageChange } = usePagination(searchResults, 1, pageSize);
|
const { page, pageItems, numberOfPages, onPageChange } = usePagination(searchResults, 1, pageSize);
|
||||||
@ -221,21 +209,8 @@ const ContactPointsList = ({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{pageItems.map((contactPoint, index) => {
|
{pageItems.map((contactPoint, index) => {
|
||||||
const provisioned = isProvisioned(contactPoint);
|
|
||||||
const policies = contactPoint.policies ?? [];
|
|
||||||
const key = `${contactPoint.name}-${index}`;
|
const key = `${contactPoint.name}-${index}`;
|
||||||
|
return <ContactPoint key={key} contactPoint={contactPoint} disabled={disabled} />;
|
||||||
return (
|
|
||||||
<ContactPoint
|
|
||||||
key={key}
|
|
||||||
name={contactPoint.name}
|
|
||||||
disabled={disabled}
|
|
||||||
onDelete={onDelete}
|
|
||||||
receivers={contactPoint.grafana_managed_receiver_configs}
|
|
||||||
provisioned={provisioned}
|
|
||||||
policies={policies}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
})}
|
||||||
<Pagination currentPage={page} numberOfPages={numberOfPages} onNavigate={onPageChange} hideWhenSinglePage />
|
<Pagination currentPage={page} numberOfPages={numberOfPages} onNavigate={onPageChange} hideWhenSinglePage />
|
||||||
</>
|
</>
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import { RouteChildrenProps } from 'react-router-dom';
|
import { RouteChildrenProps } from 'react-router-dom';
|
||||||
|
|
||||||
import { Alert } from '@grafana/ui';
|
import { Alert, LoadingPlaceholder } from '@grafana/ui';
|
||||||
import { EntityNotFound } from 'app/core/components/PageNotFound/EntityNotFound';
|
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 { useAlertmanager } from '../../state/AlertmanagerContext';
|
||||||
import { EditReceiverView } from '../receivers/EditReceiverView';
|
import { EditReceiverView } from '../receivers/EditReceiverView';
|
||||||
|
|
||||||
@ -11,36 +11,35 @@ type Props = RouteChildrenProps<{ name: string }>;
|
|||||||
|
|
||||||
const EditContactPoint = ({ match }: Props) => {
|
const EditContactPoint = ({ match }: Props) => {
|
||||||
const { selectedAlertmanager } = useAlertmanager();
|
const { selectedAlertmanager } = useAlertmanager();
|
||||||
const { data, isLoading, error } = useAlertmanagerConfig(selectedAlertmanager);
|
|
||||||
|
|
||||||
const contactPointName = match?.params.name;
|
const contactPointName = decodeURIComponent(match?.params.name!);
|
||||||
if (!contactPointName) {
|
const {
|
||||||
return <EntityNotFound entity="Contact point" />;
|
isLoading,
|
||||||
}
|
error,
|
||||||
|
data: contactPoint,
|
||||||
|
} = useGetContactPoint({ name: contactPointName, alertmanager: selectedAlertmanager! });
|
||||||
|
|
||||||
if (isLoading && !data) {
|
if (isLoading) {
|
||||||
return 'loading...';
|
return <LoadingPlaceholder text="Loading..." />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<Alert severity="error" title="Failed to fetch contact point">
|
<Alert severity="error" title="Failed to fetch contact point">
|
||||||
{String(error)}
|
{stringifyErrorLike(error)}
|
||||||
</Alert>
|
</Alert>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!data) {
|
if (!contactPoint) {
|
||||||
return null;
|
return (
|
||||||
|
<Alert severity="error" title="Receiver not found">
|
||||||
|
{'Sorry, this contact point does not seem to exist.'}
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return <EditReceiverView alertmanagerName={selectedAlertmanager!} contactPoint={contactPoint} />;
|
||||||
<EditReceiverView
|
|
||||||
alertManagerSourceName={selectedAlertmanager!}
|
|
||||||
config={data}
|
|
||||||
receiverName={decodeURIComponent(contactPointName)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default EditContactPoint;
|
export default EditContactPoint;
|
||||||
|
@ -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),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
@ -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;
|
|
@ -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;
|
|
||||||
};
|
|
@ -29,6 +29,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "grafana-default-email",
|
||||||
"name": "grafana-default-email",
|
"name": "grafana-default-email",
|
||||||
"policies": [
|
"policies": [
|
||||||
{
|
{
|
||||||
@ -38,6 +39,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"grafana_managed_receiver_configs": [
|
||||||
@ -64,8 +66,10 @@ exports[`useContactPoints should return contact points with status 1`] = `
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "lotsa-emails",
|
||||||
"name": "lotsa-emails",
|
"name": "lotsa-emails",
|
||||||
"policies": [],
|
"policies": [],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"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",
|
"name": "OnCall Conctact point",
|
||||||
"policies": [],
|
"policies": [],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"grafana_managed_receiver_configs": [
|
||||||
@ -116,6 +122,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "provisioned-contact-point",
|
||||||
"name": "provisioned-contact-point",
|
"name": "provisioned-contact-point",
|
||||||
"policies": [
|
"policies": [
|
||||||
{
|
{
|
||||||
@ -125,6 +132,7 @@ exports[`useContactPoints should return contact points with status 1`] = `
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"provisioned": true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"grafana_managed_receiver_configs": [
|
||||||
@ -175,8 +183,10 @@ exports[`useContactPoints should return contact points with status 1`] = `
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "Slack with multiple channels",
|
||||||
"name": "Slack with multiple channels",
|
"name": "Slack with multiple channels",
|
||||||
"policies": [],
|
"policies": [],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
"error": undefined,
|
"error": undefined,
|
||||||
@ -213,6 +223,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "grafana-default-email",
|
||||||
"name": "grafana-default-email",
|
"name": "grafana-default-email",
|
||||||
"policies": [
|
"policies": [
|
||||||
{
|
{
|
||||||
@ -222,6 +233,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"grafana_managed_receiver_configs": [
|
||||||
@ -248,8 +260,10 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "lotsa-emails",
|
||||||
"name": "lotsa-emails",
|
"name": "lotsa-emails",
|
||||||
"policies": [],
|
"policies": [],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"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",
|
"name": "OnCall Conctact point",
|
||||||
"policies": [],
|
"policies": [],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"grafana_managed_receiver_configs": [
|
||||||
@ -303,6 +319,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "provisioned-contact-point",
|
||||||
"name": "provisioned-contact-point",
|
"name": "provisioned-contact-point",
|
||||||
"policies": [
|
"policies": [
|
||||||
{
|
{
|
||||||
@ -312,6 +329,7 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"provisioned": true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"grafana_managed_receiver_configs": [
|
"grafana_managed_receiver_configs": [
|
||||||
@ -362,8 +380,10 @@ exports[`useContactPoints when having oncall plugin installed and no alert manag
|
|||||||
Symbol(receiver_plugin_metadata): undefined,
|
Symbol(receiver_plugin_metadata): undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
"id": "Slack with multiple channels",
|
||||||
"name": "Slack with multiple channels",
|
"name": "Slack with multiple channels",
|
||||||
"policies": [],
|
"policies": [],
|
||||||
|
"provisioned": false,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
"error": undefined,
|
"error": undefined,
|
||||||
|
@ -4,40 +4,41 @@ import { Button, Modal, ModalProps } from '@grafana/ui';
|
|||||||
|
|
||||||
import { stringifyErrorLike } from '../../../utils/misc';
|
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
|
* This hook controls the delete modal for contact points, showing loading and error states when appropriate
|
||||||
*/
|
*/
|
||||||
export const useDeleteContactPointModal = (
|
export const useDeleteContactPointModal = (
|
||||||
handleDelete: (name: string) => Promise<void>,
|
handleDelete: ({ name, resourceVersion }: { name: string; resourceVersion?: string }) => Promise<unknown>
|
||||||
isLoading: boolean
|
) => {
|
||||||
): ModalHook<string> => {
|
|
||||||
const [showModal, setShowModal] = useState(false);
|
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 [error, setError] = useState<unknown | undefined>();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
const handleDismiss = useCallback(() => {
|
const handleDismiss = useCallback(() => {
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setContactPoint(undefined);
|
setContactPoint(undefined);
|
||||||
setShowModal(false);
|
setShowModal(false);
|
||||||
setError(undefined);
|
setError(undefined);
|
||||||
}, [isLoading]);
|
}, [isLoading]);
|
||||||
|
|
||||||
const handleShow = useCallback((name: string) => {
|
const handleShow = useCallback(({ name, resourceVersion }: { name: string; resourceVersion?: string }) => {
|
||||||
setContactPoint(name);
|
setContactPoint({ name, resourceVersion });
|
||||||
setShowModal(true);
|
setShowModal(true);
|
||||||
setError(undefined);
|
setError(undefined);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSubmit = useCallback(() => {
|
const handleSubmit = useCallback(() => {
|
||||||
if (contactPoint) {
|
if (contactPoint) {
|
||||||
|
setIsLoading(true);
|
||||||
handleDelete(contactPoint)
|
handleDelete(contactPoint)
|
||||||
.then(() => setShowModal(false))
|
.then(() => setShowModal(false))
|
||||||
.catch(setError);
|
.catch(setError)
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}, [handleDelete, contactPoint]);
|
}, [handleDelete, contactPoint]);
|
||||||
|
|
||||||
@ -69,7 +70,7 @@ export const useDeleteContactPointModal = (
|
|||||||
);
|
);
|
||||||
}, [error, handleDismiss, handleSubmit, isLoading, showModal]);
|
}, [error, handleDismiss, handleSubmit, isLoading, showModal]);
|
||||||
|
|
||||||
return [modalElement, handleShow, handleDismiss];
|
return [modalElement, handleShow, handleDismiss] as const;
|
||||||
};
|
};
|
||||||
|
|
||||||
interface ErrorModalProps extends Pick<ModalProps, 'isOpen' | 'onDismiss'> {
|
interface ErrorModalProps extends Pick<ModalProps, 'isOpen' | 'onDismiss'> {
|
||||||
@ -84,10 +85,8 @@ const ErrorModal = ({ isOpen, onDismiss, error }: ErrorModalProps) => (
|
|||||||
title={'Something went wrong'}
|
title={'Something went wrong'}
|
||||||
>
|
>
|
||||||
<p>Failed to update your configuration:</p>
|
<p>Failed to update your configuration:</p>
|
||||||
<p>
|
|
||||||
<pre>
|
<pre>
|
||||||
<code>{stringifyErrorLike(error)}</code>
|
<code>{stringifyErrorLike(error)}</code>
|
||||||
</pre>
|
</pre>
|
||||||
</p>
|
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
@ -65,10 +65,32 @@ describe('useContactPoints', () => {
|
|||||||
expect(snapshot).toMatchSnapshot();
|
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 snapshotAmConfig = await getHookResponse(false);
|
||||||
const snapshotAlertingApiServer = await getHookResponse(true);
|
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', () => {
|
describe('when having oncall plugin installed and no alert manager config data', () => {
|
||||||
|
@ -7,14 +7,29 @@ import { produce } from 'immer';
|
|||||||
import { remove } from 'lodash';
|
import { remove } from 'lodash';
|
||||||
import { useMemo } from 'react';
|
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 {
|
import {
|
||||||
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver,
|
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver,
|
||||||
generatedReceiversApi,
|
generatedReceiversApi,
|
||||||
} from 'app/features/alerting/unified/openapi/receiversApi.gen';
|
} 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 { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
|
||||||
import { cloudNotifierTypes } from 'app/features/alerting/unified/utils/cloud-alertmanager-notifier-types';
|
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 { 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 { alertmanagerApi } from '../../api/alertmanagerApi';
|
||||||
import { onCallApi } from '../../api/onCallApi';
|
import { onCallApi } from '../../api/onCallApi';
|
||||||
@ -42,7 +57,13 @@ const {
|
|||||||
useUpdateAlertmanagerConfigurationMutation,
|
useUpdateAlertmanagerConfigurationMutation,
|
||||||
} = alertmanagerApi;
|
} = alertmanagerApi;
|
||||||
const { useGrafanaOnCallIntegrationsQuery } = onCallApi;
|
const { useGrafanaOnCallIntegrationsQuery } = onCallApi;
|
||||||
const { useListNamespacedReceiverQuery } = generatedReceiversApi;
|
const {
|
||||||
|
useListNamespacedReceiverQuery,
|
||||||
|
useReadNamespacedReceiverQuery,
|
||||||
|
useDeleteNamespacedReceiverMutation,
|
||||||
|
useCreateNamespacedReceiverMutation,
|
||||||
|
useReplaceNamespacedReceiverMutation,
|
||||||
|
} = receiversApi;
|
||||||
|
|
||||||
const defaultOptions = {
|
const defaultOptions = {
|
||||||
refetchOnFocus: true,
|
refetchOnFocus: true,
|
||||||
@ -71,19 +92,26 @@ const useOnCallIntegrations = ({ skip }: Skippable = {}) => {
|
|||||||
|
|
||||||
type K8sReceiver = ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
|
type K8sReceiver = ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
|
||||||
|
|
||||||
// TODO: Make this typed as returning `GrafanaManagedContactPoint` - we can't yet do this as the schema thinks
|
const parseK8sReceiver = (item: K8sReceiver): GrafanaManagedContactPoint => {
|
||||||
// its returning integration settings as a `string` rather than `Record<string, any>`
|
return {
|
||||||
const parseK8sReceiver = (item: K8sReceiver) => {
|
id: item.metadata.uid || item.spec.title,
|
||||||
return { name: item.spec.title, grafana_managed_receiver_configs: item.spec.integrations };
|
name: item.spec.title,
|
||||||
|
provisioned: isK8sEntityProvisioned(item),
|
||||||
|
grafana_managed_receiver_configs: item.spec.integrations,
|
||||||
|
metadata: item.metadata,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const useK8sContactPoints = (...[hookParams, queryOptions]: Parameters<typeof useListNamespacedReceiverQuery>) => {
|
const useK8sContactPoints = (...[hookParams, queryOptions]: Parameters<typeof useListNamespacedReceiverQuery>) => {
|
||||||
return useListNamespacedReceiverQuery(hookParams, {
|
return useListNamespacedReceiverQuery(hookParams, {
|
||||||
...queryOptions,
|
...queryOptions,
|
||||||
selectFromResult: ({ data, ...rest }) => {
|
selectFromResult: (result) => {
|
||||||
|
const data = result.data?.items.map((item) => parseK8sReceiver(item));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...rest,
|
...result,
|
||||||
data: data?.items.map((item) => parseK8sReceiver(item)),
|
data,
|
||||||
|
currentData: data,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@ -97,7 +125,21 @@ const useFetchGrafanaContactPoints = ({ skip }: Skippable = {}) => {
|
|||||||
const namespace = getK8sNamespace();
|
const namespace = getK8sNamespace();
|
||||||
const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);
|
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 });
|
const k8sResponse = useK8sContactPoints({ namespace }, { skip: skip || !useK8sApi });
|
||||||
|
|
||||||
return useK8sApi ? k8sResponse : grafanaResponse;
|
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
|
* OnCall integrations and any additional metadata from list of notifiers
|
||||||
* (e.g. hydrate with additional names/descriptions)
|
* (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({
|
export function useContactPointsWithStatus({
|
||||||
alertmanager,
|
alertmanager,
|
||||||
fetchStatuses,
|
fetchStatuses,
|
||||||
@ -203,30 +310,182 @@ export function useContactPointsWithStatus({
|
|||||||
return isGrafanaAlertmanager ? grafanaResponse : alertmanagerConfigResponse;
|
return isGrafanaAlertmanager ? grafanaResponse : alertmanagerConfigResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDeleteContactPoint(selectedAlertmanager: string) {
|
export function useDeleteContactPoint({ alertmanager }: BaseAlertmanagerArgs) {
|
||||||
const [fetchAlertmanagerConfig] = useLazyGetAlertmanagerConfigurationQuery();
|
const [fetchAlertmanagerConfig] = useLazyGetAlertmanagerConfigurationQuery();
|
||||||
const [updateAlertManager, updateAlertmanagerState] = useUpdateAlertmanagerConfigurationMutation();
|
const [updateAlertManager] = useUpdateAlertmanagerConfigurationMutation();
|
||||||
|
const [deleteReceiver] = useDeleteNamespacedReceiverMutation();
|
||||||
|
|
||||||
const deleteTrigger = (contactPointName: string) => {
|
const useK8sApi = shouldUseK8sApi(alertmanager);
|
||||||
return fetchAlertmanagerConfig(selectedAlertmanager).then(({ data }) => {
|
|
||||||
if (!data) {
|
return async ({ name, resourceVersion }: { name: string; resourceVersion?: string }) => {
|
||||||
return;
|
if (useK8sApi) {
|
||||||
|
const namespace = getK8sNamespace();
|
||||||
|
return deleteReceiver({
|
||||||
|
name,
|
||||||
|
namespace,
|
||||||
|
ioK8SApimachineryPkgApisMetaV1DeleteOptions: { preconditions: { resourceVersion } },
|
||||||
|
}).unwrap();
|
||||||
}
|
}
|
||||||
|
const config = await fetchAlertmanagerConfig(alertmanager).unwrap();
|
||||||
|
|
||||||
const newConfig = produce(data, (draft) => {
|
const newConfig = produce(config, (draft) => {
|
||||||
remove(draft?.alertmanager_config?.receivers ?? [], (receiver) => receiver.name === contactPointName);
|
remove(draft?.alertmanager_config?.receivers ?? [], (receiver) => receiver.name === name);
|
||||||
return draft;
|
return draft;
|
||||||
});
|
});
|
||||||
|
|
||||||
return updateAlertManager({
|
return updateAlertManager({
|
||||||
selectedAlertmanager,
|
selectedAlertmanager: alertmanager,
|
||||||
config: newConfig,
|
config: newConfig,
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
deleteTrigger,
|
|
||||||
updateAlertmanagerState,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
};
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
import { GrafanaManagedContactPoint } from 'app/plugins/datasource/alertmanager/types';
|
|
||||||
|
|
||||||
import { ReceiverTypes } from '../receivers/grafanaAppReceivers/onCall/onCall';
|
import { ReceiverTypes } from '../receivers/grafanaAppReceivers/onCall/onCall';
|
||||||
|
|
||||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from './constants';
|
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from './constants';
|
||||||
@ -7,34 +5,9 @@ import {
|
|||||||
ReceiverConfigWithMetadata,
|
ReceiverConfigWithMetadata,
|
||||||
getReceiverDescription,
|
getReceiverDescription,
|
||||||
isAutoGeneratedPolicy,
|
isAutoGeneratedPolicy,
|
||||||
isProvisioned,
|
|
||||||
summarizeEmailAddresses,
|
summarizeEmailAddresses,
|
||||||
} from './utils';
|
} 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', () => {
|
describe('isAutoGeneratedPolicy', () => {
|
||||||
it('should return false when not enabled', () => {
|
it('should return false when not enabled', () => {
|
||||||
expect(isAutoGeneratedPolicy({})).toBe(false);
|
expect(isAutoGeneratedPolicy({})).toBe(false);
|
||||||
|
@ -22,13 +22,6 @@ import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from
|
|||||||
|
|
||||||
const AUTOGENERATED_RECEIVER_POLICY_MATCHER_KEY = '__grafana_receiver__';
|
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...
|
// TODO we should really add some type information to these receiver settings...
|
||||||
export function getReceiverDescription(receiver: ReceiverConfigWithMetadata): ReactNode | undefined {
|
export function getReceiverDescription(receiver: ReceiverConfigWithMetadata): ReactNode | undefined {
|
||||||
if (!receiver.settings) {
|
if (!receiver.settings) {
|
||||||
@ -98,6 +91,7 @@ export interface ReceiverConfigWithMetadata extends GrafanaManagedReceiverConfig
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ContactPointWithMetadata extends GrafanaManagedContactPoint {
|
export interface ContactPointWithMetadata extends GrafanaManagedContactPoint {
|
||||||
|
id: string;
|
||||||
policies?: RouteReference[]; // now is optional as we don't have the data from the read-only endpoint
|
policies?: RouteReference[]; // now is optional as we don't have the data from the read-only endpoint
|
||||||
grafana_managed_receiver_configs: ReceiverConfigWithMetadata[];
|
grafana_managed_receiver_configs: ReceiverConfigWithMetadata[];
|
||||||
}
|
}
|
||||||
@ -134,8 +128,11 @@ export function enhanceContactPointsWithMetadata({
|
|||||||
const receivers = extractReceivers(contactPoint);
|
const receivers = extractReceivers(contactPoint);
|
||||||
const statusForReceiver = status.find((status) => status.name === contactPoint.name);
|
const statusForReceiver = status.find((status) => status.name === contactPoint.name);
|
||||||
|
|
||||||
|
const id = 'id' in contactPoint && contactPoint.id ? contactPoint.id : contactPoint.name;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...contactPoint,
|
...contactPoint,
|
||||||
|
id,
|
||||||
policies:
|
policies:
|
||||||
alertmanagerConfiguration && usedContactPointsByName && (usedContactPointsByName[contactPoint.name] ?? []),
|
alertmanagerConfiguration && usedContactPointsByName && (usedContactPointsByName[contactPoint.name] ?? []),
|
||||||
grafana_managed_receiver_configs: receivers.map((receiver, index) => {
|
grafana_managed_receiver_configs: receivers.map((receiver, index) => {
|
||||||
|
@ -9,8 +9,12 @@ import {
|
|||||||
} from 'app/features/alerting/unified/openapi/timeIntervalsApi.gen';
|
} from 'app/features/alerting/unified/openapi/timeIntervalsApi.gen';
|
||||||
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
|
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
|
||||||
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
|
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 { PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
|
||||||
import { getK8sNamespace, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
|
import {
|
||||||
|
getK8sNamespace,
|
||||||
|
isK8sEntityProvisioned,
|
||||||
|
shouldUseK8sApi,
|
||||||
|
} from 'app/features/alerting/unified/utils/k8s/utils';
|
||||||
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
|
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
|
||||||
|
|
||||||
import { useAsync } from '../../hooks/useAsync';
|
import { useAsync } from '../../hooks/useAsync';
|
||||||
@ -48,7 +52,7 @@ const parseK8sTimeInterval: (item: TimeIntervalV0Alpha1) => MuteTiming = (item)
|
|||||||
...spec,
|
...spec,
|
||||||
id: spec.name,
|
id: spec.name,
|
||||||
metadata,
|
metadata,
|
||||||
provisioned: metadata.annotations?.[PROVENANCE_ANNOTATION] !== PROVENANCE_NONE,
|
provisioned: isK8sEntityProvisioned(item),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import { Alert } from '@grafana/ui';
|
import { GrafanaManagedContactPoint, Receiver } from 'app/plugins/datasource/alertmanager/types';
|
||||||
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
|
|
||||||
|
|
||||||
import { AlertmanagerAction, useAlertmanagerAbility } from '../../hooks/useAbilities';
|
import { AlertmanagerAction, useAlertmanagerAbility } from '../../hooks/useAbilities';
|
||||||
import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
|
import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
|
||||||
@ -8,41 +7,25 @@ import { CloudReceiverForm } from './form/CloudReceiverForm';
|
|||||||
import { GrafanaReceiverForm } from './form/GrafanaReceiverForm';
|
import { GrafanaReceiverForm } from './form/GrafanaReceiverForm';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
receiverName: string;
|
alertmanagerName: string;
|
||||||
config: AlertManagerCortexConfig;
|
contactPoint: GrafanaManagedContactPoint | Receiver;
|
||||||
alertManagerSourceName: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const EditReceiverView = ({ config, receiverName, alertManagerSourceName }: Props) => {
|
export const EditReceiverView = ({ contactPoint, alertmanagerName }: Props) => {
|
||||||
const [editSupported, editAllowed] = useAlertmanagerAbility(AlertmanagerAction.UpdateContactPoint);
|
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;
|
const readOnly = !editSupported || !editAllowed;
|
||||||
|
|
||||||
if (alertManagerSourceName === GRAFANA_RULES_SOURCE_NAME) {
|
if (alertmanagerName === GRAFANA_RULES_SOURCE_NAME) {
|
||||||
return (
|
console.log(contactPoint);
|
||||||
<GrafanaReceiverForm
|
return <GrafanaReceiverForm contactPoint={contactPoint} readOnly={readOnly} editMode />;
|
||||||
config={config}
|
|
||||||
alertManagerSourceName={alertManagerSourceName}
|
|
||||||
existing={receiver}
|
|
||||||
readOnly={readOnly}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
return (
|
return (
|
||||||
<CloudReceiverForm
|
<CloudReceiverForm
|
||||||
config={config}
|
alertManagerSourceName={alertmanagerName}
|
||||||
alertManagerSourceName={alertManagerSourceName}
|
contactPoint={contactPoint}
|
||||||
existing={receiver}
|
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
|
editMode
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -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/),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
@ -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 { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
|
||||||
|
|
||||||
import { CloudReceiverForm } from './form/CloudReceiverForm';
|
import { CloudReceiverForm } from './form/CloudReceiverForm';
|
||||||
import { GrafanaReceiverForm } from './form/GrafanaReceiverForm';
|
import { GrafanaReceiverForm } from './form/GrafanaReceiverForm';
|
||||||
|
|
||||||
interface Props {
|
const NewReceiverView = () => {
|
||||||
config: AlertManagerCortexConfig;
|
const { selectedAlertmanager } = useAlertmanager();
|
||||||
alertManagerSourceName: string;
|
if (selectedAlertmanager === GRAFANA_RULES_SOURCE_NAME) {
|
||||||
}
|
return <GrafanaReceiverForm />;
|
||||||
|
|
||||||
export const NewReceiverView = ({ alertManagerSourceName, config }: Props) => {
|
|
||||||
if (alertManagerSourceName === GRAFANA_RULES_SOURCE_NAME) {
|
|
||||||
return <GrafanaReceiverForm alertManagerSourceName={alertManagerSourceName} config={config} />;
|
|
||||||
} else {
|
} else {
|
||||||
return <CloudReceiverForm alertManagerSourceName={alertManagerSourceName} config={config} />;
|
return <CloudReceiverForm alertManagerSourceName={selectedAlertmanager!} />;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export default NewReceiverView;
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
// 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": {
|
"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": {
|
"alertmanager_config": {
|
@ -1,19 +1,18 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
|
import { locationService } from '@grafana/runtime';
|
||||||
import { Alert } from '@grafana/ui';
|
import { Alert } from '@grafana/ui';
|
||||||
import { AlertManagerCortexConfig, Receiver } from 'app/plugins/datasource/alertmanager/types';
|
import { alertmanagerApi } from 'app/features/alerting/unified/api/alertmanagerApi';
|
||||||
import { useDispatch } from 'app/types';
|
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 { CloudChannelValues, ReceiverFormValues, CloudChannelMap } from '../../../types/receiver-form';
|
||||||
import { cloudNotifierTypes } from '../../../utils/cloud-alertmanager-notifier-types';
|
import { cloudNotifierTypes } from '../../../utils/cloud-alertmanager-notifier-types';
|
||||||
import { isVanillaPrometheusAlertManagerDataSource } from '../../../utils/datasource';
|
import { isVanillaPrometheusAlertManagerDataSource } from '../../../utils/datasource';
|
||||||
import {
|
import { cloudReceiverToFormValues, formValuesToCloudReceiver } from '../../../utils/receiver-form';
|
||||||
cloudReceiverToFormValues,
|
|
||||||
formValuesToCloudReceiver,
|
|
||||||
updateConfigWithReceiver,
|
|
||||||
} from '../../../utils/receiver-form';
|
|
||||||
|
|
||||||
import { CloudCommonChannelSettings } from './CloudCommonChannelSettings';
|
import { CloudCommonChannelSettings } from './CloudCommonChannelSettings';
|
||||||
import { ReceiverForm } from './ReceiverForm';
|
import { ReceiverForm } from './ReceiverForm';
|
||||||
@ -21,9 +20,9 @@ import { Notifier } from './notifiers';
|
|||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
alertManagerSourceName: string;
|
alertManagerSourceName: string;
|
||||||
config: AlertManagerCortexConfig;
|
contactPoint?: Receiver;
|
||||||
existing?: Receiver;
|
|
||||||
readOnly?: boolean;
|
readOnly?: boolean;
|
||||||
|
editMode?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultChannelValues: CloudChannelValues = Object.freeze({
|
const defaultChannelValues: CloudChannelValues = Object.freeze({
|
||||||
@ -36,39 +35,33 @@ const defaultChannelValues: CloudChannelValues = Object.freeze({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const cloudNotifiers = cloudNotifierTypes.map<Notifier>((n) => ({ dto: n }));
|
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 isVanillaAM = isVanillaPrometheusAlertManagerDataSource(alertManagerSourceName);
|
||||||
|
const createContactPoint = useCreateContactPoint({ alertmanager: alertManagerSourceName });
|
||||||
|
const updateContactPoint = useUpdateContactPoint({ alertmanager: alertManagerSourceName });
|
||||||
|
|
||||||
// transform receiver DTO to form values
|
// transform receiver DTO to form values
|
||||||
const [existingValue] = useMemo((): [ReceiverFormValues<CloudChannelValues> | undefined, CloudChannelMap] => {
|
const [existingValue] = useMemo((): [ReceiverFormValues<CloudChannelValues> | undefined, CloudChannelMap] => {
|
||||||
if (!existing) {
|
if (!contactPoint) {
|
||||||
return [undefined, {}];
|
return [undefined, {}];
|
||||||
}
|
}
|
||||||
return cloudReceiverToFormValues(existing, cloudNotifierTypes);
|
return cloudReceiverToFormValues(contactPoint, cloudNotifierTypes);
|
||||||
}, [existing]);
|
}, [contactPoint]);
|
||||||
|
|
||||||
const onSubmit = async (values: ReceiverFormValues<CloudChannelValues>) => {
|
const onSubmit = async (values: ReceiverFormValues<CloudChannelValues>) => {
|
||||||
const newReceiver = formValuesToCloudReceiver(values, defaultChannelValues);
|
const newReceiver = formValuesToCloudReceiver(values, defaultChannelValues);
|
||||||
await dispatch(
|
if (editMode) {
|
||||||
updateAlertManagerConfigAction({
|
await updateContactPoint({ contactPoint: newReceiver, originalName: contactPoint!.name });
|
||||||
newConfig: updateConfigWithReceiver(config, newReceiver, existing?.name),
|
} else {
|
||||||
oldConfig: config,
|
await createContactPoint({ contactPoint: newReceiver });
|
||||||
alertManagerSourceName,
|
}
|
||||||
successMessage: existing ? 'Contact point updated.' : 'Contact point created.',
|
locationService.push('/alerting/notifications');
|
||||||
redirectPath: '/alerting/notifications',
|
|
||||||
})
|
|
||||||
).then(() => {
|
|
||||||
dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration']));
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
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
|
// 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
|
// or a Mimir-based AlertManager
|
||||||
const isManageableAlertManagerDataSource =
|
const isManageableAlertManagerDataSource =
|
||||||
@ -82,15 +75,14 @@ export const CloudReceiverForm = ({ existing, alertManagerSourceName, config, re
|
|||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
<ReceiverForm<CloudChannelValues>
|
<ReceiverForm<CloudChannelValues>
|
||||||
|
showDefaultRouteWarning={!isLoading && !config?.alertmanager_config.route}
|
||||||
isEditable={isManageableAlertManagerDataSource}
|
isEditable={isManageableAlertManagerDataSource}
|
||||||
isTestable={isManageableAlertManagerDataSource}
|
isTestable={isManageableAlertManagerDataSource}
|
||||||
config={config}
|
|
||||||
onSubmit={onSubmit}
|
onSubmit={onSubmit}
|
||||||
initialValues={existingValue}
|
initialValues={existingValue}
|
||||||
notifiers={cloudNotifiers}
|
notifiers={cloudNotifiers}
|
||||||
alertManagerSourceName={alertManagerSourceName}
|
alertManagerSourceName={alertManagerSourceName}
|
||||||
defaultItem={defaultChannelValues}
|
defaultItem={defaultChannelValues}
|
||||||
takenReceiverNames={takenReceiverNames}
|
|
||||||
commonSettingsComponent={CloudCommonChannelSettings}
|
commonSettingsComponent={CloudCommonChannelSettings}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { clickSelectOption } from 'test/helpers/selectOptionInTest';
|
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 { byLabelText, byRole, byTestId, byText } from 'testing-library-selector';
|
||||||
|
|
||||||
import { disablePlugin } from 'app/features/alerting/unified/mocks/server/configure';
|
import { disablePlugin } from 'app/features/alerting/unified/mocks/server/configure';
|
||||||
@ -8,11 +8,9 @@ import {
|
|||||||
setOnCallIntegrations,
|
setOnCallIntegrations,
|
||||||
} from 'app/features/alerting/unified/mocks/server/handlers/plugins/configure-plugins';
|
} from 'app/features/alerting/unified/mocks/server/handlers/plugins/configure-plugins';
|
||||||
import { SupportedPlugin } from 'app/features/alerting/unified/types/pluginBridges';
|
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 { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
|
||||||
|
|
||||||
import { AlertmanagerConfigBuilder, setupMswServer } from '../../../mockApi';
|
import { AlertmanagerConfigBuilder, setupMswServer } from '../../../mockApi';
|
||||||
import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
|
|
||||||
|
|
||||||
import { GrafanaReceiverForm } from './GrafanaReceiverForm';
|
import { GrafanaReceiverForm } from './GrafanaReceiverForm';
|
||||||
|
|
||||||
@ -35,17 +33,11 @@ const ui = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
describe('GrafanaReceiverForm', () => {
|
describe('GrafanaReceiverForm', () => {
|
||||||
beforeEach(() => {
|
|
||||||
clearPluginSettingsCache();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('OnCall contact point', () => {
|
describe('OnCall contact point', () => {
|
||||||
it('OnCall contact point should be disabled if OnCall integration is not enabled', async () => {
|
it('OnCall contact point should be disabled if OnCall integration is not enabled', async () => {
|
||||||
disablePlugin(SupportedPlugin.OnCall);
|
disablePlugin(SupportedPlugin.OnCall);
|
||||||
|
|
||||||
const amConfig = getAmCortexConfig((_) => {});
|
render(<GrafanaReceiverForm />);
|
||||||
|
|
||||||
render(<GrafanaReceiverForm alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME} config={amConfig} />);
|
|
||||||
|
|
||||||
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
|
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' },
|
{ display_name: 'apac-oncall', value: 'apac-oncall', integration_url: 'https://apac.oncall.example.com' },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const amConfig = getAmCortexConfig((_) => {});
|
const { user } = render(<GrafanaReceiverForm />);
|
||||||
|
|
||||||
const user = userEvent.setup();
|
|
||||||
|
|
||||||
render(<GrafanaReceiverForm alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME} config={amConfig} />);
|
|
||||||
|
|
||||||
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
|
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
|
||||||
|
|
||||||
@ -121,13 +109,7 @@ describe('GrafanaReceiverForm', () => {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
render(
|
render(<GrafanaReceiverForm contactPoint={amConfig.alertmanager_config.receivers![0]} />);
|
||||||
<GrafanaReceiverForm
|
|
||||||
alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME}
|
|
||||||
config={amConfig}
|
|
||||||
existing={amConfig.alertmanager_config.receivers![0]}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
|
await waitFor(() => expect(ui.loadingIndicator.query()).not.toBeInTheDocument());
|
||||||
|
|
||||||
|
@ -1,8 +1,14 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
|
|
||||||
|
import { locationService } from '@grafana/runtime';
|
||||||
import { Alert, LoadingPlaceholder } from '@grafana/ui';
|
import { Alert, LoadingPlaceholder } from '@grafana/ui';
|
||||||
import {
|
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,
|
GrafanaManagedContactPoint,
|
||||||
GrafanaManagedReceiverConfig,
|
GrafanaManagedReceiverConfig,
|
||||||
TestReceiversAlert,
|
TestReceiversAlert,
|
||||||
@ -10,14 +16,12 @@ import {
|
|||||||
import { useDispatch } from 'app/types';
|
import { useDispatch } from 'app/types';
|
||||||
|
|
||||||
import { alertmanagerApi } from '../../../api/alertmanagerApi';
|
import { alertmanagerApi } from '../../../api/alertmanagerApi';
|
||||||
import { testReceiversAction, updateAlertManagerConfigAction } from '../../../state/actions';
|
import { testReceiversAction } from '../../../state/actions';
|
||||||
import { GrafanaChannelValues, ReceiverFormValues } from '../../../types/receiver-form';
|
import { GrafanaChannelValues, ReceiverFormValues } from '../../../types/receiver-form';
|
||||||
import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
|
|
||||||
import {
|
import {
|
||||||
formChannelValuesToGrafanaChannelConfig,
|
formChannelValuesToGrafanaChannelConfig,
|
||||||
formValuesToGrafanaReceiver,
|
formValuesToGrafanaReceiver,
|
||||||
grafanaReceiverToFormValues,
|
grafanaReceiverToFormValues,
|
||||||
updateConfigWithReceiver,
|
|
||||||
} from '../../../utils/receiver-form';
|
} from '../../../utils/receiver-form';
|
||||||
import { ProvisionedResource, ProvisioningAlert } from '../../Provisioning';
|
import { ProvisionedResource, ProvisioningAlert } from '../../Provisioning';
|
||||||
import { ReceiverTypes } from '../grafanaAppReceivers/onCall/onCall';
|
import { ReceiverTypes } from '../grafanaAppReceivers/onCall/onCall';
|
||||||
@ -28,13 +32,6 @@ import { ReceiverForm } from './ReceiverForm';
|
|||||||
import { TestContactPointModal } from './TestContactPointModal';
|
import { TestContactPointModal } from './TestContactPointModal';
|
||||||
import { Notifier } from './notifiers';
|
import { Notifier } from './notifiers';
|
||||||
|
|
||||||
interface Props {
|
|
||||||
alertManagerSourceName: string;
|
|
||||||
config: AlertManagerCortexConfig;
|
|
||||||
existing?: GrafanaManagedContactPoint;
|
|
||||||
readOnly?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaultChannelValues: GrafanaChannelValues = Object.freeze({
|
const defaultChannelValues: GrafanaChannelValues = Object.freeze({
|
||||||
__id: '',
|
__id: '',
|
||||||
secureSettings: {},
|
secureSettings: {},
|
||||||
@ -44,20 +41,28 @@ const defaultChannelValues: GrafanaChannelValues = Object.freeze({
|
|||||||
type: 'email',
|
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 dispatch = useDispatch();
|
||||||
|
const createContactPoint = useCreateContactPoint({ alertmanager: GRAFANA_RULES_SOURCE_NAME });
|
||||||
|
const updateContactPoint = useUpdateContactPoint({ alertmanager: GRAFANA_RULES_SOURCE_NAME });
|
||||||
|
|
||||||
const {
|
const {
|
||||||
onCallNotifierMeta,
|
onCallNotifierMeta,
|
||||||
extendOnCallNotifierFeatures,
|
extendOnCallNotifierFeatures,
|
||||||
extendOnCallReceivers,
|
extendOnCallReceivers,
|
||||||
onCallFormValidators,
|
onCallFormValidators,
|
||||||
createOnCallIntegrations,
|
|
||||||
isLoadingOnCallIntegration,
|
isLoadingOnCallIntegration,
|
||||||
hasOnCallError,
|
hasOnCallError,
|
||||||
} = useOnCallIntegration();
|
} = useOnCallIntegration();
|
||||||
|
|
||||||
const { useGrafanaNotifiersQuery } = alertmanagerApi;
|
|
||||||
const { data: grafanaNotifiers = [], isLoading: isLoadingNotifiers } = useGrafanaNotifiersQuery();
|
const { data: grafanaNotifiers = [], isLoading: isLoadingNotifiers } = useGrafanaNotifiersQuery();
|
||||||
|
|
||||||
const [testChannelValues, setTestChannelValues] = useState<GrafanaChannelValues>();
|
const [testChannelValues, setTestChannelValues] = useState<GrafanaChannelValues>();
|
||||||
@ -67,29 +72,26 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
|
|||||||
ReceiverFormValues<GrafanaChannelValues> | undefined,
|
ReceiverFormValues<GrafanaChannelValues> | undefined,
|
||||||
Record<string, GrafanaManagedReceiverConfig>,
|
Record<string, GrafanaManagedReceiverConfig>,
|
||||||
] => {
|
] => {
|
||||||
if (!existing || isLoadingNotifiers || isLoadingOnCallIntegration) {
|
if (!contactPoint || isLoadingNotifiers || isLoadingOnCallIntegration) {
|
||||||
return [undefined, {}];
|
return [undefined, {}];
|
||||||
}
|
}
|
||||||
|
|
||||||
return grafanaReceiverToFormValues(extendOnCallReceivers(existing), grafanaNotifiers);
|
return grafanaReceiverToFormValues(extendOnCallReceivers(contactPoint), grafanaNotifiers);
|
||||||
}, [existing, isLoadingNotifiers, grafanaNotifiers, extendOnCallReceivers, isLoadingOnCallIntegration]);
|
}, [contactPoint, isLoadingNotifiers, grafanaNotifiers, extendOnCallReceivers, isLoadingOnCallIntegration]);
|
||||||
|
|
||||||
const onSubmit = async (values: ReceiverFormValues<GrafanaChannelValues>) => {
|
const onSubmit = async (values: ReceiverFormValues<GrafanaChannelValues>) => {
|
||||||
const newReceiver = formValuesToGrafanaReceiver(values, id2original, defaultChannelValues, grafanaNotifiers);
|
const newReceiver = formValuesToGrafanaReceiver(values, id2original, defaultChannelValues, grafanaNotifiers);
|
||||||
const receiverWithOnCall = await createOnCallIntegrations(newReceiver);
|
if (editMode) {
|
||||||
|
await updateContactPoint({
|
||||||
const newConfig = updateConfigWithReceiver(config, receiverWithOnCall, existing?.name);
|
contactPoint: newReceiver,
|
||||||
await dispatch(
|
id: contactPoint!.id,
|
||||||
updateAlertManagerConfigAction({
|
resourceVersion: contactPoint?.metadata?.resourceVersion,
|
||||||
newConfig: newConfig,
|
originalName: contactPoint?.name,
|
||||||
oldConfig: config,
|
|
||||||
alertManagerSourceName: GRAFANA_RULES_SOURCE_NAME,
|
|
||||||
successMessage: existing ? 'Contact point updated.' : 'Contact point created',
|
|
||||||
redirectPath: '/alerting/notifications',
|
|
||||||
})
|
|
||||||
).then(() => {
|
|
||||||
dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration']));
|
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
await createContactPoint({ contactPoint: newReceiver });
|
||||||
|
}
|
||||||
|
locationService.push('/alerting/notifications');
|
||||||
};
|
};
|
||||||
|
|
||||||
const onTestChannel = (values: GrafanaChannelValues) => {
|
const onTestChannel = (values: GrafanaChannelValues) => {
|
||||||
@ -102,7 +104,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
|
|||||||
const chan = formChannelValuesToGrafanaChannelConfig(testChannelValues, defaultChannelValues, 'test', existing);
|
const chan = formChannelValuesToGrafanaChannelConfig(testChannelValues, defaultChannelValues, 'test', existing);
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
alertManagerSourceName,
|
alertManagerSourceName: GRAFANA_RULES_SOURCE_NAME,
|
||||||
receivers: [
|
receivers: [
|
||||||
{
|
{
|
||||||
name: 'test',
|
name: 'test',
|
||||||
@ -116,17 +118,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const takenReceiverNames = useMemo(
|
const isEditable = !readOnly && !contactPoint?.provisioned;
|
||||||
() => 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 isTestable = !readOnly;
|
const isTestable = !readOnly;
|
||||||
|
|
||||||
if (isLoadingNotifiers || isLoadingOnCallIntegration) {
|
if (isLoadingNotifiers || isLoadingOnCallIntegration) {
|
||||||
@ -134,7 +126,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
|
|||||||
}
|
}
|
||||||
|
|
||||||
const notifiers: Notifier[] = grafanaNotifiers.map((n) => {
|
const notifiers: Notifier[] = grafanaNotifiers.map((n) => {
|
||||||
if (n.type === 'oncall') {
|
if (n.type === ReceiverTypes.OnCall) {
|
||||||
return {
|
return {
|
||||||
dto: extendOnCallNotifierFeatures(n),
|
dto: extendOnCallNotifierFeatures(n),
|
||||||
meta: onCallNotifierMeta,
|
meta: onCallNotifierMeta,
|
||||||
@ -143,7 +135,7 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
|
|||||||
|
|
||||||
return { dto: n };
|
return { dto: n };
|
||||||
});
|
});
|
||||||
|
const disableEditTitle = editMode && shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{hasOnCallError && (
|
{hasOnCallError && (
|
||||||
@ -153,19 +145,18 @@ export const GrafanaReceiverForm = ({ existing, alertManagerSourceName, config,
|
|||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{hasProvisionedItems && <ProvisioningAlert resource={ProvisionedResource.ContactPoint} />}
|
{contactPoint?.provisioned && <ProvisioningAlert resource={ProvisionedResource.ContactPoint} />}
|
||||||
|
|
||||||
<ReceiverForm<GrafanaChannelValues>
|
<ReceiverForm<GrafanaChannelValues>
|
||||||
|
disableEditTitle={disableEditTitle}
|
||||||
isEditable={isEditable}
|
isEditable={isEditable}
|
||||||
isTestable={isTestable}
|
isTestable={isTestable}
|
||||||
config={config}
|
|
||||||
onSubmit={onSubmit}
|
onSubmit={onSubmit}
|
||||||
initialValues={existingValue}
|
initialValues={existingValue}
|
||||||
onTestChannel={onTestChannel}
|
onTestChannel={onTestChannel}
|
||||||
notifiers={notifiers}
|
notifiers={notifiers}
|
||||||
alertManagerSourceName={alertManagerSourceName}
|
alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME}
|
||||||
defaultItem={{ ...defaultChannelValues }}
|
defaultItem={{ ...defaultChannelValues }}
|
||||||
takenReceiverNames={takenReceiverNames}
|
|
||||||
commonSettingsComponent={GrafanaCommonChannelSettings}
|
commonSettingsComponent={GrafanaCommonChannelSettings}
|
||||||
customValidators={{ [ReceiverTypes.OnCall]: onCallFormValidators }}
|
customValidators={{ [ReceiverTypes.OnCall]: onCallFormValidators }}
|
||||||
/>
|
/>
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
import { css } from '@emotion/css';
|
import { css } from '@emotion/css';
|
||||||
import { useCallback } from 'react';
|
|
||||||
import * as React 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 { GrafanaTheme2 } from '@grafana/data';
|
||||||
import { isFetchError } from '@grafana/runtime';
|
import { isFetchError } from '@grafana/runtime';
|
||||||
import { Alert, Button, Field, Input, LinkButton, useStyles2 } from '@grafana/ui';
|
import { Alert, Button, Field, Input, LinkButton, useStyles2 } from '@grafana/ui';
|
||||||
import { useAppNotification } from 'app/core/copy/appNotification';
|
import { useAppNotification } from 'app/core/copy/appNotification';
|
||||||
import { useCleanup } from 'app/core/hooks/useCleanup';
|
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 { getMessageFromError } from '../../../../../../core/utils/errors';
|
||||||
import { logError } from '../../../Analytics';
|
import { logError } from '../../../Analytics';
|
||||||
@ -24,36 +23,45 @@ import { Notifier } from './notifiers';
|
|||||||
import { normalizeFormValues } from './util';
|
import { normalizeFormValues } from './util';
|
||||||
|
|
||||||
interface Props<R extends ChannelValues> {
|
interface Props<R extends ChannelValues> {
|
||||||
config: AlertManagerCortexConfig;
|
|
||||||
notifiers: Notifier[];
|
notifiers: Notifier[];
|
||||||
defaultItem: R;
|
defaultItem: R;
|
||||||
alertManagerSourceName: string;
|
alertManagerSourceName: string;
|
||||||
onTestChannel?: (channel: R) => void;
|
onTestChannel?: (channel: R) => void;
|
||||||
onSubmit: (values: ReceiverFormValues<R>) => Promise<void>;
|
onSubmit: (values: ReceiverFormValues<R>) => Promise<void>;
|
||||||
takenReceiverNames: string[]; // will validate that user entered receiver name is not one of these
|
|
||||||
commonSettingsComponent: CommonSettingsComponentType;
|
commonSettingsComponent: CommonSettingsComponentType;
|
||||||
initialValues?: ReceiverFormValues<R>;
|
initialValues?: ReceiverFormValues<R>;
|
||||||
isEditable: boolean;
|
isEditable: boolean;
|
||||||
isTestable?: boolean;
|
isTestable?: boolean;
|
||||||
customValidators?: Record<string, React.ComponentProps<typeof ChannelSubForm>['customValidators']>;
|
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>({
|
export function ReceiverForm<R extends ChannelValues>({
|
||||||
config,
|
|
||||||
initialValues,
|
initialValues,
|
||||||
defaultItem,
|
defaultItem,
|
||||||
notifiers,
|
notifiers,
|
||||||
alertManagerSourceName,
|
alertManagerSourceName,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onTestChannel,
|
onTestChannel,
|
||||||
takenReceiverNames,
|
|
||||||
commonSettingsComponent,
|
commonSettingsComponent,
|
||||||
isEditable,
|
isEditable,
|
||||||
isTestable,
|
isTestable,
|
||||||
customValidators,
|
customValidators,
|
||||||
}: Props<R>): JSX.Element {
|
showDefaultRouteWarning,
|
||||||
|
disableEditTitle,
|
||||||
|
}: Props<R>) {
|
||||||
const notifyApp = useAppNotification();
|
const notifyApp = useAppNotification();
|
||||||
const styles = useStyles2(getStyles);
|
const styles = useStyles2(getStyles);
|
||||||
|
const validateContactPointName = useValidateContactPoint({ alertmanager: alertManagerSourceName });
|
||||||
|
|
||||||
// normalize deprecated and new config values
|
// normalize deprecated and new config values
|
||||||
const normalizedConfig = normalizeFormValues(initialValues);
|
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 { 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>) => {
|
const submitCallback = async (values: ReceiverFormValues<R>) => {
|
||||||
try {
|
try {
|
||||||
await onSubmit({
|
await onSubmit({
|
||||||
@ -116,7 +116,7 @@ export function ReceiverForm<R extends ChannelValues>({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<FormProvider {...formAPI}>
|
<FormProvider {...formAPI}>
|
||||||
{!config.alertmanager_config.route && (
|
{showDefaultRouteWarning && (
|
||||||
<Alert severity="warning" title="Attention">
|
<Alert severity="warning" title="Attention">
|
||||||
Because there is no default policy configured yet, this contact point will automatically be set as default.
|
Because there is no default policy configured yet, this contact point will automatically be set as default.
|
||||||
</Alert>
|
</Alert>
|
||||||
@ -127,11 +127,15 @@ export function ReceiverForm<R extends ChannelValues>({
|
|||||||
</h4>
|
</h4>
|
||||||
<Field label="Name" invalid={!!errors.name} error={errors.name && errors.name.message} required>
|
<Field label="Name" invalid={!!errors.name} error={errors.name && errors.name.message} required>
|
||||||
<Input
|
<Input
|
||||||
|
disabled={disableEditTitle}
|
||||||
readOnly={!isEditable}
|
readOnly={!isEditable}
|
||||||
id="name"
|
id="name"
|
||||||
{...register('name', {
|
{...register('name', {
|
||||||
required: 'Name is required',
|
required: 'Name is required',
|
||||||
validate: { nameIsAvailable: validateNameIsAvailable },
|
validate: async (value) => {
|
||||||
|
const existingValue = initialValues?.name;
|
||||||
|
return validateContactPointName(value, existingValue);
|
||||||
|
},
|
||||||
})}
|
})}
|
||||||
width={39}
|
width={39}
|
||||||
placeholder="Name"
|
placeholder="Name"
|
||||||
@ -198,7 +202,7 @@ export function ReceiverForm<R extends ChannelValues>({
|
|||||||
disabled={isSubmitting}
|
disabled={isSubmitting}
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
data-testid="cancel-button"
|
data-testid="cancel-button"
|
||||||
href={makeAMLink('alerting/notifications', alertManagerSourceName)}
|
href={makeAMLink('/alerting/notifications', alertManagerSourceName)}
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</LinkButton>
|
</LinkButton>
|
||||||
|
@ -35,6 +35,7 @@ export const OptionField: FC<Props> = ({
|
|||||||
customValidator,
|
customValidator,
|
||||||
}) => {
|
}) => {
|
||||||
const optionPath = `${pathPrefix}${pathSuffix}`;
|
const optionPath = `${pathPrefix}${pathSuffix}`;
|
||||||
|
const isSecure = pathSuffix === 'secureSettings.';
|
||||||
|
|
||||||
if (option.element === 'subform') {
|
if (option.element === 'subform') {
|
||||||
return (
|
return (
|
||||||
@ -75,12 +76,13 @@ export const OptionField: FC<Props> = ({
|
|||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
pathIndex={pathPrefix}
|
pathIndex={pathPrefix}
|
||||||
customValidator={customValidator}
|
customValidator={customValidator}
|
||||||
|
isSecure={isSecure}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const OptionInput: FC<Props & { id: string; pathIndex?: string }> = ({
|
const OptionInput: FC<Props & { id: string; pathIndex?: string; isSecure?: boolean }> = ({
|
||||||
option,
|
option,
|
||||||
invalid,
|
invalid,
|
||||||
id,
|
id,
|
||||||
@ -88,11 +90,19 @@ const OptionInput: FC<Props & { id: string; pathIndex?: string }> = ({
|
|||||||
pathIndex = '',
|
pathIndex = '',
|
||||||
readOnly = false,
|
readOnly = false,
|
||||||
customValidator,
|
customValidator,
|
||||||
|
isSecure,
|
||||||
}) => {
|
}) => {
|
||||||
const styles = useStyles2(getStyles);
|
const styles = useStyles2(getStyles);
|
||||||
const { control, register, unregister, getValues, setValue } = useFormContext();
|
const { control, register, unregister, getValues, setValue } = useFormContext();
|
||||||
const name = `${pathPrefix}${option.propertyName}`;
|
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
|
// workaround for https://github.com/react-hook-form/react-hook-form/issues/4993#issuecomment-829012506
|
||||||
useEffect(
|
useEffect(
|
||||||
() => () => {
|
() => () => {
|
||||||
|
@ -142,7 +142,8 @@ export function useOnCallIntegration() {
|
|||||||
return receiver;
|
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(
|
const newOnCallIntegrations = onCallIntegrations.filter(
|
||||||
(c) => c.settings[OnCallIntegrationSetting.IntegrationType] === OnCallIntegrationType.NewIntegration
|
(c) => c.settings[OnCallIntegrationSetting.IntegrationType] === OnCallIntegrationType.NewIntegration
|
||||||
);
|
);
|
||||||
|
@ -95,6 +95,12 @@ const getReceiversHandler = () =>
|
|||||||
return HttpResponse.json({ message: 'Not found.' }, { status: 404 });
|
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 = () =>
|
const getGroupsHandler = () =>
|
||||||
http.get<{ datasourceUid: string }>('/api/alertmanager/:datasourceUid/api/v2/alerts/groups', () =>
|
http.get<{ datasourceUid: string }>('/api/alertmanager/:datasourceUid/api/v2/alerts/groups', () =>
|
||||||
// TODO: Scaffold out response with better data as required by tests
|
// TODO: Scaffold out response with better data as required by tests
|
||||||
@ -110,6 +116,7 @@ const handlers = [
|
|||||||
updateAlertmanagerConfigHandler(),
|
updateAlertmanagerConfigHandler(),
|
||||||
getGrafanaAlertmanagerTemplatePreview(),
|
getGrafanaAlertmanagerTemplatePreview(),
|
||||||
getReceiversHandler(),
|
getReceiversHandler(),
|
||||||
|
testReceiversHandler(),
|
||||||
getGroupsHandler(),
|
getGroupsHandler(),
|
||||||
];
|
];
|
||||||
export default handlers;
|
export default handlers;
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { camelCase } from 'lodash';
|
||||||
import { HttpResponse, http } from 'msw';
|
import { HttpResponse, http } from 'msw';
|
||||||
|
|
||||||
import alertmanagerConfig from 'app/features/alerting/unified/components/contact-points/__mocks__/alertmanager.config.mock.json';
|
import alertmanagerConfig from 'app/features/alerting/unified/components/contact-points/__mocks__/alertmanager.config.mock.json';
|
||||||
@ -16,7 +17,11 @@ const mappedReceivers =
|
|||||||
return integration.provenance;
|
return integration.provenance;
|
||||||
})?.provenance || PROVENANCE_NONE;
|
})?.provenance || PROVENANCE_NONE;
|
||||||
return {
|
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: {
|
spec: {
|
||||||
title: contactPoint.name,
|
title: contactPoint.name,
|
||||||
integrations: contactPoint.grafana_managed_receiver_configs || [],
|
integrations: contactPoint.grafana_managed_receiver_configs || [],
|
||||||
@ -34,5 +39,31 @@ const listNamespacedReceiverHandler = () =>
|
|||||||
return HttpResponse.json(parsedReceivers);
|
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;
|
export default handlers;
|
||||||
|
@ -25,6 +25,56 @@ const injectedRtkApi = api
|
|||||||
}),
|
}),
|
||||||
providesTags: ['Receiver'],
|
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,
|
overrideExisting: false,
|
||||||
});
|
});
|
||||||
@ -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 for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */
|
||||||
watch?: boolean;
|
watch?: boolean;
|
||||||
};
|
};
|
||||||
|
export type 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 IoK8SApimachineryPkgApisMetaV1Time = string;
|
||||||
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
||||||
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
|
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
|
||||||
@ -159,12 +274,13 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = {
|
|||||||
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
|
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
|
||||||
uid?: string;
|
uid?: string;
|
||||||
};
|
};
|
||||||
|
export type ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured = {
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Integration = {
|
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Integration = {
|
||||||
SecureFields?: {
|
SecureFields?: ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured;
|
||||||
[key: string]: boolean;
|
|
||||||
};
|
|
||||||
disableResolveMessage?: boolean;
|
disableResolveMessage?: boolean;
|
||||||
settings: string;
|
settings: ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured;
|
||||||
type: string;
|
type: string;
|
||||||
uid?: string;
|
uid?: string;
|
||||||
};
|
};
|
||||||
@ -198,3 +314,69 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1ReceiverL
|
|||||||
kind?: string;
|
kind?: string;
|
||||||
metadata: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
metadata: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
||||||
};
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1StatusCause = {
|
||||||
|
/** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
"name" - the field "name" on the current resource
|
||||||
|
"items[0].name" - the field "name" on the first array entry in "items" */
|
||||||
|
field?: string;
|
||||||
|
/** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */
|
||||||
|
message?: string;
|
||||||
|
/** A machine-readable description of the cause of the error. If this value is empty there is no information available. */
|
||||||
|
reason?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1StatusDetails = {
|
||||||
|
/** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */
|
||||||
|
causes?: IoK8SApimachineryPkgApisMetaV1StatusCause[];
|
||||||
|
/** The group attribute of the resource associated with the status StatusReason. */
|
||||||
|
group?: string;
|
||||||
|
/** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
kind?: string;
|
||||||
|
/** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */
|
||||||
|
name?: string;
|
||||||
|
/** If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. */
|
||||||
|
retryAfterSeconds?: number;
|
||||||
|
/** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
|
||||||
|
uid?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1Status = {
|
||||||
|
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
|
||||||
|
apiVersion?: string;
|
||||||
|
/** Suggested HTTP return code for this status, 0 if not set. */
|
||||||
|
code?: number;
|
||||||
|
/** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */
|
||||||
|
details?: IoK8SApimachineryPkgApisMetaV1StatusDetails;
|
||||||
|
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
kind?: string;
|
||||||
|
/** A human-readable description of the status of this operation. */
|
||||||
|
message?: string;
|
||||||
|
/** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
metadata?: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
||||||
|
/** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */
|
||||||
|
reason?: string;
|
||||||
|
/** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */
|
||||||
|
status?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1Preconditions = {
|
||||||
|
/** Specifies the target ResourceVersion */
|
||||||
|
resourceVersion?: string;
|
||||||
|
/** Specifies the target UID. */
|
||||||
|
uid?: string;
|
||||||
|
};
|
||||||
|
export type IoK8SApimachineryPkgApisMetaV1DeleteOptions = {
|
||||||
|
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
|
||||||
|
apiVersion?: string;
|
||||||
|
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
|
||||||
|
dryRun?: string[];
|
||||||
|
/** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */
|
||||||
|
gracePeriodSeconds?: number;
|
||||||
|
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||||
|
kind?: string;
|
||||||
|
/** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */
|
||||||
|
orphanDependents?: boolean;
|
||||||
|
/** Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */
|
||||||
|
preconditions?: IoK8SApimachineryPkgApisMetaV1Preconditions;
|
||||||
|
/** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */
|
||||||
|
propagationPolicy?: string;
|
||||||
|
};
|
||||||
|
@ -77,24 +77,6 @@ const injectedRtkApi = api
|
|||||||
}),
|
}),
|
||||||
invalidatesTags: ['TimeInterval'],
|
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,
|
overrideExisting: false,
|
||||||
});
|
});
|
||||||
@ -202,26 +184,6 @@ export type DeleteNamespacedTimeIntervalApiArg = {
|
|||||||
propagationPolicy?: string;
|
propagationPolicy?: string;
|
||||||
ioK8SApimachineryPkgApisMetaV1DeleteOptions: IoK8SApimachineryPkgApisMetaV1DeleteOptions;
|
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 IoK8SApimachineryPkgApisMetaV1Time = string;
|
||||||
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
||||||
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
|
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. */
|
/** 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;
|
propagationPolicy?: string;
|
||||||
};
|
};
|
||||||
export type IoK8SApimachineryPkgApisMetaV1Patch = object;
|
|
||||||
|
@ -331,7 +331,14 @@ export const updateAlertManagerConfigAction = createAsyncThunk<void, UpdateAlert
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
await updateAlertManagerConfig(alertManagerSourceName, addDefaultsToAlertmanagerConfig(newConfig));
|
await updateAlertManagerConfig(alertManagerSourceName, addDefaultsToAlertmanagerConfig(newConfig));
|
||||||
thunkAPI.dispatch(alertmanagerApi.util.invalidateTags(['AlertmanagerConfiguration']));
|
thunkAPI.dispatch(
|
||||||
|
alertmanagerApi.util.invalidateTags([
|
||||||
|
'AlertmanagerConfiguration',
|
||||||
|
'ContactPoint',
|
||||||
|
'ContactPointsStatus',
|
||||||
|
'Receiver',
|
||||||
|
])
|
||||||
|
);
|
||||||
if (redirectPath) {
|
if (redirectPath) {
|
||||||
const options = new URLSearchParams(redirectSearch ?? '');
|
const options = new URLSearchParams(redirectSearch ?? '');
|
||||||
locationService.push(makeAMLink(redirectPath, alertManagerSourceName, options));
|
locationService.push(makeAMLink(redirectPath, alertManagerSourceName, options));
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
import { config } from '@grafana/runtime';
|
import { config } from '@grafana/runtime';
|
||||||
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
|
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.
|
* 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;
|
const featureToggleEnabled = config.featureToggles.alertingApiServer;
|
||||||
return featureToggleEnabled && alertmanager === GRAFANA_RULES_SOURCE_NAME;
|
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;
|
||||||
|
@ -125,38 +125,39 @@ export function formValuesToCloudReceiver(
|
|||||||
export function updateConfigWithReceiver(
|
export function updateConfigWithReceiver(
|
||||||
config: AlertManagerCortexConfig,
|
config: AlertManagerCortexConfig,
|
||||||
receiver: Receiver,
|
receiver: Receiver,
|
||||||
replaceReceiverName?: string
|
existingReceiverName?: string
|
||||||
): AlertManagerCortexConfig {
|
): 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
|
// 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}`);
|
throw new Error(`Duplicate receiver name ${receiver.name}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// sanity check that existing receiver exists
|
// sanity check that existing receiver exists
|
||||||
if (replaceReceiverName && !oldReceivers.find(({ name }) => name === replaceReceiverName)) {
|
if (existingReceiverName && !existingReceivers.find(({ name }) => name === existingReceiverName)) {
|
||||||
throw new Error(`Expected receiver ${replaceReceiverName} to exist, but did not find it in the config`);
|
throw new Error(`Expected receiver ${existingReceiverName} to exist, but did not find it in the config`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const updated: AlertManagerCortexConfig = {
|
const updated: AlertManagerCortexConfig = {
|
||||||
...config,
|
...config,
|
||||||
alertmanager_config: {
|
alertmanager_config: {
|
||||||
// @todo rename receiver on routes as necessary
|
|
||||||
...config.alertmanager_config,
|
...config.alertmanager_config,
|
||||||
receivers: replaceReceiverName
|
receivers: existingReceiverName
|
||||||
? oldReceivers.map((existingReceiver) =>
|
? existingReceivers.map((existingReceiver) =>
|
||||||
existingReceiver.name === replaceReceiverName ? receiver : existingReceiver
|
existingReceiver.name === existingReceiverName ? receiver : existingReceiver
|
||||||
)
|
)
|
||||||
: [...oldReceivers, receiver],
|
: [...existingReceivers, receiver],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// if receiver was renamed, rename it in routes as well
|
// 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 = renameReceiverInRoute(
|
||||||
updated.alertmanager_config.route,
|
updated.alertmanager_config.route,
|
||||||
replaceReceiverName,
|
existingReceiverName,
|
||||||
receiver.name
|
receiver.name
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
//DOCS: https://prometheus.io/docs/alerting/latest/configuration/
|
//DOCS: https://prometheus.io/docs/alerting/latest/configuration/
|
||||||
import { DataSourceJsonData, WithAccessControlMetadata } from '@grafana/data';
|
import { DataSourceJsonData, WithAccessControlMetadata } from '@grafana/data';
|
||||||
|
import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/unified/openapi/receiversApi.gen';
|
||||||
|
|
||||||
export type AlertManagerCortexConfig = {
|
export type AlertManagerCortexConfig = {
|
||||||
template_files: Record<string, string>;
|
template_files: Record<string, string>;
|
||||||
@ -65,12 +66,15 @@ export type WebhookConfig = {
|
|||||||
max_alerts?: number;
|
max_alerts?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type GrafanaManagedReceiverConfigSettings<T = any> = Record<string, T>;
|
||||||
export type GrafanaManagedReceiverConfig = {
|
export type GrafanaManagedReceiverConfig = {
|
||||||
uid?: string;
|
uid?: string;
|
||||||
disableResolveMessage?: boolean;
|
disableResolveMessage?: boolean;
|
||||||
secureFields?: Record<string, boolean>;
|
secureFields?: Record<string, boolean>;
|
||||||
secureSettings?: Record<string, any>;
|
secureSettings?: GrafanaManagedReceiverConfigSettings;
|
||||||
settings?: Record<string, any>; // sometimes settings are optional for security reasons (RBAC)
|
/** If retrieved from k8s API, SecureSettings property name is different */
|
||||||
|
// SecureSettings?: GrafanaManagedReceiverConfigSettings<boolean>;
|
||||||
|
settings: GrafanaManagedReceiverConfigSettings;
|
||||||
type: string;
|
type: string;
|
||||||
/**
|
/**
|
||||||
* Name of the _receiver_, which in most cases will be the
|
* Name of the _receiver_, which in most cases will be the
|
||||||
@ -88,6 +92,10 @@ export type GrafanaManagedReceiverConfig = {
|
|||||||
|
|
||||||
export interface GrafanaManagedContactPoint {
|
export interface GrafanaManagedContactPoint {
|
||||||
name: string;
|
name: string;
|
||||||
|
/** If parsed from k8s API, we'll have an ID property */
|
||||||
|
id?: string;
|
||||||
|
metadata?: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
|
||||||
|
provisioned?: boolean;
|
||||||
grafana_managed_receiver_configs?: GrafanaManagedReceiverConfig[];
|
grafana_managed_receiver_configs?: GrafanaManagedReceiverConfig[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -32,7 +32,6 @@ const config: ConfigFile = {
|
|||||||
'listNamespacedTimeInterval',
|
'listNamespacedTimeInterval',
|
||||||
'createNamespacedTimeInterval',
|
'createNamespacedTimeInterval',
|
||||||
'deleteNamespacedTimeInterval',
|
'deleteNamespacedTimeInterval',
|
||||||
'patchNamespacedTimeInterval',
|
|
||||||
'replaceNamespacedTimeInterval',
|
'replaceNamespacedTimeInterval',
|
||||||
],
|
],
|
||||||
exportName: 'generatedTimeIntervalsApi',
|
exportName: 'generatedTimeIntervalsApi',
|
||||||
@ -41,7 +40,13 @@ const config: ConfigFile = {
|
|||||||
'../public/app/features/alerting/unified/openapi/receiversApi.gen.ts': {
|
'../public/app/features/alerting/unified/openapi/receiversApi.gen.ts': {
|
||||||
apiFile: '../public/app/features/alerting/unified/api/alertingApi.ts',
|
apiFile: '../public/app/features/alerting/unified/api/alertingApi.ts',
|
||||||
apiImport: 'alertingApi',
|
apiImport: 'alertingApi',
|
||||||
filterEndpoints: ['listNamespacedReceiver'],
|
filterEndpoints: [
|
||||||
|
'listNamespacedReceiver',
|
||||||
|
'createNamespacedReceiver',
|
||||||
|
'readNamespacedReceiver',
|
||||||
|
'deleteNamespacedReceiver',
|
||||||
|
'replaceNamespacedReceiver',
|
||||||
|
],
|
||||||
exportName: 'generatedReceiversApi',
|
exportName: 'generatedReceiversApi',
|
||||||
flattenArg: false,
|
flattenArg: false,
|
||||||
},
|
},
|
||||||
|
Loading…
Reference in New Issue
Block a user