-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathtask_runner.ts
1149 lines (1041 loc) · 37.1 KB
/
task_runner.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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 apm from 'elastic-apm-node';
import { cloneDeep, mapValues, omit, pickBy, without } from 'lodash';
import type { Request } from '@hapi/hapi';
import { UsageCounter } from '@kbn/usage-collection-plugin/server';
import uuid from 'uuid';
import { addSpaceIdToPath } from '@kbn/spaces-plugin/server';
import { KibanaRequest, Logger } from '@kbn/core/server';
import { ConcreteTaskInstance, throwUnrecoverableError } from '@kbn/task-manager-plugin/server';
import { millisToNanos, nanosToMillis } from '@kbn/event-log-plugin/server';
import { TaskRunnerContext } from './task_runner_factory';
import { createExecutionHandler, ExecutionHandler } from './create_execution_handler';
import { Alert, createAlertFactory } from '../alert';
import {
ElasticsearchError,
ErrorWithReason,
executionStatusFromError,
executionStatusFromState,
getRecoveredAlerts,
ruleExecutionStatusToRaw,
validateRuleTypeParams,
isRuleSnoozed,
} from '../lib';
import {
Rule,
RuleExecutionStatus,
RuleExecutionStatusErrorReasons,
IntervalSchedule,
RawAlertInstance,
RawRule,
RawRuleExecutionStatus,
RuleMonitoring,
RuleMonitoringHistory,
RuleTaskState,
RuleTypeRegistry,
SanitizedRule,
} from '../types';
import { asErr, asOk, map, promiseResult, resolveErr, Resultable } from '../lib/result_type';
import { getExecutionDurationPercentiles, getExecutionSuccessRatio } from '../lib/monitoring';
import { taskInstanceToAlertTaskInstance } from './alert_task_instance';
import { EVENT_LOG_ACTIONS } from '../plugin';
import { isAlertSavedObjectNotFoundError, isEsUnavailableError } from '../lib/is_alerting_error';
import { partiallyUpdateAlert } from '../saved_objects';
import {
AlertInstanceContext,
AlertInstanceState,
RuleTypeParams,
RuleTypeState,
MONITORING_HISTORY_LIMIT,
parseDuration,
WithoutReservedActionGroups,
} from '../../common';
import { NormalizedRuleType, UntypedNormalizedRuleType } from '../rule_type_registry';
import { getEsErrorMessage } from '../lib/errors';
import { InMemoryMetrics, IN_MEMORY_METRICS } from '../monitoring';
import {
GenerateNewAndRecoveredAlertEventsParams,
LogActiveAndRecoveredAlertsParams,
RuleTaskInstance,
RuleTaskRunResult,
ScheduleActionsForRecoveredAlertsParams,
TrackAlertDurationsParams,
RuleRunResult,
RuleTaskStateAndMetrics,
} from './types';
import { createWrappedScopedClusterClientFactory } from '../lib/wrap_scoped_cluster_client';
import { IExecutionStatusAndMetrics } from '../lib/rule_execution_status';
import { RuleRunMetricsStore } from '../lib/rule_run_metrics_store';
import { wrapSearchSourceClient } from '../lib/wrap_search_source_client';
import { AlertingEventLogger } from '../lib/alerting_event_logger/alerting_event_logger';
import { SearchMetrics } from '../lib/types';
const FALLBACK_RETRY_INTERVAL = '5m';
const CONNECTIVITY_RETRY_INTERVAL = '5m';
export const getDefaultRuleMonitoring = (): RuleMonitoring => ({
execution: {
history: [],
calculated_metrics: {
success_ratio: 0,
},
},
});
export class TaskRunner<
Params extends RuleTypeParams,
ExtractedParams extends RuleTypeParams,
State extends RuleTypeState,
InstanceState extends AlertInstanceState,
InstanceContext extends AlertInstanceContext,
ActionGroupIds extends string,
RecoveryActionGroupId extends string
> {
private context: TaskRunnerContext;
private logger: Logger;
private taskInstance: RuleTaskInstance;
private ruleConsumer: string | null;
private ruleType: NormalizedRuleType<
Params,
ExtractedParams,
State,
InstanceState,
InstanceContext,
ActionGroupIds,
RecoveryActionGroupId
>;
private readonly executionId: string;
private readonly ruleTypeRegistry: RuleTypeRegistry;
private readonly inMemoryMetrics: InMemoryMetrics;
private alertingEventLogger: AlertingEventLogger;
private usageCounter?: UsageCounter;
private searchAbortController: AbortController;
private cancelled: boolean;
constructor(
ruleType: NormalizedRuleType<
Params,
ExtractedParams,
State,
InstanceState,
InstanceContext,
ActionGroupIds,
RecoveryActionGroupId
>,
taskInstance: ConcreteTaskInstance,
context: TaskRunnerContext,
inMemoryMetrics: InMemoryMetrics
) {
this.context = context;
this.logger = context.logger;
this.usageCounter = context.usageCounter;
this.ruleType = ruleType;
this.ruleConsumer = null;
this.taskInstance = taskInstanceToAlertTaskInstance(taskInstance);
this.ruleTypeRegistry = context.ruleTypeRegistry;
this.searchAbortController = new AbortController();
this.cancelled = false;
this.executionId = uuid.v4();
this.inMemoryMetrics = inMemoryMetrics;
this.alertingEventLogger = new AlertingEventLogger(this.context.eventLogger);
}
private async getDecryptedAttributes(
ruleId: string,
spaceId: string
): Promise<{ apiKey: string | null; enabled: boolean; consumer: string }> {
const namespace = this.context.spaceIdToNamespace(spaceId);
// Only fetch encrypted attributes here, we'll create a saved objects client
// scoped with the API key to fetch the remaining data.
const {
attributes: { apiKey, enabled, consumer },
} = await this.context.encryptedSavedObjectsClient.getDecryptedAsInternalUser<RawRule>(
'alert',
ruleId,
{ namespace }
);
return { apiKey, enabled, consumer };
}
private getFakeKibanaRequest(spaceId: string, apiKey: RawRule['apiKey']) {
const requestHeaders: Record<string, string> = {};
if (apiKey) {
requestHeaders.authorization = `ApiKey ${apiKey}`;
}
const path = addSpaceIdToPath('/', spaceId);
const fakeRequest = KibanaRequest.from({
headers: requestHeaders,
path: '/',
route: { settings: {} },
url: {
href: '/',
},
raw: {
req: {
url: '/',
},
},
} as unknown as Request);
this.context.basePathService.set(fakeRequest, path);
return fakeRequest;
}
private getExecutionHandler(
ruleId: string,
ruleName: string,
tags: string[] | undefined,
spaceId: string,
apiKey: RawRule['apiKey'],
kibanaBaseUrl: string | undefined,
actions: Rule<Params>['actions'],
ruleParams: Params,
request: KibanaRequest
) {
return createExecutionHandler<
Params,
ExtractedParams,
State,
InstanceState,
InstanceContext,
ActionGroupIds,
RecoveryActionGroupId
>({
ruleId,
ruleName,
ruleConsumer: this.ruleConsumer!,
tags,
executionId: this.executionId,
logger: this.logger,
actionsPlugin: this.context.actionsPlugin,
apiKey,
actions,
spaceId,
ruleType: this.ruleType,
kibanaBaseUrl,
alertingEventLogger: this.alertingEventLogger,
request,
ruleParams,
supportsEphemeralTasks: this.context.supportsEphemeralTasks,
maxEphemeralActionsPerRule: this.context.maxEphemeralActionsPerRule,
actionsConfigMap: this.context.actionsConfigMap,
});
}
private async updateRuleSavedObject(
ruleId: string,
namespace: string | undefined,
attributes: { executionStatus?: RawRuleExecutionStatus; monitoring?: RuleMonitoring }
) {
const client = this.context.internalSavedObjectsRepository;
try {
await partiallyUpdateAlert(client, ruleId, attributes, {
ignore404: true,
namespace,
refresh: false,
});
} catch (err) {
this.logger.error(`error updating rule for ${this.ruleType.id}:${ruleId} ${err.message}`);
}
}
private shouldLogAndScheduleActionsForAlerts() {
// if execution hasn't been cancelled, return true
if (!this.cancelled) {
return true;
}
// if execution has been cancelled, return true if EITHER alerting config or rule type indicate to proceed with scheduling actions
return !this.context.cancelAlertsOnRuleTimeout || !this.ruleType.cancelAlertsOnRuleTimeout;
}
private countUsageOfActionExecutionAfterRuleCancellation() {
if (this.cancelled && this.usageCounter) {
if (this.context.cancelAlertsOnRuleTimeout && this.ruleType.cancelAlertsOnRuleTimeout) {
// Increment usage counter for skipped actions
this.usageCounter.incrementCounter({
counterName: `alertsSkippedDueToRuleExecutionTimeout_${this.ruleType.id}`,
incrementBy: 1,
});
}
}
}
private async executeAlert(
alertId: string,
alert: Alert<InstanceState, InstanceContext>,
executionHandler: ExecutionHandler<ActionGroupIds | RecoveryActionGroupId>,
ruleRunMetricsStore: RuleRunMetricsStore
) {
const {
actionGroup,
subgroup: actionSubgroup,
context,
state,
} = alert.getScheduledActionOptions()!;
alert.updateLastScheduledActions(actionGroup, actionSubgroup);
alert.unscheduleActions();
return executionHandler({
actionGroup,
actionSubgroup,
context,
state,
alertId,
ruleRunMetricsStore,
});
}
private async executeRule(
fakeRequest: KibanaRequest,
rule: SanitizedRule<Params>,
params: Params,
executionHandler: ExecutionHandler<ActionGroupIds | RecoveryActionGroupId>,
spaceId: string
): Promise<RuleTaskStateAndMetrics> {
const {
alertTypeId,
consumer,
schedule,
throttle,
notifyWhen,
mutedInstanceIds,
name,
tags,
createdBy,
updatedBy,
createdAt,
updatedAt,
enabled,
actions,
} = rule;
const {
params: { alertId: ruleId },
state: { alertInstances: alertRawInstances = {}, alertTypeState = {}, previousStartedAt },
} = this.taskInstance;
const namespace = this.context.spaceIdToNamespace(spaceId);
const ruleType = this.ruleTypeRegistry.get(alertTypeId);
const alerts = mapValues<
Record<string, RawAlertInstance>,
Alert<InstanceState, InstanceContext>
>(
alertRawInstances,
(rawAlert, alertId) => new Alert<InstanceState, InstanceContext>(alertId, rawAlert)
);
const originalAlerts = cloneDeep(alerts);
const originalAlertIds = new Set(Object.keys(originalAlerts));
const ruleLabel = `${this.ruleType.id}:${ruleId}: '${name}'`;
const wrappedClientOptions = {
rule: {
name: rule.name,
alertTypeId: rule.alertTypeId,
id: rule.id,
spaceId,
},
logger: this.logger,
abortController: this.searchAbortController,
};
const scopedClusterClient = this.context.elasticsearch.client.asScoped(fakeRequest);
const wrappedScopedClusterClient = createWrappedScopedClusterClientFactory({
...wrappedClientOptions,
scopedClusterClient,
});
const searchSourceClient = await this.context.data.search.searchSource.asScoped(fakeRequest);
const wrappedSearchSourceClient = wrapSearchSourceClient({
...wrappedClientOptions,
searchSourceClient,
});
let updatedRuleTypeState: void | Record<string, unknown>;
try {
const ctx = {
type: 'alert',
name: `execute ${rule.alertTypeId}`,
id: ruleId,
description: `execute [${rule.alertTypeId}] with name [${name}] in [${
namespace ?? 'default'
}] namespace`,
};
const savedObjectsClient = this.context.savedObjects.getScopedClient(fakeRequest, {
includedHiddenTypes: ['alert', 'action'],
});
updatedRuleTypeState = await this.context.executionContext.withContext(ctx, () =>
this.ruleType.executor({
alertId: ruleId,
executionId: this.executionId,
services: {
savedObjectsClient,
searchSourceClient: wrappedSearchSourceClient.searchSourceClient,
uiSettingsClient: this.context.uiSettings.asScopedToClient(savedObjectsClient),
scopedClusterClient: wrappedScopedClusterClient.client(),
alertFactory: createAlertFactory<
InstanceState,
InstanceContext,
WithoutReservedActionGroups<ActionGroupIds, RecoveryActionGroupId>
>({
alerts,
logger: this.logger,
canSetRecoveryContext: ruleType.doesSetRecoveryContext ?? false,
}),
shouldWriteAlerts: () => this.shouldLogAndScheduleActionsForAlerts(),
shouldStopExecution: () => this.cancelled,
},
params,
state: alertTypeState as State,
startedAt: this.taskInstance.startedAt!,
previousStartedAt: previousStartedAt ? new Date(previousStartedAt) : null,
spaceId,
namespace,
name,
tags,
createdBy,
updatedBy,
rule: {
name,
tags,
consumer,
producer: ruleType.producer,
ruleTypeId: rule.alertTypeId,
ruleTypeName: ruleType.name,
enabled,
schedule,
actions,
createdBy,
updatedBy,
createdAt,
updatedAt,
throttle,
notifyWhen,
},
})
);
} catch (err) {
this.alertingEventLogger.setExecutionFailed(
`rule execution failure: ${ruleLabel}`,
err.message
);
throw new ErrorWithReason(RuleExecutionStatusErrorReasons.Execute, err);
}
this.alertingEventLogger.setExecutionSucceeded(`rule executed: ${ruleLabel}`);
const scopedClusterClientMetrics = wrappedScopedClusterClient.getMetrics();
const searchSourceClientMetrics = wrappedSearchSourceClient.getMetrics();
const searchMetrics: SearchMetrics = {
numSearches: scopedClusterClientMetrics.numSearches + searchSourceClientMetrics.numSearches,
totalSearchDurationMs:
scopedClusterClientMetrics.totalSearchDurationMs +
searchSourceClientMetrics.totalSearchDurationMs,
esSearchDurationMs:
scopedClusterClientMetrics.esSearchDurationMs +
searchSourceClientMetrics.esSearchDurationMs,
};
const ruleRunMetricsStore = new RuleRunMetricsStore();
ruleRunMetricsStore.setNumSearches(searchMetrics.numSearches);
ruleRunMetricsStore.setTotalSearchDurationMs(searchMetrics.totalSearchDurationMs);
ruleRunMetricsStore.setEsSearchDurationMs(searchMetrics.esSearchDurationMs);
// Cleanup alerts that are no longer scheduling actions to avoid over populating the alertInstances object
const alertsWithScheduledActions = pickBy(
alerts,
(alert: Alert<InstanceState, InstanceContext>) => alert.hasScheduledActions()
);
const recoveredAlerts = getRecoveredAlerts(alerts, originalAlertIds);
logActiveAndRecoveredAlerts({
logger: this.logger,
activeAlerts: alertsWithScheduledActions,
recoveredAlerts,
ruleLabel,
canSetRecoveryContext: ruleType.doesSetRecoveryContext ?? false,
});
trackAlertDurations({
originalAlerts,
currentAlerts: alertsWithScheduledActions,
recoveredAlerts,
});
if (this.shouldLogAndScheduleActionsForAlerts()) {
generateNewAndRecoveredAlertEvents({
alertingEventLogger: this.alertingEventLogger,
originalAlerts,
currentAlerts: alertsWithScheduledActions,
recoveredAlerts,
ruleLabel,
ruleRunMetricsStore,
});
}
const ruleIsSnoozed = isRuleSnoozed(rule);
if (ruleIsSnoozed) {
this.markRuleAsSnoozed(rule.id);
}
if (!ruleIsSnoozed && this.shouldLogAndScheduleActionsForAlerts()) {
const mutedAlertIdsSet = new Set(mutedInstanceIds);
const alertsWithExecutableActions = Object.entries(alertsWithScheduledActions).filter(
([alertName, alert]: [string, Alert<InstanceState, InstanceContext>]) => {
const throttled = alert.isThrottled(throttle);
const muted = mutedAlertIdsSet.has(alertName);
let shouldExecuteAction = true;
if (throttled || muted) {
shouldExecuteAction = false;
this.logger.debug(
`skipping scheduling of actions for '${alertName}' in rule ${ruleLabel}: rule is ${
muted ? 'muted' : 'throttled'
}`
);
} else if (
notifyWhen === 'onActionGroupChange' &&
!alert.scheduledActionGroupOrSubgroupHasChanged()
) {
shouldExecuteAction = false;
this.logger.debug(
`skipping scheduling of actions for '${alertName}' in rule ${ruleLabel}: alert is active but action group has not changed`
);
}
return shouldExecuteAction;
}
);
await Promise.all(
alertsWithExecutableActions.map(
([alertId, alert]: [string, Alert<InstanceState, InstanceContext>]) =>
this.executeAlert(alertId, alert, executionHandler, ruleRunMetricsStore)
)
);
await scheduleActionsForRecoveredAlerts<
InstanceState,
InstanceContext,
RecoveryActionGroupId
>({
recoveryActionGroup: this.ruleType.recoveryActionGroup,
recoveredAlerts,
executionHandler,
mutedAlertIdsSet,
logger: this.logger,
ruleLabel,
ruleRunMetricsStore,
});
} else {
if (ruleIsSnoozed) {
this.logger.debug(`no scheduling of actions for rule ${ruleLabel}: rule is snoozed.`);
}
if (!this.shouldLogAndScheduleActionsForAlerts()) {
this.logger.debug(
`no scheduling of actions for rule ${ruleLabel}: rule execution has been cancelled.`
);
// Usage counter for telemetry
// This keeps track of how many times action executions were skipped after rule
// execution completed successfully after the execution timeout
// This can occur when rule executors do not short circuit execution in response
// to timeout
this.countUsageOfActionExecutionAfterRuleCancellation();
}
}
return {
metrics: ruleRunMetricsStore.getMetrics(),
alertTypeState: updatedRuleTypeState || undefined,
alertInstances: mapValues<
Record<string, Alert<InstanceState, InstanceContext>>,
RawAlertInstance
>(alertsWithScheduledActions, (alert) => alert.toRaw()),
};
}
private async validateAndExecuteRule(
fakeRequest: KibanaRequest,
apiKey: RawRule['apiKey'],
rule: SanitizedRule<Params>
) {
const {
params: { alertId: ruleId, spaceId },
} = this.taskInstance;
// Validate
const validatedParams = validateRuleTypeParams(rule.params, this.ruleType.validate?.params);
const executionHandler = this.getExecutionHandler(
ruleId,
rule.name,
rule.tags,
spaceId,
apiKey,
this.context.kibanaBaseUrl,
rule.actions,
rule.params,
fakeRequest
);
return this.executeRule(fakeRequest, rule, validatedParams, executionHandler, spaceId);
}
private async markRuleAsSnoozed(id: string) {
let apiKey: string | null;
const {
params: { alertId: ruleId, spaceId },
} = this.taskInstance;
try {
const decryptedAttributes = await this.getDecryptedAttributes(ruleId, spaceId);
apiKey = decryptedAttributes.apiKey;
} catch (err) {
throw new ErrorWithReason(RuleExecutionStatusErrorReasons.Decrypt, err);
}
const fakeRequest = this.getFakeKibanaRequest(spaceId, apiKey);
const rulesClient = this.context.getRulesClientWithRequest(fakeRequest);
await rulesClient.updateSnoozedUntilTime({ id });
}
private async loadRuleAttributesAndRun(): Promise<Resultable<RuleRunResult, Error>> {
const {
params: { alertId: ruleId, spaceId },
} = this.taskInstance;
let enabled: boolean;
let apiKey: string | null;
let consumer: string;
try {
const decryptedAttributes = await this.getDecryptedAttributes(ruleId, spaceId);
apiKey = decryptedAttributes.apiKey;
enabled = decryptedAttributes.enabled;
consumer = decryptedAttributes.consumer;
} catch (err) {
throw new ErrorWithReason(RuleExecutionStatusErrorReasons.Decrypt, err);
}
this.ruleConsumer = consumer;
if (!enabled) {
throw new ErrorWithReason(
RuleExecutionStatusErrorReasons.Disabled,
new Error(`Rule failed to execute because rule ran after it was disabled.`)
);
}
const fakeRequest = this.getFakeKibanaRequest(spaceId, apiKey);
// Get rules client with space level permissions
const rulesClient = this.context.getRulesClientWithRequest(fakeRequest);
let rule: SanitizedRule<Params>;
// Ensure API key is still valid and user has access
try {
rule = await rulesClient.get({ id: ruleId });
if (apm.currentTransaction) {
apm.currentTransaction.name = `Execute Alerting Rule: "${rule.name}"`;
apm.currentTransaction.addLabels({
alerting_rule_consumer: rule.consumer,
alerting_rule_name: rule.name,
alerting_rule_tags: rule.tags.join(', '),
alerting_rule_type_id: rule.alertTypeId,
alerting_rule_params: JSON.stringify(rule.params),
});
}
} catch (err) {
throw new ErrorWithReason(RuleExecutionStatusErrorReasons.Read, err);
}
this.alertingEventLogger.setRuleName(rule.name);
try {
this.ruleTypeRegistry.ensureRuleTypeEnabled(rule.alertTypeId);
} catch (err) {
throw new ErrorWithReason(RuleExecutionStatusErrorReasons.License, err);
}
if (rule.monitoring) {
if (rule.monitoring.execution.history.length >= MONITORING_HISTORY_LIMIT) {
// Remove the first (oldest) record
rule.monitoring.execution.history.shift();
}
}
return {
monitoring: asOk(rule.monitoring),
stateWithMetrics: await promiseResult<RuleTaskStateAndMetrics, Error>(
this.validateAndExecuteRule(fakeRequest, apiKey, rule)
),
schedule: asOk(
// fetch the rule again to ensure we return the correct schedule as it may have
// changed during the task execution
(await rulesClient.get({ id: ruleId })).schedule
),
};
}
async run(): Promise<RuleTaskRunResult> {
const {
params: { alertId: ruleId, spaceId, consumer },
startedAt,
state: originalState,
schedule: taskSchedule,
} = this.taskInstance;
// Initially use consumer as stored inside the task instance
// Replace this with consumer as read from the rule saved object after
// we successfully read the rule SO. This allows us to populate a consumer
// value for `execute-start` events (which are written before the rule SO is read)
// and in the event of decryption errors (where we cannot read the rule SO)
// Because "consumer" is set when a rule is created, this value should be static
// for the life of a rule but there may be edge cases where migrations cause
// the consumer values to become out of sync.
if (consumer) {
this.ruleConsumer = consumer;
}
if (apm.currentTransaction) {
apm.currentTransaction.name = `Execute Alerting Rule`;
apm.currentTransaction.addLabels({
alerting_rule_id: ruleId,
});
}
const runDate = new Date();
const runDateString = runDate.toISOString();
this.logger.debug(`executing rule ${this.ruleType.id}:${ruleId} at ${runDateString}`);
const namespace = this.context.spaceIdToNamespace(spaceId);
this.alertingEventLogger.initialize({
ruleId,
ruleType: this.ruleType as UntypedNormalizedRuleType,
consumer: this.ruleConsumer!,
spaceId,
executionId: this.executionId,
taskScheduledAt: this.taskInstance.scheduledAt,
...(namespace ? { namespace } : {}),
});
this.alertingEventLogger.start();
const { stateWithMetrics, schedule, monitoring } = await errorAsRuleTaskRunResult(
this.loadRuleAttributesAndRun()
);
const ruleMonitoring =
resolveErr<RuleMonitoring | undefined, Error>(monitoring, () => {
return getDefaultRuleMonitoring();
}) ?? getDefaultRuleMonitoring();
const { status: executionStatus, metrics: executionMetrics } = map<
RuleTaskStateAndMetrics,
ElasticsearchError,
IExecutionStatusAndMetrics
>(
stateWithMetrics,
(ruleRunStateWithMetrics) => executionStatusFromState(ruleRunStateWithMetrics, runDate),
(err: ElasticsearchError) => executionStatusFromError(err, runDate)
);
if (apm.currentTransaction) {
if (executionStatus.status === 'ok' || executionStatus.status === 'active') {
apm.currentTransaction.setOutcome('success');
} else if (executionStatus.status === 'error' || executionStatus.status === 'unknown') {
apm.currentTransaction.setOutcome('failure');
}
}
this.logger.debug(
`ruleRunStatus for ${this.ruleType.id}:${ruleId}: ${JSON.stringify(executionStatus)}`
);
if (executionMetrics) {
this.logger.debug(
`ruleRunMetrics for ${this.ruleType.id}:${ruleId}: ${JSON.stringify(executionMetrics)}`
);
}
this.alertingEventLogger.done({ status: executionStatus, metrics: executionMetrics });
const monitoringHistory: RuleMonitoringHistory = {
success: true,
timestamp: +new Date(),
};
// set start and duration based on event log
const { start, duration } = this.alertingEventLogger.getStartAndDuration();
if (null != start) {
executionStatus.lastExecutionDate = start;
}
if (null != duration) {
executionStatus.lastDuration = nanosToMillis(duration);
monitoringHistory.duration = executionStatus.lastDuration;
}
// if executionStatus indicates an error, fill in fields in
// event from it
if (executionStatus.error) {
monitoringHistory.success = false;
}
ruleMonitoring.execution.history.push(monitoringHistory);
ruleMonitoring.execution.calculated_metrics = {
success_ratio: getExecutionSuccessRatio(ruleMonitoring),
...getExecutionDurationPercentiles(ruleMonitoring),
};
if (!this.cancelled) {
this.inMemoryMetrics.increment(IN_MEMORY_METRICS.RULE_EXECUTIONS);
if (executionStatus.error) {
this.inMemoryMetrics.increment(IN_MEMORY_METRICS.RULE_FAILURES);
}
this.logger.debug(
`Updating rule task for ${this.ruleType.id} rule with id ${ruleId} - ${JSON.stringify(
executionStatus
)}`
);
await this.updateRuleSavedObject(ruleId, namespace, {
executionStatus: ruleExecutionStatusToRaw(executionStatus),
monitoring: ruleMonitoring,
});
}
const transformRunStateToTaskState = (
runStateWithMetrics: RuleTaskStateAndMetrics
): RuleTaskState => {
return {
...omit(runStateWithMetrics, ['metrics']),
previousStartedAt: startedAt,
};
};
return {
state: map<RuleTaskStateAndMetrics, ElasticsearchError, RuleTaskState>(
stateWithMetrics,
(ruleRunStateWithMetrics: RuleTaskStateAndMetrics) =>
transformRunStateToTaskState(ruleRunStateWithMetrics),
(err: ElasticsearchError) => {
const message = `Executing Rule ${spaceId}:${
this.ruleType.id
}:${ruleId} has resulted in Error: ${getEsErrorMessage(err)}`;
if (isAlertSavedObjectNotFoundError(err, ruleId)) {
this.logger.debug(message);
} else {
this.logger.error(message);
}
return originalState;
}
),
schedule: resolveErr<IntervalSchedule | undefined, Error>(schedule, (error) => {
if (isAlertSavedObjectNotFoundError(error, ruleId)) {
const spaceMessage = spaceId ? `in the "${spaceId}" space ` : '';
this.logger.warn(
`Unable to execute rule "${ruleId}" ${spaceMessage}because ${error.message} - this rule will not be rescheduled. To restart rule execution, try disabling and re-enabling this rule.`
);
throwUnrecoverableError(error);
}
let retryInterval = taskSchedule?.interval ?? FALLBACK_RETRY_INTERVAL;
// Set retry interval smaller for ES connectivity errors
if (isEsUnavailableError(error, ruleId)) {
retryInterval =
parseDuration(retryInterval) > parseDuration(CONNECTIVITY_RETRY_INTERVAL)
? CONNECTIVITY_RETRY_INTERVAL
: retryInterval;
}
return { interval: retryInterval };
}),
monitoring: ruleMonitoring,
};
}
async cancel(): Promise<void> {
if (this.cancelled) {
return;
}
this.cancelled = true;
// Write event log entry
const {
params: { alertId: ruleId, spaceId, consumer },
} = this.taskInstance;
const namespace = this.context.spaceIdToNamespace(spaceId);
if (consumer && !this.ruleConsumer) {
this.ruleConsumer = consumer;
}
this.logger.debug(
`Cancelling rule type ${this.ruleType.id} with id ${ruleId} - execution exceeded rule type timeout of ${this.ruleType.ruleTaskTimeout}`
);
this.logger.debug(
`Aborting any in-progress ES searches for rule type ${this.ruleType.id} with id ${ruleId}`
);
this.searchAbortController.abort();
this.alertingEventLogger.logTimeout();
this.inMemoryMetrics.increment(IN_MEMORY_METRICS.RULE_TIMEOUTS);
// Update the rule saved object with execution status
const executionStatus: RuleExecutionStatus = {
lastExecutionDate: new Date(),
status: 'error',
error: {
reason: RuleExecutionStatusErrorReasons.Timeout,
message: `${this.ruleType.id}:${ruleId}: execution cancelled due to timeout - exceeded rule type timeout of ${this.ruleType.ruleTaskTimeout}`,
},
};
this.logger.debug(
`Updating rule task for ${this.ruleType.id} rule with id ${ruleId} - execution error due to timeout`
);
await this.updateRuleSavedObject(ruleId, namespace, {
executionStatus: ruleExecutionStatusToRaw(executionStatus),
});
}
}
function trackAlertDurations<
InstanceState extends AlertInstanceState,
InstanceContext extends AlertInstanceContext
>(params: TrackAlertDurationsParams<InstanceState, InstanceContext>) {
const currentTime = new Date().toISOString();
const { currentAlerts, originalAlerts, recoveredAlerts } = params;
const originalAlertIds = Object.keys(originalAlerts);
const currentAlertIds = Object.keys(currentAlerts);
const recoveredAlertIds = Object.keys(recoveredAlerts);
const newAlertIds = without(currentAlertIds, ...originalAlertIds);
// Inject start time into alert state of new alerts
for (const id of newAlertIds) {
const state = currentAlerts[id].getState();
currentAlerts[id].replaceState({ ...state, start: currentTime });
}
// Calculate duration to date for active alerts
for (const id of currentAlertIds) {
const state = originalAlertIds.includes(id)
? originalAlerts[id].getState()
: currentAlerts[id].getState();
const durationInMs =
new Date(currentTime).valueOf() - new Date(state.start as string).valueOf();
const duration = state.start ? millisToNanos(durationInMs) : undefined;
currentAlerts[id].replaceState({
...state,
...(state.start ? { start: state.start } : {}),
...(duration !== undefined ? { duration } : {}),
});
}
// Inject end time into alert state of recovered alerts
for (const id of recoveredAlertIds) {
const state = recoveredAlerts[id].getState();
const durationInMs =
new Date(currentTime).valueOf() - new Date(state.start as string).valueOf();
const duration = state.start ? millisToNanos(durationInMs) : undefined;
recoveredAlerts[id].replaceState({
...state,
...(duration ? { duration } : {}),
...(state.start ? { end: currentTime } : {}),
});
}
}
function generateNewAndRecoveredAlertEvents<
InstanceState extends AlertInstanceState,
InstanceContext extends AlertInstanceContext
>(params: GenerateNewAndRecoveredAlertEventsParams<InstanceState, InstanceContext>) {
const {
alertingEventLogger,
currentAlerts,
originalAlerts,
recoveredAlerts,
ruleRunMetricsStore,
} = params;
const originalAlertIds = Object.keys(originalAlerts);
const currentAlertIds = Object.keys(currentAlerts);
const recoveredAlertIds = Object.keys(recoveredAlerts);
const newIds = without(currentAlertIds, ...originalAlertIds);
if (apm.currentTransaction) {
apm.currentTransaction.addLabels({
alerting_new_alerts: newIds.length,
});
}
ruleRunMetricsStore.setNumberOfActiveAlerts(currentAlertIds.length);
ruleRunMetricsStore.setNumberOfNewAlerts(newIds.length);
ruleRunMetricsStore.setNumberOfRecoveredAlerts(recoveredAlertIds.length);
for (const id of recoveredAlertIds) {
const { group: actionGroup, subgroup: actionSubgroup } =
recoveredAlerts[id].getLastScheduledActions() ?? {};
const state = recoveredAlerts[id].getState();
const message = `${params.ruleLabel} alert '${id}' has recovered`;
alertingEventLogger.logAlert({
action: EVENT_LOG_ACTIONS.recoveredInstance,
id,
group: actionGroup,
subgroup: actionSubgroup,
message,
state,
});
}