This repository has been archived by the owner on Jan 5, 2019. It is now read-only.
/
api.js
2445 lines (2214 loc) · 78.3 KB
/
api.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
992
993
994
995
996
997
998
999
1000
let debug = require('debug')('app:api');
let slugid = require('slugid');
let assert = require('assert');
let _ = require('lodash');
let APIBuilder = require('taskcluster-lib-api');
let Entity = require('azure-entities');
let taskcluster = require('taskcluster-client');
let taskCreds = require('./task-creds');
// Maximum number runs allowed
const MAX_RUNS_ALLOWED = 50;
// Priority levels in order from high to low
const PRIORITY_LEVELS = [
'highest',
'very-high',
'high',
'medium',
'low',
'very-low',
'lowest',
];
/**
* **Azure Queue Invariants**
*
* We use azure queue storage queues for 3 purposes:
* A) distribution of tasks to workers,
* B) expiration of task-claims, and
* C) resolution by deadline expiration.
*
* Messages for the purposes of (A) are stored on queues specific the
* _provisionerId_ and _workerType_ of the tasks. All messages in azure queues
* are advisory. Meaning that duplicating them, or forgetting to delete them and
* handling them twice shall not cause issues.
*
* That said we do need a few invariants, this comment doesn't attempt to
* formally establish correctness. Instead we just seek to explain the
* intuition, so others have a chance and understanding what is going on.
*
* i) For any `pending` task there is at least one message with payload
* `{taskId, runId}` in a _workerType_ specific queue.
*
* ii) For any `running` task there is at least one message with payload
* `{taskId, runId, takenUntil}` in the queue for claim expiration,
* such that the message becomes visible after the claim on the
* current run has expired.
*
* iii) For any unresolved task there is at least one message with payload
* `{taskId, deadline}` in the queue for deadline resolution, such that
* the message becomes visible after the tasks deadline has expired.
*
* Using invariants above it's easy to ensure (A), (B) and (C), so long as we
* always remember that a message is only advisory. Hence, if the task mentioned
* doesn't exist, or is already resolved, then no error is reported and no
* action is taken.
*
* To avoid the case, where we ignore the only message during expiration of
* claims (B) due to server clock drift, we shall put the `takenUntil` time
* into the message, so we just check if it has been updated to see if the
* message is recent. We shall employ the same trick to ensure that clock drift
* can't cause the last deadline message to get ignored either.
*/
// Common patterns URL parameters
var SLUGID_PATTERN = /^[A-Za-z0-9_-]{8}[Q-T][A-Za-z0-9_-][CGKOSWaeimquy26-][A-Za-z0-9_-]{10}[AQgw]$/;
var GENERIC_ID_PATTERN = /^[a-zA-Z0-9-_]{1,22}$/;
var RUN_ID_PATTERN = /^[1-9]*[0-9]+$/;
/** API end-point for version v1/ */
var builder = new APIBuilder({
title: 'Queue API Documentation',
description: [
'The queue service is responsible for accepting tasks and track their state',
'as they are executed by workers. In order ensure they are eventually',
'resolved.',
'',
'This document describes the API end-points offered by the queue. These ',
'end-points targets the following audience:',
' * Schedulers, who create tasks to be executed,',
' * Workers, who execute tasks, and',
' * Tools, that wants to inspect the state of a task.',
].join('\n'),
serviceName: 'queue',
apiVersion: 'v1',
params: {
taskId: SLUGID_PATTERN,
taskGroupId: SLUGID_PATTERN,
provisionerId: GENERIC_ID_PATTERN,
workerType: GENERIC_ID_PATTERN,
workerGroup: GENERIC_ID_PATTERN,
workerId: GENERIC_ID_PATTERN,
runId: RUN_ID_PATTERN,
name: /^[\x20-\x7e]+$/, // Artifact names must be printable ASCII
},
context: [
'Task', // data.Task instance
'Artifact', // data.Artifact instance
'TaskGroup', // data.TaskGroup instance
'taskGroupExpiresExtension', // Time delay before expiring a task-group
'TaskGroupMember', // data.TaskGroupMember instance
'TaskGroupActiveSet', // data.TaskGroupMember instance (but in a different table)
'TaskDependency', // data.TaskDependency instance
'Provisioner', // data.Provisioner instance
'WorkerType', // data.WorkerType instance
'Worker', // data.Worker instance
'publicBucket', // bucket instance for public artifacts
'privateBucket', // bucket instance for private artifacts
'blobStore', // BlobStore for azure artifacts
'publisher', // publisher from base.Exchanges
'claimTimeout', // Number of seconds before a claim expires
'queueService', // Azure QueueService object from queueservice.js
'regionResolver', // Instance of EC2RegionResolver,
'credentials', // TC credentials for issuing temp creds on claim
'dependencyTracker', // Instance of DependencyTracker
'monitor', // base.monitor instance
'workClaimer', // Instance of WorkClaimer
'workerInfo', // Instance of WorkerInfo
's3Controller', // Instance of remotely-signed-s3.Controller
's3Runner', // Instance of remotely-signed-s3.Runner
'useCloudMirror', // If true, use the cloud-mirror service
'cloudMirrorHost', // Hostname of the cloud-mirror service
'artifactRegion', // Region where artifacts are stored (no cloud-mirror)
'blobRegion', // Region where blobs are stored (no cloud-mirror)
'publicBlobBucket', // Bucket containing public blobs
'privateBlobBucket', // Bucket containing private blobs
],
});
// Export builder
module.exports = builder;
/** Get task */
builder.declare({
method: 'get',
route: '/task/:taskId',
name: 'task',
stability: APIBuilder.stability.stable,
idempotent: true,
output: 'task.yml',
title: 'Get Task Definition',
description: [
'This end-point will return the task-definition. Notice that the task',
'definition may have been modified by queue, if an optional property is',
'not specified the queue may provide a default value.',
].join('\n'),
}, async function(req, res) {
// Load Task entity
let task = await this.Task.load({
taskId: req.params.taskId,
}, true);
// Handle cases where the task doesn't exist
if (!task) {
return res.reportError('ResourceNotFound', [
'`{{taskId}}` does not correspond to a task that exists.',
'Are you sure this task has already been submitted?',
].join('\n'), {
taskId: req.params.taskId,
});
}
// Create task definition
let definition = await task.definition();
return res.reply(definition);
});
/** Get task status */
builder.declare({
method: 'get',
route: '/task/:taskId/status',
name: 'status',
stability: APIBuilder.stability.stable,
input: undefined, // No input is accepted
output: 'task-status-response.yml',
title: 'Get task status',
description: [
'Get task status structure from `taskId`',
].join('\n'),
}, async function(req, res) {
// Load Task entity
let task = await this.Task.load({
taskId: req.params.taskId,
}, true);
// Handle cases where the task doesn't exist
if (!task) {
return res.reportError('ResourceNotFound', [
'`{{taskId}}` does not correspond to a task that exists.',
'Are you sure this task exists?',
].join('\n'), {
taskId: req.params.taskId,
});
}
// Reply with task status
return res.reply({
status: task.status(),
});
});
/** List taskIds by taskGroupId */
builder.declare({
method: 'get',
route: '/task-group/:taskGroupId/list',
query: {
continuationToken: Entity.continuationTokenPattern,
limit: /^[0-9]+$/,
},
name: 'listTaskGroup',
stability: APIBuilder.stability.stable,
output: 'list-task-group-response.yml',
title: 'List Task Group',
description: [
'List tasks sharing the same `taskGroupId`.',
'',
'As a task-group may contain an unbounded number of tasks, this end-point',
'may return a `continuationToken`. To continue listing tasks you must call',
'the `listTaskGroup` again with the `continuationToken` as the',
'query-string option `continuationToken`.',
'',
'By default this end-point will try to return up to 1000 members in one',
'request. But it **may return less**, even if more tasks are available.',
'It may also return a `continuationToken` even though there are no more',
'results. However, you can only be sure to have seen all results if you',
'keep calling `listTaskGroup` with the last `continuationToken` until you',
'get a result without a `continuationToken`.',
'',
'If you are not interested in listing all the members at once, you may',
'use the query-string option `limit` to return fewer.',
].join('\n'),
}, async function(req, res) {
let taskGroupId = req.params.taskGroupId;
let continuation = req.query.continuationToken || null;
let limit = parseInt(req.query.limit || 1000, 10);
// Find taskGroup and list of members
let [
taskGroup,
members,
] = await Promise.all([
this.TaskGroup.load({taskGroupId}, true),
this.TaskGroupMember.query({
taskGroupId,
expires: Entity.op.greaterThanOrEqual(new Date()),
}, {continuation, limit}),
]);
// If no taskGroup was found
if (!taskGroup) {
return res.reportError('ResourceNotFound',
'No task-group with taskGroupId: `{{taskGroupId}}`', {
taskGroupId,
},
);
}
/* eslint-disable no-extra-parens */
// Load tasks
let tasks = (await Promise.all(members.entries.map(member => {
return this.Task.load({taskId: member.taskId}, true);
}))).filter(task => {
// Remove tasks that don't exist, this happens on creation errors
// Remove tasks with wrong schedulerId, this shouldn't happen unless of some
// creation errors (probably something that involves dependency errors).
return task && task.schedulerId === taskGroup.schedulerId;
});
/* eslint-enable no-extra-parens */
// Build result
let result = {
taskGroupId,
tasks: await Promise.all(tasks.map(async (task) => {
return {
status: task.status(),
task: await task.definition(),
};
})),
};
if (members.continuation) {
result.continuationToken = members.continuation;
}
return res.reply(result);
});
/** List tasks dependents */
builder.declare({
method: 'get',
route: '/task/:taskId/dependents',
query: {
continuationToken: Entity.continuationTokenPattern,
limit: /^[0-9]+$/,
},
name: 'listDependentTasks',
stability: APIBuilder.stability.stable,
output: 'list-dependent-tasks-response.yml',
title: 'List Dependent Tasks',
description: [
'List tasks that depend on the given `taskId`.',
'',
'As many tasks from different task-groups may dependent on a single tasks,',
'this end-point may return a `continuationToken`. To continue listing',
'tasks you must call `listDependentTasks` again with the',
'`continuationToken` as the query-string option `continuationToken`.',
'',
'By default this end-point will try to return up to 1000 tasks in one',
'request. But it **may return less**, even if more tasks are available.',
'It may also return a `continuationToken` even though there are no more',
'results. However, you can only be sure to have seen all results if you',
'keep calling `listDependentTasks` with the last `continuationToken` until',
'you get a result without a `continuationToken`.',
'',
'If you are not interested in listing all the tasks at once, you may',
'use the query-string option `limit` to return fewer.',
].join('\n'),
}, async function(req, res) {
let taskId = req.params.taskId;
let continuation = req.query.continuationToken || null;
let limit = parseInt(req.query.limit || 1000, 10);
// Find task and list dependents
let [
task,
dependents,
] = await Promise.all([
this.Task.load({taskId}, true),
this.TaskDependency.query({
taskId,
expires: Entity.op.greaterThanOrEqual(new Date()),
}, {continuation, limit}),
]);
// Check if task exists
if (!task) {
return res.reportError(
'ResourceNotFound',
'Task with taskId: `{{taskId}}` was not found',
{taskId},
);
}
/* eslint-disable no-extra-parens */
// Load tasks
let tasks = (await Promise.all(dependents.entries.map(dependent => {
return this.Task.load({taskId: dependent.dependentTaskId}, true);
}))).filter(task => !!task);
/* eslint-enable no-extra-parens */
// Build result
let result = {
taskId,
tasks: await Promise.all(tasks.map(async (task) => {
return {
status: task.status(),
task: await task.definition(),
};
})),
};
if (dependents.continuation) {
result.continuationToken = dependents.continuation;
}
return res.reply(result);
});
/**
* Generate the list of acceptable priorities for a task with this priority
*/
const authorizeTaskCreation = async function(req, taskId, taskDef) {
const priority = taskDef.priority === 'normal' ? 'lowest' : taskDef.priority;
const priorities = PRIORITY_LEVELS.slice(0, PRIORITY_LEVELS.indexOf(priority) + 1);
assert(priorities.length > 0, 'must have a non-empty list of priorities');
await req.authorize({
legacyScopes: priority === 'lowest',
taskId,
priorities,
routes: taskDef.routes,
scopes: taskDef.scopes,
schedulerId: taskDef.schedulerId,
taskGroupId: taskDef.taskGroupId || taskId,
provisionerId: taskDef.provisionerId,
workerType: taskDef.workerType,
});
};
/** Construct default values and validate dates */
var patchAndValidateTaskDef = function(taskId, taskDef) {
// Set taskGroupId to taskId if not provided
if (!taskDef.taskGroupId) {
taskDef.taskGroupId = taskId;
}
// Ensure: created < now < deadline (with drift up to 15 min)
var created = new Date(taskDef.created);
var deadline = new Date(taskDef.deadline);
if (created.getTime() < new Date().getTime() - 15 * 60 * 1000) {
return {
code: 'InputError',
message: 'Created timestamp cannot be in the past (max 15min drift)',
details: {created: taskDef.created},
};
}
if (created.getTime() > new Date().getTime() + 15 * 60 * 1000) {
return {
code: 'InputError',
message: 'Created timestamp cannot be in the future (max 15min drift)',
details: {created: taskDef.created},
};
}
if (created.getTime() > deadline.getTime()) {
return {
code: 'InputError',
message: 'Deadline cannot be past created',
details: {created: taskDef.created, deadline: taskDef.deadline},
};
}
if (deadline.getTime() < new Date().getTime()) {
return {
code: 'InputError',
message: 'Deadline cannot be in the past',
details: {deadline: taskDef.deadline},
};
}
var msToDeadline = deadline.getTime() - new Date().getTime();
// Validate that deadline is less than 5 days from now, allow 15 min drift
if (msToDeadline > 5 * 24 * 60 * 60 * 1000 + 15 * 60 * 1000) {
return {
code: 'InputError',
message: 'Deadline cannot be more than 5 days into the future',
details: {deadline: taskDef.deadline},
};
}
// Set expires, if not defined
if (!taskDef.expires) {
var expires = new Date(taskDef.deadline);
expires.setFullYear(expires.getFullYear() + 1);
taskDef.expires = expires.toJSON();
}
// Validate that expires is past deadline
if (deadline.getTime() > new Date(taskDef.expires).getTime()) {
return {
code: 'InputError',
message: 'Expires cannot be before the deadline',
details: {deadline: taskDef.deadline, expires: taskDef.expires},
};
}
// Ensure that date formats are encoded as we store them for idempotent
// operations to work with date format that has more or fewer digits
taskDef.created = new Date(taskDef.created).toJSON();
taskDef.deadline = new Date(taskDef.deadline).toJSON();
taskDef.expires = new Date(taskDef.expires).toJSON();
// Migrate normal -> lowest, as it is the new default
if (taskDef.priority === 'normal') {
taskDef.priority = 'lowest';
}
return null;
};
/** Ensure the taskGroup exists and that membership is declared */
let ensureTaskGroup = async (ctx, taskId, taskDef, res) => {
let taskGroupId = taskDef.taskGroupId;
let taskGroup = await ctx.TaskGroup.load({taskGroupId}, true);
let expires = new Date(taskDef.expires);
let taskGroupExpiration = new Date(
expires.getTime() + ctx.taskGroupExpiresExtension * 1000
);
if (!taskGroup) {
taskGroup = await ctx.TaskGroup.create({
taskGroupId,
schedulerId: taskDef.schedulerId,
expires: taskGroupExpiration,
}).catch(err => {
// We only handle cases where the entity already exists
if (!err || err.code !== 'EntityAlreadyExists') {
throw err;
}
return ctx.TaskGroup.load({taskGroupId});
});
}
if (taskGroup.schedulerId !== taskDef.schedulerId) {
res.reportError(
'RequestConflict', [
'Task group `{{taskGroupId}}` contains tasks with',
'schedulerId `{{taskGroupSchedulerId}}`. You are attempting',
'to include tasks from schedulerId `{{taskSchedulerId}}`,',
'which is not permitted.',
'All tasks in the same task-group must have the same schedulerId.',
].join('\n'), {
taskGroupId,
taskGroupSchedulerId: taskGroup.schedulerId,
taskSchedulerId: taskDef.schedulerId,
});
return false;
}
// Update taskGroup.expires if necessary
await taskGroup.modify(taskGroup => {
if (taskGroup.expires.getTime() < expires.getTime()) {
taskGroup.expires = taskGroupExpiration;
}
});
// Ensure the group membership relation is constructed too
await ctx.TaskGroupMember.create({
taskGroupId,
taskId,
expires,
}).catch(err => {
// If the entity already exists, then we're happy no need to crash
if (!err || err.code !== 'EntityAlreadyExists') {
throw err;
}
});
// Now we also add the task to the group size counters as well
await ctx.TaskGroupActiveSet.create({
taskGroupId,
taskId,
expires,
}).catch(async (err) => {
// If the entity already exists, then we're happy no need to crash
if (!err || err.code !== 'EntityAlreadyExists') {
throw err;
}
let active = await ctx.TaskGroupActiveSet.load({taskId, taskGroupId});
if (!_.isEqual(new Date(active.expires), expires)) {
return res.reportError('RequestConflict', [
'taskId `{{taskId}}` already used by another task.',
'This could be the result of faulty idempotency!',
].join('\n'), {
taskId,
});
}
});
return true;
};
/** Create tasks */
builder.declare({
method: 'put',
route: '/task/:taskId',
name: 'createTask',
stability: APIBuilder.stability.stable,
idempotent: true,
scopes: {AllOf: [
{for: 'scope', in: 'scopes', each: '<scope>'},
{for: 'route', in: 'routes', each: 'queue:route:<route>'},
{AnyOf: [
{AllOf: [
'queue:scheduler-id:<schedulerId>',
{AnyOf: [
{
for: 'priority',
in: 'priorities',
each: 'queue:create-task:<priority>:<provisionerId>/<workerType>',
},
]},
]},
{
if: 'legacyScopes',
then: {AnyOf: [
'queue:create-task:<provisionerId>/<workerType>',
{
AllOf: [
'queue:define-task:<provisionerId>/<workerType>',
'queue:task-group-id:<schedulerId>/<taskGroupId>',
'queue:schedule-task:<schedulerId>/<taskGroupId>/<taskId>',
],
},
]},
},
]},
]},
input: 'create-task-request.yml',
output: 'task-status-response.yml',
title: 'Create New Task',
description: [
'Create a new task, this is an **idempotent** operation, so repeat it if',
'you get an internal server error or network connection is dropped.',
'',
'**Task `deadline`**: the deadline property can be no more than 5 days',
'into the future. This is to limit the amount of pending tasks not being',
'taken care of. Ideally, you should use a much shorter deadline.',
'',
'**Task expiration**: the `expires` property must be greater than the',
'task `deadline`. If not provided it will default to `deadline` + one',
'year. Notice, that artifacts created by task must expire before the task.',
'',
'**Task specific routing-keys**: using the `task.routes` property you may',
'define task specific routing-keys. If a task has a task specific ',
'routing-key: `<route>`, then when the AMQP message about the task is',
'published, the message will be CC\'ed with the routing-key: ',
'`route.<route>`. This is useful if you want another component to listen',
'for completed tasks you have posted. The caller must have scope',
'`queue:route:<route>` for each route.',
'',
'**Dependencies**: any tasks referenced in `task.dependencies` must have',
'already been created at the time of this call.',
'',
'**Scopes**: Note that the scopes required to complete this API call depend',
'on the content of the `scopes`, `routes`, `schedulerId`, `priority`,',
'`provisionerId`, and `workerType` properties of the task definition.',
'',
'**Legacy Scopes**: The `queue:create-task:..` scope without a priority and',
'the `queue:define-task:..` and `queue:task-group-id:..` scopes are considered',
'legacy and should not be used. Note that the new, non-legacy scopes require',
'a `queue:scheduler-id:..` scope as well as scopes for the proper priority.',
].join('\n'),
}, async function(req, res) {
var taskId = req.params.taskId;
var taskDef = req.body;
await authorizeTaskCreation(req, taskId, taskDef);
// Patch default values and validate timestamps
var detail = patchAndValidateTaskDef(taskId, taskDef);
if (detail) {
return res.reportError(detail.code, detail.message, detail.details);
}
if (taskDef.scopes.some(s => s.endsWith('**'))) {
return res.reportError('InputError', 'scopes must not end with `**`', {});
}
// Ensure group membership is declared, and that schedulerId isn't conflicting
if (!await ensureTaskGroup(this, taskId, taskDef, res)) {
return;
}
// Parse timestamps
let created = new Date(taskDef.created);
let deadline = new Date(taskDef.deadline);
let expires = new Date(taskDef.expires);
// Insert entry in deadline queue
await this.queueService.putDeadlineMessage(
taskId,
taskDef.taskGroupId,
taskDef.schedulerId,
deadline
);
// Try to create Task entity
try {
let runs = [];
// Add run if there is no dependencies
if (taskDef.dependencies.length === 0) {
runs.push({
state: 'pending',
reasonCreated: 'scheduled',
scheduled: new Date().toJSON(),
});
}
var task = await this.Task.create({
taskId: taskId,
provisionerId: taskDef.provisionerId,
workerType: taskDef.workerType,
schedulerId: taskDef.schedulerId,
taskGroupId: taskDef.taskGroupId,
dependencies: taskDef.dependencies,
requires: taskDef.requires,
routes: taskDef.routes,
priority: taskDef.priority,
retries: taskDef.retries,
retriesLeft: taskDef.retries,
created: created,
deadline: deadline,
expires: expires,
scopes: taskDef.scopes,
payload: taskDef.payload,
metadata: taskDef.metadata,
tags: taskDef.tags,
extra: taskDef.extra,
runs: runs,
takenUntil: new Date(0),
});
} catch (err) {
// We can handle cases where entity already exists, not that, we re-throw
if (!err || err.code !== 'EntityAlreadyExists') {
throw err;
}
// load task, and task definition
task = await this.Task.load({taskId: taskId});
let def = await task.definition();
// Compare the two task definitions
if (!_.isEqual(taskDef, def)) {
return res.reportError('RequestConflict', [
'taskId `{{taskId}}` already used by another task.',
'This could be the result of faulty idempotency!',
'Existing task definition was:\n ```js\n{{existingTask}}\n```',
'This request tried to define:\n ```js\n{{taskDefinition}}\n```',
].join('\n'), {
taskId,
existingTask: def,
taskDefinition: taskDef,
});
}
}
// Track dependencies, if not already scheduled
if (task.state() === 'unscheduled') {
// Track dependencies, adds a pending run if ready to run
let err = await this.dependencyTracker.trackDependencies(task);
// If we get an error here the task will be left in state = 'unscheduled',
// any attempt to use the same taskId will fail. And eventually the task
// will be resolved deadline-expired. But since createTask never returned
// successfully...
if (err) {
return res.reportError('InputError', err.message, err.details);
}
}
// Construct task status, as we'll return this many times
let status = task.status();
// If first run isn't unscheduled or pending, all message must have been
// published before, this can happen if we came from the catch-branch
// (it's unlikely to happen). But no need to publish messages again
let runZeroState = (task.runs[0] || {state: 'unscheduled'}).state;
if (runZeroState !== 'unscheduled' && runZeroState !== 'pending') {
return res.reply({status});
}
// Publish task-defined message, we want this arriving before the
// task-pending message, so we have to await publication here
await this.publisher.taskDefined({status}, task.routes);
// If first run is pending we publish messages about this
if (runZeroState === 'pending') {
await Promise.all([
// Put message into the task pending queue
this.queueService.putPendingMessage(task, 0),
// Put message in appropriate azure queue, and publish message to pulse
this.publisher.taskPending({status, runId: 0}, task.routes),
]);
}
// Reply
return res.reply({status});
});
/** Define tasks */
builder.declare({
method: 'post',
route: '/task/:taskId/define',
name: 'defineTask',
stability: APIBuilder.stability.deprecated,
scopes: {AllOf: [
{for: 'scope', in: 'scopes', each: '<scope>'},
{for: 'route', in: 'routes', each: 'queue:route:<route>'},
{AnyOf: [
{AllOf: [
'queue:scheduler-id:<schedulerId>',
{AnyOf: [
{
for: 'priority',
in: 'priorities',
each: 'queue:create-task:<priority>:<provisionerId>/<workerType>',
},
]},
]},
{
if: 'legacyScopes',
then: {AnyOf: [
'queue:define-task:<provisionerId>/<workerType>',
'queue:create-task:<provisionerId>/<workerType>',
{
AllOf: [
'queue:define-task:<provisionerId>/<workerType>',
'queue:task-group-id:<schedulerId>/<taskGroupId>',
],
},
]},
},
]},
]},
input: 'create-task-request.yml',
output: 'task-status-response.yml',
title: 'Define Task',
description: [
'**Deprecated**, this is the same as `createTask` with a **self-dependency**.',
'This is only present for legacy.',
].join('\n'),
}, async function(req, res) {
var taskId = req.params.taskId;
var taskDef = req.body;
await authorizeTaskCreation(req, taskId, taskDef);
// Patch default values and validate timestamps
var detail = patchAndValidateTaskDef(taskId, taskDef);
if (detail) {
return res.reportError(detail.code, detail.message, detail.details);
}
// Ensure we have a self-dependency, this is how defineTask works now
if (!_.includes(taskDef.dependencies, taskId)) {
// Trick as taskDef.dependencies may be a default from schema validation
// HACK: Yes, schema validator really should clone its default values!
taskDef.dependencies = _.flatten([taskId, taskDef.dependencies]);
}
// Ensure group membership is declared, and that schedulerId isn't conflicting
if (!await ensureTaskGroup(this, taskId, taskDef, res)) {
return;
}
// Parse timestamps
let created = new Date(taskDef.created);
let deadline = new Date(taskDef.deadline);
let expires = new Date(taskDef.expires);
// Insert entry in deadline queue (garbage entries are acceptable)
await this.queueService.putDeadlineMessage(
taskId,
taskDef.taskGroupId,
taskDef.schedulerId,
deadline
);
// Try to create Task entity
try {
var task = await this.Task.create({
taskId: taskId,
provisionerId: taskDef.provisionerId,
workerType: taskDef.workerType,
schedulerId: taskDef.schedulerId,
taskGroupId: taskDef.taskGroupId,
dependencies: taskDef.dependencies,
requires: taskDef.requires,
routes: taskDef.routes,
priority: taskDef.priority,
retries: taskDef.retries,
retriesLeft: taskDef.retries,
created: created,
deadline: deadline,
expires: expires,
scopes: taskDef.scopes,
payload: taskDef.payload,
metadata: taskDef.metadata,
tags: taskDef.tags,
extra: taskDef.extra,
runs: [],
takenUntil: new Date(0),
});
} catch (err) {
// We can handle cases where entity already exists, not that, we re-throw
if (!err || err.code !== 'EntityAlreadyExists') {
throw err;
}
// load task, and task definition
task = await this.Task.load({taskId: taskId});
let def = await task.definition();
// Compare the two task definitions
// (ignore runs as this method don't create them)
if (!_.isEqual(taskDef, def)) {
return res.reportError('RequestConflict', [
'taskId `{{taskId}}` already used by another task.',
'This could be the result of faulty idempotency!',
'Existing task definition was:\n ```js\n{{existingTask}}\n```',
'This request tried to define:\n ```js\n{{taskDefinition}}\n```',
].join('\n'), {
taskId,
existingTask: def,
taskDefinition: taskDef,
});
}
}
// Track dependencies, if not already scheduled
if (task.state() === 'unscheduled') {
// Track dependencies, adds a pending run if ready to run
let err = await this.dependencyTracker.trackDependencies(task);
// We get an error here the task will be left in state = 'unscheduled',
// any attempt to use the same taskId will fail. And eventually the task
// will be resolved deadline-expired. But since createTask never returned
// successfully...
if (err) {
return res.reportError('InputError', err.message, err.details);
}
// Validate sanity...
assert(task.state() === 'unscheduled', 'task should be unscheduled here!');
}
// Construct task status
let status = task.status();
// If runs are present, then we don't need to publish messages as this must
// have happened already...
// this can happen if we came from the catch-branch (it's unlikely to happen)
if (task.runs.length > 0) {
return res.reply({status});
}
// Publish task-defined message
await this.publisher.taskDefined({status}, task.routes);
// Reply
return res.reply({status});
});
/** Schedule previously defined tasks */
builder.declare({
method: 'post',
route: '/task/:taskId/schedule',
name: 'scheduleTask',
stability: APIBuilder.stability.stable,
scopes: {AnyOf: [
'queue:schedule-task:<schedulerId>/<taskGroupId>/<taskId>',
{AllOf: [ // Legacy scopes
'queue:schedule-task',
'assume:scheduler-id:<schedulerId>/<taskGroupId>',
]},
]},
input: undefined, // No input accepted
output: 'task-status-response.yml',
title: 'Schedule Defined Task',
description: [
'scheduleTask will schedule a task to be executed, even if it has',
'unresolved dependencies. A task would otherwise only be scheduled if',
'its dependencies were resolved.',
'',
'This is useful if you have defined a task that depends on itself or on',
'some other task that has not been resolved, but you wish the task to be',
'scheduled immediately.',
'',
'This will announce the task as pending and workers will be allowed to',
'claim it and resolve the task.',
'',
'**Note** this operation is **idempotent** and will not fail or complain',
'if called with a `taskId` that is already scheduled, or even resolved.',
'To reschedule a task previously resolved, use `rerunTask`.',
].join('\n'),
}, async function(req, res) {
// Load Task entity
var taskId = req.params.taskId;
var task = await this.Task.load({taskId: taskId}, true);
// If task entity doesn't exists, we return ResourceNotFound
if (!task) {
return res.reportError(
'ResourceNotFound',
'taskId `{{taskId}}` not found. Are you sure it exists?',
{taskId},
);
}
await req.authorize({
taskId,
schedulerId: task.schedulerId,
taskGroupId: task.taskGroupId,
});
// Attempt to schedule task
let status = await this.dependencyTracker.scheduleTask(task);
// If null it must because deadline is exceeded
if (status === null) {
return res.reportError(
'RequestConflict',
'Task `{{taskId}}` Can\'t be scheduled past its deadline at ' +
'{{deadline}}.', {
taskId,
deadline: task.deadline.toJSON(),
}
);
}
return res.reply({status});
});
/** Rerun a previously resolved task */
builder.declare({
method: 'post',
route: '/task/:taskId/rerun',
name: 'rerunTask',
stability: APIBuilder.stability.deprecated,
scopes: {AnyOf: [
'queue:rerun-task:<schedulerId>/<taskGroupId>/<taskId>',
{AllOf: [ // Legacy scopes
'queue:rerun-task',
'assume:scheduler-id:<schedulerId>/<taskGroupId>',
]},
]},