-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
index.ts
336 lines (294 loc) · 10.3 KB
/
index.ts
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import pMap from 'p-map';
import { isEmpty } from 'lodash';
import type { ElasticsearchClient, Logger } from '@kbn/core/server';
import type { STATUS_VALUES } from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names';
import { ALERT_WORKFLOW_STATUS } from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names';
import type { MgetResponse } from '@elastic/elasticsearch/lib/api/types';
import type { AlertsClient } from '@kbn/rule-registry-plugin/server';
import type { PublicMethodsOf } from '@kbn/utility-types';
import { CaseStatuses } from '../../../common/types/domain';
import { MAX_ALERTS_PER_CASE, MAX_CONCURRENT_SEARCHES } from '../../../common/constants';
import { createCaseError } from '../../common/error';
import type { AlertInfo } from '../../common/types';
import type {
RemoveCaseIdFromAlertsRequest,
UpdateAlertCasesRequest,
UpdateAlertStatusRequest,
} from '../../client/alerts/types';
import type { AggregationBuilder, AggregationResponse } from '../../client/metrics/types';
export class AlertService {
constructor(
private readonly scopedClusterClient: ElasticsearchClient,
private readonly logger: Logger,
private readonly alertsClient: PublicMethodsOf<AlertsClient>
) {}
public async executeAggregations({
aggregationBuilders,
alerts,
}: {
aggregationBuilders: Array<AggregationBuilder<unknown>>;
alerts: AlertIdIndex[];
}): Promise<AggregationResponse> {
try {
const { ids, indices } = AlertService.getUniqueIdsIndices(alerts);
const builtAggs = aggregationBuilders.reduce((acc, agg) => {
return Object.assign(acc, agg.build());
}, {});
const res = await this.scopedClusterClient.search({
index: indices,
ignore_unavailable: true,
query: { ids: { values: ids } },
size: 0,
aggregations: builtAggs,
});
return res.aggregations;
} catch (error) {
const aggregationNames = aggregationBuilders.map((agg) => agg.getName());
throw createCaseError({
message: `Failed to execute aggregations [${aggregationNames.join(',')}]: ${error}`,
error,
logger: this.logger,
});
}
}
private static getUniqueIdsIndices(alerts: AlertIdIndex[]): { ids: string[]; indices: string[] } {
const { ids, indices } = alerts.reduce(
(acc, alert) => {
acc.ids.add(alert.id);
acc.indices.add(alert.index);
return acc;
},
{ ids: new Set<string>(), indices: new Set<string>() }
);
return {
ids: Array.from(ids),
indices: Array.from(indices),
};
}
public async updateAlertsStatus(alerts: UpdateAlertStatusRequest[]) {
try {
const bucketedAlerts = this.bucketAlertsByIndexAndStatus(alerts);
const indexBuckets = Array.from(bucketedAlerts.entries());
await pMap(
indexBuckets,
async (indexBucket: [string, Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]>]) =>
this.updateByQuery(indexBucket),
{ concurrency: MAX_CONCURRENT_SEARCHES }
);
} catch (error) {
throw createCaseError({
message: `Failed to update alert status ids: ${JSON.stringify(alerts)}: ${error}`,
error,
logger: this.logger,
});
}
}
private bucketAlertsByIndexAndStatus(
alerts: UpdateAlertStatusRequest[]
): Map<string, Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]>> {
return alerts.reduce<Map<string, Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]>>>(
(acc, alert) => {
// skip any alerts that are empty
if (AlertService.isEmptyAlert(alert)) {
return acc;
}
const translatedAlert = { ...alert, status: this.translateStatus(alert) };
const statusToAlertId = acc.get(translatedAlert.index);
// if we haven't seen the index before
if (!statusToAlertId) {
// add a new index in the parent map, with an entry for the status the alert set to pointing
// to an initial array of only the current alert
acc.set(translatedAlert.index, createStatusToAlertMap(translatedAlert));
} else {
// We had the index in the map so check to see if we have a bucket for the
// status, if not add a new status entry with the alert, if so update the status entry
// with the alert
updateIndexEntryWithStatus(statusToAlertId, translatedAlert);
}
return acc;
},
new Map()
);
}
private static isEmptyAlert(alert: AlertInfo): boolean {
return isEmpty(alert.id) || isEmpty(alert.index);
}
private translateStatus(alert: UpdateAlertStatusRequest): STATUS_VALUES {
const translatedStatuses: Record<string, STATUS_VALUES> = {
[CaseStatuses.open]: 'open',
[CaseStatuses['in-progress']]: 'acknowledged',
[CaseStatuses.closed]: 'closed',
};
const translatedStatus = translatedStatuses[alert.status];
if (!translatedStatus) {
this.logger.error(
`Unable to translate case status ${alert.status} during alert update: ${JSON.stringify(
alert
)}`
);
}
return translatedStatus ?? 'open';
}
private async updateByQuery([index, statusToAlertMap]: [
string,
Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]>
]) {
const statusBuckets = Array.from(statusToAlertMap);
return Promise.all(
// this will create three update by query calls one for each of the three statuses
statusBuckets.map(([status, translatedAlerts]) =>
this.scopedClusterClient.updateByQuery({
index,
conflicts: 'abort',
body: {
script: {
source: `if (ctx._source['${ALERT_WORKFLOW_STATUS}'] != null) {
ctx._source['${ALERT_WORKFLOW_STATUS}'] = '${status}'
}
if (ctx._source.signal != null && ctx._source.signal.status != null) {
ctx._source.signal.status = '${status}'
}`,
lang: 'painless',
},
// the query here will contain all the ids that have the same status for the same index
// being updated
query: { ids: { values: translatedAlerts.map(({ id }) => id) } },
},
ignore_unavailable: true,
})
)
);
}
private getNonEmptyAlerts(alerts: AlertInfo[]): AlertInfo[] {
return alerts.filter((alert) => !AlertService.isEmptyAlert(alert));
}
public async getAlerts(alertsInfo: AlertInfo[]): Promise<MgetResponse<Alert> | undefined> {
try {
const docs = alertsInfo
.filter((alert) => !AlertService.isEmptyAlert(alert))
.slice(0, MAX_ALERTS_PER_CASE)
.map((alert) => ({ _id: alert.id, _index: alert.index }));
if (docs.length <= 0) {
return;
}
const results = await this.scopedClusterClient.mget<Alert>({ body: { docs } });
return results;
} catch (error) {
throw createCaseError({
message: `Failed to retrieve alerts ids: ${JSON.stringify(alertsInfo)}: ${error}`,
error,
logger: this.logger,
});
}
}
public async bulkUpdateCases({ alerts, caseIds }: UpdateAlertCasesRequest): Promise<void> {
try {
const nonEmptyAlerts = this.getNonEmptyAlerts(alerts);
if (nonEmptyAlerts.length <= 0) {
return;
}
await this.alertsClient.bulkUpdateCases({
alerts: nonEmptyAlerts,
caseIds,
});
} catch (error) {
throw createCaseError({
message: `Failed to add case info to alerts for caseIds ${caseIds}: ${error}`,
error,
logger: this.logger,
});
}
}
public async removeCaseIdFromAlerts({
alerts,
caseId,
}: RemoveCaseIdFromAlertsRequest): Promise<void> {
try {
const nonEmptyAlerts = this.getNonEmptyAlerts(alerts);
if (nonEmptyAlerts.length <= 0) {
return;
}
await this.alertsClient.removeCaseIdFromAlerts({
alerts: nonEmptyAlerts,
caseId,
});
} catch (error) {
/**
* We intentionally do not throw an error.
* Users should be able to remove alerts from a case even
* in the event of an error produced by the alerts client
*/
this.logger.error(`Failed removing case ${caseId} from alerts: ${error}`);
}
}
public async removeCaseIdsFromAllAlerts({ caseIds }: { caseIds: string[] }): Promise<void> {
try {
if (caseIds.length <= 0) {
return;
}
await this.alertsClient.removeCaseIdsFromAllAlerts({
caseIds,
});
} catch (error) {
/**
* We intentionally do not throw an error.
* Users should be able to remove alerts from cases even
* in the event of an error produced by the alerts client
*/
this.logger.error(`Failed removing cases ${caseIds} for all alerts: ${error}`);
}
}
public async ensureAlertsAuthorized({ alerts }: { alerts: AlertInfo[] }): Promise<void> {
try {
const nonEmptyAlerts = this.getNonEmptyAlerts(alerts);
if (nonEmptyAlerts.length <= 0) {
return;
}
await this.alertsClient.ensureAllAlertsAuthorizedRead({
alerts: nonEmptyAlerts,
});
} catch (error) {
throw createCaseError({
message: `Failed to authorize alerts: ${error}`,
error,
logger: this.logger,
});
}
}
}
interface TranslatedUpdateAlertRequest {
id: string;
index: string;
status: STATUS_VALUES;
}
function createStatusToAlertMap(
alert: TranslatedUpdateAlertRequest
): Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]> {
return new Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]>([[alert.status, [alert]]]);
}
function updateIndexEntryWithStatus(
statusToAlerts: Map<STATUS_VALUES, TranslatedUpdateAlertRequest[]>,
alert: TranslatedUpdateAlertRequest
) {
const statusBucket = statusToAlerts.get(alert.status);
if (!statusBucket) {
statusToAlerts.set(alert.status, [alert]);
} else {
statusBucket.push(alert);
}
}
export interface Alert {
_id: string;
_index: string;
_source: Record<string, unknown>;
}
interface AlertIdIndex {
id: string;
index: string;
}