Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch Reporting to Task Manager #64853

Merged
merged 35 commits into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
d4deb04
[Reporting] Task Manager
tsullivan Dec 14, 2020
4d14065
fix startup
tsullivan Feb 3, 2021
5954017
use synchronous config for task registration
tsullivan Feb 3, 2021
c30a4a5
fix eslint
tsullivan Feb 5, 2021
72a3918
Merge branch 'master' into reporting/switch-to-tm
tsullivan Feb 10, 2021
fff9cd2
pr-90365
tsullivan Feb 10, 2021
3debc63
--wip-- [skip ci]
tsullivan Feb 10, 2021
c6b5b7f
Merge branch 'master' into reporting/switch-to-tm
kibanamachine Feb 16, 2021
4478036
Merge branch 'reporting/switch-to-tm' of github.com:tsullivan/kibana …
tsullivan Feb 16, 2021
7e7abf9
Merge branch 'master' into reporting/switch-to-tm
tsullivan Feb 16, 2021
f5e95e3
set maxConcurrency to 0 if pollEnabled is false
tsullivan Feb 16, 2021
45c64df
add test for execute_report
tsullivan Feb 16, 2021
f41af01
remove unused test file
tsullivan Feb 16, 2021
96afb39
more tests
tsullivan Feb 16, 2021
6de9dd6
remove unused test files
tsullivan Feb 16, 2021
5cdb489
remove priority
tsullivan Feb 16, 2021
8d98f1c
logging cleanups
tsullivan Feb 16, 2021
dc466ee
fix for queue.pollEnabled: false
tsullivan Feb 16, 2021
b3f01bf
more logging fixes for less duplicated code
tsullivan Feb 16, 2021
6a619a8
update jest snapshots
tsullivan Feb 16, 2021
95f6a4e
polish
tsullivan Feb 16, 2021
278268b
remove unnecessary
tsullivan Feb 16, 2021
f1198f3
Update mapping.ts
tsullivan Feb 16, 2021
70441c1
polish
tsullivan Feb 16, 2021
141ecca
fix bug if instance gets a monitoring task and pollEnabled is false
tsullivan Feb 16, 2021
ea66569
simplification
tsullivan Feb 17, 2021
49a1478
Merge branch 'master' into reporting/switch-to-tm
kibanamachine Feb 18, 2021
e9dbbb1
Merge branch 'master' into reporting/switch-to-tm
tsullivan Mar 1, 2021
8fc0afc
cosmetic
tsullivan Mar 1, 2021
aab4890
Merge branch 'master' into reporting/switch-to-tm
tsullivan Mar 5, 2021
907d209
fix test
tsullivan Mar 5, 2021
65d752d
stop monitoring task sabotage
tsullivan Mar 5, 2021
425c623
Merge branch 'master' into reporting/switch-to-tm
tsullivan Mar 6, 2021
8dbabd5
update api docs
tsullivan Mar 6, 2021
2b7b49c
Merge branch 'master' into reporting/switch-to-tm
kibanamachine Mar 7, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
305 changes: 256 additions & 49 deletions api_docs/reporting.json

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions docs/user/reporting/script-example.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ Here is an example response for a successfully queued report:
"created_by": "elastic",
"payload": ..., <2>
"timeout": 120000,
"max_attempts": 3,
"priority": 10
"max_attempts": 3
}
}
---------------------------------------------------------
Expand Down
16 changes: 16 additions & 0 deletions x-pack/plugins/reporting/common/schema_utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* 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 moment from 'moment';
import { numberToDuration } from './schema_utils';

describe('Schema Utils', () => {
it('numberToDuration converts a number/Duration into a Duration object', () => {
expect(numberToDuration(500)).toMatchInlineSnapshot(`"PT0.5S"`);
expect(numberToDuration(moment.duration(1, 'hour'))).toMatchInlineSnapshot(`"PT1H"`);
});
});
7 changes: 7 additions & 0 deletions x-pack/plugins/reporting/common/schema_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ export const durationToNumber = (value: number | moment.Duration): number => {
return value.asMilliseconds();
};

export const numberToDuration = (value: number | moment.Duration): moment.Duration => {
if (typeof value === 'number') {
return moment.duration(value, 'milliseconds');
}
return value;
};

