mirror of
https://github.com/SigNoz/signoz.git
synced 2026-07-30 09:40:41 +01:00
Compare commits
20 Commits
main
...
feat/alert
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c639cbf8c7 | ||
|
|
a86e9f958d | ||
|
|
e865648db2 | ||
|
|
dd64bdb5cc | ||
|
|
9c82342cbf | ||
|
|
589e33eb39 | ||
|
|
91064d0b63 | ||
|
|
23a9497cce | ||
|
|
b48542d2c7 | ||
|
|
ab0d13814a | ||
|
|
ac5a3bbd57 | ||
|
|
0500d14054 | ||
|
|
a9051c4e9e | ||
|
|
17f4b4af91 | ||
|
|
759d2f6db5 | ||
|
|
b9156ac4b0 | ||
|
|
1300dbc1c2 | ||
|
|
0f657b946e | ||
|
|
376c1d9fcc | ||
|
|
e90783d3ed |
@@ -24,6 +24,8 @@
|
||||
"tooltip_opsgenie_api_key": "Learn how to obtain the API key from your OpsGenie account [here](https://support.atlassian.com/opsgenie/docs/integrate-opsgenie-with-prometheus/).",
|
||||
"tooltip_email_to": "Enter email addresses separated by commas.",
|
||||
"tooltip_ms_teams_url": "The URL of the Microsoft Teams [webhook](https://support.microsoft.com/en-us/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498) to send alerts to. Learn more about Microsoft Teams integration in the docs [here](https://signoz.io/docs/alerts-management/notification-channel/ms-teams/).",
|
||||
"tooltip_google_chat_url": "The URL of the Google Chat space [incoming webhook](https://developers.google.com/workspace/chat/quickstart/webhooks) to send alerts to. It must be an https URL on chat.googleapis.com.",
|
||||
"google_chat_webhook_url_invalid": "Webhook URL must be an https URL on chat.googleapis.com",
|
||||
|
||||
"field_slack_recipient": "Recipient",
|
||||
"field_slack_title": "Title",
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
"tooltip_opsgenie_api_key": "Learn how to obtain the API key from your OpsGenie account [here](https://support.atlassian.com/opsgenie/docs/integrate-opsgenie-with-prometheus/).",
|
||||
"tooltip_email_to": "Enter email addresses separated by commas.",
|
||||
"tooltip_ms_teams_url": "The URL of the Microsoft Teams [webhook](https://support.microsoft.com/en-us/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498) to send alerts to. Learn more about Microsoft Teams integration in the docs [here](https://signoz.io/docs/alerts-management/notification-channel/ms-teams/).",
|
||||
"tooltip_google_chat_url": "The URL of the Google Chat space [incoming webhook](https://developers.google.com/workspace/chat/quickstart/webhooks) to send alerts to. It must be an https URL on chat.googleapis.com.",
|
||||
"google_chat_webhook_url_invalid": "Webhook URL must be an https URL on chat.googleapis.com",
|
||||
"field_slack_recipient": "Recipient",
|
||||
"field_slack_title": "Title",
|
||||
"field_slack_description": "Description",
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import CreateAlertChannels from 'container/CreateAlertChannels';
|
||||
import { ChannelType } from 'container/CreateAlertChannels/config';
|
||||
import { GoogleChatInitialConfig } from 'container/CreateAlertChannels/defaults';
|
||||
import {
|
||||
googleChatDescriptionDefaultValue,
|
||||
googleChatTitleDefaultValue,
|
||||
opsGenieDescriptionDefaultValue,
|
||||
opsGenieMessageDefaultValue,
|
||||
opsGeniePriorityDefaultValue,
|
||||
@@ -419,5 +422,99 @@ describe('Create Alert Channel', () => {
|
||||
expect(descriptionTextArea).toHaveTextContent(slackDescriptionDefaultValue);
|
||||
});
|
||||
});
|
||||
describe('Google Chat', () => {
|
||||
const validWebhookUrl =
|
||||
'https://chat.googleapis.com/v1/spaces/AAAA/messages?key=dummy_key&token=dummy_token';
|
||||
|
||||
beforeEach(() => {
|
||||
render(<CreateAlertChannels preType={ChannelType.GoogleChat} />);
|
||||
});
|
||||
|
||||
it('Should check if the selected item in the type dropdown has text "Google Chat"', () => {
|
||||
expect(screen.getByText('Google Chat')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Should check if Webhook URL label and input are displayed properly', () => {
|
||||
testLabelInputAndHelpValue({
|
||||
labelText: 'field_webhook_url',
|
||||
testId: 'webhook-url-textbox',
|
||||
});
|
||||
});
|
||||
|
||||
it('Should check if Title contains the google chat template', () => {
|
||||
expect(screen.getByTestId('title-textarea')).toHaveTextContent(
|
||||
googleChatTitleDefaultValue,
|
||||
);
|
||||
});
|
||||
|
||||
it('Should check if Description contains the google chat template', () => {
|
||||
expect(screen.getByTestId('description-textarea')).toHaveTextContent(
|
||||
googleChatDescriptionDefaultValue,
|
||||
);
|
||||
});
|
||||
|
||||
it('Should check if saving with a webhook url outside chat.googleapis.com displays error notification', async () => {
|
||||
fireEvent.change(screen.getByTestId('channel-name-textbox'), {
|
||||
target: { value: 'gchat-channel' },
|
||||
});
|
||||
fireEvent.change(screen.getByTestId('webhook-url-textbox'), {
|
||||
target: { value: 'https://example.com/webhook' },
|
||||
});
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: 'button_save_channel' }),
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(errorNotification).toHaveBeenCalledWith({
|
||||
message: 'Error',
|
||||
description: 'google_chat_webhook_url_invalid',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('Should check if saving sends a googlechat_configs payload', async () => {
|
||||
let requestBody: unknown;
|
||||
server.use(
|
||||
rest.post('http://localhost/api/v1/channels', async (req, res, ctx) => {
|
||||
requestBody = await req.json();
|
||||
return res(
|
||||
ctx.status(201),
|
||||
ctx.json({ status: 'success', data: 'channel created' }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByTestId('channel-name-textbox'), {
|
||||
target: { value: 'gchat-channel' },
|
||||
});
|
||||
fireEvent.change(screen.getByTestId('webhook-url-textbox'), {
|
||||
target: { value: validWebhookUrl },
|
||||
});
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: 'button_save_channel' }),
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(successNotification).toHaveBeenCalledWith({
|
||||
message: 'Success',
|
||||
description: 'channel_creation_done',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(requestBody).toStrictEqual({
|
||||
name: 'gchat-channel',
|
||||
googlechat_configs: [
|
||||
{
|
||||
webhook_url: validWebhookUrl,
|
||||
title: GoogleChatInitialConfig.title,
|
||||
text: GoogleChatInitialConfig.text,
|
||||
send_resolved: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,6 +104,7 @@ export enum ChannelType {
|
||||
Pagerduty = 'pagerduty',
|
||||
Opsgenie = 'opsgenie',
|
||||
MsTeams = 'msteams',
|
||||
GoogleChat = 'googlechat',
|
||||
}
|
||||
|
||||
// LabelFilterStatement will be used for preparing filter conditions / matchers
|
||||
@@ -125,3 +126,11 @@ export interface MsTeamsChannel extends Channel {
|
||||
title?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
export interface GoogleChatChannel extends Channel {
|
||||
// incoming webhook url of the google chat space, must be an
|
||||
// https url on chat.googleapis.com
|
||||
webhook_url?: string;
|
||||
title?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,48 @@
|
||||
import { EmailChannel, OpsgenieChannel, PagerChannel } from './config';
|
||||
import {
|
||||
EmailChannel,
|
||||
GoogleChatChannel,
|
||||
OpsgenieChannel,
|
||||
PagerChannel,
|
||||
SlackChannel,
|
||||
} from './config';
|
||||
|
||||
// shared by slack and ms teams, both render the same title / description boxes
|
||||
export const SlackInitialConfig: Partial<SlackChannel> = {
|
||||
text: `{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
*RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}
|
||||
*RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}`,
|
||||
title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
|
||||
{{- if gt (len .CommonLabels) (len .GroupLabels) -}}
|
||||
{{" "}}(
|
||||
{{- with .CommonLabels.Remove .GroupLabels.Names }}
|
||||
{{- range $index, $label := .SortedPairs -}}
|
||||
{{ if $index }}, {{ end }}
|
||||
{{- $label.Name }}="{{ $label.Value -}}"
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
)
|
||||
{{- end }}`,
|
||||
};
|
||||
|
||||
// mirrors DefaultGoogleChatReceiverConfig in pkg/types/alertmanagertypes/googlechat.go,
|
||||
// which the backend applies when title / text are left empty
|
||||
export const GoogleChatInitialConfig: Partial<GoogleChatChannel> = {
|
||||
title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
|
||||
text: `{{ range .Alerts -}}
|
||||
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}
|
||||
**Summary:** {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}
|
||||
**Description:** {{ .Annotations.description }}{{ end }}
|
||||
{{ end }}`,
|
||||
};
|
||||
|
||||
export const PagerInitialConfig: Partial<PagerChannel> = {
|
||||
description: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
|
||||
|
||||
@@ -14,16 +14,24 @@ import testPagerApi from 'api/channels/testPager';
|
||||
import testSlackApi from 'api/channels/testSlack';
|
||||
import testWebhookApi from 'api/channels/testWebhook';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
useCreateChannel,
|
||||
useTestChannel,
|
||||
} from 'api/generated/services/channels';
|
||||
import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { ErrorType } from 'api/generatedAPIInstance';
|
||||
import ROUTES from 'constants/routes';
|
||||
import FormAlertChannels from 'container/FormAlertChannels';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import history from 'lib/history';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
|
||||
import {
|
||||
ChannelType,
|
||||
EmailChannel,
|
||||
GoogleChatChannel,
|
||||
MsTeamsChannel,
|
||||
OpsgenieChannel,
|
||||
PagerChannel,
|
||||
@@ -33,10 +41,16 @@ import {
|
||||
} from './config';
|
||||
import {
|
||||
EmailInitialConfig,
|
||||
GoogleChatInitialConfig,
|
||||
OpsgenieInitialConfig,
|
||||
PagerInitialConfig,
|
||||
SlackInitialConfig,
|
||||
} from './defaults';
|
||||
import { isChannelType } from './utils';
|
||||
import {
|
||||
isChannelType,
|
||||
isValidGoogleChatWebhookURL,
|
||||
prepareGoogleChatRequest,
|
||||
} from './utils';
|
||||
|
||||
import './CreateAlertChannels.styles.scss';
|
||||
|
||||
@@ -60,38 +74,22 @@ function CreateAlertChannels({
|
||||
PagerChannel &
|
||||
MsTeamsChannel &
|
||||
OpsgenieChannel &
|
||||
EmailChannel
|
||||
EmailChannel &
|
||||
GoogleChatChannel
|
||||
>
|
||||
>({
|
||||
>(() => ({
|
||||
send_resolved: true,
|
||||
text: `{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
*RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}
|
||||
*RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
{{ end }}
|
||||
{{ end }}`,
|
||||
title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
|
||||
{{- if gt (len .CommonLabels) (len .GroupLabels) -}}
|
||||
{{" "}}(
|
||||
{{- with .CommonLabels.Remove .GroupLabels.Names }}
|
||||
{{- range $index, $label := .SortedPairs -}}
|
||||
{{ if $index }}, {{ end }}
|
||||
{{- $label.Name }}="{{ $label.Value -}}"
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
)
|
||||
{{- end }}`,
|
||||
});
|
||||
...(preType === ChannelType.GoogleChat
|
||||
? GoogleChatInitialConfig
|
||||
: SlackInitialConfig),
|
||||
}));
|
||||
const [savingState, setSavingState] = useState<boolean>(false);
|
||||
const [testingState, setTestingState] = useState<boolean>(false);
|
||||
const { notifications } = useNotifications();
|
||||
|
||||
const { mutateAsync: createChannel } = useCreateChannel();
|
||||
const { mutateAsync: testChannel } = useTestChannel();
|
||||
|
||||
const [type, setType] = useState<ChannelType>(preType);
|
||||
const onTypeChangeHandler = useCallback(
|
||||
(value: string) => {
|
||||
@@ -121,8 +119,26 @@ function CreateAlertChannels({
|
||||
...EmailInitialConfig,
|
||||
}));
|
||||
}
|
||||
|
||||
// google chat prefills its own title / description templates, so switching
|
||||
// in or out of it has to swap the templates the form is showing
|
||||
if (
|
||||
currentType !== value &&
|
||||
(value === ChannelType.GoogleChat || currentType === ChannelType.GoogleChat)
|
||||
) {
|
||||
const templates =
|
||||
value === ChannelType.GoogleChat
|
||||
? GoogleChatInitialConfig
|
||||
: SlackInitialConfig;
|
||||
|
||||
setSelectedConfig((selectedConfig) => ({
|
||||
...selectedConfig,
|
||||
...templates,
|
||||
}));
|
||||
formInstance.setFieldsValue(templates);
|
||||
}
|
||||
},
|
||||
[type, selectedConfig],
|
||||
[type, selectedConfig, formInstance],
|
||||
);
|
||||
|
||||
const prepareSlackRequest = useCallback(
|
||||
@@ -407,6 +423,56 @@ function CreateAlertChannels({
|
||||
showErrorModal,
|
||||
]);
|
||||
|
||||
const validateGoogleChatConfig = useCallback((): boolean => {
|
||||
if (!selectedConfig.webhook_url) {
|
||||
notifications.error({
|
||||
message: 'Error',
|
||||
description: t('webhook_url_required'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isValidGoogleChatWebhookURL(selectedConfig.webhook_url)) {
|
||||
notifications.error({
|
||||
message: 'Error',
|
||||
description: t('google_chat_webhook_url_invalid'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, [selectedConfig.webhook_url, notifications, t]);
|
||||
|
||||
const onGoogleChatHandler = useCallback(async () => {
|
||||
if (!validateGoogleChatConfig()) {
|
||||
return { status: 'failed', statusMessage: t('channel_creation_failed') };
|
||||
}
|
||||
|
||||
setSavingState(true);
|
||||
|
||||
try {
|
||||
await createChannel({ data: prepareGoogleChatRequest(selectedConfig) });
|
||||
notifications.success({
|
||||
message: 'Success',
|
||||
description: t('channel_creation_done'),
|
||||
});
|
||||
history.replace(ROUTES.ALL_CHANNELS);
|
||||
return { status: 'success', statusMessage: t('channel_creation_done') };
|
||||
} catch (error) {
|
||||
showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
|
||||
return { status: 'failed', statusMessage: t('channel_creation_failed') };
|
||||
} finally {
|
||||
setSavingState(false);
|
||||
}
|
||||
}, [
|
||||
validateGoogleChatConfig,
|
||||
createChannel,
|
||||
selectedConfig,
|
||||
notifications,
|
||||
t,
|
||||
showErrorModal,
|
||||
]);
|
||||
|
||||
const onSaveHandler = useCallback(
|
||||
async (value: ChannelType) => {
|
||||
if (!selectedConfig.name) {
|
||||
@@ -424,6 +490,7 @@ function CreateAlertChannels({
|
||||
[ChannelType.Opsgenie]: onOpsgenieHandler,
|
||||
[ChannelType.MsTeams]: onMsTeamsHandler,
|
||||
[ChannelType.Email]: onEmailHandler,
|
||||
[ChannelType.GoogleChat]: onGoogleChatHandler,
|
||||
};
|
||||
|
||||
if (isChannelType(value)) {
|
||||
@@ -455,6 +522,7 @@ function CreateAlertChannels({
|
||||
onOpsgenieHandler,
|
||||
onMsTeamsHandler,
|
||||
onEmailHandler,
|
||||
onGoogleChatHandler,
|
||||
notifications,
|
||||
t,
|
||||
],
|
||||
@@ -492,6 +560,13 @@ function CreateAlertChannels({
|
||||
request = prepareEmailRequest();
|
||||
await testEmail(request);
|
||||
break;
|
||||
case ChannelType.GoogleChat:
|
||||
if (!validateGoogleChatConfig()) {
|
||||
setTestingState(false);
|
||||
return;
|
||||
}
|
||||
await testChannel({ data: prepareGoogleChatRequest(selectedConfig) });
|
||||
break;
|
||||
default:
|
||||
notifications.error({
|
||||
message: 'Error',
|
||||
@@ -513,7 +588,11 @@ function CreateAlertChannels({
|
||||
status: 'Test success',
|
||||
});
|
||||
} catch (error) {
|
||||
showErrorModal(error as APIError);
|
||||
showErrorModal(
|
||||
error instanceof APIError
|
||||
? error
|
||||
: toAPIError(error as ErrorType<RenderErrorResponseDTO>),
|
||||
);
|
||||
|
||||
logEvent('Alert Channel: Test notification', {
|
||||
type: channelType,
|
||||
@@ -535,6 +614,8 @@ function CreateAlertChannels({
|
||||
prepareSlackRequest,
|
||||
prepareMsTeamsRequest,
|
||||
prepareEmailRequest,
|
||||
validateGoogleChatConfig,
|
||||
testChannel,
|
||||
notifications,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,4 +1,39 @@
|
||||
import { ChannelType } from './config';
|
||||
import {
|
||||
AlertmanagertypesPostableChannelDTO,
|
||||
ConfigSecretURLDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { ChannelType, GoogleChatChannel } from './config';
|
||||
|
||||
export const isChannelType = (type: string): type is ChannelType =>
|
||||
Object.values(ChannelType).includes(type as ChannelType);
|
||||
|
||||
const GOOGLE_CHAT_WEBHOOK_HOST = 'chat.googleapis.com';
|
||||
|
||||
// the backend enforces the same two rules, this is only for a nicer error experience
|
||||
export const isValidGoogleChatWebhookURL = (url: string): boolean => {
|
||||
try {
|
||||
const { protocol, hostname } = new URL(url);
|
||||
return (
|
||||
protocol === 'https:' && hostname.toLowerCase() === GOOGLE_CHAT_WEBHOOK_HOST
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// create, update and test all send the same body shape
|
||||
export const prepareGoogleChatRequest = (
|
||||
config: Partial<GoogleChatChannel>,
|
||||
): AlertmanagertypesPostableChannelDTO => ({
|
||||
name: config.name || '',
|
||||
googlechat_configs: [
|
||||
{
|
||||
// the generated type models go's config.SecretURL as an object, the api takes a string
|
||||
webhook_url: (config.webhook_url || '') as unknown as ConfigSecretURLDTO,
|
||||
title: config.title || '',
|
||||
text: config.text || '',
|
||||
send_resolved: config.send_resolved || false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -14,10 +14,17 @@ import testPagerApi from 'api/channels/testPager';
|
||||
import testSlackApi from 'api/channels/testSlack';
|
||||
import testWebhookApi from 'api/channels/testWebhook';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
useTestChannel,
|
||||
useUpdateChannelByID,
|
||||
} from 'api/generated/services/channels';
|
||||
import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { ErrorType } from 'api/generatedAPIInstance';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
ChannelType,
|
||||
EmailChannel,
|
||||
GoogleChatChannel,
|
||||
MsTeamsChannel,
|
||||
OpsgenieChannel,
|
||||
PagerChannel,
|
||||
@@ -25,10 +32,15 @@ import {
|
||||
ValidatePagerChannel,
|
||||
WebhookChannel,
|
||||
} from 'container/CreateAlertChannels/config';
|
||||
import {
|
||||
isValidGoogleChatWebhookURL,
|
||||
prepareGoogleChatRequest,
|
||||
} from 'container/CreateAlertChannels/utils';
|
||||
import FormAlertChannels from 'container/FormAlertChannels';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import history from 'lib/history';
|
||||
import APIError from 'types/api/error';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
|
||||
function EditAlertChannels({
|
||||
initialValue,
|
||||
@@ -45,7 +57,8 @@ function EditAlertChannels({
|
||||
PagerChannel &
|
||||
MsTeamsChannel &
|
||||
OpsgenieChannel &
|
||||
EmailChannel
|
||||
EmailChannel &
|
||||
GoogleChatChannel
|
||||
>
|
||||
>({
|
||||
...initialValue,
|
||||
@@ -54,6 +67,26 @@ function EditAlertChannels({
|
||||
const [testingState, setTestingState] = useState<boolean>(false);
|
||||
const { notifications } = useNotifications();
|
||||
|
||||
const { mutateAsync: updateChannel } = useUpdateChannelByID();
|
||||
const { mutateAsync: testChannel } = useTestChannel();
|
||||
|
||||
const notifyError = useCallback(
|
||||
(error: unknown): APIError => {
|
||||
const apiError =
|
||||
error instanceof APIError
|
||||
? error
|
||||
: toAPIError(error as ErrorType<RenderErrorResponseDTO>);
|
||||
|
||||
notifications.error({
|
||||
message: apiError.getErrorCode(),
|
||||
description: apiError.getErrorMessage(),
|
||||
});
|
||||
|
||||
return apiError;
|
||||
},
|
||||
[notifications],
|
||||
);
|
||||
|
||||
const [type, setType] = useState<ChannelType>(
|
||||
initialValue?.type ? (initialValue.type as ChannelType) : ChannelType.Slack,
|
||||
);
|
||||
@@ -364,6 +397,61 @@ function EditAlertChannels({
|
||||
}
|
||||
}, [prepareMsTeamsRequest, t, notifications, selectedConfig]);
|
||||
|
||||
const validateGoogleChatConfig = useCallback((): string => {
|
||||
if (!selectedConfig?.webhook_url) {
|
||||
return t('webhook_url_required');
|
||||
}
|
||||
|
||||
if (!isValidGoogleChatWebhookURL(selectedConfig.webhook_url)) {
|
||||
return t('google_chat_webhook_url_invalid');
|
||||
}
|
||||
|
||||
return '';
|
||||
}, [selectedConfig, t]);
|
||||
|
||||
const onGoogleChatEditHandler = useCallback(async () => {
|
||||
const validationError = validateGoogleChatConfig();
|
||||
|
||||
if (validationError !== '') {
|
||||
notifications.error({
|
||||
message: 'Error',
|
||||
description: validationError,
|
||||
});
|
||||
return { status: 'failed', statusMessage: validationError };
|
||||
}
|
||||
|
||||
setSavingState(true);
|
||||
|
||||
try {
|
||||
await updateChannel({
|
||||
pathParams: { id },
|
||||
data: prepareGoogleChatRequest(selectedConfig),
|
||||
});
|
||||
notifications.success({
|
||||
message: 'Success',
|
||||
description: t('channel_edit_done'),
|
||||
});
|
||||
history.replace(ROUTES.ALL_CHANNELS);
|
||||
return { status: 'success', statusMessage: t('channel_edit_done') };
|
||||
} catch (error) {
|
||||
const apiError = notifyError(error);
|
||||
return {
|
||||
status: 'failed',
|
||||
statusMessage: apiError.getErrorMessage() || t('channel_edit_failed'),
|
||||
};
|
||||
} finally {
|
||||
setSavingState(false);
|
||||
}
|
||||
}, [
|
||||
validateGoogleChatConfig,
|
||||
updateChannel,
|
||||
id,
|
||||
selectedConfig,
|
||||
notifications,
|
||||
notifyError,
|
||||
t,
|
||||
]);
|
||||
|
||||
const onSaveHandler = useCallback(
|
||||
async (value: ChannelType) => {
|
||||
let result;
|
||||
@@ -379,6 +467,8 @@ function EditAlertChannels({
|
||||
result = await onOpsgenieEditHandler();
|
||||
} else if (value === ChannelType.Email) {
|
||||
result = await onEmailEditHandler();
|
||||
} else if (value === ChannelType.GoogleChat) {
|
||||
result = await onGoogleChatEditHandler();
|
||||
}
|
||||
logEvent('Alert Channel: Save channel', {
|
||||
type: value,
|
||||
@@ -397,6 +487,7 @@ function EditAlertChannels({
|
||||
onMsTeamsEditHandler,
|
||||
onOpsgenieEditHandler,
|
||||
onEmailEditHandler,
|
||||
onGoogleChatEditHandler,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -438,6 +529,19 @@ function EditAlertChannels({
|
||||
await testEmail(request);
|
||||
}
|
||||
break;
|
||||
case ChannelType.GoogleChat: {
|
||||
const validationError = validateGoogleChatConfig();
|
||||
if (validationError !== '') {
|
||||
notifications.error({
|
||||
message: 'Error',
|
||||
description: validationError,
|
||||
});
|
||||
setTestingState(false);
|
||||
return;
|
||||
}
|
||||
await testChannel({ data: prepareGoogleChatRequest(selectedConfig) });
|
||||
break;
|
||||
}
|
||||
default:
|
||||
notifications.error({
|
||||
message: 'Error',
|
||||
@@ -459,10 +563,7 @@ function EditAlertChannels({
|
||||
status: 'Test success',
|
||||
});
|
||||
} catch (error) {
|
||||
notifications.error({
|
||||
message: (error as APIError).getErrorCode(),
|
||||
description: (error as APIError).getErrorMessage(),
|
||||
});
|
||||
notifyError(error);
|
||||
logEvent('Alert Channel: Test notification', {
|
||||
type: channelType,
|
||||
sendResolvedAlert: selectedConfig?.send_resolved,
|
||||
@@ -476,6 +577,9 @@ function EditAlertChannels({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[
|
||||
t,
|
||||
notifyError,
|
||||
validateGoogleChatConfig,
|
||||
testChannel,
|
||||
prepareWebhookRequest,
|
||||
preparePagerRequest,
|
||||
prepareSlackRequest,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Form, Input } from 'antd';
|
||||
import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
|
||||
|
||||
import { GoogleChatChannel } from '../../CreateAlertChannels/config';
|
||||
import { isValidGoogleChatWebhookURL } from '../../CreateAlertChannels/utils';
|
||||
|
||||
function GoogleChat({ setSelectedConfig }: GoogleChatProps): JSX.Element {
|
||||
const { t } = useTranslation('channels');
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form.Item
|
||||
name="webhook_url"
|
||||
label={t('field_webhook_url')}
|
||||
required
|
||||
rules={[
|
||||
{
|
||||
validator: (_, value: string): Promise<void> =>
|
||||
!value || isValidGoogleChatWebhookURL(value)
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error(t('google_chat_webhook_url_invalid'))),
|
||||
},
|
||||
]}
|
||||
tooltip={{
|
||||
title: (
|
||||
<MarkdownRenderer
|
||||
markdownContent={t('tooltip_google_chat_url')}
|
||||
variables={{}}
|
||||
/>
|
||||
),
|
||||
overlayInnerStyle: { maxWidth: 400 },
|
||||
placement: 'right',
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
onChange={(event): void => {
|
||||
setSelectedConfig((value) => ({
|
||||
...value,
|
||||
webhook_url: event.target.value,
|
||||
}));
|
||||
}}
|
||||
data-testid="webhook-url-textbox"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="title" label={t('field_slack_title')}>
|
||||
<Input.TextArea
|
||||
rows={4}
|
||||
onChange={(event): void =>
|
||||
setSelectedConfig((value) => ({
|
||||
...value,
|
||||
title: event.target.value,
|
||||
}))
|
||||
}
|
||||
data-testid="title-textarea"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="text" label={t('field_slack_description')}>
|
||||
<Input.TextArea
|
||||
rows={4}
|
||||
onChange={(event): void =>
|
||||
setSelectedConfig((value) => ({
|
||||
...value,
|
||||
text: event.target.value,
|
||||
}))
|
||||
}
|
||||
data-testid="description-textarea"
|
||||
placeholder={t('placeholder_slack_description')}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface GoogleChatProps {
|
||||
setSelectedConfig: Dispatch<SetStateAction<Partial<GoogleChatChannel>>>;
|
||||
}
|
||||
|
||||
export default GoogleChat;
|
||||
@@ -9,6 +9,7 @@ import ROUTES from 'constants/routes';
|
||||
import {
|
||||
ChannelType,
|
||||
EmailChannel,
|
||||
GoogleChatChannel,
|
||||
OpsgenieChannel,
|
||||
PagerChannel,
|
||||
SlackChannel,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import history from 'lib/history';
|
||||
|
||||
import EmailSettings from './Settings/Email';
|
||||
import GoogleChatSettings from './Settings/GoogleChat';
|
||||
import MsTeamsSettings from './Settings/MsTeams';
|
||||
import OpsgenieSettings from './Settings/Opsgenie';
|
||||
import PagerSettings from './Settings/Pager';
|
||||
@@ -49,6 +51,8 @@ function FormAlertChannels({
|
||||
return <PagerSettings setSelectedConfig={setSelectedConfig} />;
|
||||
case ChannelType.MsTeams:
|
||||
return <MsTeamsSettings setSelectedConfig={setSelectedConfig} />;
|
||||
case ChannelType.GoogleChat:
|
||||
return <GoogleChatSettings setSelectedConfig={setSelectedConfig} />;
|
||||
case ChannelType.Opsgenie:
|
||||
return <OpsgenieSettings setSelectedConfig={setSelectedConfig} />;
|
||||
case ChannelType.Email:
|
||||
@@ -129,6 +133,14 @@ function FormAlertChannels({
|
||||
<Select.Option value="msteams" key="msteams" data-testid="select-option">
|
||||
Microsoft Teams
|
||||
</Select.Option>
|
||||
|
||||
<Select.Option
|
||||
value="googlechat"
|
||||
key="googlechat"
|
||||
data-testid="select-option"
|
||||
>
|
||||
Google Chat
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
@@ -176,7 +188,8 @@ interface FormAlertChannelsProps {
|
||||
WebhookChannel &
|
||||
PagerChannel &
|
||||
OpsgenieChannel &
|
||||
EmailChannel
|
||||
EmailChannel &
|
||||
GoogleChatChannel
|
||||
>
|
||||
>
|
||||
>;
|
||||
|
||||
@@ -27,6 +27,10 @@ export const slackTitleDefaultValue = `[{{ .Status | toUpper }}{{ if eq .Status
|
||||
|
||||
export const slackDescriptionDefaultValue = `{{ range .Alerts -}} *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }} *Summary:* {{ .Annotations.summary }} *Description:* {{ .Annotations.description }} *RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}} *RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}} *Details:* {{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }} {{ end }} {{ end }}`;
|
||||
|
||||
export const googleChatTitleDefaultValue = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`;
|
||||
|
||||
export const googleChatDescriptionDefaultValue = `{{ range .Alerts -}} **Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }} **Summary:** {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }} **Description:** {{ .Annotations.description }}{{ end }} {{ end }}`;
|
||||
|
||||
export const editSlackDescriptionDefaultValue = `{{ range .Alerts -}} *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }} dummy_summary *Summary:* {{ .Annotations.summary }} *Description:* {{ .Annotations.description }} *Details:* {{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }} {{ end }} {{ end }}`;
|
||||
|
||||
export const pagerDutyDescriptionDefaultVaule = `{{ if gt (len .Alerts.Firing) 0 -}} Alerts Firing: {{ range .Alerts.Firing }} - Message: {{ .Annotations.description }} Labels: {{ range .Labels.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Annotations: {{ range .Annotations.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Source: {{ .GeneratorURL }} {{ end }} {{- end }} {{ if gt (len .Alerts.Resolved) 0 -}} Alerts Resolved: {{ range .Alerts.Resolved }} - Message: {{ .Annotations.description }} Labels: {{ range .Labels.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Annotations: {{ range .Annotations.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Source: {{ .GeneratorURL }} {{ end }} {{- end }}`;
|
||||
|
||||
@@ -10,6 +10,7 @@ import Spinner from 'components/Spinner';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
ChannelType,
|
||||
GoogleChatChannel,
|
||||
MsTeamsChannel,
|
||||
PagerChannel,
|
||||
SlackChannel,
|
||||
@@ -59,9 +60,17 @@ function ChannelsEdit(): JSX.Element {
|
||||
|
||||
const prepChannelConfig = (): {
|
||||
type: string;
|
||||
channel: SlackChannel & WebhookChannel & PagerChannel & MsTeamsChannel;
|
||||
channel: SlackChannel &
|
||||
WebhookChannel &
|
||||
PagerChannel &
|
||||
MsTeamsChannel &
|
||||
GoogleChatChannel;
|
||||
} => {
|
||||
let channel: SlackChannel & WebhookChannel & PagerChannel & MsTeamsChannel = {
|
||||
let channel: SlackChannel &
|
||||
WebhookChannel &
|
||||
PagerChannel &
|
||||
MsTeamsChannel &
|
||||
GoogleChatChannel = {
|
||||
name: '',
|
||||
};
|
||||
if (value && 'slack_configs' in value) {
|
||||
@@ -81,6 +90,15 @@ function ChannelsEdit(): JSX.Element {
|
||||
channel,
|
||||
};
|
||||
}
|
||||
if (value && 'googlechat_configs' in value) {
|
||||
const [googleChatConfig] = value.googlechat_configs;
|
||||
channel = googleChatConfig;
|
||||
return {
|
||||
type: ChannelType.GoogleChat,
|
||||
channel,
|
||||
};
|
||||
}
|
||||
|
||||
if (value && 'pagerduty_configs' in value) {
|
||||
const pagerConfig = value.pagerduty_configs[0];
|
||||
channel = pagerConfig;
|
||||
|
||||
212
pkg/alertmanager/alertmanagernotify/googlechat/googlechat.go
Normal file
212
pkg/alertmanager/alertmanagernotify/googlechat/googlechat.go
Normal file
@@ -0,0 +1,212 @@
|
||||
package googlechat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/templating/markdownrenderer"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
"github.com/prometheus/alertmanager/notify"
|
||||
"github.com/prometheus/alertmanager/template"
|
||||
"github.com/prometheus/alertmanager/types"
|
||||
"github.com/prometheus/common/model"
|
||||
)
|
||||
|
||||
func New(conf *alertmanagertypes.GoogleChatReceiverConfig, t *template.Template, l *slog.Logger, templater alertmanagertypes.Templater) (*Notifier, error) {
|
||||
client, err := notify.NewClientWithTracing(*conf.HTTPConfig, Integration)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Notifier{
|
||||
conf: conf,
|
||||
tmpl: t,
|
||||
logger: l,
|
||||
client: client,
|
||||
retrier: ¬ify.Retrier{RetryCodes: []int{http.StatusTooManyRequests}},
|
||||
templater: templater,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, error) {
|
||||
if n.conf.WebhookURL == nil {
|
||||
return false, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url is empty")
|
||||
}
|
||||
|
||||
key, err := notify.ExtractGroupKey(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n.logger.DebugContext(ctx, "sending google chat notification", slog.Any("group_key", key))
|
||||
|
||||
c, err := n.prepareContent(ctx, alerts)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// Empty title AND body means a misconfigured template, so fail loudly and
|
||||
// non-retryably instead of sending a card with no content.
|
||||
if c.title == "" && c.body == "" {
|
||||
return false, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat message rendered empty; check the channel title/text templates")
|
||||
}
|
||||
|
||||
status := statusLine(alerts)
|
||||
buttons := linkButtons(alerts[0])
|
||||
|
||||
// Serialized-size guard: keep the payload within Google Chat's byte limit by
|
||||
// trimming the body first, then the title (which appears in both the summary
|
||||
// and the card header). Buttons/status are small and bounded, so trimming the
|
||||
// two text fields should always bring the payload under the limit.
|
||||
title, body := c.title, c.body
|
||||
buf, err := encodeMessage(buildMessage(title, status, body, buttons))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for buf.Len() > maxMessageBytes {
|
||||
if body == "" && title == "" {
|
||||
break
|
||||
}
|
||||
over := buf.Len() - maxMessageBytes
|
||||
if body != "" {
|
||||
body = truncateToByteLimit(body, max(len(body)-over, 0))
|
||||
} else {
|
||||
title = truncateToByteLimit(title, max(len(title)-over, 0))
|
||||
}
|
||||
if buf, err = encodeMessage(buildMessage(title, status, body, buttons)); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
// Thread same-rule alerts together: threadKey is a stable hash of the
|
||||
// alert group key. Changing a rule's grouping starts a new thread.
|
||||
u, err := url.Parse(n.conf.WebhookURL.String())
|
||||
if err != nil {
|
||||
return false, errors.WrapInternalf(err, errors.CodeInternal, "parse google chat webhook url")
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("threadKey", key.Hash())
|
||||
q.Set("messageReplyOption", "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD")
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
resp, err := notify.PostJSON(ctx, n.client, u.String(), buf) //nolint:bodyclose
|
||||
if err != nil {
|
||||
return true, notify.RedactURL(err)
|
||||
}
|
||||
defer notify.Drain(resp)
|
||||
|
||||
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
|
||||
if err != nil {
|
||||
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
|
||||
}
|
||||
return shouldRetry, err
|
||||
}
|
||||
|
||||
// prepareContent expands the title and body templates. Custom templates (from
|
||||
// alert annotations) override the channel defaults. The title is used as a plain
|
||||
// summary + card header; the body is converted to HTML for the card text widget.
|
||||
func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) (content, error) {
|
||||
customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)
|
||||
result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{
|
||||
TitleTemplate: customTitle,
|
||||
BodyTemplate: customBody,
|
||||
DefaultTitleTemplate: n.conf.Title,
|
||||
DefaultBodyTemplate: n.conf.Text,
|
||||
}, alerts)
|
||||
if err != nil {
|
||||
return content{}, err
|
||||
}
|
||||
|
||||
title := result.Title
|
||||
body := strings.Join(result.Body, "\n\n")
|
||||
// The body goes into a card textParagraph, which renders HTML. Default and
|
||||
// custom templates are both standard markdown, so convert uniformly.
|
||||
if body != "" {
|
||||
if body, err = markdownrenderer.RenderHTML(body); err != nil {
|
||||
return content{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return content{title: title, body: body}, nil
|
||||
}
|
||||
|
||||
// statusLine returns a colored firing/resolved banner for the card body.
|
||||
func statusLine(alerts []*types.Alert) string {
|
||||
if types.Alerts(alerts...).Status() == model.AlertResolved {
|
||||
return `<font color="#33a853"><b>🟢 RESOLVED</b></font>`
|
||||
}
|
||||
return `<font color="#d32f2f"><b>🔴 FIRING</b></font>`
|
||||
}
|
||||
|
||||
// linkButtons builds openLink buttons from the rule/link data the ruler attaches
|
||||
// to every alert. Empty links are skipped.
|
||||
func linkButtons(alert *types.Alert) []button {
|
||||
var buttons []button
|
||||
add := func(text, u string) {
|
||||
if u != "" {
|
||||
buttons = append(buttons, button{Text: text, OnClick: onClick{OpenLink: openLink{URL: u}}})
|
||||
}
|
||||
}
|
||||
add("Open in SigNoz", string(alert.Labels[ruletypes.LabelRuleSource]))
|
||||
add("View Related Logs", string(alert.Annotations[ruletypes.AnnotationRelatedLogs]))
|
||||
add("View Related Traces", string(alert.Annotations[ruletypes.AnnotationRelatedTraces]))
|
||||
return buttons
|
||||
}
|
||||
|
||||
// buildMessage assembles the text+card payload: a plain text summary plus a card
|
||||
// with a status banner, the body, and link buttons.
|
||||
func buildMessage(title, statusHTML, bodyHTML string, buttons []button) Message {
|
||||
widgets := []widget{{TextParagraph: &textParagraph{Text: statusHTML}}}
|
||||
if bodyHTML != "" {
|
||||
widgets = append(widgets, widget{TextParagraph: &textParagraph{Text: bodyHTML}})
|
||||
}
|
||||
if len(buttons) > 0 {
|
||||
widgets = append(widgets, widget{ButtonList: &buttonList{Buttons: buttons}})
|
||||
}
|
||||
return Message{
|
||||
Text: title,
|
||||
CardsV2: []cardWithID{{
|
||||
CardID: "signoz-alert",
|
||||
Card: card{
|
||||
Header: &cardHeader{Title: title},
|
||||
Sections: []cardSection{{Widgets: widgets}},
|
||||
},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func encodeMessage(msg Message) (*bytes.Buffer, error) {
|
||||
var buf bytes.Buffer
|
||||
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &buf, nil
|
||||
}
|
||||
|
||||
// truncateToByteLimit trims s to at most maxBytes bytes on a rune boundary,
|
||||
// appending an ellipsis when it truncates.
|
||||
func truncateToByteLimit(s string, maxBytes int) string {
|
||||
if len(s) <= maxBytes {
|
||||
return s
|
||||
}
|
||||
const ellipsis = "..."
|
||||
target := maxBytes - len(ellipsis)
|
||||
if target <= 0 {
|
||||
return ellipsis[:maxBytes]
|
||||
}
|
||||
truncated := s
|
||||
for len(truncated) > target {
|
||||
_, size := utf8.DecodeLastRuneInString(truncated)
|
||||
if size == 0 {
|
||||
break
|
||||
}
|
||||
truncated = truncated[:len(truncated)-size]
|
||||
}
|
||||
return truncated + ellipsis
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package googlechat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/ruletypes"
|
||||
commoncfg "github.com/prometheus/common/config"
|
||||
"github.com/prometheus/common/model"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/prometheus/alertmanager/config"
|
||||
"github.com/prometheus/alertmanager/notify"
|
||||
"github.com/prometheus/alertmanager/notify/test"
|
||||
"github.com/prometheus/alertmanager/template"
|
||||
"github.com/prometheus/alertmanager/types"
|
||||
)
|
||||
|
||||
func newTestTemplater(tmpl *template.Template) alertmanagertypes.Templater {
|
||||
return alertmanagertemplate.New(tmpl, slog.New(slog.DiscardHandler))
|
||||
}
|
||||
|
||||
func secretURLFromString(t *testing.T, rawURL string) *config.SecretURL {
|
||||
t.Helper()
|
||||
parsed, err := url.Parse(rawURL)
|
||||
require.NoError(t, err)
|
||||
return &config.SecretURL{URL: parsed}
|
||||
}
|
||||
|
||||
func newTestNotifier(t *testing.T, webhookURL, title, text string) *Notifier {
|
||||
t.Helper()
|
||||
tmpl := test.CreateTmpl(t)
|
||||
n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{
|
||||
HTTPConfig: &commoncfg.HTTPClientConfig{},
|
||||
WebhookURL: secretURLFromString(t, webhookURL),
|
||||
Title: title,
|
||||
Text: text,
|
||||
}, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))
|
||||
require.NoError(t, err)
|
||||
return n
|
||||
}
|
||||
|
||||
func newTestAlerts(alertname string) []*types.Alert {
|
||||
return []*types.Alert{{
|
||||
Alert: model.Alert{
|
||||
Labels: model.LabelSet{"alertname": model.LabelValue(alertname)},
|
||||
Annotations: model.LabelSet{"summary": model.LabelValue("summary for " + alertname)},
|
||||
StartsAt: time.Now(),
|
||||
EndsAt: time.Now().Add(time.Minute),
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func newTestContext() context.Context {
|
||||
return notify.WithGroupKey(context.Background(), "test-receiver")
|
||||
}
|
||||
|
||||
// captureServer starts an httptest server that decodes the posted Google Chat
|
||||
// Message into got and replies 200.
|
||||
func captureServer(t *testing.T, got *Message) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got != nil {
|
||||
_ = json.NewDecoder(r.Body).Decode(got)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
}
|
||||
|
||||
func TestGoogleChatSend(t *testing.T) {
|
||||
var got Message
|
||||
server := captureServer(t, &got)
|
||||
defer server.Close()
|
||||
|
||||
n := newTestNotifier(t, server.URL, `[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}`, "")
|
||||
retry, err := n.Notify(newTestContext(), newTestAlerts("TestAlert")...)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, retry)
|
||||
require.Contains(t, got.Text, "FIRING")
|
||||
require.Contains(t, got.Text, "TestAlert")
|
||||
}
|
||||
|
||||
func TestGoogleChatTitleAndBody(t *testing.T) {
|
||||
var got Message
|
||||
server := captureServer(t, &got)
|
||||
defer server.Close()
|
||||
|
||||
n := newTestNotifier(t, server.URL, "TITLE", "BODY")
|
||||
retry, err := n.Notify(newTestContext(), newTestAlerts("TestAlert")...)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, retry)
|
||||
// Title is the plain summary + card header; body lives in a card widget.
|
||||
require.Equal(t, "TITLE", got.Text)
|
||||
require.Equal(t, "TITLE", got.CardsV2[0].Card.Header.Title)
|
||||
require.Contains(t, cardBody(t, got), "BODY")
|
||||
}
|
||||
|
||||
// cardBody concatenates the text of all textParagraph widgets in the message.
|
||||
func cardBody(t *testing.T, m Message) string {
|
||||
t.Helper()
|
||||
require.NotEmpty(t, m.CardsV2)
|
||||
var b strings.Builder
|
||||
for _, s := range m.CardsV2[0].Card.Sections {
|
||||
for _, w := range s.Widgets {
|
||||
if w.TextParagraph != nil {
|
||||
b.WriteString(w.TextParagraph.Text)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// cardButtons returns the buttons of the first buttonList widget.
|
||||
func cardButtons(t *testing.T, m Message) []button {
|
||||
t.Helper()
|
||||
require.NotEmpty(t, m.CardsV2)
|
||||
for _, s := range m.CardsV2[0].Card.Sections {
|
||||
for _, w := range s.Widgets {
|
||||
if w.ButtonList != nil {
|
||||
return w.ButtonList.Buttons
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestGoogleChatRetryCodes(t *testing.T) {
|
||||
tmpl := test.CreateTmpl(t)
|
||||
n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{
|
||||
HTTPConfig: &commoncfg.HTTPClientConfig{},
|
||||
WebhookURL: secretURLFromString(t, "https://chat.googleapis.com/v1/spaces/test/messages"),
|
||||
}, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))
|
||||
require.NoError(t, err)
|
||||
|
||||
cases := []struct {
|
||||
code int
|
||||
retry bool
|
||||
}{
|
||||
{http.StatusOK, false},
|
||||
{http.StatusBadRequest, false}, // 400: malformed payload, permanent
|
||||
{http.StatusTooManyRequests, true}, // 429: rate limited, retry (our RetryCodes)
|
||||
{http.StatusInternalServerError, true}, // 5xx: retry
|
||||
{http.StatusServiceUnavailable, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(http.StatusText(c.code), func(t *testing.T) {
|
||||
actual, _ := n.retrier.Check(c.code, nil)
|
||||
require.Equal(t, c.retry, actual, "retry mismatch on status %d", c.code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoogleChatRedactedURL(t *testing.T) {
|
||||
ctx, u, fn := test.GetContextWithCancelingURL()
|
||||
defer fn()
|
||||
ctx = notify.WithGroupKey(ctx, "test-receiver")
|
||||
|
||||
tmpl := test.CreateTmpl(t)
|
||||
n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{
|
||||
HTTPConfig: &commoncfg.HTTPClientConfig{},
|
||||
WebhookURL: &config.SecretURL{URL: u},
|
||||
Title: "alert", // non-empty so it reaches the POST (not the empty-text guard)
|
||||
}, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))
|
||||
require.NoError(t, err)
|
||||
|
||||
test.AssertNotifyLeaksNoSecret(ctx, t, n, u.String())
|
||||
}
|
||||
|
||||
func TestTruncateToByteLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
max int
|
||||
wantLen int // upper bound on byte length of result
|
||||
wantHas string // substring the result must contain (or "")
|
||||
}{
|
||||
{"under limit passthrough", "hello", 100, 5, "hello"},
|
||||
{"over limit trims with ellipsis", strings.Repeat("a", 50), 10, 10, "..."},
|
||||
{"exact limit passthrough", "hello", 5, 5, "hello"},
|
||||
{"tiny limit", "hello", 2, 2, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := truncateToByteLimit(c.in, c.max)
|
||||
require.LessOrEqual(t, len(got), c.wantLen)
|
||||
if c.wantHas != "" {
|
||||
require.Contains(t, got, c.wantHas)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoogleChatMessageSizeLimit(t *testing.T) {
|
||||
var bodyLen int
|
||||
var valid bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
bodyLen = len(raw)
|
||||
valid = json.Valid(raw)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// Huge plain-ASCII title so one-time truncation lands deterministically under the limit.
|
||||
n := newTestNotifier(t, server.URL, strings.Repeat("A", 40000), "")
|
||||
retry, err := n.Notify(newTestContext(), newTestAlerts("Big")...)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, retry)
|
||||
require.True(t, valid, "posted body must be valid JSON")
|
||||
require.LessOrEqual(t, bodyLen, maxMessageBytes, "posted body must be within the size limit")
|
||||
}
|
||||
|
||||
func TestGoogleChatThreading(t *testing.T) {
|
||||
var query url.Values
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
query = r.URL.Query()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cases := []struct{ name, groupKey string }{
|
||||
{"rule a", "{ruleId=\"aaa\"}"},
|
||||
{"rule b", "{ruleId=\"bbb\"}"},
|
||||
}
|
||||
seen := map[string]string{}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
n := newTestNotifier(t, server.URL, "T", "")
|
||||
ctx := notify.WithGroupKey(context.Background(), c.groupKey)
|
||||
_, err := n.Notify(ctx, newTestAlerts("X")...)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD", query.Get("messageReplyOption"))
|
||||
threadKey := query.Get("threadKey")
|
||||
require.Equal(t, notify.Key(c.groupKey).Hash(), threadKey, "threadKey must be the group key hash")
|
||||
seen[c.name] = threadKey
|
||||
})
|
||||
}
|
||||
require.NotEqual(t, seen["rule a"], seen["rule b"], "distinct group keys must yield distinct threadKeys")
|
||||
}
|
||||
|
||||
func TestGoogleChatCustomTemplateMarkdown(t *testing.T) {
|
||||
var got Message
|
||||
server := captureServer(t, &got)
|
||||
defer server.Close()
|
||||
|
||||
// Custom body template (standard markdown) supplied via annotation → the
|
||||
// !IsDefaultBody path must convert it to Google Chat dialect.
|
||||
alerts := []*types.Alert{{
|
||||
Alert: model.Alert{
|
||||
Labels: model.LabelSet{"alertname": "X"},
|
||||
Annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "**bold** and [link](https://x)"},
|
||||
StartsAt: time.Now(),
|
||||
EndsAt: time.Now().Add(time.Minute),
|
||||
},
|
||||
}}
|
||||
n := newTestNotifier(t, server.URL, "Alert", "default body")
|
||||
_, err := n.Notify(newTestContext(), alerts...)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Custom body is standard markdown → converted to card HTML.
|
||||
body := cardBody(t, got)
|
||||
require.Contains(t, body, "<strong>bold</strong>", "** should convert to HTML bold")
|
||||
require.Contains(t, body, `<a href="https://x">link</a>`, "[t](u) should convert to an HTML link")
|
||||
}
|
||||
|
||||
func TestGoogleChatSerializedSizeUnderLimit(t *testing.T) {
|
||||
var bodyLen int
|
||||
var valid bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
bodyLen = len(raw)
|
||||
valid = json.Valid(raw)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// Escaping-dense payload: <, >, & and newlines each expand under JSON
|
||||
// encoding, so this is the shape that would push the serialized body over
|
||||
// the limit if we measured the text bytes instead of the marshaled buffer.
|
||||
dense := strings.Repeat("<https://example.com/a?x=1&y=2|link>\n", 2000)
|
||||
n := newTestNotifier(t, server.URL, dense, "")
|
||||
_, err := n.Notify(newTestContext(), newTestAlerts("Dense")...)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, valid, "posted body must be valid JSON")
|
||||
require.LessOrEqual(t, bodyLen, maxMessageBytes, "serialized body must be within the limit")
|
||||
}
|
||||
|
||||
func TestGoogleChatEmptyText(t *testing.T) {
|
||||
server := captureServer(t, nil)
|
||||
defer server.Close()
|
||||
|
||||
// Empty title and body templates → must not POST; fail non-retryably.
|
||||
n := newTestNotifier(t, server.URL, "", "")
|
||||
retry, err := n.Notify(newTestContext(), newTestAlerts("X")...)
|
||||
|
||||
require.Error(t, err)
|
||||
require.False(t, retry)
|
||||
}
|
||||
|
||||
func TestGoogleChatLinkButtons(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
labels model.LabelSet
|
||||
annotations model.LabelSet
|
||||
wantButtons map[string]string
|
||||
}{
|
||||
{
|
||||
name: "all links present",
|
||||
labels: model.LabelSet{
|
||||
"alertname": "X",
|
||||
ruletypes.LabelRuleSource: "https://signoz.example/alerts/1",
|
||||
},
|
||||
annotations: model.LabelSet{
|
||||
ruletypes.AnnotationRelatedLogs: "https://signoz.example/logs",
|
||||
ruletypes.AnnotationRelatedTraces: "https://signoz.example/traces",
|
||||
},
|
||||
wantButtons: map[string]string{
|
||||
"Open in SigNoz": "https://signoz.example/alerts/1",
|
||||
"View Related Logs": "https://signoz.example/logs",
|
||||
"View Related Traces": "https://signoz.example/traces",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no links → no buttons",
|
||||
labels: model.LabelSet{"alertname": "X"},
|
||||
annotations: model.LabelSet{"summary": "s"},
|
||||
wantButtons: map[string]string{},
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var got Message
|
||||
server := captureServer(t, &got)
|
||||
defer server.Close()
|
||||
|
||||
alerts := []*types.Alert{{Alert: model.Alert{
|
||||
Labels: c.labels,
|
||||
Annotations: c.annotations,
|
||||
StartsAt: time.Now(),
|
||||
EndsAt: time.Now().Add(time.Minute),
|
||||
}}}
|
||||
n := newTestNotifier(t, server.URL, "T", "")
|
||||
_, err := n.Notify(newTestContext(), alerts...)
|
||||
require.NoError(t, err)
|
||||
|
||||
buttons := cardButtons(t, got)
|
||||
require.Len(t, buttons, len(c.wantButtons))
|
||||
for _, b := range buttons {
|
||||
require.Equal(t, c.wantButtons[b.Text], b.OnClick.OpenLink.URL, "button %q", b.Text)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoogleChatStatusLine(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
resolved bool
|
||||
want string
|
||||
}{
|
||||
{"firing", false, "🔴 FIRING"},
|
||||
{"resolved", true, "🟢 RESOLVED"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var got Message
|
||||
server := captureServer(t, &got)
|
||||
defer server.Close()
|
||||
|
||||
endsAt := time.Now().Add(time.Minute)
|
||||
if c.resolved {
|
||||
endsAt = time.Now().Add(-time.Minute) // EndsAt in the past → resolved
|
||||
}
|
||||
alerts := []*types.Alert{{Alert: model.Alert{
|
||||
Labels: model.LabelSet{"alertname": "X"},
|
||||
StartsAt: time.Now().Add(-2 * time.Minute),
|
||||
EndsAt: endsAt,
|
||||
}}}
|
||||
n := newTestNotifier(t, server.URL, "T", "")
|
||||
_, err := n.Notify(newTestContext(), alerts...)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Contains(t, cardBody(t, got), c.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
86
pkg/alertmanager/alertmanagernotify/googlechat/types.go
Normal file
86
pkg/alertmanager/alertmanagernotify/googlechat/types.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package googlechat
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
|
||||
"github.com/prometheus/alertmanager/notify"
|
||||
"github.com/prometheus/alertmanager/template"
|
||||
)
|
||||
|
||||
const (
|
||||
Integration = "googlechat"
|
||||
// maxMessageBytes is the Google Chat message payload limit.
|
||||
// https://developers.google.com/chat/api/guides/message-formats/basic#maximum_size
|
||||
maxMessageBytes = 32000
|
||||
)
|
||||
|
||||
// Notifier implements notify.Notifier for Google Chat.
|
||||
type Notifier struct {
|
||||
conf *alertmanagertypes.GoogleChatReceiverConfig
|
||||
tmpl *template.Template
|
||||
logger *slog.Logger
|
||||
client *http.Client
|
||||
retrier *notify.Retrier
|
||||
templater alertmanagertypes.Templater
|
||||
}
|
||||
|
||||
// Message is the Google Chat webhook payload. A message carries a short text
|
||||
// summary (space list / push preview) and a rich card.
|
||||
type Message struct {
|
||||
Text string `json:"text,omitempty"`
|
||||
CardsV2 []cardWithID `json:"cardsV2,omitempty"`
|
||||
}
|
||||
|
||||
type cardWithID struct {
|
||||
CardID string `json:"cardId"`
|
||||
Card card `json:"card"`
|
||||
}
|
||||
|
||||
type card struct {
|
||||
Header *cardHeader `json:"header,omitempty"`
|
||||
Sections []cardSection `json:"sections"`
|
||||
}
|
||||
|
||||
type cardHeader struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Subtitle string `json:"subtitle,omitempty"`
|
||||
}
|
||||
|
||||
type cardSection struct {
|
||||
Header string `json:"header,omitempty"`
|
||||
Widgets []widget `json:"widgets"`
|
||||
}
|
||||
|
||||
// widget is a one-of: exactly one field is set per instance.
|
||||
type widget struct {
|
||||
TextParagraph *textParagraph `json:"textParagraph,omitempty"`
|
||||
ButtonList *buttonList `json:"buttonList,omitempty"`
|
||||
}
|
||||
|
||||
type textParagraph struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type buttonList struct {
|
||||
Buttons []button `json:"buttons"`
|
||||
}
|
||||
|
||||
type button struct {
|
||||
Text string `json:"text"`
|
||||
OnClick onClick `json:"onClick"`
|
||||
}
|
||||
|
||||
type onClick struct {
|
||||
OpenLink openLink `json:"openLink"`
|
||||
}
|
||||
|
||||
type openLink struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// content holds the rendered title and body for a Google Chat message.
|
||||
type content struct {
|
||||
title, body string
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"slices"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/email"
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/googlechat"
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/msteamsv2"
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/opsgenie"
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/pagerduty"
|
||||
@@ -24,6 +25,7 @@ var customNotifierIntegrations = []string{
|
||||
opsgenie.Integration,
|
||||
slack.Integration,
|
||||
msteamsv2.Integration,
|
||||
googlechat.Integration,
|
||||
}
|
||||
|
||||
func NewReceiverIntegrations(nc *alertmanagertypes.Receiver, tmpl *template.Template, logger *slog.Logger, templater alertmanagertypes.Templater) ([]notify.Integration, error) {
|
||||
@@ -74,6 +76,11 @@ func NewReceiverIntegrations(nc *alertmanagertypes.Receiver, tmpl *template.Temp
|
||||
return msteamsv2.New(c, tmpl, `{{ template "msteamsv2.default.titleLink" . }}`, l, templater)
|
||||
})
|
||||
}
|
||||
for i, c := range nc.GoogleChatConfigs {
|
||||
add(googlechat.Integration, i, c, func(l *slog.Logger) (notify.Notifier, error) {
|
||||
return googlechat.New(c, tmpl, l, templater)
|
||||
})
|
||||
}
|
||||
|
||||
if errs.Len() > 0 {
|
||||
return nil, &errs
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package alertmanagertypes
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/prometheus/alertmanager/config"
|
||||
commoncfg "github.com/prometheus/common/config"
|
||||
)
|
||||
@@ -21,9 +25,9 @@ var DefaultGoogleChatReceiverConfig = GoogleChatReceiverConfig{
|
||||
},
|
||||
Title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
|
||||
Text: `{{ range .Alerts -}}
|
||||
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}
|
||||
*Summary:* {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}
|
||||
*Description:* {{ .Annotations.description }}{{ end }}
|
||||
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}
|
||||
**Summary:** {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}
|
||||
**Description:** {{ .Annotations.description }}{{ end }}
|
||||
{{ end }}`,
|
||||
}
|
||||
|
||||
@@ -32,3 +36,18 @@ func (c *GoogleChatReceiverConfig) UnmarshalYAML(unmarshal func(any) error) erro
|
||||
type plain GoogleChatReceiverConfig
|
||||
return unmarshal((*plain)(c))
|
||||
}
|
||||
|
||||
// ValidateGoogleChatWebhookURL validates the Google Chat webhook URL format.
|
||||
func ValidateGoogleChatWebhookURL(rawURL string) error {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid google chat webhook_url: %v", err)
|
||||
}
|
||||
if u.Scheme != "https" {
|
||||
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url must use https")
|
||||
}
|
||||
if strings.ToLower(u.Hostname()) != "chat.googleapis.com" {
|
||||
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url must use chat.googleapis.com")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
44
pkg/types/alertmanagertypes/googlechat_test.go
Normal file
44
pkg/types/alertmanagertypes/googlechat_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package alertmanagertypes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateGoogleChatWebhookURL(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
url string
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid", "https://chat.googleapis.com/v1/spaces/AAA/messages?key=k&token=t", false},
|
||||
{"http scheme rejected", "http://chat.googleapis.com/v1/spaces/AAA/messages", true},
|
||||
{"wrong host rejected", "https://example.com/v1/spaces/AAA/messages", true},
|
||||
{"empty rejected", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
err := ValidateGoogleChatWebhookURL(c.url)
|
||||
if c.wantErr {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewReceiverGoogleChatRejectsBadURL(t *testing.T) {
|
||||
// http scheme
|
||||
_, err := NewReceiver(`{"name":"gc","googlechat_configs":[{"webhook_url":"http://chat.googleapis.com/v1/spaces/x/messages"}]}`)
|
||||
require.Error(t, err)
|
||||
|
||||
// wrong host
|
||||
_, err = NewReceiver(`{"name":"gc","googlechat_configs":[{"webhook_url":"https://example.com/x"}]}`)
|
||||
require.Error(t, err)
|
||||
|
||||
// missing webhook_url
|
||||
_, err = NewReceiver(`{"name":"gc","googlechat_configs":[{"title":"x"}]}`)
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -45,12 +45,23 @@ func NewReceiver(input string) (*Receiver, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateGoogleChatConfig(defaulted); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
receiver.GoogleChatConfigs[i] = defaulted
|
||||
}
|
||||
|
||||
return receiver, nil
|
||||
}
|
||||
|
||||
// validateGoogleChatConfig validates a Google Chat receiver configuration.
|
||||
func validateGoogleChatConfig(cfg *GoogleChatReceiverConfig) error {
|
||||
if cfg.WebhookURL == nil {
|
||||
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url is required")
|
||||
}
|
||||
return ValidateGoogleChatWebhookURL(cfg.WebhookURL.String())
|
||||
}
|
||||
|
||||
func defaultedBaseReceiver(base *config.Receiver) (*config.Receiver, error) {
|
||||
bytes, err := yaml.Marshal(base)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user