forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.ts
More file actions
172 lines (153 loc) · 5.24 KB
/
task.ts
File metadata and controls
172 lines (153 loc) · 5.24 KB
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
/*
* 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 type { Logger, LogMeta } from '@kbn/core/server';
import type {
ConcreteTaskInstance,
TaskManagerSetupContract,
TaskManagerStartContract,
} from '@kbn/task-manager-plugin/server';
import type { ITelemetryReceiver } from './receiver';
import type { ITelemetryEventsSender } from './sender';
import type { ITaskMetricsService } from './task_metrics.types';
import { stateSchemaByVersion, emptyState, type LatestTaskStateSchema } from './task_state';
import { newTelemetryLogger, withErrorMessage } from './helpers';
import { type TelemetryLogger } from './telemetry_logger';
export interface SecurityTelemetryTaskConfig {
type: string;
title: string;
interval: string;
timeout: string;
version: string;
getLastExecutionTime?: LastExecutionTimestampCalculator;
runTask: SecurityTelemetryTaskRunner;
}
export type SecurityTelemetryTaskRunner = (
taskId: string,
logger: Logger,
receiver: ITelemetryReceiver,
sender: ITelemetryEventsSender,
taskMetricsService: ITaskMetricsService,
taskExecutionPeriod: TaskExecutionPeriod
) => Promise<number>;
export interface TaskExecutionPeriod {
last?: string;
current: string;
}
export type LastExecutionTimestampCalculator = (
executeTo: string,
lastExecutionTimestamp?: string
) => string;
export class SecurityTelemetryTask {
private readonly config: SecurityTelemetryTaskConfig;
private readonly logger: TelemetryLogger;
private readonly sender: ITelemetryEventsSender;
private readonly receiver: ITelemetryReceiver;
private readonly taskMetricsService: ITaskMetricsService;
constructor(
config: SecurityTelemetryTaskConfig,
logger: Logger,
sender: ITelemetryEventsSender,
receiver: ITelemetryReceiver,
taskMetricsService: ITaskMetricsService
) {
this.config = config;
this.logger = newTelemetryLogger(logger.get('task'));
this.sender = sender;
this.receiver = receiver;
this.taskMetricsService = taskMetricsService;
}
public getLastExecutionTime = (
taskExecutionTime: string,
taskInstance: ConcreteTaskInstance
): string | undefined => {
return this.config.getLastExecutionTime
? this.config.getLastExecutionTime(
taskExecutionTime,
taskInstance.state?.lastExecutionTimestamp
)
: undefined;
};
public getTaskId = (): string => {
return `${this.config.type}:${this.config.version}`;
};
public register = (taskManager: TaskManagerSetupContract) => {
taskManager.registerTaskDefinitions({
[this.config.type]: {
title: this.config.title,
timeout: this.config.timeout,
stateSchemaByVersion,
createTaskRunner: ({ taskInstance }: { taskInstance: ConcreteTaskInstance }) => {
const state = taskInstance.state as LatestTaskStateSchema;
return {
run: async () => {
const taskExecutionTime = moment().utc().toISOString();
const executionPeriod = {
last: this.getLastExecutionTime(taskExecutionTime, taskInstance),
current: taskExecutionTime,
};
const hits = await this.runTask(taskInstance.id, executionPeriod);
const updatedState: LatestTaskStateSchema = {
lastExecutionTimestamp: taskExecutionTime,
runs: state.runs + 1,
hits,
};
return {
state: updatedState,
};
},
cancel: async () => {},
};
},
},
});
};
public start = async (taskManager: TaskManagerStartContract) => {
const taskId = this.getTaskId();
this.logger.debug('Attempting to schedule task', { taskId } as LogMeta);
try {
await taskManager.ensureScheduled({
id: taskId,
taskType: this.config.type,
scope: ['securitySolution'],
schedule: {
interval: this.config.interval,
},
state: emptyState,
params: { version: this.config.version },
});
} catch (error) {
this.logger.error('Error scheduling task', withErrorMessage(error));
}
};
public runTask = async (taskId: string, executionPeriod: TaskExecutionPeriod) => {
this.logger.debug('Attempting to run', { taskId } as LogMeta);
if (taskId !== this.getTaskId()) {
this.logger.info('outdated task', { taskId } as LogMeta);
return 0;
}
const isOptedIn = await this.sender.isTelemetryOptedIn();
if (!isOptedIn) {
this.logger.info('Telemetry is not opted-in', { taskId } as LogMeta);
return 0;
}
const isTelemetryServicesReachable = await this.sender.isTelemetryServicesReachable();
if (!isTelemetryServicesReachable) {
this.logger.info('Cannot reach telemetry services', { taskId } as LogMeta);
return 0;
}
this.logger.debug('Running task', { taskId } as LogMeta);
return this.config.runTask(
taskId,
this.logger,
this.receiver,
this.sender,
this.taskMetricsService,
executionPeriod
);
};
}