-
Notifications
You must be signed in to change notification settings - Fork 88
/
ConfigureActions.js
281 lines (255 loc) · 9.59 KB
/
ConfigureActions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import React from 'react';
import _ from 'lodash';
import { EuiPanel, EuiText } from '@elastic/eui';
import Action from '../../components/Action';
import ActionEmptyPrompt from '../../components/ActionEmptyPrompt';
import AddActionButton from '../../components/AddActionButton';
import { DEFAULT_MESSAGE_SOURCE, FORMIK_INITIAL_ACTION_VALUES } from '../../utils/constants';
import { DESTINATION_OPTIONS } from '../../../Destinations/utils/constants';
import { getAllowList } from '../../../Destinations/utils/helpers';
import { MONITOR_TYPE } from '../../../../utils/constants';
import { backendErrorNotification } from '../../../../utils/helpers';
import { TRIGGER_TYPE } from '../CreateTrigger/utils/constants';
import { formikToTrigger } from '../CreateTrigger/utils/formikToTrigger';
import { MAX_DESTINATIONS } from '../../../Destinations/containers/DestinationsList/utils/constants';
const createActionContext = (context, action) => ({
ctx: {
...context,
action,
},
});
export const checkForError = (response, error) => {
for (const trigger_name in response.resp.trigger_results) {
// Check for errors in the trigger response
if (!response.resp.trigger_results[trigger_name].error) {
// Check for errors in the actions configured
for (const action_result in response.resp.trigger_results[trigger_name].action_results) {
error = response.resp.trigger_results[trigger_name].action_results[action_result].error;
}
} else {
error = response.resp.trigger_results[trigger_name].error;
}
}
return error;
};
class ConfigureActions extends React.Component {
constructor(props) {
super(props);
this.state = {
destinations: [],
allowList: [],
loadingDestinations: true,
actionDeleted: false,
};
}
async componentDidMount() {
const { httpClient } = this.props;
const allowList = await getAllowList(httpClient);
this.setState({ allowList });
this.loadDestinations();
}
/**
* Returns all destinations in consecutive requests until all destinations are returned
* @returns {Promise<*[]>}
*/
getDestinations = async () => {
const { httpClient } = this.props;
const { allowList } = this.state;
const getDestinationLabel = (destination) => {
const foundDestination = DESTINATION_OPTIONS.find(({ value }) => value === destination.type);
if (foundDestination) return foundDestination.text;
return destination.type;
};
let destinations = [];
let index = 0;
const getDestinations = async () => {
const getDestinationsQuery = {
from: index,
size: MAX_DESTINATIONS,
};
const destinationsResponse = await httpClient.get('../api/alerting/destinations', {
query: getDestinationsQuery,
});
destinations = destinations.concat(
destinationsResponse.destinations
.map((destination) => ({
label: `${destination.name} - (${getDestinationLabel(destination)})`,
value: destination.id,
type: destination.type,
}))
.filter(({ type }) => allowList.includes(type))
);
if (
destinationsResponse.totalDestinations &&
destinations.length < destinationsResponse.totalDestinations
) {
index += MAX_DESTINATIONS;
await getDestinations();
}
};
await getDestinations();
return destinations;
};
loadDestinations = async () => {
const { values, arrayHelpers, fieldPath } = this.props;
const { actionDeleted } = this.state;
this.setState({ loadingDestinations: true });
try {
const destinations = await this.getDestinations();
this.setState({ destinations, loadingDestinations: false });
const monitorType = _.get(arrayHelpers, 'form.values.monitor_type', MONITOR_TYPE.QUERY_LEVEL);
const initialActionValues = _.cloneDeep(FORMIK_INITIAL_ACTION_VALUES);
switch (monitorType) {
case MONITOR_TYPE.BUCKET_LEVEL:
_.set(
initialActionValues,
'message_template.source',
DEFAULT_MESSAGE_SOURCE.BUCKET_LEVEL_MONITOR
);
break;
case MONITOR_TYPE.QUERY_LEVEL:
case MONITOR_TYPE.CLUSTER_METRICS:
_.set(
initialActionValues,
'message_template.source',
DEFAULT_MESSAGE_SOURCE.QUERY_LEVEL_MONITOR
);
break;
}
// If actions is not defined If user choose to delete actions, it will not override customer's preferences.
if (destinations.length > 0 && !_.get(values, `${fieldPath}actions`) && !actionDeleted) {
arrayHelpers.insert(0, initialActionValues);
}
} catch (err) {
console.error(err);
this.setState({ destinations: [], loadingDestinations: false });
}
};
sendTestMessage = async (index) => {
const {
context: { monitor },
httpClient,
notifications,
triggerIndex,
values,
} = this.props;
const { destinations } = this.state;
// TODO: For bucket-level triggers, sendTestMessage will only send a test message if there is
// at least one bucket of data from the monitor input query.
let testTrigger = _.cloneDeep(formikToTrigger(values, monitor.ui_metadata)[triggerIndex]);
let action;
let condition;
switch (monitor.monitor_type) {
case MONITOR_TYPE.BUCKET_LEVEL:
action = _.get(testTrigger, `${TRIGGER_TYPE.BUCKET_LEVEL}.actions[${index}]`);
condition = {
..._.get(testTrigger, `${TRIGGER_TYPE.BUCKET_LEVEL}.condition`),
buckets_path: { _count: '_count' },
script: {
source: 'params._count >= 0',
},
};
_.set(testTrigger, `${TRIGGER_TYPE.BUCKET_LEVEL}.actions`, [action]);
_.set(testTrigger, `${TRIGGER_TYPE.BUCKET_LEVEL}.condition`, condition);
break;
case MONITOR_TYPE.QUERY_LEVEL:
case MONITOR_TYPE.CLUSTER_METRICS:
action = _.get(testTrigger, `actions[${index}]`);
condition = {
..._.get(testTrigger, 'condition'),
script: { lang: 'painless', source: 'return true' },
};
_.set(testTrigger, 'actions', [action]);
_.set(testTrigger, 'condition', condition);
break;
}
const testMonitor = { ...monitor, triggers: [{ ...testTrigger }] };
try {
const response = await httpClient.post('../api/alerting/monitors/_execute', {
query: { dryrun: false },
body: JSON.stringify(testMonitor),
});
let error = null;
if (response.ok) {
error = checkForError(response, error);
if (!_.isEmpty(action.destination_id)) {
const destinationName = _.get(
_.find(destinations, { value: action.destination_id }),
'label'
);
notifications.toasts.addSuccess(`Test message sent to "${destinationName}."`);
}
}
if (error || !response.ok) {
const errorMessage = error == null ? response.resp : error;
console.error('There was an error trying to send test message', errorMessage);
backendErrorNotification(notifications, 'send', 'test message', errorMessage);
}
} catch (err) {
console.error('There was an error trying to send test message', err);
}
};
renderActions = (arrayHelpers) => {
const { context, setFlyout, values, fieldPath } = this.props;
const { destinations } = this.state;
const hasDestinations = !_.isEmpty(destinations);
const hasActions = !_.isEmpty(_.get(values, `${fieldPath}actions`));
const shouldRenderActions = hasActions || (hasDestinations && hasActions);
return shouldRenderActions ? (
_.get(values, `${fieldPath}actions`).map((action, index) => (
<Action
key={index}
action={action}
arrayHelpers={arrayHelpers}
context={createActionContext(context, action)}
destinations={destinations}
index={index}
onDelete={() => {
this.setState({ actionDeleted: true });
arrayHelpers.remove(index);
}}
sendTestMessage={this.sendTestMessage}
setFlyout={setFlyout}
fieldPath={fieldPath}
values={values}
/>
))
) : (
<ActionEmptyPrompt arrayHelpers={arrayHelpers} hasDestinations={hasDestinations} />
);
};
render() {
const { loadingDestinations } = this.state;
const { arrayHelpers, values, fieldPath } = this.props;
const numOfActions = _.get(values, `${fieldPath}actions`, []).length;
const displayAddActionButton = numOfActions > 0;
//TODO:: Handle loading Destinations inside the Action which will be more intuitive for customers.
return (
<div style={{ paddingLeft: '10px', paddingRight: '10px' }}>
<EuiText>
<h4>{`Actions (${numOfActions})`}</h4>
</EuiText>
<EuiText color={'subdued'} size={'xs'} style={{ paddingBottom: '5px' }}>
Define actions when trigger conditions are met.
</EuiText>
<EuiPanel style={{ backgroundColor: '#F7F7F7', padding: '20px' }}>
{loadingDestinations ? (
<div style={{ display: 'flex', justifyContent: 'center' }}>Loading Destinations...</div>
) : (
this.renderActions(arrayHelpers)
)}
{displayAddActionButton ? (
<div style={{ paddingBottom: '5px', paddingTop: '20px' }}>
<AddActionButton arrayHelpers={arrayHelpers} numOfActions={numOfActions} />
</div>
) : null}
</EuiPanel>
</div>
);
}
}
export default ConfigureActions;