export const byteSizeValueToNumber = (value: number | ByteSizeValue) => {
if (typeof value === 'number') {
return value;
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/reporting/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"management",
"licensing",
"uiActions",
"taskManager",
"embeddable",
"share",
"features"
Expand Down
51 changes: 45 additions & 6 deletions x-pack/plugins/reporting/server/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
BasePath,
ElasticsearchServiceSetup,
KibanaRequest,
PluginInitializerContext,
SavedObjectsClientContract,
SavedObjectsServiceStart,
UiSettingsServiceStart,
Expand All @@ -21,12 +22,14 @@ import { LicensingPluginSetup } from '../../licensing/server';
import { SecurityPluginSetup } from '../../security/server';
import { DEFAULT_SPACE_ID } from '../../spaces/common/constants';
import { SpacesPluginSetup } from '../../spaces/server';
import { TaskManagerSetupContract, TaskManagerStartContract } from '../../task_manager/server';
import { ReportingConfig } from './';
import { HeadlessChromiumDriverFactory } from './browsers/chromium/driver_factory';
import { ReportingConfigType } from './config';
import { checkLicense, getExportTypesRegistry, LevelLogger } from './lib';
import { ESQueueInstance } from './lib/create_queue';
import { screenshotsObservableFactory, ScreenshotsObservableFn } from './lib/screenshots';
import { ReportingStore } from './lib/store';
import { ExecuteReportTask, MonitorReportsTask, ReportTaskParams } from './lib/tasks';
import { ReportingPluginRouter } from './types';

export interface ReportingInternalSetup {
Expand All @@ -37,14 +40,15 @@ export interface ReportingInternalSetup {
licensing: LicensingPluginSetup;
security?: SecurityPluginSetup;
spaces?: SpacesPluginSetup;
taskManager: TaskManagerSetupContract;
}

export interface ReportingInternalStart {
browserDriverFactory: HeadlessChromiumDriverFactory;
esqueue: ESQueueInstance;
store: ReportingStore;
savedObjects: SavedObjectsServiceStart;
uiSettings: UiSettingsServiceStart;
taskManager: TaskManagerStartContract;
}

export class ReportingCore {
Expand All @@ -53,24 +57,43 @@ export class ReportingCore {
private readonly pluginSetup$ = new Rx.ReplaySubject<boolean>(); // observe async background setupDeps and config each are done
private readonly pluginStart$ = new Rx.ReplaySubject<ReportingInternalStart>(); // observe async background startDeps
private exportTypesRegistry = getExportTypesRegistry();
private executeTask: ExecuteReportTask;
private monitorTask: MonitorReportsTask;
private config?: ReportingConfig;
private executing: Set<string>;

constructor(private logger: LevelLogger) {}
constructor(private logger: LevelLogger, context: PluginInitializerContext<ReportingConfigType>) {
const config = context.config.get<ReportingConfigType>();
this.executeTask = new ExecuteReportTask(this, config, this.logger);
this.monitorTask = new MonitorReportsTask(this, config, this.logger);
this.executing = new Set();
}

/*
* Register setupDeps
*/
public pluginSetup(setupDeps: ReportingInternalSetup) {
this.pluginSetup$.next(true); // trigger the observer
this.pluginSetupDeps = setupDeps; // cache

const { executeTask, monitorTask } = this;
setupDeps.taskManager.registerTaskDefinitions({
[executeTask.TYPE]: executeTask.getTaskDefinition(),
[monitorTask.TYPE]: monitorTask.getTaskDefinition(),
});
}

/*
* Register startDeps
*/
public pluginStart(startDeps: ReportingInternalStart) {
public async pluginStart(startDeps: ReportingInternalStart) {
this.pluginStart$.next(startDeps); // trigger the observer
this.pluginStartDeps = startDeps; // cache

const { taskManager } = startDeps;
const { executeTask, monitorTask } = this;
// enable this instance to generate reports and to monitor for pending reports
await Promise.all([executeTask.init(taskManager), monitorTask.init(taskManager)]);
}

/*
Expand Down Expand Up @@ -151,8 +174,12 @@ export class ReportingCore {
return this.exportTypesRegistry;
}

public async getEsqueue() {
return (await this.getPluginStartDeps()).esqueue;
public async scheduleTask(report: ReportTaskParams) {
return await this.executeTask.scheduleTask(report);
}

public async getStore() {
return (await this.getPluginStartDeps()).store;
}

public async getLicenseInfo() {
Expand Down Expand Up @@ -239,4 +266,16 @@ export class ReportingCore {
const savedObjectsClient = await this.getSavedObjectsClient(request);
return await this.getUiSettingsServiceFactory(savedObjectsClient);
}

public trackReport(reportId: string) {
this.executing.add(reportId);
}

public untrackReport(reportId: string) {
this.executing.delete(reportId);
}

public countConcurrentReports(): number {
return this.executing.size;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* 2.0.
*/

import { CSV_JOB_TYPE_DEPRECATED } from '../../../common/constants';
import { cryptoFactory } from '../../lib';
import { CreateJobFn, CreateJobFnFactory } from '../../types';
import {
Expand All @@ -16,9 +15,7 @@ import {

export const createJobFnFactory: CreateJobFnFactory<
CreateJobFn<JobParamsDeprecatedCSV, TaskPayloadDeprecatedCSV>
> = function createJobFactoryFn(reporting, parentLogger) {
const logger = parentLogger.clone([CSV_JOB_TYPE_DEPRECATED, 'create-job']);

> = function createJobFactoryFn(reporting, logger) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are some unrelated logging cleanups: the enqueue_job function has been rewritten and it now provides a more decorated logger to this function, so there can be less parentLogger.clone() in various files.

const config = reporting.getConfig();
const crypto = cryptoFactory(config.get('encryptionKey'));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { CONTENT_TYPE_CSV, CSV_JOB_TYPE_DEPRECATED } from '../../../common/constants';
import { CONTENT_TYPE_CSV } from '../../../common/constants';
import { RunTaskFn, RunTaskFnFactory } from '../../types';
import { decryptJobHeaders } from '../common';
import { createGenerateCsv } from './generate_csv';
Expand All @@ -18,7 +18,7 @@ export const runTaskFnFactory: RunTaskFnFactory<

return async function runTask(jobId, job, cancellationToken) {
const elasticsearch = reporting.getElasticsearchService();
const logger = parentLogger.clone([CSV_JOB_TYPE_DEPRECATED, 'execute-job', jobId]);
const logger = parentLogger.clone([jobId]);
const generateCsv = createGenerateCsv(logger);

const encryptionKey = config.get('encryptionKey');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

import { notFound, notImplemented } from '@hapi/boom';
import { get } from 'lodash';
import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants';
import { CsvFromSavedObjectRequest } from '../../routes/generate_from_savedobject_immediate';
import type { ReportingRequestHandlerContext } from '../../types';
import { CreateJobFnFactory } from '../../types';
import {
JobParamsPanelCsv,
Expand All @@ -18,7 +18,6 @@ import {
SavedObjectServiceError,
VisObjectAttributesJSON,
} from './types';
import type { ReportingRequestHandlerContext } from '../../types';

export type ImmediateCreateJobFn = (
jobParams: JobParamsPanelCsv,
Expand All @@ -30,7 +29,7 @@ export const createJobFnFactory: CreateJobFnFactory<ImmediateCreateJobFn> = func
reporting,
parentLogger
) {
const logger = parentLogger.clone([CSV_FROM_SAVEDOBJECT_JOB_TYPE, 'create-job']);
const logger = parentLogger.clone(['create-job']);

return async function createJob(jobParams, context, req) {
const { savedObjectType, savedObjectId } = jobParams;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@

import { KibanaRequest } from 'src/core/server';
import { CancellationToken } from '../../../common';
import { CONTENT_TYPE_CSV, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants';
import { CONTENT_TYPE_CSV } from '../../../common/constants';
import { TaskRunResult } from '../../lib/tasks';
import type { ReportingRequestHandlerContext } from '../../types';
import { RunTaskFnFactory } from '../../types';
import { createGenerateCsv } from '../csv/generate_csv';
import { getGenerateCsvParams } from './lib/get_csv_job';
import { JobPayloadPanelCsv } from './types';
import type { ReportingRequestHandlerContext } from '../../types';

/*
* ImmediateExecuteFn receives the job doc payload because the payload was
Expand All @@ -31,7 +31,7 @@ export const runTaskFnFactory: RunTaskFnFactory<ImmediateExecuteFn> = function e
parentLogger
) {
const config = reporting.getConfig();
const logger = parentLogger.clone([CSV_FROM_SAVEDOBJECT_JOB_TYPE, 'execute-job']);
const logger = parentLogger.clone(['execute-job']);

return async function runTask(jobId, jobPayload, context, req) {
const generateCsv = createGenerateCsv(logger);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@
* 2.0.
*/

import { PNG_JOB_TYPE } from '../../../../common/constants';
import { cryptoFactory } from '../../../lib';
import { CreateJobFn, CreateJobFnFactory } from '../../../types';
import { validateUrls } from '../../common';
import { JobParamsPNG, TaskPayloadPNG } from '../types';

export const createJobFnFactory: CreateJobFnFactory<
CreateJobFn<JobParamsPNG, TaskPayloadPNG>
> = function createJobFactoryFn(reporting, parentLogger) {
const logger = parentLogger.clone([PNG_JOB_TYPE, 'execute-job']);
> = function createJobFactoryFn(reporting, logger) {
const config = reporting.getConfig();
const crypto = cryptoFactory(config.get('encryptionKey'));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,16 @@
* 2.0.
*/

import { PDF_JOB_TYPE } from '../../../../common/constants';
import { cryptoFactory } from '../../../lib';
import { CreateJobFn, CreateJobFnFactory } from '../../../types';
import { validateUrls } from '../../common';
import { JobParamsPDF, TaskPayloadPDF } from '../types';

export const createJobFnFactory: CreateJobFnFactory<
CreateJobFn<JobParamsPDF, TaskPayloadPDF>
> = function createJobFactoryFn(reporting, parentLogger) {
> = function createJobFactoryFn(reporting, logger) {
const config = reporting.getConfig();
const crypto = cryptoFactory(config.get('encryptionKey'));
const logger = parentLogger.clone([PDF_JOB_TYPE, 'create-job']);

return async function createJob(
{ title, relativeUrls, browserTimezone, layout, objectType },
Expand Down
75 changes: 0 additions & 75 deletions x-pack/plugins/reporting/server/lib/create_queue.ts

This file was deleted.

Loading