-
Notifications
You must be signed in to change notification settings - Fork 8k
/
utils.js
447 lines (415 loc) · 13.9 KB
/
utils.js
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
439
440
441
442
443
444
445
446
447
/*
* 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 { each } from 'lodash';
import { i18n } from '@kbn/i18n';
import { mlJobService } from '../../../services/job_service';
import {
getToastNotificationService,
toastNotificationServiceProvider,
} from '../../../services/toast_notification_service';
import { getToastNotifications } from '../../../util/dependency_cache';
import { ml } from '../../../services/ml_api_service';
import { stringMatch } from '../../../util/string_utils';
import { JOB_STATE, DATAFEED_STATE } from '../../../../../common/constants/states';
import { JOB_ACTION } from '../../../../../common/constants/job_actions';
import { parseInterval } from '../../../../../common/util/parse_interval';
import { mlCalendarService } from '../../../services/calendar_service';
import { isPopulatedObject } from '../../../../../common/util/object_utils';
export function loadFullJob(jobId) {
return new Promise((resolve, reject) => {
ml.jobs
.jobs([jobId])
.then((jobs) => {
if (jobs.length) {
resolve(jobs[0]);
} else {
throw new Error(`Could not find job ${jobId}`);
}
})
.catch((error) => {
reject(error);
});
});
}
export function loadJobForCloning(jobId) {
return new Promise((resolve, reject) => {
ml.jobs
.jobForCloning(jobId)
.then((resp) => {
if (resp) {
resolve(resp);
} else {
throw new Error(`Could not find job ${jobId}`);
}
})
.catch((error) => {
reject(error);
});
});
}
export function isStartable(jobs) {
return jobs.some(
(j) => j.datafeedState === DATAFEED_STATE.STOPPED && j.jobState !== JOB_STATE.CLOSING
);
}
export function isStoppable(jobs) {
return jobs.some(
(j) => j.datafeedState === DATAFEED_STATE.STARTED || j.datafeedState === DATAFEED_STATE.STARTING
);
}
export function isClosable(jobs) {
return jobs.some(
(j) =>
j.datafeedState === DATAFEED_STATE.STOPPED &&
j.jobState !== JOB_STATE.CLOSED &&
j.jobState !== JOB_STATE.CLOSING
);
}
export function isResettable(jobs) {
return jobs.some((j) => j.jobState === JOB_STATE.CLOSED);
}
export function forceStartDatafeeds(jobs, start, end, finish = () => {}) {
const datafeedIds = jobs.filter((j) => j.hasDatafeed).map((j) => j.datafeedId);
mlJobService
.forceStartDatafeeds(datafeedIds, start, end)
.then((resp) => {
showResults(resp, DATAFEED_STATE.STARTED);
finish();
})
.catch((error) => {
const toastNotifications = getToastNotifications();
toastNotifications.addDanger(
i18n.translate('xpack.ml.jobsList.startJobErrorMessage', {
defaultMessage: 'Jobs failed to start',
}),
error
);
finish();
});
}
export function stopDatafeeds(jobs, finish = () => {}) {
const datafeedIds = jobs.filter((j) => j.hasDatafeed).map((j) => j.datafeedId);
mlJobService
.stopDatafeeds(datafeedIds)
.then((resp) => {
showResults(resp, DATAFEED_STATE.STOPPED);
finish();
})
.catch((error) => {
const toastNotifications = getToastNotifications();
toastNotifications.addDanger(
i18n.translate('xpack.ml.jobsList.stopJobErrorMessage', {
defaultMessage: 'Jobs failed to stop',
}),
error
);
finish();
});
}
function showResults(resp, action) {
const successes = [];
const failures = [];
for (const d in resp) {
if (
resp[d][action] === true ||
(resp[d][action] === false &&
resp[d].error.statusCode === 409 &&
action === DATAFEED_STATE.STARTED)
) {
successes.push(d);
} else {
failures.push({
id: d,
result: resp[d],
});
}
}
let actionText = '';
let actionTextPT = '';
if (action === DATAFEED_STATE.STARTED) {
actionText = i18n.translate('xpack.ml.jobsList.startActionStatusText', {
defaultMessage: 'start',
});
actionTextPT = i18n.translate('xpack.ml.jobsList.startedActionStatusText', {
defaultMessage: 'started',
});
} else if (action === DATAFEED_STATE.STOPPED) {
actionText = i18n.translate('xpack.ml.jobsList.stopActionStatusText', {
defaultMessage: 'stop',
});
actionTextPT = i18n.translate('xpack.ml.jobsList.stoppedActionStatusText', {
defaultMessage: 'stopped',
});
} else if (action === DATAFEED_STATE.DELETED) {
actionText = i18n.translate('xpack.ml.jobsList.deleteActionStatusText', {
defaultMessage: 'delete',
});
actionTextPT = i18n.translate('xpack.ml.jobsList.deletedActionStatusText', {
defaultMessage: 'deleted',
});
} else if (action === JOB_STATE.CLOSED) {
actionText = i18n.translate('xpack.ml.jobsList.closeActionStatusText', {
defaultMessage: 'close',
});
actionTextPT = i18n.translate('xpack.ml.jobsList.closedActionStatusText', {
defaultMessage: 'closed',
});
} else if (action === JOB_ACTION.RESET) {
actionText = i18n.translate('xpack.ml.jobsList.resetActionStatusText', {
defaultMessage: 'reset',
});
actionTextPT = i18n.translate('xpack.ml.jobsList.resetActionStatusText', {
defaultMessage: 'reset',
});
}
const toastNotifications = getToastNotifications();
toastNotifications.addSuccess(
i18n.translate('xpack.ml.jobsList.actionExecuteSuccessfullyNotificationMessage', {
defaultMessage:
'{successesJobsCount, plural, one{{successJob}} other{# jobs}} {actionTextPT} successfully',
values: {
successesJobsCount: successes.length,
successJob: successes[0],
actionTextPT,
},
})
);
if (failures.length > 0) {
failures.forEach((f) => {
const toastNotificationService = toastNotificationServiceProvider(toastNotifications);
toastNotificationService.displayErrorToast(
f.result.error,
i18n.translate('xpack.ml.jobsList.actionFailedNotificationMessage', {
defaultMessage: '{failureId} failed to {actionText}',
values: {
failureId: f.id,
actionText,
},
})
);
});
}
}
export async function cloneJob(jobId) {
try {
const [{ job: cloneableJob, datafeed }, originalJob] = await Promise.all([
loadJobForCloning(jobId),
loadFullJob(jobId, false),
]);
if (cloneableJob !== undefined && originalJob?.custom_settings?.created_by !== undefined) {
// if the job is from a wizards, i.e. contains a created_by property
// use tempJobCloningObjects to temporarily store the job
mlJobService.tempJobCloningObjects.createdBy = originalJob?.custom_settings?.created_by;
mlJobService.tempJobCloningObjects.job = cloneableJob;
if (
originalJob.data_counts.earliest_record_timestamp !== undefined &&
originalJob.data_counts.latest_record_timestamp !== undefined &&
originalJob.data_counts.latest_bucket_timestamp !== undefined
) {
// if the job has run before, use the earliest and latest record timestamp
// as the cloned job's time range
let start = originalJob.data_counts.earliest_record_timestamp;
let end = originalJob.data_counts.latest_record_timestamp;
if (originalJob.datafeed_config.aggregations !== undefined) {
// if the datafeed uses aggregations the earliest and latest record timestamps may not be the same
// as the start and end of the data in the index.
const bucketSpanMs = parseInterval(
originalJob.analysis_config.bucket_span
).asMilliseconds();
// round down to the start of the nearest bucket
start =
Math.floor(originalJob.data_counts.earliest_record_timestamp / bucketSpanMs) *
bucketSpanMs;
// use latest_bucket_timestamp and add two bucket spans minus one ms
end = originalJob.data_counts.latest_bucket_timestamp + bucketSpanMs * 2 - 1;
}
mlJobService.tempJobCloningObjects.start = start;
mlJobService.tempJobCloningObjects.end = end;
}
} else {
// otherwise use the tempJobCloningObjects
mlJobService.tempJobCloningObjects.job = cloneableJob;
// resets the createdBy field in case it still retains previous settings
mlJobService.tempJobCloningObjects.createdBy = undefined;
}
if (datafeed !== undefined) {
mlJobService.tempJobCloningObjects.datafeed = datafeed;
}
if (originalJob.calendars) {
mlJobService.tempJobCloningObjects.calendars = await mlCalendarService.fetchCalendarsByIds(
originalJob.calendars
);
}
window.location.href = '#/jobs/new_job';
} catch (error) {
getToastNotificationService().displayErrorToast(
error,
i18n.translate('xpack.ml.jobsList.cloneJobErrorMessage', {
defaultMessage: 'Could not clone {jobId}. Job could not be found',
values: { jobId },
})
);
}
}
export function closeJobs(jobs, finish = () => {}) {
const jobIds = jobs.map((j) => j.id);
mlJobService
.closeJobs(jobIds)
.then((resp) => {
showResults(resp, JOB_STATE.CLOSED);
finish();
})
.catch((error) => {
getToastNotificationService().displayErrorToast(
error,
i18n.translate('xpack.ml.jobsList.closeJobErrorMessage', {
defaultMessage: 'Jobs failed to close',
})
);
finish();
});
}
export function resetJobs(jobIds, finish = () => {}) {
mlJobService
.resetJobs(jobIds)
.then((resp) => {
showResults(resp, JOB_ACTION.RESET);
finish();
})
.catch((error) => {
getToastNotificationService().displayErrorToast(
error,
i18n.translate('xpack.ml.jobsList.resetJobErrorMessage', {
defaultMessage: 'Jobs failed to reset',
})
);
finish();
});
}
export function deleteJobs(jobs, finish = () => {}) {
const jobIds = jobs.map((j) => j.id);
mlJobService
.deleteJobs(jobIds)
.then((resp) => {
showResults(resp, JOB_STATE.DELETED);
finish();
})
.catch((error) => {
getToastNotificationService().displayErrorToast(
error,
i18n.translate('xpack.ml.jobsList.deleteJobErrorMessage', {
defaultMessage: 'Jobs failed to delete',
})
);
finish();
});
}
export function filterJobs(jobs, clauses) {
if (clauses.length === 0) {
return jobs;
}
// keep count of the number of matches we make as we're looping over the clauses
// we only want to return jobs which match all clauses, i.e. each search term is ANDed
const matches = jobs.reduce((p, c) => {
p[c.id] = {
job: c,
count: 0,
};
return p;
}, {});
clauses.forEach((c) => {
// the search term could be negated with a minus, e.g. -bananas
const bool = c.match === 'must';
let js = [];
if (c.type === 'term') {
// filter term based clauses, e.g. bananas
// match on id, description and memory_status
// if the term has been negated, AND the matches
if (bool === true) {
js = jobs.filter(
(job) =>
stringMatch(job.id, c.value) === bool ||
stringMatch(job.description, c.value) === bool ||
stringMatch(job.memory_status, c.value) === bool
);
} else {
js = jobs.filter(
(job) =>
stringMatch(job.id, c.value) === bool &&
stringMatch(job.description, c.value) === bool &&
stringMatch(job.memory_status, c.value) === bool
);
}
} else {
// filter other clauses, i.e. the toggle group buttons
if (Array.isArray(c.value)) {
// if it's an array of job ids
if (c.field === 'id') {
js = jobs.filter((job) => c.value.indexOf(jobProperty(job, c.field)) >= 0);
} else if (c.field === 'groups') {
// the groups value is an array of group ids
js = jobs.filter((job) => jobProperty(job, c.field).some((g) => c.value.indexOf(g) >= 0));
} else if (c.field === 'job_tags') {
js = jobTagFilter(jobs, c.value);
}
} else {
if (c.field === 'job_tags') {
js = js = jobTagFilter(jobs, [c.value]);
} else {
js = jobs.filter((job) => jobProperty(job, c.field) === c.value);
}
}
}
js.forEach((j) => matches[j.id].count++);
});
// loop through the matches and return only those jobs which have match all the clauses
const filteredJobs = [];
each(matches, (m) => {
if (m.count >= clauses.length) {
filteredJobs.push(m.job);
}
});
return filteredJobs;
}
function jobProperty(job, prop) {
const propMap = {
job_state: 'jobState',
datafeed_state: 'datafeedState',
groups: 'groups',
id: 'id',
job_tags: 'jobTags',
};
return job[propMap[prop]];
}
function jobTagFilter(jobs, value) {
return jobs.filter((job) => {
const tags = jobProperty(job, 'job_tags');
return Object.entries(tags)
.map((t) => t.join(':'))
.find((t) => value.some((t1) => t1 === t));
});
}
// check to see if a job has been stored in mlJobService.tempJobCloningObjects
// if it has, return an object with the minimum properties needed for the
// start datafeed modal.
export function checkForAutoStartDatafeed() {
const job = mlJobService.tempJobCloningObjects.job;
const datafeed = mlJobService.tempJobCloningObjects.datafeed;
if (job !== undefined) {
mlJobService.tempJobCloningObjects.job = undefined;
mlJobService.tempJobCloningObjects.datafeed = undefined;
mlJobService.tempJobCloningObjects.createdBy = undefined;
const hasDatafeed = isPopulatedObject(datafeed);
const datafeedId = hasDatafeed ? datafeed.datafeed_id : '';
return {
id: job.job_id,
hasDatafeed,
latestTimestampSortValue: 0,
datafeedId,
};
}
}