mirror of
https://github.com/grafana/grafana.git
synced 2024-12-28 01:41:24 -06:00
Alerting: Conditionally use k8s API for simplified routing contact points selector (#90901)
This commit is contained in:
parent
c76d1e04e8
commit
17067824fb
@ -14,7 +14,7 @@ import { MOCK_DATASOURCE_EXTERNAL_VANILLA_ALERTMANAGER_UID } from 'app/features/
|
||||
import {
|
||||
TIME_INTERVAL_UID_HAPPY_PATH,
|
||||
TIME_INTERVAL_UID_FILE_PROVISIONED,
|
||||
} from 'app/features/alerting/unified/mocks/server/handlers/timeIntervals.k8s';
|
||||
} from 'app/features/alerting/unified/mocks/server/handlers/k8s/timeIntervals.k8s';
|
||||
import { setupDataSources } from 'app/features/alerting/unified/testSetup/datasources';
|
||||
import { AlertManagerCortexConfig, MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
|
||||
import { AccessControlAction } from 'app/types';
|
||||
|
@ -16,7 +16,7 @@ import { MetaText } from '../MetaText';
|
||||
import { ReceiverMetadataBadge } from '../receivers/grafanaAppReceivers/ReceiverMetadataBadge';
|
||||
import { ReceiverPluginMetadata } from '../receivers/grafanaAppReceivers/useReceiversMetadata';
|
||||
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from './useContactPoints';
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from './constants';
|
||||
import { getReceiverDescription, ReceiverConfigWithMetadata, RouteReference } from './utils';
|
||||
|
||||
interface ContactPointProps {
|
||||
|
@ -0,0 +1,3 @@
|
||||
export const RECEIVER_STATUS_KEY = Symbol('receiver_status');
|
||||
export const RECEIVER_META_KEY = Symbol('receiver_metadata');
|
||||
export const RECEIVER_PLUGIN_META_KEY = Symbol('receiver_plugin_metadata');
|
@ -7,6 +7,13 @@ import { produce } from 'immer';
|
||||
import { remove } from 'lodash';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import {
|
||||
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver,
|
||||
generatedReceiversApi,
|
||||
} from 'app/features/alerting/unified/openapi/receiversApi.gen';
|
||||
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
|
||||
import { getNamespace, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
|
||||
|
||||
import { alertmanagerApi } from '../../api/alertmanagerApi';
|
||||
import { onCallApi } from '../../api/onCallApi';
|
||||
import { usePluginBridge } from '../../hooks/usePluginBridge';
|
||||
@ -15,10 +22,6 @@ import { SupportedPlugin } from '../../types/pluginBridges';
|
||||
|
||||
import { enhanceContactPointsWithMetadata } from './utils';
|
||||
|
||||
export const RECEIVER_STATUS_KEY = Symbol('receiver_status');
|
||||
export const RECEIVER_META_KEY = Symbol('receiver_metadata');
|
||||
export const RECEIVER_PLUGIN_META_KEY = Symbol('receiver_plugin_metadata');
|
||||
|
||||
const RECEIVER_STATUS_POLLING_INTERVAL = 10 * 1000; // 10 seconds
|
||||
|
||||
/**
|
||||
@ -37,8 +40,8 @@ const {
|
||||
useLazyGetAlertmanagerConfigurationQuery,
|
||||
useUpdateAlertmanagerConfigurationMutation,
|
||||
} = alertmanagerApi;
|
||||
|
||||
const { useGrafanaOnCallIntegrationsQuery } = onCallApi;
|
||||
const { useListNamespacedReceiverQuery } = generatedReceiversApi;
|
||||
|
||||
/**
|
||||
* Check if OnCall is installed, and fetch the list of integrations if so.
|
||||
@ -60,6 +63,35 @@ const useOnCallIntegrations = ({ skip }: { skip?: boolean } = {}) => {
|
||||
}, [installed, loading, oncallIntegrationsResponse]);
|
||||
};
|
||||
|
||||
type K8sReceiver = ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver;
|
||||
|
||||
// TODO: Make this typed as returning `GrafanaManagedContactPoint` - we can't yet do this as the schema thinks
|
||||
// its returning integration settings as a `string` rather than `Record<string, any>`
|
||||
const parseK8sReceiver = (item: K8sReceiver) => {
|
||||
return { name: item.spec.title, grafana_managed_receiver_configs: item.spec.integrations };
|
||||
};
|
||||
|
||||
const useK8sContactPoints = (...[hookParams, queryOptions]: Parameters<typeof useListNamespacedReceiverQuery>) => {
|
||||
return useListNamespacedReceiverQuery(hookParams, {
|
||||
...queryOptions,
|
||||
selectFromResult: ({ data, ...rest }) => {
|
||||
return {
|
||||
...rest,
|
||||
data: data?.items.map((item) => parseK8sReceiver(item)),
|
||||
};
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const useGetGrafanaContactPoints = () => {
|
||||
const namespace = getNamespace();
|
||||
const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME);
|
||||
const grafanaResponse = useGetContactPointsListQuery(undefined, { skip: useK8sApi });
|
||||
const k8sResponse = useK8sContactPoints({ namespace }, { skip: !useK8sApi });
|
||||
|
||||
return useK8sApi ? k8sResponse : grafanaResponse;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch contact points from separate endpoint (i.e. not the Alertmanager config) and combine with
|
||||
* OnCall integrations and any additional metadata from list of notifiers
|
||||
@ -68,7 +100,7 @@ const useOnCallIntegrations = ({ skip }: { skip?: boolean } = {}) => {
|
||||
export const useGetContactPoints = () => {
|
||||
const onCallResponse = useOnCallIntegrations();
|
||||
const alertNotifiers = useGrafanaNotifiersQuery();
|
||||
const contactPointsListResponse = useGetContactPointsListQuery();
|
||||
const contactPointsListResponse = useGetGrafanaContactPoints();
|
||||
|
||||
return useMemo(() => {
|
||||
const isLoading = onCallResponse.isLoading || alertNotifiers.isLoading || contactPointsListResponse.isLoading;
|
||||
|
@ -2,7 +2,7 @@ import uFuzzy from '@leeoniya/ufuzzy';
|
||||
import { uniq } from 'lodash';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { RECEIVER_META_KEY } from 'app/features/alerting/unified/components/contact-points/useContactPoints';
|
||||
import { RECEIVER_META_KEY } from 'app/features/alerting/unified/components/contact-points/constants';
|
||||
import { ContactPointWithMetadata } from 'app/features/alerting/unified/components/contact-points/utils';
|
||||
|
||||
const fuzzyFinder = new uFuzzy({
|
||||
|
@ -2,7 +2,7 @@ import { GrafanaManagedContactPoint } from 'app/plugins/datasource/alertmanager/
|
||||
|
||||
import { ReceiverTypes } from '../receivers/grafanaAppReceivers/onCall/onCall';
|
||||
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from './useContactPoints';
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from './constants';
|
||||
import {
|
||||
ReceiverConfigWithMetadata,
|
||||
getReceiverDescription,
|
||||
|
@ -18,7 +18,7 @@ import { extractReceivers } from '../../utils/receivers';
|
||||
import { ReceiverTypes } from '../receivers/grafanaAppReceivers/onCall/onCall';
|
||||
import { getOnCallMetadata, ReceiverPluginMetadata } from '../receivers/grafanaAppReceivers/useReceiversMetadata';
|
||||
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from './useContactPoints';
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY, RECEIVER_STATUS_KEY } from './constants';
|
||||
|
||||
const AUTOGENERATED_RECEIVER_POLICY_MATCHER_KEY = '__grafana_receiver__';
|
||||
|
||||
|
@ -8,7 +8,7 @@ import {
|
||||
setMuteTimingsListError,
|
||||
} from 'app/features/alerting/unified/mocks/server/configure';
|
||||
import { captureRequests } from 'app/features/alerting/unified/mocks/server/events';
|
||||
import { TIME_INTERVAL_UID_HAPPY_PATH } from 'app/features/alerting/unified/mocks/server/handlers/timeIntervals.k8s';
|
||||
import { TIME_INTERVAL_UID_HAPPY_PATH } from 'app/features/alerting/unified/mocks/server/handlers/k8s/timeIntervals.k8s';
|
||||
import { AccessControlAction } from 'app/types';
|
||||
|
||||
import { grantUserPermissions } from '../../mocks';
|
||||
|
@ -1,11 +1,8 @@
|
||||
import { SelectableValue } from '@grafana/data';
|
||||
import { Select, SelectCommonProps, Text, Stack } from '@grafana/ui';
|
||||
|
||||
import {
|
||||
RECEIVER_META_KEY,
|
||||
RECEIVER_PLUGIN_META_KEY,
|
||||
useContactPointsWithStatus,
|
||||
} from '../contact-points/useContactPoints';
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from '../contact-points/constants';
|
||||
import { useContactPointsWithStatus } from '../contact-points/useContactPoints';
|
||||
import { ReceiverConfigWithMetadata } from '../contact-points/utils';
|
||||
|
||||
export const ContactPointSelector = (props: SelectCommonProps<string>) => {
|
||||
|
@ -66,7 +66,7 @@ const selectFolderAndGroup = async () => {
|
||||
await clickSelectOption(groupInput, grafanaRulerEmptyGroup.name);
|
||||
};
|
||||
|
||||
describe('Can create a new grafana managed alert unsing simplified routing', () => {
|
||||
describe('Can create a new grafana managed alert using simplified routing', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
contextSrv.isEditor = true;
|
||||
@ -169,6 +169,26 @@ describe('Can create a new grafana managed alert unsing simplified routing', ()
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('alertingApiServer enabled', () => {
|
||||
beforeEach(() => {
|
||||
config.featureToggles.alertingApiServer = true;
|
||||
});
|
||||
|
||||
it('allows selecting a contact point when using alerting API server', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderSimplifiedRuleEditor();
|
||||
await waitForElementToBeRemoved(screen.queryAllByTestId('Spinner'));
|
||||
|
||||
await user.click(await ui.inputs.simplifiedRouting.contactPointRouting.find());
|
||||
|
||||
const contactPointInput = await ui.inputs.simplifiedRouting.contactPoint.find();
|
||||
await user.click(byRole('combobox').get(contactPointInput));
|
||||
await clickSelectOption(contactPointInput, 'lotsa-emails');
|
||||
|
||||
expect(await screen.findByText('Email')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function renderSimplifiedRuleEditor() {
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { Stack } from '@grafana/ui';
|
||||
|
||||
import { ContactPointReceiverTitleRow } from '../../../../contact-points/ContactPoint';
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from '../../../../contact-points/useContactPoints';
|
||||
import { RECEIVER_META_KEY, RECEIVER_PLUGIN_META_KEY } from '../../../../contact-points/constants';
|
||||
import { ReceiverConfigWithMetadata, getReceiverDescription } from '../../../../contact-points/utils';
|
||||
|
||||
interface ContactPointDetailsProps {
|
||||
|
@ -8,6 +8,8 @@ import datasourcesHandlers from 'app/features/alerting/unified/mocks/server/hand
|
||||
import evalHandlers from 'app/features/alerting/unified/mocks/server/handlers/eval';
|
||||
import folderHandlers from 'app/features/alerting/unified/mocks/server/handlers/folders';
|
||||
import grafanaRulerHandlers from 'app/features/alerting/unified/mocks/server/handlers/grafanaRuler';
|
||||
import receiverK8sHandlers from 'app/features/alerting/unified/mocks/server/handlers/k8s/receivers.k8s';
|
||||
import timeIntervalK8sHandlers from 'app/features/alerting/unified/mocks/server/handlers/k8s/timeIntervals.k8s';
|
||||
import mimirRulerHandlers from 'app/features/alerting/unified/mocks/server/handlers/mimirRuler';
|
||||
import notificationsHandlers from 'app/features/alerting/unified/mocks/server/handlers/notifications';
|
||||
import pluginsHandlers from 'app/features/alerting/unified/mocks/server/handlers/plugins';
|
||||
@ -15,7 +17,6 @@ import allPluginHandlers from 'app/features/alerting/unified/mocks/server/handle
|
||||
import provisioningHandlers from 'app/features/alerting/unified/mocks/server/handlers/provisioning';
|
||||
import searchHandlers from 'app/features/alerting/unified/mocks/server/handlers/search';
|
||||
import silenceHandlers from 'app/features/alerting/unified/mocks/server/handlers/silences';
|
||||
import timeIntervalK8sHandlers from 'app/features/alerting/unified/mocks/server/handlers/timeIntervals.k8s';
|
||||
|
||||
/**
|
||||
* Array of all mock handlers that are required across Alerting tests
|
||||
@ -38,6 +39,7 @@ const allHandlers = [
|
||||
|
||||
// Kubernetes-style handlers
|
||||
...timeIntervalK8sHandlers,
|
||||
...receiverK8sHandlers,
|
||||
];
|
||||
|
||||
export default allHandlers;
|
||||
|
@ -9,11 +9,11 @@ import {
|
||||
grafanaAlertingConfigurationStatusHandler,
|
||||
} from 'app/features/alerting/unified/mocks/server/handlers/alertmanagers';
|
||||
import { getFolderHandler } from 'app/features/alerting/unified/mocks/server/handlers/folders';
|
||||
import { listNamespacedTimeIntervalHandler } from 'app/features/alerting/unified/mocks/server/handlers/k8s/timeIntervals.k8s';
|
||||
import {
|
||||
getDisabledPluginHandler,
|
||||
getPluginMissingHandler,
|
||||
} from 'app/features/alerting/unified/mocks/server/handlers/plugins';
|
||||
import { listNamespacedTimeIntervalHandler } from 'app/features/alerting/unified/mocks/server/handlers/timeIntervals.k8s';
|
||||
import { SupportedPlugin } from 'app/features/alerting/unified/types/pluginBridges';
|
||||
import { AlertManagerCortexConfig, AlertmanagerChoice } from 'app/plugins/datasource/alertmanager/types';
|
||||
import { FolderDTO } from 'app/types';
|
||||
|
@ -0,0 +1,38 @@
|
||||
import { HttpResponse, http } from 'msw';
|
||||
|
||||
import alertmanagerConfig from 'app/features/alerting/unified/components/contact-points/__mocks__/alertmanager.config.mock.json';
|
||||
import { ALERTING_API_SERVER_BASE_URL, getK8sResponse } from 'app/features/alerting/unified/mocks/server/utils';
|
||||
import { ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver } from 'app/features/alerting/unified/openapi/receiversApi.gen';
|
||||
import { PROVENANCE_ANNOTATION, PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
|
||||
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
|
||||
|
||||
const config: AlertManagerCortexConfig = alertmanagerConfig;
|
||||
|
||||
// Turn our mock alertmanager config into the format that we expect to be returned by the k8s API
|
||||
const mappedReceivers =
|
||||
config.alertmanager_config?.receivers?.map((contactPoint) => {
|
||||
const provenance =
|
||||
contactPoint.grafana_managed_receiver_configs?.find((integration) => {
|
||||
return integration.provenance;
|
||||
})?.provenance || PROVENANCE_NONE;
|
||||
return {
|
||||
metadata: { annotations: { [PROVENANCE_ANNOTATION]: provenance } },
|
||||
spec: {
|
||||
title: contactPoint.name,
|
||||
integrations: contactPoint.grafana_managed_receiver_configs || [],
|
||||
},
|
||||
};
|
||||
}) || [];
|
||||
|
||||
const parsedReceivers = getK8sResponse<ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver>(
|
||||
'ReceiverList',
|
||||
mappedReceivers
|
||||
);
|
||||
|
||||
const listNamespacedReceiverHandler = () =>
|
||||
http.get<{ namespace: string }>(`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/receivers`, () => {
|
||||
return HttpResponse.json(parsedReceivers);
|
||||
});
|
||||
|
||||
const handlers = [listNamespacedReceiverHandler()];
|
||||
export default handlers;
|
@ -4,19 +4,9 @@ import {
|
||||
PROVENANCE_ANNOTATION,
|
||||
PROVENANCE_NONE,
|
||||
} from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
|
||||
import { ALERTING_API_SERVER_BASE_URL, getK8sResponse } from 'app/features/alerting/unified/mocks/server/utils';
|
||||
import { ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TimeInterval } from 'app/features/alerting/unified/openapi/timeIntervalsApi.gen';
|
||||
|
||||
const baseUrl = '/apis/notifications.alerting.grafana.app/v0alpha1';
|
||||
|
||||
const getK8sResponse = <T>(kind: string, items: T[]) => {
|
||||
return {
|
||||
kind,
|
||||
apiVersion: 'notifications.alerting.grafana.app/v0alpha1',
|
||||
metadata: {},
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
/** UID of a time interval that we expect to follow all happy paths within tests/mocks */
|
||||
export const TIME_INTERVAL_UID_HAPPY_PATH = 'f4eae7a4895fa786';
|
||||
/** UID of a (file) provisioned time interval */
|
||||
@ -57,25 +47,28 @@ const getIntervalByName = (name: string) => {
|
||||
};
|
||||
|
||||
export const listNamespacedTimeIntervalHandler = () =>
|
||||
http.get<{ namespace: string }>(`${baseUrl}/namespaces/:namespace/timeintervals`, ({ params }) => {
|
||||
const { namespace } = params;
|
||||
http.get<{ namespace: string }>(
|
||||
`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/timeintervals`,
|
||||
({ params }) => {
|
||||
const { namespace } = params;
|
||||
|
||||
// k8s APIs expect `default` rather than `org-1` - this is one particular example
|
||||
// to make sure we're performing the correct logic when calling this API
|
||||
if (namespace === 'org-1') {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
message: 'error reading namespace: use default rather than org-1',
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
// k8s APIs expect `default` rather than `org-1` - this is one particular example
|
||||
// to make sure we're performing the correct logic when calling this API
|
||||
if (namespace === 'org-1') {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
message: 'error reading namespace: use default rather than org-1',
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
return HttpResponse.json(allTimeIntervals);
|
||||
}
|
||||
return HttpResponse.json(allTimeIntervals);
|
||||
});
|
||||
);
|
||||
|
||||
const readNamespacedTimeIntervalHandler = () =>
|
||||
http.get<{ namespace: string; name: string }>(
|
||||
`${baseUrl}/namespaces/:namespace/timeintervals/:name`,
|
||||
`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/timeintervals/:name`,
|
||||
({ params }) => {
|
||||
const { name } = params;
|
||||
|
||||
@ -89,7 +82,7 @@ const readNamespacedTimeIntervalHandler = () =>
|
||||
|
||||
const replaceNamespacedTimeIntervalHandler = () =>
|
||||
http.put<{ namespace: string; name: string }>(
|
||||
`${baseUrl}/namespaces/:namespace/timeintervals/:name`,
|
||||
`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/timeintervals/:name`,
|
||||
async ({ params, request }) => {
|
||||
const { name } = params;
|
||||
|
||||
@ -104,14 +97,17 @@ const replaceNamespacedTimeIntervalHandler = () =>
|
||||
);
|
||||
|
||||
const createNamespacedTimeIntervalHandler = () =>
|
||||
http.post<{ namespace: string }>(`${baseUrl}/namespaces/:namespace/timeintervals`, () => {
|
||||
http.post<{ namespace: string }>(`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/timeintervals`, () => {
|
||||
return HttpResponse.json({});
|
||||
});
|
||||
|
||||
const deleteNamespacedTimeIntervalHandler = () =>
|
||||
http.delete<{ namespace: string }>(`${baseUrl}/namespaces/:namespace/timeintervals/:name`, () => {
|
||||
return HttpResponse.json({});
|
||||
});
|
||||
http.delete<{ namespace: string }>(
|
||||
`${ALERTING_API_SERVER_BASE_URL}/namespaces/:namespace/timeintervals/:name`,
|
||||
() => {
|
||||
return HttpResponse.json({});
|
||||
}
|
||||
);
|
||||
|
||||
const handlers = [
|
||||
listNamespacedTimeIntervalHandler(),
|
12
public/app/features/alerting/unified/mocks/server/utils.ts
Normal file
12
public/app/features/alerting/unified/mocks/server/utils.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/** Helper method to help generate a kubernetes-style response with a list of items */
|
||||
export const getK8sResponse = <T>(kind: string, items: T[]) => {
|
||||
return {
|
||||
kind,
|
||||
apiVersion: 'notifications.alerting.grafana.app/v0alpha1',
|
||||
metadata: {},
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
/** Expected base URL for our k8s APIs */
|
||||
export const ALERTING_API_SERVER_BASE_URL = '/apis/notifications.alerting.grafana.app/v0alpha1';
|
200
public/app/features/alerting/unified/openapi/receiversApi.gen.ts
Normal file
200
public/app/features/alerting/unified/openapi/receiversApi.gen.ts
Normal file
@ -0,0 +1,200 @@
|
||||
import { alertingApi as api } from '../api/alertingApi';
|
||||
export const addTagTypes = ['Receiver'] as const;
|
||||
const injectedRtkApi = api
|
||||
.enhanceEndpoints({
|
||||
addTagTypes,
|
||||
})
|
||||
.injectEndpoints({
|
||||
endpoints: (build) => ({
|
||||
listNamespacedReceiver: build.query<ListNamespacedReceiverApiResponse, ListNamespacedReceiverApiArg>({
|
||||
query: (queryArg) => ({
|
||||
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/receivers`,
|
||||
params: {
|
||||
pretty: queryArg.pretty,
|
||||
allowWatchBookmarks: queryArg.allowWatchBookmarks,
|
||||
continue: queryArg['continue'],
|
||||
fieldSelector: queryArg.fieldSelector,
|
||||
labelSelector: queryArg.labelSelector,
|
||||
limit: queryArg.limit,
|
||||
resourceVersion: queryArg.resourceVersion,
|
||||
resourceVersionMatch: queryArg.resourceVersionMatch,
|
||||
sendInitialEvents: queryArg.sendInitialEvents,
|
||||
timeoutSeconds: queryArg.timeoutSeconds,
|
||||
watch: queryArg.watch,
|
||||
},
|
||||
}),
|
||||
providesTags: ['Receiver'],
|
||||
}),
|
||||
}),
|
||||
overrideExisting: false,
|
||||
});
|
||||
export { injectedRtkApi as generatedReceiversApi };
|
||||
export type ListNamespacedReceiverApiResponse =
|
||||
/** status 200 OK */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1ReceiverList;
|
||||
export type ListNamespacedReceiverApiArg = {
|
||||
/** 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;
|
||||
/** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */
|
||||
allowWatchBookmarks?: boolean;
|
||||
/** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key".
|
||||
|
||||
This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */
|
||||
continue?: string;
|
||||
/** A selector to restrict the list of returned objects by their fields. Defaults to everything. */
|
||||
fieldSelector?: string;
|
||||
/** A selector to restrict the list of returned objects by their labels. Defaults to everything. */
|
||||
labelSelector?: string;
|
||||
/** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
|
||||
|
||||
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */
|
||||
limit?: number;
|
||||
/** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
|
||||
|
||||
Defaults to unset */
|
||||
resourceVersion?: string;
|
||||
/** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
|
||||
|
||||
Defaults to unset */
|
||||
resourceVersionMatch?: string;
|
||||
/** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.
|
||||
|
||||
When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan
|
||||
is interpreted as "data at least as new as the provided `resourceVersion`"
|
||||
and the bookmark event is send when the state is synced
|
||||
to a `resourceVersion` at least as fresh as the one provided by the ListOptions.
|
||||
If `resourceVersion` is unset, this is interpreted as "consistent read" and the
|
||||
bookmark event is send when the state is synced at least to the moment
|
||||
when request started being processed.
|
||||
- `resourceVersionMatch` set to any other value or unset
|
||||
Invalid error is returned.
|
||||
|
||||
Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */
|
||||
sendInitialEvents?: boolean;
|
||||
/** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */
|
||||
timeoutSeconds?: number;
|
||||
/** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */
|
||||
watch?: boolean;
|
||||
};
|
||||
export type IoK8SApimachineryPkgApisMetaV1Time = string;
|
||||
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
|
||||
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
|
||||
/** APIVersion defines the version of this resource that this field set applies to. The format is "group/version" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. */
|
||||
apiVersion?: string;
|
||||
/** FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: "FieldsV1" */
|
||||
fieldsType?: string;
|
||||
/** FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. */
|
||||
fieldsV1?: IoK8SApimachineryPkgApisMetaV1FieldsV1;
|
||||
/** Manager is an identifier of the workflow managing these fields. */
|
||||
manager?: string;
|
||||
/** Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. */
|
||||
operation?: string;
|
||||
/** Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. */
|
||||
subresource?: string;
|
||||
/** Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. */
|
||||
time?: IoK8SApimachineryPkgApisMetaV1Time;
|
||||
};
|
||||
export type IoK8SApimachineryPkgApisMetaV1OwnerReference = {
|
||||
/** API version of the referent. */
|
||||
apiVersion: string;
|
||||
/** If true, AND if the owner has the "foregroundDeletion" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs "delete" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. */
|
||||
blockOwnerDeletion?: boolean;
|
||||
/** If true, this reference points to the managing controller. */
|
||||
controller?: boolean;
|
||||
/** Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||
kind: string;
|
||||
/** Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
|
||||
name: string;
|
||||
/** UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
|
||||
uid: string;
|
||||
};
|
||||
export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = {
|
||||
/** Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations */
|
||||
annotations?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.
|
||||
|
||||
Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
|
||||
creationTimestamp?: IoK8SApimachineryPkgApisMetaV1Time;
|
||||
/** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */
|
||||
deletionGracePeriodSeconds?: number;
|
||||
/** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.
|
||||
|
||||
Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
|
||||
deletionTimestamp?: IoK8SApimachineryPkgApisMetaV1Time;
|
||||
/** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */
|
||||
finalizers?: string[];
|
||||
/** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
|
||||
|
||||
If this field is specified and the generated name exists, the server will return a 409.
|
||||
|
||||
Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */
|
||||
generateName?: string;
|
||||
/** A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. */
|
||||
generation?: number;
|
||||
/** Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels */
|
||||
labels?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/** ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like "ci-cd". The set of fields is always in the version that the workflow used when modifying the object. */
|
||||
managedFields?: IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry[];
|
||||
/** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
|
||||
name?: string;
|
||||
/** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
|
||||
|
||||
Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */
|
||||
namespace?: string;
|
||||
/** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */
|
||||
ownerReferences?: IoK8SApimachineryPkgApisMetaV1OwnerReference[];
|
||||
/** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.
|
||||
|
||||
Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
|
||||
resourceVersion?: string;
|
||||
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
|
||||
selfLink?: string;
|
||||
/** UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.
|
||||
|
||||
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
|
||||
uid?: string;
|
||||
};
|
||||
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Integration = {
|
||||
SecureFields?: {
|
||||
[key: string]: boolean;
|
||||
};
|
||||
disableResolveMessage?: boolean;
|
||||
settings: string;
|
||||
type: string;
|
||||
uid?: string;
|
||||
};
|
||||
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1ReceiverSpec = {
|
||||
integrations: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Integration[];
|
||||
title: string;
|
||||
};
|
||||
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver = {
|
||||
/** 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;
|
||||
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||
kind?: string;
|
||||
metadata: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
|
||||
spec: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1ReceiverSpec;
|
||||
};
|
||||
export type IoK8SApimachineryPkgApisMetaV1ListMeta = {
|
||||
/** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */
|
||||
continue?: string;
|
||||
/** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */
|
||||
remainingItemCount?: number;
|
||||
/** String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
|
||||
resourceVersion?: string;
|
||||
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
|
||||
selfLink?: string;
|
||||
};
|
||||
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1ReceiverList = {
|
||||
/** 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;
|
||||
items: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver[];
|
||||
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
|
||||
kind?: string;
|
||||
metadata: IoK8SApimachineryPkgApisMetaV1ListMeta;
|
||||
};
|
@ -26,7 +26,7 @@ export interface CloudChannelValues extends ChannelValues {
|
||||
export interface GrafanaChannelValues extends ChannelValues {
|
||||
type: NotifierType;
|
||||
provenance?: string;
|
||||
disableResolveMessage: boolean;
|
||||
disableResolveMessage?: boolean;
|
||||
}
|
||||
|
||||
export interface CommonSettingsComponentProps {
|
||||
|
@ -0,0 +1,5 @@
|
||||
/** Name of the custom annotation label used in k8s APIs for us to discern if a given entity was provisioned */
|
||||
export const PROVENANCE_ANNOTATION = 'grafana.com/provenance';
|
||||
|
||||
/** Value of {@link PROVENANCE_ANNOTATION} given for entities that were not provisioned */
|
||||
export const PROVENANCE_NONE = 'none';
|
18
public/app/features/alerting/unified/utils/k8s/utils.ts
Normal file
18
public/app/features/alerting/unified/utils/k8s/utils.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { config } from '@grafana/runtime';
|
||||
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
|
||||
|
||||
/**
|
||||
* Get the correct namespace to use when using the K8S API.
|
||||
*/
|
||||
export const getNamespace = () => config.namespace;
|
||||
|
||||
/**
|
||||
* Should we call the kubernetes-style API for managing alertmanager entities?
|
||||
*
|
||||
* Requires the alertmanager referenced being the Grafana AM,
|
||||
* and the `alertingApiServer` feature toggle being enabled
|
||||
*/
|
||||
export const shouldUseK8sApi = (alertmanager?: string) => {
|
||||
const featureToggleEnabled = config.featureToggles.alertingApiServer;
|
||||
return featureToggleEnabled && alertmanager === GRAFANA_RULES_SOURCE_NAME;
|
||||
};
|
@ -67,12 +67,20 @@ export type WebhookConfig = {
|
||||
|
||||
export type GrafanaManagedReceiverConfig = {
|
||||
uid?: string;
|
||||
disableResolveMessage: boolean;
|
||||
disableResolveMessage?: boolean;
|
||||
secureFields?: Record<string, boolean>;
|
||||
secureSettings?: Record<string, any>;
|
||||
settings?: Record<string, any>; // sometimes settings are optional for security reasons (RBAC)
|
||||
type: string;
|
||||
name: string;
|
||||
/**
|
||||
* Name of the _receiver_, which in most cases will be the
|
||||
* same as the contact point's name. This should not be used, and is optional because the
|
||||
* kubernetes API does not return it for us (and we don't want to/shouldn't use it)
|
||||
*
|
||||
* @deprecated Do not rely on this property - it won't be present in kuberenetes API responses
|
||||
* and should be the same as the contact point name anyway
|
||||
*/
|
||||
name?: string;
|
||||
updated?: string;
|
||||
created?: string;
|
||||
provenance?: string;
|
||||
|
@ -39,6 +39,13 @@ const config: ConfigFile = {
|
||||
exportName: 'generatedTimeIntervalsApi',
|
||||
flattenArg: false,
|
||||
},
|
||||
'../public/app/features/alerting/unified/openapi/receiversApi.gen.ts': {
|
||||
apiFile: '../public/app/features/alerting/unified/api/alertingApi.ts',
|
||||
apiImport: 'alertingApi',
|
||||
filterEndpoints: ['listNamespacedReceiver'],
|
||||
exportName: 'generatedReceiversApi',
|
||||
flattenArg: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user