-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
create_lifecycle_executor.ts
338 lines (296 loc) · 9.28 KB
/
create_lifecycle_executor.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
337
338
/*
* 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 type { Logger } from '@kbn/logging';
import type { PublicContract } from '@kbn/utility-types';
import { getOrElse } from 'fp-ts/lib/Either';
import * as rt from 'io-ts';
import { Mutable } from 'utility-types';
import { v4 } from 'uuid';
import {
AlertExecutorOptions,
AlertInstance,
AlertInstanceContext,
AlertInstanceState,
AlertTypeParams,
AlertTypeState,
} from '../../../alerting/server';
import { ParsedTechnicalFields, parseTechnicalFields } from '../../common/parse_technical_fields';
import {
ALERT_DURATION,
ALERT_END,
ALERT_ID,
ALERT_START,
ALERT_STATUS,
ALERT_UUID,
EVENT_ACTION,
EVENT_KIND,
OWNER,
RULE_UUID,
TIMESTAMP,
SPACE_IDS,
} from '../../common/technical_rule_data_field_names';
import { RuleDataClient } from '../rule_data_client';
import { AlertExecutorOptionsWithExtraServices } from '../types';
import { getRuleData } from './get_rule_executor_data';
type LifecycleAlertService<
InstanceState extends AlertInstanceState = never,
InstanceContext extends AlertInstanceContext = never,
ActionGroupIds extends string = never
> = (alert: {
id: string;
fields: Record<string, unknown>;
}) => AlertInstance<InstanceState, InstanceContext, ActionGroupIds>;
export interface LifecycleAlertServices<
InstanceState extends AlertInstanceState = never,
InstanceContext extends AlertInstanceContext = never,
ActionGroupIds extends string = never
> {
alertWithLifecycle: LifecycleAlertService<InstanceState, InstanceContext, ActionGroupIds>;
}
export type LifecycleRuleExecutor<
Params extends AlertTypeParams = never,
State extends AlertTypeState = never,
InstanceState extends AlertInstanceState = never,
InstanceContext extends AlertInstanceContext = never,
ActionGroupIds extends string = never
> = (
options: AlertExecutorOptionsWithExtraServices<
Params,
State,
InstanceState,
InstanceContext,
ActionGroupIds,
LifecycleAlertServices<InstanceState, InstanceContext, ActionGroupIds>
>
) => Promise<State | void>;
const trackedAlertStateRt = rt.type({
alertId: rt.string,
alertUuid: rt.string,
started: rt.string,
});
export type TrackedLifecycleAlertState = rt.TypeOf<typeof trackedAlertStateRt>;
const alertTypeStateRt = <State extends AlertTypeState>() =>
rt.record(rt.string, rt.unknown) as rt.Type<State, State, unknown>;
const wrappedStateRt = <State extends AlertTypeState>() =>
rt.type({
wrapped: alertTypeStateRt<State>(),
trackedAlerts: rt.record(rt.string, trackedAlertStateRt),
});
/**
* This is redefined instead of derived from above `wrappedStateRt` because
* there's no easy way to instantiate generic values such as the runtime type
* factory function.
*/
export type WrappedLifecycleRuleState<State extends AlertTypeState> = AlertTypeState & {
wrapped: State | void;
trackedAlerts: Record<string, TrackedLifecycleAlertState>;
};
export const createLifecycleExecutor = (
logger: Logger,
ruleDataClient: PublicContract<RuleDataClient>
) => <
Params extends AlertTypeParams = never,
State extends AlertTypeState = never,
InstanceState extends AlertInstanceState = never,
InstanceContext extends AlertInstanceContext = never,
ActionGroupIds extends string = never
>(
wrappedExecutor: LifecycleRuleExecutor<
Params,
State,
InstanceState,
InstanceContext,
ActionGroupIds
>
) => async (
options: AlertExecutorOptions<
Params,
WrappedLifecycleRuleState<State>,
InstanceState,
InstanceContext,
ActionGroupIds
>
): Promise<WrappedLifecycleRuleState<State>> => {
const {
rule,
services: { alertInstanceFactory },
state: previousState,
spaceId,
} = options;
const ruleExecutorData = getRuleData(options);
const state = getOrElse(
(): WrappedLifecycleRuleState<State> => ({
wrapped: previousState as State,
trackedAlerts: {},
})
)(wrappedStateRt<State>().decode(previousState));
const currentAlerts: Record<string, { [ALERT_ID]: string }> = {};
const timestamp = options.startedAt.toISOString();
const lifecycleAlertServices: LifecycleAlertServices<
InstanceState,
InstanceContext,
ActionGroupIds
> = {
alertWithLifecycle: ({ id, fields }) => {
currentAlerts[id] = {
...fields,
[ALERT_ID]: id,
};
return alertInstanceFactory(id);
},
};
const nextWrappedState = await wrappedExecutor({
...options,
state: state.wrapped != null ? state.wrapped : ({} as State),
services: {
...options.services,
...lifecycleAlertServices,
},
});
const currentAlertIds = Object.keys(currentAlerts);
const trackedAlertIds = Object.keys(state.trackedAlerts);
const newAlertIds = currentAlertIds.filter((alertId) => !trackedAlertIds.includes(alertId));
const allAlertIds = [...new Set(currentAlertIds.concat(trackedAlertIds))];
const trackedAlertStatesOfRecovered = Object.values(state.trackedAlerts).filter(
(trackedAlertState) => !currentAlerts[trackedAlertState.alertId]
);
logger.debug(
`Tracking ${allAlertIds.length} alerts (${newAlertIds.length} new, ${trackedAlertStatesOfRecovered.length} recovered)`
);
const alertsDataMap: Record<
string,
{
[ALERT_ID]: string;
}
> = {
...currentAlerts,
};
if (trackedAlertStatesOfRecovered.length) {
const { hits } = await ruleDataClient.getReader().search({
body: {
query: {
bool: {
filter: [
{
term: {
[RULE_UUID]: ruleExecutorData[RULE_UUID],
},
},
{
terms: {
[ALERT_UUID]: trackedAlertStatesOfRecovered.map(
(trackedAlertState) => trackedAlertState.alertUuid
),
},
},
],
},
},
size: trackedAlertStatesOfRecovered.length,
collapse: {
field: ALERT_UUID,
},
_source: false,
fields: [{ field: '*', include_unmapped: true }],
sort: {
[TIMESTAMP]: 'desc' as const,
},
},
allow_no_indices: true,
});
hits.hits.forEach((hit) => {
const fields = parseTechnicalFields(hit.fields);
const alertId = fields[ALERT_ID]!;
alertsDataMap[alertId] = {
...fields,
[ALERT_ID]: alertId,
};
});
}
const eventsToIndex = allAlertIds.map((alertId) => {
const alertData = alertsDataMap[alertId];
if (!alertData) {
logger.warn(`Could not find alert data for ${alertId}`);
}
const event: Mutable<ParsedTechnicalFields> = {
...alertData,
...ruleExecutorData,
[TIMESTAMP]: timestamp,
[EVENT_KIND]: 'signal',
[OWNER]: rule.consumer,
[ALERT_ID]: alertId,
};
const isNew = !state.trackedAlerts[alertId];
const isRecovered = !currentAlerts[alertId];
const isActiveButNotNew = !isNew && !isRecovered;
const isActive = !isRecovered;
const { alertUuid, started } = state.trackedAlerts[alertId] ?? {
alertUuid: v4(),
started: timestamp,
};
event[ALERT_START] = started;
event[ALERT_UUID] = alertUuid;
// not sure why typescript needs the non-null assertion here
// we already assert the value is not undefined with the ternary
// still getting an error with the ternary.. strange.
event[SPACE_IDS] =
event[SPACE_IDS] == null
? [spaceId]
: [spaceId, ...event[SPACE_IDS]!.filter((sid) => sid !== spaceId)];
if (isNew) {
event[EVENT_ACTION] = 'open';
}
if (isRecovered) {
event[ALERT_END] = timestamp;
event[EVENT_ACTION] = 'close';
event[ALERT_STATUS] = 'closed';
}
if (isActiveButNotNew) {
event[EVENT_ACTION] = 'active';
}
if (isActive) {
event[ALERT_STATUS] = 'open';
}
event[ALERT_DURATION] =
(options.startedAt.getTime() - new Date(event[ALERT_START]!).getTime()) * 1000;
return event;
});
if (eventsToIndex.length) {
const alertEvents: Map<string, ParsedTechnicalFields> = new Map();
for (const event of eventsToIndex) {
const uuid = event[ALERT_UUID]!;
let storedEvent = alertEvents.get(uuid);
if (!storedEvent) {
storedEvent = event;
}
alertEvents.set(uuid, {
...storedEvent,
[EVENT_KIND]: 'signal',
});
}
logger.debug(`Preparing to index ${eventsToIndex.length} alerts.`);
if (ruleDataClient.isWriteEnabled()) {
await ruleDataClient.getWriter().bulk({
body: eventsToIndex.flatMap((event) => [{ index: { _id: event[ALERT_UUID]! } }, event]),
});
}
}
const nextTrackedAlerts = Object.fromEntries(
eventsToIndex
.filter((event) => event[ALERT_STATUS] !== 'closed')
.map((event) => {
const alertId = event[ALERT_ID]!;
const alertUuid = event[ALERT_UUID]!;
const started = new Date(event[ALERT_START]!).toISOString();
return [alertId, { alertId, alertUuid, started }];
})
);
return {
wrapped: nextWrappedState ?? ({} as State),
trackedAlerts: ruleDataClient.isWriteEnabled() ? nextTrackedAlerts : {},
};
};