-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathexpression.tsx
523 lines (480 loc) · 15.7 KB
/
expression.tsx
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
* 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 { debounce } from 'lodash';
import React, { useCallback, useMemo, useEffect, useState, ChangeEvent } from 'react';
import {
EuiFlexGroup,
EuiFlexItem,
EuiButtonIcon,
EuiSpacer,
EuiText,
EuiFormRow,
EuiButtonEmpty,
EuiFieldSearch,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';
import { i18n } from '@kbn/i18n';
import {
Comparator,
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
} from '../../../../server/lib/alerting/metric_threshold/types';
import { euiStyled } from '../../../../../observability/public';
import {
ThresholdExpression,
ForLastExpression,
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
} from '../../../../../triggers_actions_ui/public/common';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { IErrorObject } from '../../../../../triggers_actions_ui/public/types';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { AlertsContextValue } from '../../../../../triggers_actions_ui/public/application/context/alerts_context';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { MetricsExplorerKueryBar } from '../../../pages/metrics/metrics_explorer/components/kuery_bar';
import { useSourceViaHttp } from '../../../containers/source/use_source_via_http';
import { toMetricOpt } from '../../../pages/metrics/inventory_view/components/toolbars/toolbar_wrapper';
import { sqsMetricTypes } from '../../../../common/inventory_models/aws_sqs/toolbar_items';
import { ec2MetricTypes } from '../../../../common/inventory_models/aws_ec2/toolbar_items';
import { s3MetricTypes } from '../../../../common/inventory_models/aws_s3/toolbar_items';
import { rdsMetricTypes } from '../../../../common/inventory_models/aws_rds/toolbar_items';
import { hostMetricTypes } from '../../../../common/inventory_models/host/toolbar_items';
import { containerMetricTypes } from '../../../../common/inventory_models/container/toolbar_items';
import { podMetricTypes } from '../../../../common/inventory_models/pod/toolbar_items';
import { findInventoryModel } from '../../../../common/inventory_models';
import { InventoryItemType, SnapshotMetricType } from '../../../../common/inventory_models/types';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { InventoryMetricConditions } from '../../../../server/lib/alerting/inventory_metric_threshold/types';
import { MetricExpression } from './metric';
import { NodeTypeExpression } from './node_type';
import { InfraWaffleMapOptions } from '../../../lib/lib';
import { convertKueryToElasticSearchQuery } from '../../../utils/kuery';
const FILTER_TYPING_DEBOUNCE_MS = 500;
interface AlertContextMeta {
options?: Partial<InfraWaffleMapOptions>;
nodeType?: InventoryItemType;
filter?: string;
}
interface Props {
errors: IErrorObject[];
alertParams: {
criteria: InventoryMetricConditions[];
nodeType: InventoryItemType;
groupBy?: string;
filterQuery?: string;
filterQueryText?: string;
sourceId?: string;
};
alertsContext: AlertsContextValue<AlertContextMeta>;
setAlertParams(key: string, value: any): void;
setAlertProperty(key: string, value: any): void;
}
type TimeUnit = 's' | 'm' | 'h' | 'd';
const defaultExpression = {
metric: 'cpu' as SnapshotMetricType,
comparator: Comparator.GT,
threshold: [],
timeSize: 1,
timeUnit: 'm',
} as InventoryMetricConditions;
export const Expressions: React.FC<Props> = props => {
const { setAlertParams, alertParams, errors, alertsContext } = props;
const { source, createDerivedIndexPattern } = useSourceViaHttp({
sourceId: 'default',
type: 'metrics',
fetch: alertsContext.http.fetch,
toastWarning: alertsContext.toastNotifications.addWarning,
});
const [timeSize, setTimeSize] = useState<number | undefined>(1);
const [timeUnit, setTimeUnit] = useState<TimeUnit>('m');
const derivedIndexPattern = useMemo(() => createDerivedIndexPattern('metrics'), [
createDerivedIndexPattern,
]);
const updateParams = useCallback(
(id, e: InventoryMetricConditions) => {
const exp = alertParams.criteria ? alertParams.criteria.slice() : [];
exp[id] = { ...exp[id], ...e };
setAlertParams('criteria', exp);
},
[setAlertParams, alertParams.criteria]
);
const addExpression = useCallback(() => {
const exp = alertParams.criteria.slice();
exp.push(defaultExpression);
setAlertParams('criteria', exp);
}, [setAlertParams, alertParams.criteria]);
const removeExpression = useCallback(
(id: number) => {
const exp = alertParams.criteria.slice();
if (exp.length > 1) {
exp.splice(id, 1);
setAlertParams('criteria', exp);
}
},
[setAlertParams, alertParams.criteria]
);
const onFilterChange = useCallback(
(filter: any) => {
setAlertParams('filterQueryText', filter || '');
setAlertParams(
'filterQuery',
convertKueryToElasticSearchQuery(filter, derivedIndexPattern) || ''
);
},
[derivedIndexPattern, setAlertParams]
);
const debouncedOnFilterChange = useCallback(debounce(onFilterChange, FILTER_TYPING_DEBOUNCE_MS), [
onFilterChange,
]);
const emptyError = useMemo(() => {
return {
aggField: [],
timeSizeUnit: [],
timeWindowSize: [],
};
}, []);
const updateTimeSize = useCallback(
(ts: number | undefined) => {
const criteria = alertParams.criteria.map(c => ({
...c,
timeSize: ts,
}));
setTimeSize(ts || undefined);
setAlertParams('criteria', criteria);
},
[alertParams.criteria, setAlertParams]
);
const updateTimeUnit = useCallback(
(tu: string) => {
const criteria = alertParams.criteria.map(c => ({
...c,
timeUnit: tu,
}));
setTimeUnit(tu as TimeUnit);
setAlertParams('criteria', criteria);
},
[alertParams.criteria, setAlertParams]
);
const updateNodeType = useCallback(
(nt: any) => {
setAlertParams('nodeType', nt);
},
[setAlertParams]
);
const handleFieldSearchChange = useCallback(
(e: ChangeEvent<HTMLInputElement>) => onFilterChange(e.target.value),
[onFilterChange]
);
const preFillAlertCriteria = useCallback(() => {
const md = alertsContext.metadata;
if (md && md.options) {
setAlertParams('criteria', [
{
...defaultExpression,
metric: md.options.metric!.type,
} as InventoryMetricConditions,
]);
} else {
setAlertParams('criteria', [defaultExpression]);
}
}, [alertsContext.metadata, setAlertParams]);
const preFillAlertFilter = useCallback(() => {
const md = alertsContext.metadata;
if (md && md.filter) {
setAlertParams('filterQueryText', md.filter);
setAlertParams(
'filterQuery',
convertKueryToElasticSearchQuery(md.filter, derivedIndexPattern) || ''
);
}
}, [alertsContext.metadata, derivedIndexPattern, setAlertParams]);
useEffect(() => {
const md = alertsContext.metadata;
if (!alertParams.nodeType) {
if (md && md.nodeType) {
setAlertParams('nodeType', md.nodeType);
} else {
setAlertParams('nodeType', 'host');
}
}
if (alertParams.criteria && alertParams.criteria.length) {
setTimeSize(alertParams.criteria[0].timeSize);
setTimeUnit(alertParams.criteria[0].timeUnit);
} else {
preFillAlertCriteria();
}
if (!alertParams.filterQuery) {
preFillAlertFilter();
}
if (!alertParams.sourceId) {
setAlertParams('sourceId', source?.id || 'default');
}
}, [alertsContext.metadata, derivedIndexPattern, defaultExpression, source]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<>
<EuiSpacer size={'m'} />
<EuiText size="xs">
<h4>
<FormattedMessage
id="xpack.infra.metrics.alertFlyout.conditions"
defaultMessage="Conditions"
/>
</h4>
</EuiText>
<StyledExpression>
<StyledExpressionRow>
<NodeTypeExpression
options={nodeTypes}
value={alertParams.nodeType || 'host'}
onChange={updateNodeType}
/>
</StyledExpressionRow>
</StyledExpression>
<EuiSpacer size={'xs'} />
{alertParams.criteria &&
alertParams.criteria.map((e, idx) => {
return (
<ExpressionRow
nodeType={alertParams.nodeType}
canDelete={alertParams.criteria.length > 1}
remove={removeExpression}
addExpression={addExpression}
key={idx} // idx's don't usually make good key's but here the index has semantic meaning
expressionId={idx}
setAlertParams={updateParams}
errors={errors[idx] || emptyError}
expression={e || {}}
/>
);
})}
<ForLastExpression
timeWindowSize={timeSize}
timeWindowUnit={timeUnit}
errors={emptyError}
onChangeWindowSize={updateTimeSize}
onChangeWindowUnit={updateTimeUnit}
/>
<div>
<EuiButtonEmpty
color={'primary'}
iconSide={'left'}
flush={'left'}
iconType={'plusInCircleFilled'}
onClick={addExpression}
>
<FormattedMessage
id="xpack.infra.metrics.alertFlyout.addCondition"
defaultMessage="Add condition"
/>
</EuiButtonEmpty>
</div>
<EuiSpacer size={'m'} />
<EuiFormRow
label={i18n.translate('xpack.infra.metrics.alertFlyout.filterLabel', {
defaultMessage: 'Filter (optional)',
})}
helpText={i18n.translate('xpack.infra.metrics.alertFlyout.filterHelpText', {
defaultMessage: 'Use a KQL expression to limit the scope of your alert trigger.',
})}
fullWidth
compressed
>
{(alertsContext.metadata && (
<MetricsExplorerKueryBar
derivedIndexPattern={derivedIndexPattern}
onSubmit={onFilterChange}
onChange={debouncedOnFilterChange}
value={alertParams.filterQueryText}
/>
)) || (
<EuiFieldSearch
onChange={handleFieldSearchChange}
value={alertParams.filterQueryText}
fullWidth
/>
)}
</EuiFormRow>
<EuiSpacer size={'m'} />
</>
);
};
interface ExpressionRowProps {
nodeType: InventoryItemType;
expressionId: number;
expression: Omit<InventoryMetricConditions, 'metric'> & {
metric?: SnapshotMetricType;
};
errors: IErrorObject;
canDelete: boolean;
addExpression(): void;
remove(id: number): void;
setAlertParams(id: number, params: Partial<InventoryMetricConditions>): void;
}
const StyledExpressionRow = euiStyled(EuiFlexGroup)`
display: flex;
flex-wrap: wrap;
margin: 0 -4px;
`;
const StyledExpression = euiStyled.div`
padding: 0 4px;
`;
export const ExpressionRow: React.FC<ExpressionRowProps> = props => {
const { setAlertParams, expression, errors, expressionId, remove, canDelete } = props;
const { metric, comparator = Comparator.GT, threshold = [] } = expression;
const updateMetric = useCallback(
(m?: SnapshotMetricType) => {
setAlertParams(expressionId, { ...expression, metric: m });
},
[expressionId, expression, setAlertParams]
);
const updateComparator = useCallback(
(c?: string) => {
setAlertParams(expressionId, { ...expression, comparator: c as Comparator | undefined });
},
[expressionId, expression, setAlertParams]
);
const updateThreshold = useCallback(
t => {
if (t.join() !== expression.threshold.join()) {
setAlertParams(expressionId, { ...expression, threshold: t });
}
},
[expressionId, expression, setAlertParams]
);
const ofFields = useMemo(() => {
let myMetrics = hostMetricTypes;
switch (props.nodeType) {
case 'awsEC2':
myMetrics = ec2MetricTypes;
break;
case 'awsRDS':
myMetrics = rdsMetricTypes;
break;
case 'awsS3':
myMetrics = s3MetricTypes;
break;
case 'awsSQS':
myMetrics = sqsMetricTypes;
break;
case 'host':
myMetrics = hostMetricTypes;
break;
case 'pod':
myMetrics = podMetricTypes;
break;
case 'container':
myMetrics = containerMetricTypes;
break;
}
return myMetrics.map(toMetricOpt);
}, [props.nodeType]);
return (
<>
<EuiFlexGroup gutterSize="xs">
<EuiFlexItem grow>
<StyledExpressionRow>
<StyledExpression>
<MetricExpression
metric={{
value: metric!,
text: ofFields.find(v => v?.value === metric)?.text || '',
}}
metrics={
ofFields.filter(m => m !== undefined && m.value !== undefined) as Array<{
value: SnapshotMetricType;
text: string;
}>
}
onChange={updateMetric}
errors={errors}
/>
</StyledExpression>
<StyledExpression>
<ThresholdExpression
thresholdComparator={comparator || Comparator.GT}
threshold={threshold}
onChangeSelectedThresholdComparator={updateComparator}
onChangeSelectedThreshold={updateThreshold}
errors={errors}
/>
</StyledExpression>
{metric && (
<div
style={{
alignSelf: 'center',
}}
>
<EuiText size={'s'}>{metricUnit[metric]?.label || ''}</EuiText>
</div>
)}
</StyledExpressionRow>
</EuiFlexItem>
{canDelete && (
<EuiFlexItem grow={false}>
<EuiButtonIcon
aria-label={i18n.translate('xpack.infra.metrics.alertFlyout.removeCondition', {
defaultMessage: 'Remove condition',
})}
color={'danger'}
iconType={'trash'}
onClick={() => remove(expressionId)}
/>
</EuiFlexItem>
)}
</EuiFlexGroup>
<EuiSpacer size={'s'} />
</>
);
};
const getDisplayNameForType = (type: InventoryItemType) => {
const inventoryModel = findInventoryModel(type);
return inventoryModel.displayName;
};
export const nodeTypes: { [key: string]: any } = {
host: {
text: getDisplayNameForType('host'),
value: 'host',
},
pod: {
text: getDisplayNameForType('pod'),
value: 'pod',
},
container: {
text: getDisplayNameForType('container'),
value: 'container',
},
awsEC2: {
text: getDisplayNameForType('awsEC2'),
value: 'awsEC2',
},
awsS3: {
text: getDisplayNameForType('awsS3'),
value: 'awsS3',
},
awsRDS: {
text: getDisplayNameForType('awsRDS'),
value: 'awsRDS',
},
awsSQS: {
text: getDisplayNameForType('awsSQS'),
value: 'awsSQS',
},
};
const metricUnit: Record<string, { label: string }> = {
count: { label: '' },
cpu: { label: '%' },
memory: { label: '%' },
rx: { label: 'bits/s' },
tx: { label: 'bits/s' },
logRate: { label: '/s' },
diskIOReadBytes: { label: 'bytes/s' },
diskIOWriteBytes: { label: 'bytes/s' },
s3BucketSize: { label: 'bytes' },
s3TotalRequests: { label: '' },
s3NumberOfObjects: { label: '' },
s3UploadBytes: { label: 'bytes' },
s3DownloadBytes: { label: 'bytes' },
sqsOldestMessage: { label: 'seconds' },
rdsLatency: { label: 'ms' },
};