-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathindex.js
More file actions
708 lines (641 loc) · 20.1 KB
/
index.js
File metadata and controls
708 lines (641 loc) · 20.1 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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/**
* Copyright IBM Corp. 2015, 2025
* SPDX-License-Identifier: BUSL-1.1
*/
// @ts-check
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action, computed, set } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import localStorageProperty from 'nomad-ui/utils/properties/local-storage';
import { restartableTask, timeout } from 'ember-concurrency';
import Ember from 'ember';
// eslint-disable-next-line no-unused-vars
import JobModel from '../../models/job';
const JOB_LIST_THROTTLE = 5000;
const JOB_DETAILS_THROTTLE = 1000;
export default class JobsIndexController extends Controller {
@service router;
@service system;
@service store;
@service userSettings;
@service watchList;
@service notifications;
@tracked pageSize;
constructor() {
super(...arguments);
this.pageSize = this.userSettings.pageSize;
this.rawSearchText = this.searchText || '';
}
queryParams = ['cursorAt', 'pageSize', 'filter'];
isForbidden = false;
@tracked jobQueryIndex = 0;
@tracked jobAllocsQueryIndex = 0;
get tableColumns() {
return [
'name',
this.system.shouldShowNamespaces ? 'namespace' : null,
'status',
'type',
this.system.shouldShowNodepools ? 'node pool' : null, // TODO: implement on system service
'running allocations',
]
.filter((c) => !!c)
.map((c) => {
return {
label: c.charAt(0).toUpperCase() + c.slice(1),
width: c === 'running allocations' ? '200px' : undefined,
};
});
}
@tracked jobs = [];
@tracked jobIDs = [];
@tracked pendingJobs = null;
@tracked pendingJobIDs = null;
/**
* Trigger can either be the pointer event itself, or if the keyboard shorcut was used, the html element corresponding to the job.
* @param {JobModel} job
* @param {PointerEvent|HTMLElement} trigger
*/
@action
gotoJob(job, trigger) {
// Don't navigate if the user clicked on a link; this will happen with modifier keys like cmd/ctrl on the link itself
if (
trigger instanceof PointerEvent &&
/** @type {HTMLElement} */ (trigger.target).tagName === 'A'
) {
return;
}
this.router.transitionTo('jobs.job.index', job.idWithNamespace);
}
@action
goToRun() {
this.router.transitionTo('jobs.run');
}
// #region pagination
@tracked cursorAt;
@tracked nextToken; // route sets this when new data is fetched
/**
*
* @param {"prev"|"next"} page
*/
@action async handlePageChange(page) {
// reset indexes
this.jobQueryIndex = 0;
this.jobAllocsQueryIndex = 0;
if (page === 'prev') {
if (!this.cursorAt) {
return;
}
// Note (and TODO:) this isn't particularly efficient!
// We're making an extra full request to get the nextToken we need,
// but actually the results of that request are the reverse order, plus one job,
// of what we actually want to show on the page!
// I should investigate whether I can use the results of this query to
// overwrite this controller's jobIDs, leverage its index, and
// restart a blocking watchJobIDs here.
let prevPageToken = await this.loadPreviousPageToken();
// If there's no nextToken, we're at the "start" of our list and can drop the cursorAt
if (!prevPageToken.meta.nextToken) {
this.cursorAt = undefined;
} else {
// cursorAt should be the highest modifyIndex from the previous query.
// This will immediately fire the route model hook with the new cursorAt
this.cursorAt = prevPageToken
.sortBy('modifyIndex')
.get('lastObject').modifyIndex;
}
} else if (page === 'next') {
if (!this.nextToken) {
return;
}
this.cursorAt = this.nextToken;
} else if (page === 'first') {
this.cursorAt = undefined;
} else if (page === 'last') {
let prevPageToken = await this.loadPreviousPageToken({ last: true });
this.cursorAt = prevPageToken
.sortBy('modifyIndex')
.get('lastObject').modifyIndex;
}
}
@action handlePageSizeChange(size) {
this.pageSize = size;
}
get pendingJobIDDiff() {
return (
this.pendingJobIDs &&
JSON.stringify(
this.pendingJobIDs.map((j) => `${j.namespace}.${j.id}`)
) !== JSON.stringify(this.jobIDs.map((j) => `${j.namespace}.${j.id}`))
);
}
/**
* Manually, on click, update jobs from pendingJobs
* when live updates are disabled (via nomadLiveUpdateJobsIndex)
*/
@restartableTask *updateJobList() {
this.jobs = this.pendingJobs;
this.pendingJobs = null;
this.jobIDs = this.pendingJobIDs;
this.pendingJobIDs = null;
yield this.watchJobs.perform(
this.jobIDs,
Ember.testing ? 0 : JOB_DETAILS_THROTTLE
);
}
/**
* In case the user wants to specifically stop polling for new jobs
*/
@action pauseJobFetching() {
let notification = this.notifications.queue.find(
(n) => n.title === 'Error fetching jobs'
);
if (notification) {
notification.destroyMessage();
}
this.watchList.jobsIndexIDsController.abort();
this.watchList.jobsIndexDetailsController.abort();
this.watchJobIDs.cancelAll();
this.watchJobs.cancelAll();
}
@action restartJobList() {
this.showingCachedJobs = false;
let notification = this.notifications.queue.find(
(n) => n.title === 'Error fetching jobs'
);
if (notification) {
notification.destroyMessage();
}
this.watchList.jobsIndexIDsController.abort();
this.watchList.jobsIndexDetailsController.abort();
this.watchJobIDs.cancelAll();
this.watchJobs.cancelAll();
this.watchJobIDs.perform({}, JOB_LIST_THROTTLE);
this.watchJobs.perform(this.jobIDs, JOB_DETAILS_THROTTLE);
}
@localStorageProperty('nomadLiveUpdateJobsIndex', true) liveUpdatesEnabled;
// #endregion pagination
//#region querying
/**
*
* Let the user know that there was difficulty fetching jobs, but don't overload their screen with notifications.
* Set showingCachedJobs to tell the template to prompt them to extend timeouts
* @param {Error} e
*/
notifyFetchError(e) {
const firstError = e.errors?.objectAt(0);
this.notifications.add({
title: 'Error fetching jobs',
message: `The backend returned an error with status ${firstError.status} while fetching jobs`,
color: 'critical',
sticky: true,
preventDuplicates: true,
});
// Specific check for a proxy timeout error
if (
!this.showingCachedJobs &&
(firstError.status === '502' || firstError.status === '504')
) {
this.showingCachedJobs = true;
}
}
@tracked showingCachedJobs = false;
jobQuery(params) {
this.watchList.jobsIndexIDsController.abort();
this.watchList.jobsIndexIDsController = new AbortController();
return this.store
.query('job', params, {
adapterOptions: {
abortController: this.watchList.jobsIndexIDsController,
},
})
.then((jobs) => {
this.showingCachedJobs = false;
return jobs;
})
.catch((e) => {
if (e.name !== 'AbortError') {
console.log('error fetching job ids', e);
this.notifyFetchError(e);
}
if (this.jobs?.length) {
return this.jobs;
}
return;
});
}
jobAllocsQuery(params) {
this.watchList.jobsIndexDetailsController.abort();
this.watchList.jobsIndexDetailsController = new AbortController();
params.namespace = '*';
return this.store
.query('job', params, {
adapterOptions: {
method: 'POST',
abortController: this.watchList.jobsIndexDetailsController,
},
})
.catch((e) => {
if (e.name !== 'AbortError') {
console.log('error fetching job allocs', e);
this.notifyFetchError(e);
}
if (this.jobs?.length) {
return this.jobs;
}
return;
});
}
// Ask for the previous #page_size jobs, starting at the first job that's currently shown
// on our page, and the last one in our list should be the one we use for our
// subsequent nextToken.
async loadPreviousPageToken({ last = false } = {}) {
let next_token = +this.cursorAt + 1;
if (last) {
next_token = undefined;
}
let prevPageToken = await this.store.query(
'job',
{
next_token,
per_page: this.pageSize,
reverse: true,
},
{
adapterOptions: {
method: 'GET',
},
}
);
return prevPageToken;
}
@restartableTask *watchJobIDs(
params,
throttle = Ember.testing ? 0 : JOB_LIST_THROTTLE
) {
while (true) {
let currentParams = params;
currentParams.index = this.jobQueryIndex;
const newJobs = yield this.jobQuery(currentParams, {});
if (newJobs) {
if (newJobs.meta.index) {
this.jobQueryIndex = newJobs.meta.index;
}
if (newJobs.meta.nextToken) {
this.nextToken = newJobs.meta.nextToken;
} else {
this.nextToken = null;
}
const jobIDs = newJobs.map((job) => ({
id: job.plainId,
namespace: job.belongsTo('namespace').id(),
}));
const okayToJostle = this.liveUpdatesEnabled;
if (okayToJostle) {
this.jobIDs = jobIDs;
this.watchList.jobsIndexDetailsController.abort();
this.jobAllocsQueryIndex = 0;
this.watchList.jobsIndexDetailsController = new AbortController();
this.watchJobs.perform(jobIDs, throttle);
} else {
this.pendingJobIDs = jobIDs;
this.pendingJobs = newJobs;
}
if (Ember.testing) {
break;
}
yield timeout(throttle);
} else {
if (Ember.testing) {
break;
}
// This returns undefined on page change / cursorAt change, resulting from the aborting of the old query.
yield timeout(throttle);
this.watchJobs.perform(this.jobIDs, throttle);
continue;
}
if (Ember.testing) {
break;
}
}
}
// Called in 3 ways:
// 1. via the setupController of the jobs index route's model
// (which can happen both on initial load, and should the queryParams change)
// 2. via the watchJobIDs task seeing new jobIDs
// 3. via the user manually clicking to updateJobList()
@restartableTask *watchJobs(
jobIDs,
throttle = Ember.testing ? 0 : JOB_DETAILS_THROTTLE
) {
while (true) {
if (jobIDs && jobIDs.length > 0) {
let jobDetails = yield this.jobAllocsQuery({
jobs: jobIDs,
index: this.jobAllocsQueryIndex,
});
if (jobDetails) {
if (jobDetails.meta.index) {
this.jobAllocsQueryIndex = jobDetails.meta.index;
}
}
this.jobs = jobDetails;
} else {
// No jobs have returned, so clear the list
this.jobs = [];
}
yield timeout(throttle);
if (Ember.testing) {
break;
}
}
}
//#endregion querying
//#region filtering and searching
@tracked statusFacet = {
label: 'Status',
options: [
{
key: 'pending',
string: 'Status == pending',
checked: false,
},
{
key: 'running',
string: 'Status == running',
checked: false,
},
{
key: 'dead',
string: 'Status == dead',
checked: false,
},
],
};
@tracked typeFacet = {
label: 'Type',
options: [
{
key: 'batch',
string: 'Type == batch',
checked: false,
},
{
key: 'service',
string: 'Type == service',
checked: false,
},
{
key: 'system',
string: 'Type == system',
checked: false,
},
{
key: 'sysbatch',
string: 'Type == sysbatch',
checked: false,
},
],
};
@tracked nodePoolFacet = {
label: 'NodePool',
options: (this.model.nodePools || []).map((nodePool) => ({
key: nodePool.name,
string: `NodePool == "${nodePool.name}"`,
checked: false,
})),
filterable: true,
filter: '',
};
@tracked namespaceFacet = {
label: 'Namespace',
options: [
...(this.model.namespaces || []).map((ns) => ({
key: ns.name,
string: `Namespace == "${ns.name}"`,
checked: false,
})),
],
filterable: true,
filter: '',
};
@computed('namespaceFacet.{filter,options}')
get filteredNamespaceOptions() {
return this.namespaceFacet.options.filter((ns) =>
ns.key.toLowerCase().includes(this.namespaceFacet.filter.toLowerCase())
);
}
@computed('nodePoolFacet.{filter,options}')
get filteredNodePoolOptions() {
return this.nodePoolFacet.options.filter((np) =>
np.key.toLowerCase().includes(this.nodePoolFacet.filter.toLowerCase())
);
}
@tracked namespaceFilter = '';
get shownNamespaces() {
return this.namespaceFacet.options.filter((option) =>
option.label.toLowerCase().includes(this.namespaceFilter)
);
}
/**
* Pares down the list of namespaces
* @param {InputEvent & { target: HTMLInputElement }} event - The input event
*/
@action filterNamespaces(event) {
this.namespaceFilter = event.target.value.toLowerCase();
}
get filterFacets() {
let facets = [this.statusFacet, this.typeFacet];
if (this.system.shouldShowNodepools) {
facets.push(this.nodePoolFacet);
}
// Note: there is a timing problem with using system.shouldShowNamespaces here, and that's
// due to parseFilter() below depending on this and being called a single time from the route's
// setupController.
// The system service's shouldShowNamespaces is a getter, and therefore cannot be made to be async,
// and since we only want to parseFilter a single time, we can use a simpler check to establish whether
// we should show the namespace facet, rendering the whole "check checkboxes based on queryParams" logic quicker.
if ((this.model.namespaces || []).length > 1) {
facets.push(this.namespaceFacet);
}
return facets;
}
/**
* On page load, takes the ?filter queryParam, and extracts it into those
* properties used by the dropdown filter toggles, and the search text.
*/
parseFilter() {
let filterString = this.filter;
if (!filterString) {
return;
}
const filterParts = filterString.split(' and ');
let unmatchedFilters = [];
// For each of those splits, if it starts and ends with (), and if all entries within it have thes ame Propname and operator of ==, populate them into the appropriate dropdown
// If it doesnt start with and end with (), or if it does but not all entries are the same propname, or not all entries have == operators, populate them into the searchbox
filterParts.forEach((part) => {
let matched = false;
if (part.startsWith('(') && part.endsWith(')')) {
part = part.slice(1, -1); // trim the parens
// Check to see if the property name (first word) is one of the ones for which we have a dropdown
let propName = part.split(' ')[0];
if (this.filterFacets.find((facet) => facet.label === propName)) {
// Split along "or" and check that all parts have the same propName
let facetParts = part.split(' or ');
let allMatch = facetParts.every((facetPart) =>
facetPart.startsWith(propName)
);
let allEqualityOperators = facetParts.every((facetPart) =>
facetPart.includes('==')
);
if (allMatch && allEqualityOperators) {
// Set all the options in the dropdown to checked
this.filterFacets.forEach((group) => {
if (group.label === propName) {
group.options.forEach((option) => {
set(option, 'checked', facetParts.includes(option.string));
});
}
});
matched = true;
}
}
}
if (!matched) {
unmatchedFilters.push(part);
}
});
// Combine all unmatched filter parts into the searchText
this.searchText = unmatchedFilters.join(' and ');
this.rawSearchText = this.searchText;
}
@computed(
'filterFacets',
'nodePoolFacet.options.@each.checked',
'searchText',
'statusFacet.options.@each.checked',
'typeFacet.options.@each.checked',
'namespaceFacet.options.@each.checked'
)
get computedFilter() {
let parts = this.searchText ? [this.searchText] : [];
this.filterFacets.forEach((group) => {
let groupParts = [];
group.options.forEach((option) => {
if (option.checked) {
groupParts.push(option.string);
}
});
if (groupParts.length) {
parts.push(`(${groupParts.join(' or ')})`);
}
});
return parts.join(' and ');
}
@action
toggleOption(option) {
set(option, 'checked', !option.checked);
this.updateFilter();
}
@action
updateFilter() {
this.cursorAt = null;
this.filter = this.computedFilter;
}
@tracked filter = '';
@tracked searchText = '';
@tracked rawSearchText = '';
@action resetFilters() {
this.searchText = '';
this.rawSearchText = '';
this.filterFacets.forEach((group) => {
group.options.forEach((option) => {
set(option, 'checked', false);
});
});
this.namespaceFacet?.options.forEach((option) => {
set(option, 'checked', false);
});
this.updateFilter();
}
/**
* Updates the filter based on the input, distinguishing between simple job names and filter expressions.
* A simple check for operators with surrounding spaces is used to identify filter expressions.
*
* @param {string} newFilter
*/
@action
updateSearchText(newFilter) {
if (!newFilter.trim()) {
this.searchText = '';
return;
}
newFilter = newFilter.trim();
const operators = [
'==',
'!=',
'contains',
'not contains',
'is empty',
'is not empty',
'matches',
'not matches',
'in',
'not in',
];
// Check for any operator surrounded by spaces
let isFilterExpression = operators.some((op) =>
newFilter.includes(` ${op}`)
);
if (isFilterExpression) {
this.searchText = newFilter;
} else {
// If it's a string without a filter operator, assume the user is trying to look up a job name
this.searchText = `Name matches "(?i)${newFilter}"`;
}
}
get humanizedFilterError() {
let baseString = `No jobs match your current filter selection: ${this.filter}.`;
if (this.model.error?.humanized) {
return `${baseString} ${this.model.error.humanized}`;
}
return baseString;
}
@action correctFilterKey({ incorrectKey, correctKey }) {
this.searchText = this.searchText.replace(incorrectKey, correctKey);
this.rawSearchText = this.searchText;
this.updateFilter();
}
@action suggestFilter({ example }) {
this.searchText = example;
this.rawSearchText = this.searchText;
this.updateFilter();
}
// A list of combinatorial filters to show off filter expressions
// Make use of our various operators, and our various known keys
@computed('filter')
get exampleFilter() {
let examples = [
'(Status == dead) and (Type != batch)',
'(Version != 0) and (Namespace == default)',
'(StatusDescription not contains "progress deadline")',
'(Region != global) and (NodePool is not empty)',
'(Namespace != myNamespace) and (Status != running)',
'NodePool is not empty',
'(dc1 in Datacenters) or (dc2 in Datacenters)',
];
// In test environments, pick deterministically so snapshots are stable.
// In production, keep it random so users discover different filter syntax.
if (Ember.testing) {
const filter = this.filter || '';
let hash = 0;
for (let i = 0; i < filter.length; i++) {
hash = (hash * 31 + filter.charCodeAt(i)) | 0;
}
return examples[Math.abs(hash) % examples.length];
}
return examples[Math.floor(Math.random() * examples.length)];
}
//#endregion filtering and searching
}