-
Notifications
You must be signed in to change notification settings - Fork 8k
/
core.ts
438 lines (380 loc) · 13.5 KB
/
core.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
/*
* 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 * as Rx from 'rxjs';
import { map, take } from 'rxjs';
import type {
AnalyticsServiceStart,
CoreSetup,
DocLinksServiceSetup,
IBasePath,
IClusterClient,
KibanaRequest,
Logger,
PackageInfo,
PluginInitializerContext,
SavedObjectsServiceStart,
StatusServiceSetup,
UiSettingsServiceStart,
} from '@kbn/core/server';
import type { PluginStart as DataPluginStart } from '@kbn/data-plugin/server';
import type { DiscoverServerPluginStart } from '@kbn/discover-plugin/server';
import type { PluginSetupContract as FeaturesPluginSetup } from '@kbn/features-plugin/server';
import type { FieldFormatsStart } from '@kbn/field-formats-plugin/server';
import type { LicensingPluginStart } from '@kbn/licensing-plugin/server';
import type { ReportingServerInfo } from '@kbn/reporting-common/types';
import {
CsvSearchSourceExportType,
CsvSearchSourceImmediateExportType,
CsvV2ExportType,
} from '@kbn/reporting-export-types-csv';
import { PdfExportType, PdfV1ExportType } from '@kbn/reporting-export-types-pdf';
import { PngExportType } from '@kbn/reporting-export-types-png';
import type { ReportingConfigType } from '@kbn/reporting-server';
import { ExportType } from '@kbn/reporting-server';
import { ScreenshottingStart } from '@kbn/screenshotting-plugin/server';
import type { SecurityPluginSetup, SecurityPluginStart } from '@kbn/security-plugin/server';
import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common';
import type { SpacesPluginSetup } from '@kbn/spaces-plugin/server';
import type {
TaskManagerSetupContract,
TaskManagerStartContract,
} from '@kbn/task-manager-plugin/server';
import type { UsageCounter } from '@kbn/usage-collection-plugin/server';
import { checkLicense } from '@kbn/reporting-server/check_license';
import { ExportTypesRegistry } from '@kbn/reporting-server/export_types_registry';
import type { ReportingSetup } from '.';
import { createConfig } from './config';
import { reportingEventLoggerFactory } from './lib/event_logger/logger';
import type { IReport, ReportingStore } from './lib/store';
import { ExecuteReportTask, ReportTaskParams } from './lib/tasks';
import type { ReportingPluginRouter } from './types';
import { EventTracker } from './usage';
export interface ReportingInternalSetup {
basePath: Pick<IBasePath, 'set'>;
router: ReportingPluginRouter;
features: FeaturesPluginSetup;
security?: SecurityPluginSetup;
spaces?: SpacesPluginSetup;
usageCounter?: UsageCounter;
taskManager: TaskManagerSetupContract;
logger: Logger;
status: StatusServiceSetup;
docLinks: DocLinksServiceSetup;
}
export interface ReportingInternalStart {
store: ReportingStore;
analytics: AnalyticsServiceStart;
savedObjects: SavedObjectsServiceStart;
uiSettings: UiSettingsServiceStart;
esClient: IClusterClient;
data: DataPluginStart;
discover: DiscoverServerPluginStart;
fieldFormats: FieldFormatsStart;
licensing: LicensingPluginStart;
logger: Logger;
screenshotting?: ScreenshottingStart;
security?: SecurityPluginStart;
taskManager: TaskManagerStartContract;
}
/**
* @internal
*/
export class ReportingCore {
private packageInfo: PackageInfo;
private pluginSetupDeps?: ReportingInternalSetup;
private pluginStartDeps?: ReportingInternalStart;
private readonly pluginSetup$ = new Rx.ReplaySubject<boolean>(); // observe async background setupDeps each are done
private readonly pluginStart$ = new Rx.ReplaySubject<ReportingInternalStart>(); // observe async background startDeps
private deprecatedAllowedRoles: string[] | false = false; // DEPRECATED. If `false`, the deprecated features have been disableed
private executeTask: ExecuteReportTask;
private config: ReportingConfigType;
private executing: Set<string>;
private exportTypesRegistry = new ExportTypesRegistry();
public getContract: () => ReportingSetup;
private kibanaShuttingDown$ = new Rx.ReplaySubject<void>(1);
constructor(
private core: CoreSetup,
private logger: Logger,
private context: PluginInitializerContext<ReportingConfigType>
) {
this.packageInfo = context.env.packageInfo;
const config = createConfig(core, context.config.get<ReportingConfigType>(), logger);
this.config = config;
this.getExportTypes().forEach((et) => {
this.exportTypesRegistry.register(et);
});
this.deprecatedAllowedRoles = config.roles.enabled ? config.roles.allow : false;
this.executeTask = new ExecuteReportTask(this, config, this.logger);
this.getContract = () => ({
usesUiCapabilities: () => config.roles.enabled === false,
registerExportTypes: (id) => id,
getSpaceId: this.getSpaceId.bind(this),
});
this.executing = new Set();
}
public getKibanaPackageInfo() {
return this.packageInfo;
}
/*
* Register setupDeps
*/
public pluginSetup(setupDeps: ReportingInternalSetup) {
this.pluginSetup$.next(true); // trigger the observer
this.pluginSetupDeps = setupDeps; // cache
this.exportTypesRegistry.getAll().forEach((et) => {
et.setup(setupDeps);
});
const { executeTask } = this;
setupDeps.taskManager.registerTaskDefinitions({
[executeTask.TYPE]: executeTask.getTaskDefinition(),
});
}
/*
* Register startDeps
*/
public async pluginStart(startDeps: ReportingInternalStart) {
this.pluginStart$.next(startDeps); // trigger the observer
this.pluginStartDeps = startDeps; // cache
this.exportTypesRegistry.getAll().forEach((et) => {
et.start({ ...startDeps });
});
const { taskManager } = startDeps;
const { executeTask } = this;
// enable this instance to generate reports
await Promise.all([executeTask.init(taskManager)]);
}
public pluginStop() {
this.kibanaShuttingDown$.next();
}
public getKibanaShutdown$(): Rx.Observable<void> {
return this.kibanaShuttingDown$.pipe(take(1));
}
/*
* Blocks the caller until setup is done
*/
public async pluginSetsUp(): Promise<boolean> {
// use deps and config as a cached resolver
if (this.pluginSetupDeps && this.config) {
return true;
}
return await Rx.firstValueFrom(this.pluginSetup$.pipe(take(2))); // once for pluginSetupDeps (sync) and twice for config (async)
}
/*
* Blocks the caller until start is done
*/
public async pluginStartsUp(): Promise<boolean> {
return await this.getPluginStartDeps().then(() => true);
}
/*
* Synchronously checks if all async background setup and startup is completed
*/
public pluginIsStarted() {
return this.pluginSetupDeps != null && this.config != null && this.pluginStartDeps != null;
}
/*
* Allows config to be set in the background
*/
public setConfig(config: ReportingConfigType) {
this.config = config;
this.pluginSetup$.next(true);
}
/**
* Validate export types with config settings
* only CSV export types should be registered in the export types registry for serverless
*/
private getExportTypes(): ExportType[] {
const { csv, pdf, png } = this.config.export_types;
const exportTypes = [];
if (csv.enabled) {
// NOTE: CsvSearchSourceExportType should be deprecated and replaced with V2 in the UI: https://github.com/elastic/kibana/issues/151190
exportTypes.push(
new CsvSearchSourceExportType(this.core, this.config, this.logger, this.context)
);
exportTypes.push(new CsvV2ExportType(this.core, this.config, this.logger, this.context));
}
if (pdf.enabled) {
// NOTE: PdfV1ExportType is deprecated and tagged for removal: https://github.com/elastic/kibana/issues/154601
exportTypes.push(new PdfV1ExportType(this.core, this.config, this.logger, this.context));
exportTypes.push(new PdfExportType(this.core, this.config, this.logger, this.context));
}
if (png.enabled) {
exportTypes.push(new PngExportType(this.core, this.config, this.logger, this.context));
}
return exportTypes;
}
/**
* If xpack.reporting.roles.enabled === true, register Reporting as a feature
* that is controlled by user role names
*/
public registerFeature() {
const { features } = this.getPluginSetupDeps();
const deprecatedRoles = this.getDeprecatedAllowedRoles();
if (deprecatedRoles !== false) {
// refer to roles.allow configuration (deprecated path)
const allowedRoles = ['superuser', ...(deprecatedRoles ?? [])];
const privileges = allowedRoles.map((role) => ({
requiredClusterPrivileges: [],
requiredRoles: [role],
ui: [],
}));
// self-register as an elasticsearch feature (deprecated)
features.registerElasticsearchFeature({
id: 'reporting',
catalogue: ['reporting'],
management: {
insightsAndAlerting: ['reporting'],
},
privileges,
});
} else {
this.logger.debug(
`Reporting roles configuration is disabled. Please assign access to Reporting use Kibana feature controls for applications.`
);
// trigger application to register Reporting as a subfeature
features.enableReportingUiCapabilities();
}
}
/*
* Returns configurable server info
*/
public getServerInfo(): ReportingServerInfo {
const { http } = this.core;
const serverInfo = http.getServerInfo();
return {
basePath: this.core.http.basePath.serverBasePath,
hostname: serverInfo.hostname,
name: serverInfo.name,
port: serverInfo.port,
uuid: this.context.env.instanceUuid,
protocol: serverInfo.protocol,
};
}
/*
* Gives synchronous access to the config
*/
public getConfig(): ReportingConfigType {
return this.config;
}
/*
* If deprecated feature has not been disabled,
* this returns an array of allowed role names
* that have access to Reporting.
*/
public getDeprecatedAllowedRoles(): string[] | false {
return this.deprecatedAllowedRoles;
}
/*
* Track usage of API endpoints
*/
public getUsageCounter(): UsageCounter | undefined {
return this.pluginSetupDeps?.usageCounter;
}
/*
* Track metrics of internal events
*/
public getEventTracker(
reportId: string,
exportType: string,
objectType: string
): EventTracker | undefined {
const { analytics } = this.pluginStartDeps ?? {};
if (analytics) {
return new EventTracker(analytics, reportId, exportType, objectType);
}
}
/*
* Gives async access to the startDeps
*/
public async getPluginStartDeps() {
if (this.pluginStartDeps) {
return this.pluginStartDeps;
}
return await Rx.firstValueFrom(this.pluginStart$);
}
public getExportTypesRegistry() {
return this.exportTypesRegistry;
}
public async scheduleTask(report: ReportTaskParams) {
return await this.executeTask.scheduleTask(report);
}
public async getStore() {
return (await this.getPluginStartDeps()).store;
}
public async getLicenseInfo() {
const { license$ } = (await this.getPluginStartDeps()).licensing;
const registry = this.getExportTypesRegistry();
return await Rx.firstValueFrom(
license$.pipe(map((license) => checkLicense(registry, license)))
);
}
/*
* Gives synchronous access to the setupDeps
*/
public getPluginSetupDeps() {
if (!this.pluginSetupDeps) {
throw new Error(`"pluginSetupDeps" dependencies haven't initialized yet`);
}
return this.pluginSetupDeps;
}
public async getDataViewsService(request: KibanaRequest) {
const { savedObjects } = await this.getPluginStartDeps();
const savedObjectsClient = savedObjects.getScopedClient(request);
const { indexPatterns } = await this.getDataService();
const { asCurrentUser: esClient } = (await this.getEsClient()).asScoped(request);
const dataViews = await indexPatterns.dataViewsServiceFactory(savedObjectsClient, esClient);
return dataViews;
}
public async getDataService() {
const startDeps = await this.getPluginStartDeps();
return startDeps.data;
}
public async getEsClient() {
const startDeps = await this.getPluginStartDeps();
return startDeps.esClient;
}
public getSpaceId(request: KibanaRequest, logger = this.logger): string | undefined {
const spacesService = this.getPluginSetupDeps().spaces?.spacesService;
if (spacesService) {
const spaceId = spacesService?.getSpaceId(request);
if (spaceId !== DEFAULT_SPACE_ID) {
logger.info(`Request uses Space ID: ${spaceId}`);
return spaceId;
} else {
logger.debug(`Request uses default Space`);
}
}
}
public trackReport(reportId: string) {
this.executing.add(reportId);
}
public untrackReport(reportId: string) {
this.executing.delete(reportId);
}
public countConcurrentReports(): number {
return this.executing.size;
}
public getEventLogger(report: IReport, task?: { id: string }) {
const ReportingEventLogger = reportingEventLoggerFactory(this.logger);
return new ReportingEventLogger(report, task);
}
/**
* @deprecated
* Requires `xpack.reporting.csv.enablePanelActionDownload` set to `true` (default is false)
*/
public async getCsvSearchSourceImmediate() {
const startDeps = await this.getPluginStartDeps();
const csvImmediateExport = new CsvSearchSourceImmediateExportType(
this.core,
this.config,
this.logger,
this.context
);
csvImmediateExport.setup(this.getPluginSetupDeps());
csvImmediateExport.start({ ...startDeps });
return csvImmediateExport;
}
}