-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathstatus_check.ts
300 lines (282 loc) · 9.71 KB
/
status_check.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { schema } from '@kbn/config-schema';
import { isRight } from 'fp-ts/lib/Either';
import { ThrowReporter } from 'io-ts/lib/ThrowReporter';
import { i18n } from '@kbn/i18n';
import { AlertExecutorOptions } from '../../../../alerts/server';
import { UptimeAlertTypeFactory } from './types';
import { GetMonitorStatusResult } from '../requests';
import { esKuery, IIndexPattern } from '../../../../../../src/plugins/data/server';
import { JsonObject } from '../../../../../../src/plugins/kibana_utils/common';
import {
StatusCheckParamsType,
StatusCheckParams,
StatusCheckFilters,
AtomicStatusCheckParamsType,
} from '../../../common/runtime_types';
import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants';
import { savedObjectsAdapter } from '../saved_objects';
import { updateState } from './common';
import { commonStateTranslations } from './translations';
import { stringifyKueries, combineFiltersAndUserSearch } from '../../../common/lib';
const { MONITOR_STATUS } = ACTION_GROUP_DEFINITIONS;
/**
* Reduce a composite-key array of status results to a set of unique IDs.
* @param items to reduce
*/
export const uniqueMonitorIds = (items: GetMonitorStatusResult[]): Set<string> =>
items.reduce((acc, { monitor_id }) => {
acc.add(monitor_id);
return acc;
}, new Set<string>());
/**
* Generates a message to include in contexts of alerts.
* @param monitors the list of monitors to include in the message
* @param max the maximum number of items the summary should contain
*/
export const contextMessage = (monitorIds: string[], max: number): string => {
const MIN = 2;
if (max < MIN) throw new Error(`Maximum value must be greater than ${MIN}, received ${max}.`);
// generate the message
let message;
if (monitorIds.length === 1) {
message = i18n.translate('xpack.uptime.alerts.message.singularTitle', {
defaultMessage: 'Down monitor: ',
});
} else if (monitorIds.length) {
message = i18n.translate('xpack.uptime.alerts.message.multipleTitle', {
defaultMessage: 'Down monitors: ',
});
}
// this shouldn't happen because the function should only be called
// when > 0 monitors are down
else {
message = i18n.translate('xpack.uptime.alerts.message.emptyTitle', {
defaultMessage: 'No down monitor IDs received',
});
}
for (let i = 0; i < monitorIds.length; i++) {
const id = monitorIds[i];
if (i === max) {
return (
message +
i18n.translate('xpack.uptime.alerts.message.overflowBody', {
defaultMessage: `... and {overflowCount} other monitors`,
values: {
overflowCount: monitorIds.length - i,
},
})
);
} else if (i === 0) {
message = message + id;
} else {
message = message + `, ${id}`;
}
}
return message;
};
/**
* Creates an exhaustive list of all the down monitors.
* @param list all the monitors that are down
* @param sizeLimit the max monitors, we shouldn't allow an arbitrarily long string
*/
export const fullListByIdAndLocation = (
list: GetMonitorStatusResult[],
sizeLimit: number = 1000
) => {
return (
list
// sort by id, then location
.sort((a, b) => {
if (a.monitor_id > b.monitor_id) {
return 1;
} else if (a.monitor_id < b.monitor_id) {
return -1;
} else if (a.location > b.location) {
return 1;
}
return -1;
})
.slice(0, sizeLimit)
.reduce(
(cur, { monitor_id: id, location }) =>
cur + `${id} from ${location ?? 'Unnamed location'}; `,
''
) +
(sizeLimit < list.length
? i18n.translate('xpack.uptime.alerts.message.fullListOverflow', {
defaultMessage: '...and {overflowCount} other {pluralizedMonitor}',
values: {
pluralizedMonitor:
list.length - sizeLimit === 1 ? 'monitor/location' : 'monitors/locations',
overflowCount: list.length - sizeLimit,
},
})
: '')
);
};
// Right now the maximum number of monitors shown in the message is hardcoded here.
// we might want to make this a parameter in the future
const DEFAULT_MAX_MESSAGE_ROWS = 3;
export const hasFilters = (filters?: StatusCheckFilters) => {
if (!filters) return false;
for (const list of Object.values(filters)) {
if (list.length > 0) {
return true;
}
}
return false;
};
export const genFilterString = async (
getIndexPattern: () => Promise<IIndexPattern | undefined>,
filters?: StatusCheckFilters,
search?: string
): Promise<JsonObject | undefined> => {
const filtersExist = hasFilters(filters);
if (!filtersExist && !search) return undefined;
let filterString: string | undefined;
if (filtersExist) {
filterString = stringifyKueries(new Map(Object.entries(filters ?? {})));
}
let combinedString: string | undefined;
if (filterString && search) {
combinedString = combineFiltersAndUserSearch(filterString, search);
} else if (filterString) {
combinedString = filterString;
} else if (search) {
combinedString = search;
}
return esKuery.toElasticsearchQuery(
esKuery.fromKueryExpression(combinedString ?? ''),
await getIndexPattern()
);
};
export const statusCheckAlertFactory: UptimeAlertTypeFactory = (_server, libs) => ({
id: 'xpack.uptime.alerts.monitorStatus',
name: i18n.translate('xpack.uptime.alerts.monitorStatus', {
defaultMessage: 'Uptime monitor status',
}),
validate: {
params: schema.object({
filters: schema.maybe(
schema.oneOf([
schema.object({
'monitor.type': schema.maybe(schema.arrayOf(schema.string())),
'observer.geo.name': schema.maybe(schema.arrayOf(schema.string())),
tags: schema.maybe(schema.arrayOf(schema.string())),
'url.port': schema.maybe(schema.arrayOf(schema.string())),
}),
schema.string(),
])
),
locations: schema.maybe(schema.arrayOf(schema.string())),
numTimes: schema.number(),
search: schema.maybe(schema.string()),
timerangeCount: schema.maybe(schema.number()),
timerangeUnit: schema.maybe(schema.string()),
timerange: schema.maybe(
schema.object({
from: schema.string(),
to: schema.string(),
})
),
}),
},
defaultActionGroupId: MONITOR_STATUS.id,
actionGroups: [
{
id: MONITOR_STATUS.id,
name: MONITOR_STATUS.name,
},
],
actionVariables: {
context: [
{
name: 'message',
description: i18n.translate(
'xpack.uptime.alerts.monitorStatus.actionVariables.context.message.description',
{
defaultMessage: 'A generated message summarizing the currently down monitors',
}
),
},
{
name: 'downMonitorsWithGeo',
description: i18n.translate(
'xpack.uptime.alerts.monitorStatus.actionVariables.context.downMonitorsWithGeo.description',
{
defaultMessage:
'A generated summary that shows some or all of the monitors detected as "down" by the alert',
}
),
},
],
state: [...commonStateTranslations],
},
producer: 'uptime',
async executor(options: AlertExecutorOptions) {
const { params: rawParams } = options;
const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings(
options.services.savedObjectsClient
);
const atomicDecoded = AtomicStatusCheckParamsType.decode(rawParams);
const decoded = StatusCheckParamsType.decode(rawParams);
let params: StatusCheckParams;
if (isRight(atomicDecoded)) {
const { filters, search, numTimes, timerangeCount, timerangeUnit } = atomicDecoded.right;
const timerange = { from: `now-${String(timerangeCount) + timerangeUnit}`, to: 'now' };
const filterString = JSON.stringify(
await genFilterString(
() =>
libs.requests.getIndexPattern({
callES: options.services.callCluster,
dynamicSettings,
}),
filters,
search
)
);
params = {
timerange,
numTimes,
locations: [],
filters: filterString,
};
} else if (isRight(decoded)) {
params = decoded.right;
} else {
ThrowReporter.report(decoded);
return {
error: 'Alert param types do not conform to required shape.',
};
}
/* This is called `monitorsByLocation` but it's really
* monitors by location by status. The query we run to generate this
* filters on the status field, so effectively there should be one and only one
* status represented in the result set. */
const monitorsByLocation = await libs.requests.getMonitorStatus({
callES: options.services.callCluster,
dynamicSettings,
...params,
});
// if no monitors are down for our query, we don't need to trigger an alert
if (monitorsByLocation.length) {
const uniqueIds = uniqueMonitorIds(monitorsByLocation);
const alertInstance = options.services.alertInstanceFactory(MONITOR_STATUS.id);
alertInstance.replaceState({
...options.state,
monitors: monitorsByLocation,
...updateState(options.state, true),
});
alertInstance.scheduleActions(MONITOR_STATUS.id, {
message: contextMessage(Array.from(uniqueIds.keys()), DEFAULT_MAX_MESSAGE_ROWS),
downMonitorsWithGeo: fullListByIdAndLocation(monitorsByLocation),
});
}
return updateState(options.state, monitorsByLocation.length > 0);
},
});