-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
plugin.ts
719 lines (661 loc) · 26.5 KB
/
plugin.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
/*
* 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 { PublicMethodsOf } from '@kbn/utility-types';
import {
BehaviorSubject,
ReplaySubject,
Subject,
Observable,
map,
distinctUntilChanged,
} from 'rxjs';
import { pick } from 'lodash';
import { UsageCollectionSetup, UsageCounter } from '@kbn/usage-collection-plugin/server';
import { SecurityPluginSetup, SecurityPluginStart } from '@kbn/security-plugin/server';
import { PluginSetup as DataPluginSetup } from '@kbn/data-plugin/server';
import { PluginStart as DataViewsPluginStart } from '@kbn/data-views-plugin/server';
import {
EncryptedSavedObjectsPluginSetup,
EncryptedSavedObjectsPluginStart,
} from '@kbn/encrypted-saved-objects-plugin/server';
import {
TaskManagerSetupContract,
TaskManagerStartContract,
} from '@kbn/task-manager-plugin/server';
import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common';
import { SpacesPluginStart } from '@kbn/spaces-plugin/server';
import {
KibanaRequest,
Logger,
PluginInitializerContext,
CoreSetup,
CoreStart,
IContextProvider,
StatusServiceSetup,
ServiceStatus,
SavedObjectsBulkGetObject,
ServiceStatusLevels,
CoreStatus,
} from '@kbn/core/server';
import {
LICENSE_TYPE,
LicensingPluginSetup,
LicensingPluginStart,
} from '@kbn/licensing-plugin/server';
import {
PluginSetupContract as ActionsPluginSetupContract,
PluginStartContract as ActionsPluginStartContract,
} from '@kbn/actions-plugin/server';
import {
IEventLogger,
IEventLogService,
IEventLogClientService,
} from '@kbn/event-log-plugin/server';
import { FeaturesPluginStart, FeaturesPluginSetup } from '@kbn/features-plugin/server';
import type { PluginSetup as UnifiedSearchServerPluginSetup } from '@kbn/unified-search-plugin/server';
import { PluginStart as DataPluginStart } from '@kbn/data-plugin/server';
import { MonitoringCollectionSetup } from '@kbn/monitoring-collection-plugin/server';
import { SharePluginStart } from '@kbn/share-plugin/server';
import { ServerlessPluginSetup } from '@kbn/serverless/server';
import { RuleTypeRegistry } from './rule_type_registry';
import { TaskRunnerFactory } from './task_runner';
import { RulesClientFactory } from './rules_client_factory';
import {
RulesSettingsClientFactory,
RulesSettingsService,
getRulesSettingsFeature,
} from './rules_settings';
import { MaintenanceWindowClientFactory } from './maintenance_window_client_factory';
import { ILicenseState, LicenseState } from './lib/license_state';
import { AlertingRequestHandlerContext, ALERTING_FEATURE_ID, RuleAlertData } from './types';
import { defineRoutes } from './routes';
import {
AlertInstanceContext,
AlertInstanceState,
AlertsHealth,
RuleType,
RuleTypeParams,
RuleTypeState,
RulesClientApi,
} from './types';
import { registerAlertingUsageCollector } from './usage';
import { initializeAlertingTelemetry, scheduleAlertingTelemetry } from './usage/task';
import {
setupSavedObjects,
RULE_SAVED_OBJECT_TYPE,
AD_HOC_RUN_SAVED_OBJECT_TYPE,
} from './saved_objects';
import {
initializeApiKeyInvalidator,
scheduleApiKeyInvalidatorTask,
} from './invalidate_pending_api_keys/task';
import { scheduleAlertingHealthCheck, initializeAlertingHealth } from './health';
import { AlertingConfig, AlertingRulesConfig } from './config';
import { getHealth } from './health/get_health';
import { AlertingAuthorizationClientFactory } from './alerting_authorization_client_factory';
import { AlertingAuthorization } from './authorization';
import { getSecurityHealth, SecurityHealth } from './lib/get_security_health';
import { registerNodeCollector, registerClusterCollector, InMemoryMetrics } from './monitoring';
import { getRuleTaskTimeout } from './lib/get_rule_task_timeout';
import { getActionsConfigMap } from './lib/get_actions_config_map';
import {
AlertsService,
type PublicFrameworkAlertsService,
type InitializationPromise,
errorResult,
} from './alerts_service';
import { maintenanceWindowFeature } from './maintenance_window_feature';
import { ConnectorAdapterRegistry } from './connector_adapters/connector_adapter_registry';
import { ConnectorAdapter, ConnectorAdapterParams } from './connector_adapters/types';
import { DataStreamAdapter, getDataStreamAdapter } from './alerts_service/lib/data_stream_adapter';
import { createGetAlertIndicesAliasFn, GetAlertIndicesAlias } from './lib';
import { BackfillClient } from './backfill_client/backfill_client';
import { MaintenanceWindowsService } from './task_runner/maintenance_windows';
export const EVENT_LOG_PROVIDER = 'alerting';
export const EVENT_LOG_ACTIONS = {
execute: 'execute',
executeStart: 'execute-start',
executeAction: 'execute-action',
executeBackfill: 'execute-backfill',
newInstance: 'new-instance',
recoveredInstance: 'recovered-instance',
activeInstance: 'active-instance',
executeTimeout: 'execute-timeout',
untrackedInstance: 'untracked-instance',
};
export const LEGACY_EVENT_LOG_ACTIONS = {
resolvedInstance: 'resolved-instance',
};
export interface PluginSetupContract {
registerConnectorAdapter<
RuleActionParams extends ConnectorAdapterParams = ConnectorAdapterParams,
ConnectorParams extends ConnectorAdapterParams = ConnectorAdapterParams
>(
adapter: ConnectorAdapter<RuleActionParams, ConnectorParams>
): void;
registerType<
Params extends RuleTypeParams = RuleTypeParams,
ExtractedParams extends RuleTypeParams = RuleTypeParams,
State extends RuleTypeState = RuleTypeState,
InstanceState extends AlertInstanceState = AlertInstanceState,
InstanceContext extends AlertInstanceContext = AlertInstanceContext,
ActionGroupIds extends string = never,
RecoveryActionGroupId extends string = never,
AlertData extends RuleAlertData = never
>(
ruleType: RuleType<
Params,
ExtractedParams,
State,
InstanceState,
InstanceContext,
ActionGroupIds,
RecoveryActionGroupId,
AlertData
>
): void;
getSecurityHealth: () => Promise<SecurityHealth>;
getConfig: () => AlertingRulesConfig;
frameworkAlerts: PublicFrameworkAlertsService;
getDataStreamAdapter: () => DataStreamAdapter;
}
export interface PluginStartContract {
listTypes: RuleTypeRegistry['list'];
getAllTypes: RuleTypeRegistry['getAllTypes'];
getType: RuleTypeRegistry['get'];
getAlertIndicesAlias: GetAlertIndicesAlias;
getRulesClientWithRequest(request: KibanaRequest): RulesClientApi;
getAlertingAuthorizationWithRequest(
request: KibanaRequest
): PublicMethodsOf<AlertingAuthorization>;
getFrameworkHealth: () => Promise<AlertsHealth>;
}
export interface AlertingPluginsSetup {
security?: SecurityPluginSetup;
taskManager: TaskManagerSetupContract;
actions: ActionsPluginSetupContract;
encryptedSavedObjects: EncryptedSavedObjectsPluginSetup;
licensing: LicensingPluginSetup;
usageCollection?: UsageCollectionSetup;
eventLog: IEventLogService;
statusService: StatusServiceSetup;
monitoringCollection: MonitoringCollectionSetup;
data: DataPluginSetup;
features: FeaturesPluginSetup;
unifiedSearch: UnifiedSearchServerPluginSetup;
serverless?: ServerlessPluginSetup;
}
export interface AlertingPluginsStart {
actions: ActionsPluginStartContract;
taskManager: TaskManagerStartContract;
encryptedSavedObjects: EncryptedSavedObjectsPluginStart;
features: FeaturesPluginStart;
eventLog: IEventLogClientService;
licensing: LicensingPluginStart;
spaces?: SpacesPluginStart;
security?: SecurityPluginStart;
data: DataPluginStart;
dataViews: DataViewsPluginStart;
share: SharePluginStart;
serverless?: ServerlessPluginSetup;
}
export class AlertingPlugin {
private readonly config: AlertingConfig;
private readonly logger: Logger;
private ruleTypeRegistry?: RuleTypeRegistry;
private readonly taskRunnerFactory: TaskRunnerFactory;
private licenseState: ILicenseState | null = null;
private isESOCanEncrypt?: boolean;
private security?: SecurityPluginSetup;
private readonly rulesClientFactory: RulesClientFactory;
private readonly alertingAuthorizationClientFactory: AlertingAuthorizationClientFactory;
private readonly rulesSettingsClientFactory: RulesSettingsClientFactory;
private readonly maintenanceWindowClientFactory: MaintenanceWindowClientFactory;
private readonly telemetryLogger: Logger;
private readonly kibanaVersion: PluginInitializerContext['env']['packageInfo']['version'];
private eventLogService?: IEventLogService;
private eventLogger?: IEventLogger;
private kibanaBaseUrl: string | undefined;
private usageCounter: UsageCounter | undefined;
private inMemoryMetrics: InMemoryMetrics;
private alertsService: AlertsService | null;
private pluginStop$: Subject<void>;
private dataStreamAdapter?: DataStreamAdapter;
private backfillClient?: BackfillClient;
private nodeRoles: PluginInitializerContext['node']['roles'];
private readonly connectorAdapterRegistry = new ConnectorAdapterRegistry();
constructor(initializerContext: PluginInitializerContext) {
this.config = initializerContext.config.get();
this.logger = initializerContext.logger.get();
this.taskRunnerFactory = new TaskRunnerFactory();
this.rulesClientFactory = new RulesClientFactory();
this.alertsService = null;
this.nodeRoles = initializerContext.node.roles;
this.alertingAuthorizationClientFactory = new AlertingAuthorizationClientFactory();
this.rulesSettingsClientFactory = new RulesSettingsClientFactory();
this.maintenanceWindowClientFactory = new MaintenanceWindowClientFactory();
this.telemetryLogger = initializerContext.logger.get('usage');
this.kibanaVersion = initializerContext.env.packageInfo.version;
this.inMemoryMetrics = new InMemoryMetrics(initializerContext.logger.get('in_memory_metrics'));
this.pluginStop$ = new ReplaySubject(1);
}
public setup(
core: CoreSetup<AlertingPluginsStart, unknown>,
plugins: AlertingPluginsSetup
): PluginSetupContract {
this.kibanaBaseUrl = core.http.basePath.publicBaseUrl;
this.licenseState = new LicenseState(plugins.licensing.license$);
this.security = plugins.security;
const elasticsearchAndSOAvailability$ = getElasticsearchAndSOAvailability(core.status.core$);
const useDataStreamForAlerts = !!plugins.serverless;
this.dataStreamAdapter = getDataStreamAdapter({ useDataStreamForAlerts });
core.capabilities.registerProvider(() => {
return {
management: {
insightsAndAlerting: {
triggersActions: true,
maintenanceWindows: true,
},
},
};
});
plugins.features.registerKibanaFeature(getRulesSettingsFeature(!!plugins.serverless));
plugins.features.registerKibanaFeature(maintenanceWindowFeature);
this.isESOCanEncrypt = plugins.encryptedSavedObjects.canEncrypt;
if (!this.isESOCanEncrypt) {
this.logger.warn(
'APIs are disabled because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.'
);
}
const taskManagerStartPromise = core
.getStartServices()
.then(([_, alertingStart]) => alertingStart.taskManager);
this.backfillClient = new BackfillClient({
logger: this.logger,
taskManagerSetup: plugins.taskManager,
taskManagerStartPromise,
taskRunnerFactory: this.taskRunnerFactory,
});
this.eventLogger = plugins.eventLog.getLogger({
event: { provider: EVENT_LOG_PROVIDER },
});
this.eventLogService = plugins.eventLog;
plugins.eventLog.registerProviderActions(EVENT_LOG_PROVIDER, Object.values(EVENT_LOG_ACTIONS));
if (this.config.enableFrameworkAlerts) {
if (this.nodeRoles.migrator) {
this.logger.info(`Skipping initialization of AlertsService on migrator node`);
} else {
this.logger.info(
`using ${
this.dataStreamAdapter.isUsingDataStreams() ? 'datastreams' : 'indexes and aliases'
} for persisting alerts`
);
this.alertsService = new AlertsService({
logger: this.logger,
pluginStop$: this.pluginStop$,
kibanaVersion: this.kibanaVersion,
dataStreamAdapter: this.dataStreamAdapter!,
elasticsearchClientPromise: core
.getStartServices()
.then(([{ elasticsearch }]) => elasticsearch.client.asInternalUser),
elasticsearchAndSOAvailability$,
});
}
}
const ruleTypeRegistry = new RuleTypeRegistry({
config: this.config,
logger: this.logger,
taskManager: plugins.taskManager,
taskRunnerFactory: this.taskRunnerFactory,
licenseState: this.licenseState,
licensing: plugins.licensing,
alertsService: this.alertsService,
minimumScheduleInterval: this.config.rules.minimumScheduleInterval,
inMemoryMetrics: this.inMemoryMetrics,
});
this.ruleTypeRegistry = ruleTypeRegistry;
const usageCollection = plugins.usageCollection;
if (usageCollection) {
registerAlertingUsageCollector(usageCollection, taskManagerStartPromise);
const eventLogIndex = this.eventLogService.getIndexPattern();
initializeAlertingTelemetry(this.telemetryLogger, core, plugins.taskManager, eventLogIndex);
}
// Usage counter for telemetry
this.usageCounter = plugins.usageCollection?.createUsageCounter(ALERTING_FEATURE_ID);
const getSearchSourceMigrations = plugins.data.search.searchSource.getAllMigrations.bind(
plugins.data.search.searchSource
);
setupSavedObjects(
core.savedObjects,
plugins.encryptedSavedObjects,
this.ruleTypeRegistry,
this.logger,
plugins.actions.isPreconfiguredConnector,
getSearchSourceMigrations
);
initializeApiKeyInvalidator(
this.logger,
core.getStartServices(),
plugins.taskManager,
this.config
);
const serviceStatus$ = new BehaviorSubject<ServiceStatus>({
level: ServiceStatusLevels.available,
summary: 'Alerting is (probably) ready',
});
core.status.set(serviceStatus$);
initializeAlertingHealth(this.logger, plugins.taskManager, core.getStartServices());
core.http.registerRouteHandlerContext<AlertingRequestHandlerContext, 'alerting'>(
'alerting',
this.createRouteHandlerContext(core)
);
if (plugins.monitoringCollection) {
registerNodeCollector({
monitoringCollection: plugins.monitoringCollection,
inMemoryMetrics: this.inMemoryMetrics,
});
registerClusterCollector({
monitoringCollection: plugins.monitoringCollection,
core,
});
}
// Routes
const router = core.http.createRouter<AlertingRequestHandlerContext>();
// Register routes
defineRoutes({
router,
licenseState: this.licenseState,
usageCounter: this.usageCounter,
getAlertIndicesAlias: createGetAlertIndicesAliasFn(this.ruleTypeRegistry!),
encryptedSavedObjects: plugins.encryptedSavedObjects,
config$: plugins.unifiedSearch.autocomplete.getInitializerContextConfig().create(),
isServerless: !!plugins.serverless,
});
return {
registerConnectorAdapter: <
RuleActionParams extends ConnectorAdapterParams = ConnectorAdapterParams,
ConnectorParams extends ConnectorAdapterParams = ConnectorAdapterParams
>(
adapter: ConnectorAdapter<RuleActionParams, ConnectorParams>
) => {
this.connectorAdapterRegistry.register(adapter);
},
registerType: <
Params extends RuleTypeParams = never,
ExtractedParams extends RuleTypeParams = never,
State extends RuleTypeState = never,
InstanceState extends AlertInstanceState = never,
InstanceContext extends AlertInstanceContext = never,
ActionGroupIds extends string = never,
RecoveryActionGroupId extends string = never,
AlertData extends RuleAlertData = never
>(
ruleType: RuleType<
Params,
ExtractedParams,
State,
InstanceState,
InstanceContext,
ActionGroupIds,
RecoveryActionGroupId,
AlertData
>
) => {
if (!(ruleType.minimumLicenseRequired in LICENSE_TYPE)) {
throw new Error(`"${ruleType.minimumLicenseRequired}" is not a valid license type`);
}
ruleType.ruleTaskTimeout = getRuleTaskTimeout({
config: this.config.rules,
ruleTaskTimeout: ruleType.ruleTaskTimeout,
ruleTypeId: ruleType.id,
});
ruleType.cancelAlertsOnRuleTimeout =
ruleType.cancelAlertsOnRuleTimeout ?? this.config.cancelAlertsOnRuleTimeout;
ruleType.doesSetRecoveryContext = ruleType.doesSetRecoveryContext ?? false;
ruleType.autoRecoverAlerts = ruleType.autoRecoverAlerts ?? true;
ruleTypeRegistry.register(ruleType);
},
getSecurityHealth: async () => {
return await getSecurityHealth(
async () => (this.licenseState ? this.licenseState.getIsSecurityEnabled() : null),
async () => plugins.encryptedSavedObjects.canEncrypt,
async () => {
const [, { security }] = await core.getStartServices();
return security?.authc.apiKeys.areAPIKeysEnabled() ?? false;
}
);
},
getConfig: () => {
return {
...pick(this.config.rules, ['minimumScheduleInterval', 'maxScheduledPerMinute', 'run']),
isUsingSecurity: this.licenseState ? !!this.licenseState.getIsSecurityEnabled() : false,
};
},
frameworkAlerts: {
enabled: () => this.config.enableFrameworkAlerts,
getContextInitializationPromise: (
context: string,
namespace: string
): Promise<InitializationPromise> => {
if (this.alertsService) {
return this.alertsService.getContextInitializationPromise(context, namespace);
}
return Promise.resolve(errorResult(`Framework alerts service not available`));
},
},
getDataStreamAdapter: () => this.dataStreamAdapter!,
};
}
public start(core: CoreStart, plugins: AlertingPluginsStart): PluginStartContract {
const {
isESOCanEncrypt,
logger,
taskRunnerFactory,
ruleTypeRegistry,
rulesClientFactory,
alertingAuthorizationClientFactory,
rulesSettingsClientFactory,
maintenanceWindowClientFactory,
security,
licenseState,
} = this;
licenseState?.setNotifyUsage(plugins.licensing.featureUsage.notifyUsage);
const encryptedSavedObjectsClient = plugins.encryptedSavedObjects.getClient({
includedHiddenTypes: [RULE_SAVED_OBJECT_TYPE, AD_HOC_RUN_SAVED_OBJECT_TYPE],
});
const spaceIdToNamespace = (spaceId?: string) => {
return plugins.spaces && spaceId
? plugins.spaces.spacesService.spaceIdToNamespace(spaceId)
: undefined;
};
alertingAuthorizationClientFactory.initialize({
ruleTypeRegistry: ruleTypeRegistry!,
securityPluginSetup: security,
securityPluginStart: plugins.security,
async getSpace(request: KibanaRequest) {
return plugins.spaces?.spacesService.getActiveSpace(request);
},
getSpaceId(request: KibanaRequest) {
return plugins.spaces?.spacesService.getSpaceId(request) ?? DEFAULT_SPACE_ID;
},
features: plugins.features,
});
rulesClientFactory.initialize({
ruleTypeRegistry: ruleTypeRegistry!,
logger,
taskManager: plugins.taskManager,
securityPluginSetup: security,
securityPluginStart: plugins.security,
internalSavedObjectsRepository: core.savedObjects.createInternalRepository([
RULE_SAVED_OBJECT_TYPE,
]),
encryptedSavedObjectsClient,
spaceIdToNamespace,
getSpaceId(request: KibanaRequest) {
return plugins.spaces?.spacesService.getSpaceId(request) ?? DEFAULT_SPACE_ID;
},
actions: plugins.actions,
eventLog: plugins.eventLog,
kibanaVersion: this.kibanaVersion,
authorization: alertingAuthorizationClientFactory,
eventLogger: this.eventLogger,
minimumScheduleInterval: this.config.rules.minimumScheduleInterval,
maxScheduledPerMinute: this.config.rules.maxScheduledPerMinute,
getAlertIndicesAlias: createGetAlertIndicesAliasFn(this.ruleTypeRegistry!),
alertsService: this.alertsService,
backfillClient: this.backfillClient!,
connectorAdapterRegistry: this.connectorAdapterRegistry,
uiSettings: core.uiSettings,
securityService: core.security,
});
rulesSettingsClientFactory.initialize({
logger: this.logger,
savedObjectsService: core.savedObjects,
securityService: core.security,
isServerless: !!plugins.serverless,
});
maintenanceWindowClientFactory.initialize({
logger: this.logger,
savedObjectsService: core.savedObjects,
securityService: core.security,
uiSettings: core.uiSettings,
});
const getRulesClientWithRequest = (request: KibanaRequest) => {
if (isESOCanEncrypt !== true) {
throw new Error(
`Unable to create alerts client because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.`
);
}
return rulesClientFactory!.create(request, core.savedObjects);
};
const getAlertingAuthorizationWithRequest = (request: KibanaRequest) => {
return alertingAuthorizationClientFactory!.create(request);
};
const getRulesSettingsClientWithRequest = (request: KibanaRequest) => {
return rulesSettingsClientFactory!.create(request);
};
const getMaintenanceWindowClientWithRequest = (request: KibanaRequest) => {
return maintenanceWindowClientFactory!.create(request);
};
taskRunnerFactory.initialize({
actionsConfigMap: getActionsConfigMap(this.config.rules.run.actions),
actionsPlugin: plugins.actions,
alertsService: this.alertsService,
backfillClient: this.backfillClient!,
basePathService: core.http.basePath,
cancelAlertsOnRuleTimeout: this.config.cancelAlertsOnRuleTimeout,
connectorAdapterRegistry: this.connectorAdapterRegistry,
data: plugins.data,
dataViews: plugins.dataViews,
elasticsearch: core.elasticsearch,
encryptedSavedObjectsClient,
eventLogger: this.eventLogger!,
executionContext: core.executionContext,
kibanaBaseUrl: this.kibanaBaseUrl,
logger,
maintenanceWindowsService: new MaintenanceWindowsService({
cacheInterval: this.config.rulesSettings.cacheInterval,
getMaintenanceWindowClientWithRequest,
logger,
}),
maxAlerts: this.config.rules.run.alerts.max,
maxEphemeralActionsPerRule: this.config.maxEphemeralActionsPerAlert,
ruleTypeRegistry: this.ruleTypeRegistry!,
rulesSettingsService: new RulesSettingsService({
cacheInterval: this.config.rulesSettings.cacheInterval,
getRulesSettingsClientWithRequest,
isServerless: !!plugins.serverless,
logger,
}),
savedObjects: core.savedObjects,
share: plugins.share,
spaceIdToNamespace,
supportsEphemeralTasks: plugins.taskManager.supportsEphemeralTasks(),
uiSettings: core.uiSettings,
usageCounter: this.usageCounter,
});
this.eventLogService!.registerSavedObjectProvider(RULE_SAVED_OBJECT_TYPE, (request) => {
const client = getRulesClientWithRequest(request);
return (objects?: SavedObjectsBulkGetObject[]) =>
objects
? Promise.all(objects.map(async (objectItem) => await client.get({ id: objectItem.id })))
: Promise.resolve([]);
});
this.eventLogService!.isEsContextReady()
.then(() => {
scheduleAlertingTelemetry(this.telemetryLogger, plugins.taskManager);
})
.catch(() => {}); // it shouldn't reject, but just in case
scheduleAlertingHealthCheck(this.logger, this.config, plugins.taskManager).catch(() => {}); // it shouldn't reject, but just in case
scheduleApiKeyInvalidatorTask(this.telemetryLogger, this.config, plugins.taskManager).catch(
() => {}
); // it shouldn't reject, but just in case
return {
listTypes: ruleTypeRegistry!.list.bind(this.ruleTypeRegistry!),
getType: ruleTypeRegistry!.get.bind(this.ruleTypeRegistry),
getAllTypes: ruleTypeRegistry!.getAllTypes.bind(this.ruleTypeRegistry!),
getAlertIndicesAlias: createGetAlertIndicesAliasFn(this.ruleTypeRegistry!),
getAlertingAuthorizationWithRequest,
getRulesClientWithRequest,
getFrameworkHealth: async () =>
await getHealth(core.savedObjects.createInternalRepository([RULE_SAVED_OBJECT_TYPE])),
};
}
private createRouteHandlerContext = (
core: CoreSetup<AlertingPluginsStart, unknown>
): IContextProvider<AlertingRequestHandlerContext, 'alerting'> => {
const {
ruleTypeRegistry,
rulesClientFactory,
rulesSettingsClientFactory,
maintenanceWindowClientFactory,
} = this;
return async function alertsRouteHandlerContext(context, request) {
const [{ savedObjects }] = await core.getStartServices();
return {
getRulesClient: () => {
return rulesClientFactory!.create(request, savedObjects);
},
getRulesSettingsClient: (withoutAuth?: boolean) => {
if (withoutAuth) {
return rulesSettingsClientFactory.create(request);
}
return rulesSettingsClientFactory.createWithAuthorization(request);
},
getMaintenanceWindowClient: () => {
return maintenanceWindowClientFactory.createWithAuthorization(request);
},
listTypes: ruleTypeRegistry!.list.bind(ruleTypeRegistry!),
getFrameworkHealth: async () =>
await getHealth(savedObjects.createInternalRepository([RULE_SAVED_OBJECT_TYPE])),
areApiKeysEnabled: async () => {
const [, { security }] = await core.getStartServices();
return security?.authc.apiKeys.areAPIKeysEnabled() ?? false;
},
};
};
};
public stop() {
if (this.licenseState) {
this.licenseState.clean();
}
this.pluginStop$.next();
this.pluginStop$.complete();
}
}
export function getElasticsearchAndSOAvailability(
core$: Observable<CoreStatus>
): Observable<boolean> {
return core$.pipe(
map(
({ elasticsearch, savedObjects }) =>
elasticsearch.level === ServiceStatusLevels.available &&
savedObjects.level === ServiceStatusLevels.available
),
distinctUntilChanged()
);
}