-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathtask.ts
198 lines (185 loc) · 7.78 KB
/
task.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
/*
* 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 { Logger, CoreSetup } from '@kbn/core/server';
import moment from 'moment';
import {
RunContext,
TaskManagerSetupContract,
TaskManagerStartContract,
} from '@kbn/task-manager-plugin/server';
import { getFailedAndUnrecognizedTasksPerDay } from './lib/get_telemetry_from_task_manager';
import { getTotalCountAggregations, getTotalCountInUse } from './lib/get_telemetry_from_kibana';
import {
getExecutionsPerDayCount,
getExecutionTimeoutsPerDayCount,
} from './lib/get_telemetry_from_event_log';
export const TELEMETRY_TASK_TYPE = 'alerting_telemetry';
export const TASK_ID = `Alerting-${TELEMETRY_TASK_TYPE}`;
export function initializeAlertingTelemetry(
logger: Logger,
core: CoreSetup,
taskManager: TaskManagerSetupContract,
kibanaIndex: string,
eventLogIndex: string
) {
registerAlertingTelemetryTask(logger, core, taskManager, kibanaIndex, eventLogIndex);
}
export function scheduleAlertingTelemetry(logger: Logger, taskManager?: TaskManagerStartContract) {
if (taskManager) {
scheduleTasks(logger, taskManager);
}
}
function registerAlertingTelemetryTask(
logger: Logger,
core: CoreSetup,
taskManager: TaskManagerSetupContract,
kibanaIndex: string,
eventLogIndex: string
) {
taskManager.registerTaskDefinitions({
[TELEMETRY_TASK_TYPE]: {
title: 'Alerting usage fetch task',
timeout: '5m',
createTaskRunner: telemetryTaskRunner(
logger,
core,
kibanaIndex,
eventLogIndex,
taskManager.index
),
},
});
}
async function scheduleTasks(logger: Logger, taskManager: TaskManagerStartContract) {
try {
await taskManager.ensureScheduled({
id: TASK_ID,
taskType: TELEMETRY_TASK_TYPE,
state: {},
params: {},
});
} catch (e) {
logger.debug(`Error scheduling task, received ${e.message}`);
}
}
export function telemetryTaskRunner(
logger: Logger,
core: CoreSetup,
kibanaIndex: string,
eventLogIndex: string,
taskManagerIndex: string
) {
return ({ taskInstance }: RunContext) => {
const { state } = taskInstance;
const getEsClient = () =>
core.getStartServices().then(
([
{
elasticsearch: { client },
},
]) => client.asInternalUser
);
return {
async run() {
const esClient = await getEsClient();
return Promise.all([
getTotalCountAggregations({ esClient, kibanaIndex, logger }),
getTotalCountInUse({ esClient, kibanaIndex, logger }),
getExecutionsPerDayCount({ esClient, eventLogIndex, logger }),
getExecutionTimeoutsPerDayCount({ esClient, eventLogIndex, logger }),
getFailedAndUnrecognizedTasksPerDay({ esClient, taskManagerIndex, logger }),
])
.then(
([
totalCountAggregations,
totalInUse,
dailyExecutionCounts,
dailyExecutionTimeoutCounts,
dailyFailedAndUnrecognizedTasks,
]) => {
const hasErrors =
totalCountAggregations.hasErrors ||
totalInUse.hasErrors ||
dailyExecutionCounts.hasErrors ||
dailyExecutionTimeoutCounts.hasErrors ||
dailyFailedAndUnrecognizedTasks.hasErrors;
const errorMessages = [
totalCountAggregations.errorMessage,
totalInUse.errorMessage,
dailyExecutionCounts.errorMessage,
dailyExecutionTimeoutCounts.errorMessage,
dailyFailedAndUnrecognizedTasks.errorMessage,
].filter((message) => message !== undefined);
return {
state: {
has_errors: hasErrors,
...(errorMessages.length > 0 && { error_messages: errorMessages }),
runs: (state.runs || 0) + 1,
count_total: totalCountAggregations.count_total,
count_by_type: totalCountAggregations.count_by_type,
throttle_time: totalCountAggregations.throttle_time,
schedule_time: totalCountAggregations.schedule_time,
throttle_time_number_s: totalCountAggregations.throttle_time_number_s,
schedule_time_number_s: totalCountAggregations.schedule_time_number_s,
connectors_per_alert: totalCountAggregations.connectors_per_alert,
count_active_by_type: totalInUse.countByType,
count_active_total: totalInUse.countTotal,
count_disabled_total: totalCountAggregations.count_total - totalInUse.countTotal,
count_rules_namespaces: totalInUse.countNamespaces,
count_rules_executions_per_day: dailyExecutionCounts.countTotalRuleExecutions,
count_rules_executions_by_type_per_day:
dailyExecutionCounts.countRuleExecutionsByType,
count_rules_executions_failured_per_day:
dailyExecutionCounts.countTotalFailedExecutions,
count_rules_executions_failured_by_reason_per_day:
dailyExecutionCounts.countFailedExecutionsByReason,
count_rules_executions_failured_by_reason_by_type_per_day:
dailyExecutionCounts.countFailedExecutionsByReasonByType,
count_rules_executions_timeouts_per_day:
dailyExecutionTimeoutCounts.countExecutionTimeouts,
count_rules_executions_timeouts_by_type_per_day:
dailyExecutionTimeoutCounts.countExecutionTimeoutsByType,
count_failed_and_unrecognized_rule_tasks_per_day:
dailyFailedAndUnrecognizedTasks.countFailedAndUnrecognizedTasks,
count_failed_and_unrecognized_rule_tasks_by_status_per_day:
dailyFailedAndUnrecognizedTasks.countFailedAndUnrecognizedTasksByStatus,
count_failed_and_unrecognized_rule_tasks_by_status_by_type_per_day:
dailyFailedAndUnrecognizedTasks.countFailedAndUnrecognizedTasksByStatusByType,
avg_execution_time_per_day: dailyExecutionCounts.avgExecutionTime,
avg_execution_time_by_type_per_day: dailyExecutionCounts.avgExecutionTimeByType,
avg_es_search_duration_per_day: dailyExecutionCounts.avgEsSearchDuration,
avg_es_search_duration_by_type_per_day:
dailyExecutionCounts.avgEsSearchDurationByType,
avg_total_search_duration_per_day: dailyExecutionCounts.avgTotalSearchDuration,
avg_total_search_duration_by_type_per_day:
dailyExecutionCounts.avgTotalSearchDurationByType,
percentile_num_generated_actions_per_day:
dailyExecutionCounts.generatedActionsPercentiles,
percentile_num_generated_actions_by_type_per_day:
dailyExecutionCounts.generatedActionsPercentilesByType,
percentile_num_alerts_per_day: dailyExecutionCounts.alertsPercentiles,
percentile_num_alerts_by_type_per_day:
dailyExecutionCounts.alertsPercentilesByType,
},
runAt: getNextMidnight(),
};
}
)
.catch((errMsg) => {
logger.warn(`Error executing alerting telemetry task: ${errMsg}`);
return {
state: {},
runAt: getNextMidnight(),
};
});
},
};
};
}
function getNextMidnight() {
return moment().add(1, 'd').startOf('d').toDate();
}