Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Alerting UI] Added ability to assign alert actions to resolved action group in UI #83139

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions x-pack/plugins/alerts/common/builtin_action_groups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { i18n } from '@kbn/i18n';
import { ActionGroup } from './alert_type';

export const ResolvedActionGroup: ActionGroup = {
id: 'resolved',
name: i18n.translate('xpack.alerts.builtinActionGroups.resolved', {
defaultMessage: 'Resolved',
}),
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's in scope for this PR but now that we will have multiple action groups for each alert type, would it make sense for each action group to define what it's own default message is instead of having a defaultActionMessage as part of the alert type definition? That way the resolved action group could have a default message and we wouldn't need to separately define a resolvedActionGroupMessage.

Copy link
Contributor Author

@YulNaumenko YulNaumenko Nov 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each alert type may want to specify their own Resolution default message (as the default message for any other group) - make sense to me. Because it can contains variables with params and alert data for which instance it was resolved. We need to discuss how it can be possible (cc: @pmuellr )

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thoughts on how to handle what the "default action message" is (and other fields like email subject), based on various things including action group, here: #66095 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pmuellr does it make sense to leave it as it is now till the #66095 (comment) ?


export function getBuiltinActionGroups(): ActionGroup[] {
return [ResolvedActionGroup];
}
1 change: 1 addition & 0 deletions x-pack/plugins/alerts/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from './alert_instance';
export * from './alert_task_instance';
export * from './alert_navigation';
export * from './alert_instance_summary';
export * from './builtin_action_groups';

export interface ActionGroup {
id: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ActionParamsProps } from '../../../../types';
import { EmailActionParams } from '../types';
import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables';
import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables';
import { resolvedActionGroupMessage } from '../../../constants';

export const EmailParamsFields = ({
actionParams,
Expand All @@ -28,11 +29,18 @@ export const EmailParamsFields = ({
const [addBCC, setAddBCC] = useState<boolean>(false);

useEffect(() => {
if (!message && defaultMessage && defaultMessage.length > 0) {
if (defaultMessage === resolvedActionGroupMessage) {
editAction('message', defaultMessage, index);
} else if (
(!message || message === resolvedActionGroupMessage) &&
defaultMessage &&
defaultMessage.length > 0
) {
editAction('message', defaultMessage, index);
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [defaultMessage]);

return (
<Fragment>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { EuiSelect, EuiFormRow } from '@elastic/eui';
import { ActionParamsProps } from '../../../../types';
import { ServerLogActionParams } from '.././types';
import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables';
import { resolvedActionGroupMessage } from '../../../constants';

export const ServerLogParamsFields: React.FunctionComponent<ActionParamsProps<
ServerLogActionParams
Expand All @@ -25,11 +26,22 @@ export const ServerLogParamsFields: React.FunctionComponent<ActionParamsProps<

useEffect(() => {
editAction('level', 'info', index);
if (!message && defaultMessage && defaultMessage.length > 0) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
if (defaultMessage === resolvedActionGroupMessage) {
editAction('message', defaultMessage, index);
} else if (
(!message || message === resolvedActionGroupMessage) &&
defaultMessage &&
defaultMessage.length > 0
) {
editAction('message', defaultMessage, index);
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [defaultMessage]);

return (
<Fragment>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { i18n } from '@kbn/i18n';
import { ActionParamsProps } from '../../../../types';
import { SlackActionParams } from '../types';
import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables';
import { resolvedActionGroupMessage } from '../../../constants';

const SlackParamsFields: React.FunctionComponent<ActionParamsProps<SlackActionParams>> = ({
actionParams,
Expand All @@ -19,11 +20,18 @@ const SlackParamsFields: React.FunctionComponent<ActionParamsProps<SlackActionPa
}) => {
const { message } = actionParams;
useEffect(() => {
if (!message && defaultMessage && defaultMessage.length > 0) {
if (defaultMessage === resolvedActionGroupMessage) {
editAction('message', defaultMessage, index);
} else if (
(!message || message === resolvedActionGroupMessage) &&
defaultMessage &&
defaultMessage.length > 0
) {
editAction('message', defaultMessage, index);
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [defaultMessage]);

return (
<TextAreaWithMessageVariables
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { i18n } from '@kbn/i18n';

export { BASE_ALERT_API_PATH } from '../../../../alerts/common';
export { BASE_ACTION_API_PATH } from '../../../../actions/common';

Expand All @@ -14,6 +16,13 @@ export const routeToConnectors = `/connectors`;
export const routeToAlerts = `/alerts`;
export const routeToAlertDetails = `/alert/:alertId`;

export const resolvedActionGroupMessage = i18n.translate(
'xpack.triggersActionsUI.sections.actionForm.ResolvedMessage',
{
defaultMessage: 'Resolved',
}
);

export { TIME_UNITS } from './time_units';
export enum SORT_ORDERS {
ASCENDING = 'asc',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ beforeEach(() => jest.resetAllMocks());
describe('actionVariablesFromAlertType', () => {
test('should return correct variables when no state or context provided', async () => {
const alertType = getAlertType({ context: [], state: [], params: [] });
expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(`
expect(actionVariablesFromAlertType(alertType.actionVariables)).toMatchInlineSnapshot(`
Array [
Object {
"description": "The id of the alert.",
Expand Down Expand Up @@ -48,7 +48,7 @@ describe('actionVariablesFromAlertType', () => {
state: [],
params: [],
});
expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(`
expect(actionVariablesFromAlertType(alertType.actionVariables)).toMatchInlineSnapshot(`
Array [
Object {
"description": "The id of the alert.",
Expand Down Expand Up @@ -91,7 +91,7 @@ describe('actionVariablesFromAlertType', () => {
],
params: [],
});
expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(`
expect(actionVariablesFromAlertType(alertType.actionVariables)).toMatchInlineSnapshot(`
Array [
Object {
"description": "The id of the alert.",
Expand Down Expand Up @@ -137,7 +137,7 @@ describe('actionVariablesFromAlertType', () => {
],
params: [{ name: 'fooP', description: 'fooP-description' }],
});
expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(`
expect(actionVariablesFromAlertType(alertType.actionVariables)).toMatchInlineSnapshot(`
Array [
Object {
"description": "The id of the alert.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@
*/

import { i18n } from '@kbn/i18n';
import { AlertType, ActionVariable } from '../../types';
import { ActionVariable, ActionVariables } from '../../types';

// return a "flattened" list of action variables for an alertType
export function actionVariablesFromAlertType(alertType: AlertType): ActionVariable[] {
export function actionVariablesFromAlertType(actionVariables: ActionVariables): ActionVariable[] {
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
const alwaysProvidedVars = getAlwaysProvidedActionVariables();
const contextVars = prefixKeys(alertType.actionVariables.context, 'context.');
const paramsVars = prefixKeys(alertType.actionVariables.params, 'params.');
const stateVars = prefixKeys(alertType.actionVariables.state, 'state.');
const contextVars = actionVariables.context
? prefixKeys(actionVariables.context, 'context.')
: [];
const paramsVars = prefixKeys(actionVariables.params, 'params.');
const stateVars = prefixKeys(actionVariables.state, 'state.');

return alwaysProvidedVars.concat(contextVars, paramsVars, stateVars);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { act } from 'react-dom/test-utils';
import { actionTypeRegistryMock } from '../../action_type_registry.mock';
import { ValidationResult, Alert, AlertAction } from '../../../types';
import ActionForm from './action_form';
import { ResolvedActionGroup } from '../../../../../alerts/common';
jest.mock('../../lib/action_connector_api', () => ({
loadAllActions: jest.fn(),
loadActionTypes: jest.fn(),
Expand Down Expand Up @@ -217,15 +218,22 @@ describe('action_form', () => {
const wrapper = mountWithIntl(
<ActionForm
actions={initialAlert.actions}
messageVariables={[
{ name: 'testVar1', description: 'test var1' },
{ name: 'testVar2', description: 'test var2' },
]}
messageVariables={{
params: [
{ name: 'testVar1', description: 'test var1' },
{ name: 'testVar2', description: 'test var2' },
],
state: [],
context: [{ name: 'contextVar', description: 'context var1' }],
}}
defaultActionGroupId={'default'}
setActionIdByIndex={(id: string, index: number) => {
initialAlert.actions[index].id = id;
}}
actionGroups={[{ id: 'default', name: 'Default' }]}
actionGroups={[
{ id: 'default', name: 'Default' },
{ id: 'resolved', name: 'Resolved' },
]}
setActionGroupIdByIndex={(group: string, index: number) => {
initialAlert.actions[index].group = group;
}}
Expand Down Expand Up @@ -346,10 +354,52 @@ describe('action_form', () => {
"inputDisplay": "Default",
"value": "default",
},
Object {
"data-test-subj": "addNewActionConnectorActionGroup-0-option-resolved",
"inputDisplay": "Resolved",
"value": "resolved",
},
]
`);
});

it('renders selected Resolved action group', async () => {
const wrapper = await setup([
{
group: ResolvedActionGroup.id,
id: 'test',
actionTypeId: actionType.id,
params: {
message: '',
},
},
]);
const actionOption = wrapper.find(
`[data-test-subj="${actionType.id}-ActionTypeSelectOption"]`
);
actionOption.first().simulate('click');
const actionGroupsSelect = wrapper.find(
`[data-test-subj="addNewActionConnectorActionGroup-0"]`
);
expect((actionGroupsSelect.first().props() as any).options).toMatchInlineSnapshot(`
Array [
Object {
"data-test-subj": "addNewActionConnectorActionGroup-0-option-default",
"inputDisplay": "Default",
"value": "default",
},
Object {
"data-test-subj": "addNewActionConnectorActionGroup-0-option-resolved",
"inputDisplay": "Resolved",
"value": "resolved",
},
]
`);
expect(actionGroupsSelect.first().text()).toEqual(
'Select an option: Resolved, is selectedResolved'
);
});

it('renders available connectors for the selected action type', async () => {
const wrapper = await setup();
const actionOption = wrapper.find(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
ActionTypeIndex,
ActionConnector,
ActionType,
ActionVariable,
ActionVariables,
} from '../../../types';
import { SectionLoading } from '../../components/section_loading';
import { ConnectorAddModal } from './connector_add_modal';
Expand All @@ -51,7 +51,7 @@ export interface ActionAccordionFormProps {
toastNotifications: ToastsSetup;
docLinks: DocLinksStart;
actionTypes?: ActionType[];
messageVariables?: ActionVariable[];
messageVariables?: ActionVariables;
defaultActionMessage?: string;
setHasActionsDisabled?: (value: boolean) => void;
setHasActionsWithBrokenConnector?: (value: boolean) => void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { Fragment, Suspense, useState } from 'react';
import React, { Fragment, Suspense, useEffect, useState } from 'react';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import {
Expand All @@ -25,10 +25,20 @@ import {
EuiLoadingSpinner,
EuiBadge,
} from '@elastic/eui';
import { IErrorObject, AlertAction, ActionTypeIndex, ActionConnector } from '../../../types';
import { ResolvedActionGroup } from '../../../../../alerts/common';
import {
IErrorObject,
AlertAction,
ActionTypeIndex,
ActionConnector,
ActionVariables,
ActionVariable,
} from '../../../types';
import { checkActionFormActionTypeEnabled } from '../../lib/check_action_type_enabled';
import { hasSaveActionsCapability } from '../../lib/capabilities';
import { ActionAccordionFormProps } from './action_form';
import { actionVariablesFromAlertType } from '../../lib/action_variables';
import { resolvedActionGroupMessage } from '../../constants';

export type ActionTypeFormProps = {
actionItem: AlertAction;
Expand Down Expand Up @@ -88,6 +98,21 @@ export const ActionTypeForm = ({
setActionGroupIdByIndex,
}: ActionTypeFormProps) => {
const [isOpen, setIsOpen] = useState(true);
const [availableActionVariables, setAvailableActionVariables] = useState<ActionVariable[]>([]);
const [availableDefaultActionMessage, setAvailableDefaultActionMessage] = useState<
string | undefined
>(undefined);

useEffect(() => {
setAvailableActionVariables(getAvailableActionVariables(messageVariables, actionItem.group));
const res =
actionItem.group === ResolvedActionGroup.id
? resolvedActionGroupMessage
: defaultActionMessage;
setAvailableDefaultActionMessage(res);
// setActionParamsProperty('message', res, index);
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [actionItem.group]);

const canSave = hasSaveActionsCapability(capabilities);
const getSelectedOptions = (actionItemId: string) => {
Expand Down Expand Up @@ -244,8 +269,8 @@ export const ActionTypeForm = ({
index={index}
errors={actionParamsErrors.errors}
editAction={setActionParamsProperty}
messageVariables={messageVariables}
defaultMessage={defaultActionMessage ?? undefined}
messageVariables={availableActionVariables}
defaultMessage={availableDefaultActionMessage}
docLinks={docLinks}
http={http}
toastNotifications={toastNotifications}
Expand Down Expand Up @@ -337,3 +362,20 @@ export const ActionTypeForm = ({
</Fragment>
);
};

function getAvailableActionVariables(
actionVariables: ActionVariables | undefined,
actionGroup: string
) {
if (!actionVariables) {
return [];
}
const filteredActionVariables =
actionGroup === ResolvedActionGroup.id
? { params: actionVariables.params, state: actionVariables.state }
: actionVariables;

return actionVariablesFromAlertType(filteredActionVariables).sort((a, b) =>
a.name.toUpperCase().localeCompare(b.name.toUpperCase())
);
}
Loading