-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathconfig.js
991 lines (820 loc) · 28.6 KB
/
config.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
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
import Ember from 'ember';
import Response from 'ember-cli-mirage/response';
import { HOSTS } from './common';
import { logFrames, logEncode } from './data/logs';
import { generateDiff } from './factories/job-version';
import { generateTaskGroupFailures } from './factories/evaluation';
import { copy } from 'ember-copy';
import formatHost from 'nomad-ui/utils/format-host';
import faker from 'nomad-ui/mirage/faker';
export function findLeader(schema) {
const agent = schema.agents.first();
return formatHost(agent.member.Address, agent.member.Tags.port);
}
export function filesForPath(allocFiles, filterPath) {
return allocFiles.where(
(file) =>
(!filterPath || file.path.startsWith(filterPath)) &&
file.path.length > filterPath.length &&
!file.path.substr(filterPath.length + 1).includes('/')
);
}
export default function () {
this.timing = 0; // delay for each request, automatically set to 0 during testing
this.logging = window.location.search.includes('mirage-logging=true');
this.namespace = 'v1';
this.trackRequests = Ember.testing;
const nomadIndices = {}; // used for tracking blocking queries
const server = this;
const withBlockingSupport = function (fn) {
return function (schema, request) {
// Get the original response
let { url } = request;
url = url.replace(/index=\d+[&;]?/, '');
const response = fn.apply(this, arguments);
// Get and increment the appropriate index
nomadIndices[url] || (nomadIndices[url] = 2);
const index = nomadIndices[url];
nomadIndices[url]++;
// Annotate the response with the index
if (response instanceof Response) {
response.headers['x-nomad-index'] = index;
return response;
}
return new Response(200, { 'x-nomad-index': index }, response);
};
};
this.get(
'/jobs',
withBlockingSupport(function ({ jobs }, { queryParams }) {
const json = this.serialize(jobs.all());
const namespace = queryParams.namespace || 'default';
return json
.filter((job) => {
if (namespace === '*') return true;
return namespace === 'default'
? !job.NamespaceID || job.NamespaceID === namespace
: job.NamespaceID === namespace;
})
.map((job) => filterKeys(job, 'TaskGroups', 'NamespaceID'));
})
);
this.post('/jobs', function (schema, req) {
const body = JSON.parse(req.requestBody);
if (!body.Job)
return new Response(
400,
{},
'Job is a required field on the request payload'
);
return okEmpty();
});
this.post('/jobs/parse', function (schema, req) {
const body = JSON.parse(req.requestBody);
if (!body.JobHCL)
return new Response(
400,
{},
'JobHCL is a required field on the request payload'
);
if (!body.Canonicalize)
return new Response(400, {}, 'Expected Canonicalize to be true');
// Parse the name out of the first real line of HCL to match IDs in the new job record
// Regex expectation:
// in: job "job-name" {
// out: job-name
const nameFromHCLBlock = /.+?"(.+?)"/;
const jobName = body.JobHCL.trim()
.split('\n')[0]
.match(nameFromHCLBlock)[1];
const job = server.create('job', { id: jobName });
return new Response(200, {}, this.serialize(job));
});
this.post('/job/:id/plan', function (schema, req) {
const body = JSON.parse(req.requestBody);
if (!body.Job)
return new Response(
400,
{},
'Job is a required field on the request payload'
);
if (!body.Diff) return new Response(400, {}, 'Expected Diff to be true');
const FailedTGAllocs =
body.Job.Unschedulable && generateFailedTGAllocs(body.Job);
return new Response(
200,
{},
JSON.stringify({ FailedTGAllocs, Diff: generateDiff(req.params.id) })
);
});
this.get(
'/job/:id',
withBlockingSupport(function ({ jobs }, { params, queryParams }) {
const job = jobs.all().models.find((job) => {
const jobIsDefault = !job.namespaceId || job.namespaceId === 'default';
const qpIsDefault =
!queryParams.namespace || queryParams.namespace === 'default';
return (
job.id === params.id &&
(job.namespaceId === queryParams.namespace ||
(jobIsDefault && qpIsDefault))
);
});
return job ? this.serialize(job) : new Response(404, {}, null);
})
);
this.post('/job/:id', function (schema, req) {
const body = JSON.parse(req.requestBody);
if (!body.Job)
return new Response(
400,
{},
'Job is a required field on the request payload'
);
return okEmpty();
});
this.get(
'/job/:id/summary',
withBlockingSupport(function ({ jobSummaries }, { params }) {
return this.serialize(jobSummaries.findBy({ jobId: params.id }));
})
);
this.get('/job/:id/allocations', function ({ allocations }, { params }) {
return this.serialize(allocations.where({ jobId: params.id }));
});
this.get('/job/:id/versions', function ({ jobVersions }, { params }) {
return this.serialize(jobVersions.where({ jobId: params.id }));
});
this.get('/job/:id/deployments', function ({ deployments }, { params }) {
return this.serialize(deployments.where({ jobId: params.id }));
});
this.get('/job/:id/deployment', function ({ deployments }, { params }) {
const deployment = deployments.where({ jobId: params.id }).models[0];
return deployment
? this.serialize(deployment)
: new Response(200, {}, 'null');
});
this.get(
'/job/:id/scale',
withBlockingSupport(function ({ jobScales }, { params }) {
const obj = jobScales.findBy({ jobId: params.id });
return this.serialize(jobScales.findBy({ jobId: params.id }));
})
);
this.post('/job/:id/periodic/force', function (schema, { params }) {
// Create the child job
const parent = schema.jobs.find(params.id);
// Use the server instead of the schema to leverage the job factory
server.create('job', 'periodicChild', {
parentId: parent.id,
namespaceId: parent.namespaceId,
namespace: parent.namespace,
createAllocations: parent.createAllocations,
});
return okEmpty();
});
this.post('/job/:id/dispatch', function (schema, { params }) {
// Create the child job
const parent = schema.jobs.find(params.id);
// Use the server instead of the schema to leverage the job factory
let dispatched = server.create('job', 'parameterizedChild', {
parentId: parent.id,
namespaceId: parent.namespaceId,
namespace: parent.namespace,
createAllocations: parent.createAllocations,
});
return new Response(
200,
{},
JSON.stringify({
DispatchedJobID: dispatched.id,
})
);
});
this.post('/job/:id/revert', function ({ jobs }, { requestBody }) {
const { JobID, JobVersion } = JSON.parse(requestBody);
const job = jobs.find(JobID);
job.version = JobVersion;
job.save();
return okEmpty();
});
this.post('/job/:id/scale', function ({ jobs }, { params }) {
return this.serialize(jobs.find(params.id));
});
this.delete('/job/:id', function (schema, { params }) {
const job = schema.jobs.find(params.id);
job.update({ status: 'dead' });
return new Response(204, {}, '');
});
this.get('/deployment/:id');
this.post('/deployment/fail/:id', function () {
return new Response(204, {}, '');
});
this.post('/deployment/promote/:id', function () {
return new Response(204, {}, '');
});
this.get('/job/:id/evaluations', function ({ evaluations }, { params }) {
return this.serialize(evaluations.where({ jobId: params.id }));
});
this.get('/evaluations');
this.get('/evaluation/:id', function ({ evaluations }, { params }) {
return evaluations.find(params.id);
});
this.get('/deployment/allocations/:id', function (schema, { params }) {
const job = schema.jobs.find(schema.deployments.find(params.id).jobId);
const allocations = schema.allocations.where({ jobId: job.id });
return this.serialize(allocations.slice(0, 3));
});
this.get('/nodes', function ({ nodes }, req) {
// authorize user permissions
const token = server.db.tokens.findBy({
secretId: req.requestHeaders['X-Nomad-Token'],
});
if (token) {
const { policyIds } = token;
const policies = server.db.policies.find(policyIds);
const hasReadPolicy = policies.find(
(p) =>
p.rulesJSON.Node?.Policy === 'read' ||
p.rulesJSON.Node?.Policy === 'write'
);
if (hasReadPolicy) {
const json = this.serialize(nodes.all());
return json;
}
return new Response(403, {}, 'Permissions have not be set-up.');
}
// TODO: Think about policy handling in Mirage set-up
return this.serialize(nodes.all());
});
this.get('/node/:id');
this.get('/node/:id/allocations', function ({ allocations }, { params }) {
return this.serialize(allocations.where({ nodeId: params.id }));
});
this.post(
'/node/:id/eligibility',
function ({ nodes }, { params, requestBody }) {
const body = JSON.parse(requestBody);
const node = nodes.find(params.id);
node.update({ schedulingEligibility: body.Elibility === 'eligible' });
return this.serialize(node);
}
);
this.post('/node/:id/drain', function ({ nodes }, { params }) {
return this.serialize(nodes.find(params.id));
});
this.get('/allocations');
this.get('/allocation/:id');
this.post('/allocation/:id/stop', function () {
return new Response(204, {}, '');
});
this.get(
'/volumes',
withBlockingSupport(function ({ csiVolumes }, { queryParams }) {
if (queryParams.type !== 'csi') {
return new Response(200, {}, '[]');
}
const json = this.serialize(csiVolumes.all());
const namespace = queryParams.namespace || 'default';
return json.filter((volume) => {
if (namespace === '*') return true;
return namespace === 'default'
? !volume.NamespaceID || volume.NamespaceID === namespace
: volume.NamespaceID === namespace;
});
})
);
this.get(
'/volume/:id',
withBlockingSupport(function ({ csiVolumes }, { params, queryParams }) {
if (!params.id.startsWith('csi/')) {
return new Response(404, {}, null);
}
const id = params.id.replace(/^csi\//, '');
const volume = csiVolumes.all().models.find((volume) => {
const volumeIsDefault =
!volume.namespaceId || volume.namespaceId === 'default';
const qpIsDefault =
!queryParams.namespace || queryParams.namespace === 'default';
return (
volume.id === id &&
(volume.namespaceId === queryParams.namespace ||
(volumeIsDefault && qpIsDefault))
);
});
return volume ? this.serialize(volume) : new Response(404, {}, null);
})
);
this.get('/plugins', function ({ csiPlugins }, { queryParams }) {
if (queryParams.type !== 'csi') {
return new Response(200, {}, '[]');
}
return this.serialize(csiPlugins.all());
});
this.get('/plugin/:id', function ({ csiPlugins }, { params }) {
if (!params.id.startsWith('csi/')) {
return new Response(404, {}, null);
}
const id = params.id.replace(/^csi\//, '');
const volume = csiPlugins.find(id);
if (!volume) {
return new Response(404, {}, null);
}
return this.serialize(volume);
});
this.get('/namespaces', function ({ namespaces }) {
const records = namespaces.all();
if (records.length) {
return this.serialize(records);
}
return this.serialize([{ Name: 'default' }]);
});
this.get('/namespace/:id', function ({ namespaces }, { params }) {
return this.serialize(namespaces.find(params.id));
});
this.get('/agent/members', function ({ agents, regions }) {
const firstRegion = regions.first();
return {
ServerRegion: firstRegion ? firstRegion.id : null,
Members: this.serialize(agents.all()).map(({ member }) => ({
...member,
})),
};
});
this.get('/agent/self', function ({ agents }) {
return agents.first();
});
this.get('/agent/monitor', function ({ agents, nodes }, { queryParams }) {
const serverId = queryParams.server_id;
const clientId = queryParams.client_id;
if (serverId && clientId)
return new Response(400, {}, 'specify a client or a server, not both');
if (serverId && !agents.findBy({ name: serverId }))
return new Response(400, {}, 'specified server does not exist');
if (clientId && !nodes.find(clientId))
return new Response(400, {}, 'specified client does not exist');
if (queryParams.plain) {
return logFrames.join('');
}
return logEncode(logFrames, logFrames.length - 1);
});
this.get('/status/leader', function (schema) {
return JSON.stringify(findLeader(schema));
});
// Note: Mirage-only route, for UI testing and not part of the Nomad API
this.get('/acl/tokens', function ({ tokens }, req) {
return this.serialize(tokens.all());
});
this.get('/acl/token/self', function ({ tokens }, req) {
const secret = req.requestHeaders['X-Nomad-Token'];
const tokenForSecret = tokens.findBy({ secretId: secret });
// Return the token if it exists
if (tokenForSecret) {
return this.serialize(tokenForSecret);
}
// Client error if it doesn't
return new Response(400, {}, null);
});
this.get('/acl/token/:id', function ({ tokens }, req) {
const token = tokens.find(req.params.id);
const secret = req.requestHeaders['X-Nomad-Token'];
const tokenForSecret = tokens.findBy({ secretId: secret });
// Return the token only if the request header matches the token
// or the token is of type management
if (
token.secretId === secret ||
(tokenForSecret && tokenForSecret.type === 'management')
) {
return this.serialize(token);
}
// Return not authorized otherwise
return new Response(403, {}, null);
});
this.post(
'/acl/token/onetime/exchange',
function ({ tokens }, { requestBody }) {
const { OneTimeSecretID } = JSON.parse(requestBody);
const tokenForSecret = tokens.findBy({ oneTimeSecret: OneTimeSecretID });
// Return the token if it exists
if (tokenForSecret) {
return {
Token: this.serialize(tokenForSecret),
};
}
// Forbidden error if it doesn't
return new Response(403, {}, null);
}
);
this.get('/acl/policy/:id', function ({ policies, tokens }, req) {
const policy = policies.find(req.params.id);
const secret = req.requestHeaders['X-Nomad-Token'];
const tokenForSecret = tokens.findBy({ secretId: secret });
if (req.params.id === 'anonymous') {
if (policy) {
return this.serialize(policy);
} else {
return new Response(404, {}, null);
}
}
// Return the policy only if the token that matches the request header
// includes the policy or if the token that matches the request header
// is of type management
if (
tokenForSecret &&
(tokenForSecret.policies.includes(policy) ||
tokenForSecret.type === 'management')
) {
return this.serialize(policy);
}
// Return not authorized otherwise
return new Response(403, {}, null);
});
this.get('/regions', function ({ regions }) {
return this.serialize(regions.all());
});
this.get('/operator/license', function ({ features }) {
const records = features.all();
if (records.length) {
return {
License: {
Features: records.models.mapBy('name'),
},
};
}
return new Response(501, {}, null);
});
const clientAllocationStatsHandler = function (
{ clientAllocationStats },
{ params }
) {
return this.serialize(clientAllocationStats.find(params.id));
};
const clientAllocationLog = function (server, { params, queryParams }) {
const allocation = server.allocations.find(params.allocation_id);
const tasks = allocation.taskStateIds.map((id) =>
server.taskStates.find(id)
);
if (!tasks.mapBy('name').includes(queryParams.task)) {
return new Response(400, {}, 'must include task name');
}
if (queryParams.plain) {
return logFrames.join('');
}
return logEncode(logFrames, logFrames.length - 1);
};
const clientAllocationFSLsHandler = function (
{ allocFiles },
{ queryParams: { path } }
) {
const filterPath = path.endsWith('/')
? path.substr(0, path.length - 1)
: path;
const files = filesForPath(allocFiles, filterPath);
return this.serialize(files);
};
const clientAllocationFSStatHandler = function (
{ allocFiles },
{ queryParams: { path } }
) {
const filterPath = path.endsWith('/')
? path.substr(0, path.length - 1)
: path;
// Root path
if (!filterPath) {
return this.serialize({
IsDir: true,
ModTime: new Date(),
});
}
// Either a file or a nested directory
const file = allocFiles.where({ path: filterPath }).models[0];
return this.serialize(file);
};
const clientAllocationCatHandler = function (
{ allocFiles },
{ queryParams }
) {
const [file, err] = fileOrError(allocFiles, queryParams.path);
if (err) return err;
return file.body;
};
const clientAllocationStreamHandler = function (
{ allocFiles },
{ queryParams }
) {
const [file, err] = fileOrError(allocFiles, queryParams.path);
if (err) return err;
// Pretender, and therefore Mirage, doesn't support streaming responses.
return file.body;
};
const clientAllocationReadAtHandler = function (
{ allocFiles },
{ queryParams }
) {
const [file, err] = fileOrError(allocFiles, queryParams.path);
if (err) return err;
return file.body.substr(queryParams.offset || 0, queryParams.limit);
};
const fileOrError = function (
allocFiles,
path,
message = 'Operation not allowed on a directory'
) {
// Root path
if (path === '/') {
return [null, new Response(400, {}, message)];
}
const file = allocFiles.where({ path }).models[0];
if (file.isDir) {
return [null, new Response(400, {}, message)];
}
return [file, null];
};
// Client requests are available on the server and the client
this.put('/client/allocation/:id/restart', function () {
return new Response(204, {}, '');
});
this.get('/client/allocation/:id/stats', clientAllocationStatsHandler);
this.get('/client/fs/logs/:allocation_id', clientAllocationLog);
this.get('/client/fs/ls/:allocation_id', clientAllocationFSLsHandler);
this.get('/client/fs/stat/:allocation_id', clientAllocationFSStatHandler);
this.get('/client/fs/cat/:allocation_id', clientAllocationCatHandler);
this.get('/client/fs/stream/:allocation_id', clientAllocationStreamHandler);
this.get('/client/fs/readat/:allocation_id', clientAllocationReadAtHandler);
this.get('/client/stats', function ({ clientStats }, { queryParams }) {
const seed = faker.random.number(10);
if (seed >= 8) {
const stats = clientStats.find(queryParams.node_id);
stats.update({
timestamp: Date.now() * 1000000,
CPUTicksConsumed:
stats.CPUTicksConsumed + faker.random.number({ min: -10, max: 10 }),
});
return this.serialize(stats);
} else {
return new Response(500, {}, null);
}
});
// TODO: in the future, this hack may be replaceable with dynamic host name
// support in pretender: https://github.com/pretenderjs/pretender/issues/210
HOSTS.forEach((host) => {
this.get(
`http://${host}/v1/client/allocation/:id/stats`,
clientAllocationStatsHandler
);
this.get(
`http://${host}/v1/client/fs/logs/:allocation_id`,
clientAllocationLog
);
this.get(
`http://${host}/v1/client/fs/ls/:allocation_id`,
clientAllocationFSLsHandler
);
this.get(
`http://${host}/v1/client/stat/ls/:allocation_id`,
clientAllocationFSStatHandler
);
this.get(
`http://${host}/v1/client/fs/cat/:allocation_id`,
clientAllocationCatHandler
);
this.get(
`http://${host}/v1/client/fs/stream/:allocation_id`,
clientAllocationStreamHandler
);
this.get(
`http://${host}/v1/client/fs/readat/:allocation_id`,
clientAllocationReadAtHandler
);
this.get(`http://${host}/v1/client/stats`, function ({ clientStats }) {
return this.serialize(clientStats.find(host));
});
});
this.post(
'/search/fuzzy',
function (
{ allocations, jobs, nodes, taskGroups, csiPlugins },
{ requestBody }
) {
const { Text } = JSON.parse(requestBody);
const matchedAllocs = allocations.where((allocation) =>
allocation.name.includes(Text)
);
const matchedGroups = taskGroups.where((taskGroup) =>
taskGroup.name.includes(Text)
);
const matchedJobs = jobs.where((job) => job.name.includes(Text));
const matchedNodes = nodes.where((node) => node.name.includes(Text));
const matchedPlugins = csiPlugins.where((plugin) =>
plugin.id.includes(Text)
);
const transformedAllocs = matchedAllocs.models.map((alloc) => ({
ID: alloc.name,
Scope: [alloc.namespace || 'default', alloc.id],
}));
const transformedGroups = matchedGroups.models.map((group) => ({
ID: group.name,
Scope: [group.job.namespace, group.job.id],
}));
const transformedJobs = matchedJobs.models.map((job) => ({
ID: job.name,
Scope: [job.namespace || 'default', job.id],
}));
const transformedNodes = matchedNodes.models.map((node) => ({
ID: node.name,
Scope: [node.id],
}));
const transformedPlugins = matchedPlugins.models.map((plugin) => ({
ID: plugin.id,
}));
const truncatedAllocs = transformedAllocs.slice(0, 20);
const truncatedGroups = transformedGroups.slice(0, 20);
const truncatedJobs = transformedJobs.slice(0, 20);
const truncatedNodes = transformedNodes.slice(0, 20);
const truncatedPlugins = transformedPlugins.slice(0, 20);
return {
Matches: {
allocs: truncatedAllocs,
groups: truncatedGroups,
jobs: truncatedJobs,
nodes: truncatedNodes,
plugins: truncatedPlugins,
},
Truncations: {
allocs: truncatedAllocs.length < truncatedAllocs.length,
groups: truncatedGroups.length < transformedGroups.length,
jobs: truncatedJobs.length < transformedJobs.length,
nodes: truncatedNodes.length < transformedNodes.length,
plugins: truncatedPlugins.length < transformedPlugins.length,
},
};
}
);
this.get(
'/recommendations',
function (
{ jobs, namespaces, recommendations },
{ queryParams: { job: id, namespace } }
) {
if (id) {
if (!namespaces.all().length) {
namespace = null;
}
const job = jobs.findBy({ id, namespace });
if (!job) {
return [];
}
const taskGroups = job.taskGroups.models;
const tasks = taskGroups.reduce((tasks, taskGroup) => {
return tasks.concat(taskGroup.tasks.models);
}, []);
const recommendationIds = tasks.reduce((recommendationIds, task) => {
return recommendationIds.concat(
task.recommendations.models.mapBy('id')
);
}, []);
return recommendations.find(recommendationIds);
} else {
return recommendations.all();
}
}
);
this.post(
'/recommendations/apply',
function ({ recommendations }, { requestBody }) {
const { Apply, Dismiss } = JSON.parse(requestBody);
Apply.concat(Dismiss).forEach((id) => {
const recommendation = recommendations.find(id);
const task = recommendation.task;
if (Apply.includes(id)) {
task.resources[recommendation.resource] = recommendation.value;
}
recommendation.destroy();
task.save();
});
return {};
}
);
//#region Variables
this.get('/vars', function (schema, { queryParams: { namespace } }) {
if (namespace && namespace !== '*') {
return schema.variables.all().filter((v) => v.namespace === namespace);
} else {
return schema.variables.all();
}
});
this.get('/var/:id', function ({ variables }, { params }) {
return variables.find(params.id);
});
this.put('/var/:id', function (schema, request) {
const { Path, Namespace, Items } = JSON.parse(request.requestBody);
if (request.url.includes('cas=') && Path === 'Auto-conflicting Variable') {
return new Response(
409,
{},
{
CreateIndex: 65,
CreateTime: faker.date.recent(14) * 1000000, // in the past couple weeks
Items: { edited_by: 'your_remote_pal' },
ModifyIndex: 2118,
ModifyTime: faker.date.recent(0.01) * 1000000, // a few minutes ago
Namespace: Namespace,
Path: Path,
}
);
} else {
return server.create('variable', {
path: Path,
namespace: Namespace,
items: Items,
id: Path,
});
}
});
this.delete('/var/:id', function (schema, request) {
const { id } = request.params;
server.db.variables.remove(id);
return '';
});
//#endregion Variables
//#region Services
const allocationServiceChecksHandler = function (schema) {
let disasters = [
"Moon's haunted",
'reticulating splines',
'The operation completed unexpectedly',
'Ran out of sriracha :(',
'¯\\_(ツ)_/¯',
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"\n "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n <head>\n <meta http-equiv="Content-Type" content="text/html;charset=utf-8">\n <title>Error response</title>\n </head>\n <body>\n <h1>Error response</h1>\n <p>Error code: 404</p>\n <p>Message: File not found.</p>\n <p>Error code explanation: HTTPStatus.NOT_FOUND - Nothing matches the given URI.</p>\n </body>\n</html>\n',
];
let fakeChecks = [];
schema.serviceFragments.all().models.forEach((frag, iter) => {
[...Array(iter)].forEach((check, checkIter) => {
const checkOK = faker.random.boolean();
fakeChecks.push({
Check: `check-${checkIter}`,
Group: `job-name.${frag.taskGroup?.name}[1]`,
Output: checkOK
? 'nomad: http ok'
: disasters[Math.floor(Math.random() * disasters.length)],
Service: frag.name,
Status: checkOK ? 'success' : 'failure',
StatusCode: checkOK ? 200 : 400,
Task: frag.task?.name,
Timestamp: new Date().getTime(),
});
});
});
return fakeChecks;
};
this.get('/job/:id/services', function (schema, { params }) {
const { services } = schema;
return this.serialize(services.where({ jobId: params.id }));
});
this.get('/client/allocation/:id/checks', allocationServiceChecksHandler);
//#endregion Services
//#region SSO
this.get('/acl/auth-methods', function (schema, request) {
return schema.authMethods.all();
});
this.post('/acl/oidc/auth-url', (schema, req) => {
const {AuthMethod, ClientNonce, RedirectUri, Meta} = JSON.parse(req.requestBody);
return new Response(200, {}, {
AuthURL: `/ui/oidc-mock?auth_method=${AuthMethod}&client_nonce=${ClientNonce}&redirect_uri=${RedirectUri}&meta=${Meta}`
});
});
// Simulate an OIDC callback by assuming the code passed is the secret of an existing token, and return that token.
this.post('/acl/oidc/complete-auth', function (schema, req) {
const code = JSON.parse(req.requestBody).Code;
const token = schema.tokens.findBy({
id: code
});
return new Response(200, {}, {
ACLToken: token.secretId
});
}, {timing: 1000});
//#endregion SSO
}
function filterKeys(object, ...keys) {
const clone = copy(object, true);
keys.forEach((key) => {
delete clone[key];
});
return clone;
}
// An empty response but not a 204 No Content. This is still a valid JSON
// response that represents a payload with no worthwhile data.
function okEmpty() {
return new Response(200, {}, '{}');
}
function generateFailedTGAllocs(job, taskGroups) {
const taskGroupsFromSpec = job.TaskGroups && job.TaskGroups.mapBy('Name');
let tgNames = ['tg-one', 'tg-two'];
if (taskGroupsFromSpec && taskGroupsFromSpec.length)
tgNames = taskGroupsFromSpec;
if (taskGroups && taskGroups.length) tgNames = taskGroups;
return tgNames.reduce((hash, tgName) => {
hash[tgName] = generateTaskGroupFailures();
return hash;
}, {});
}