-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.test.js
638 lines (561 loc) · 23.2 KB
/
index.test.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
'use strict';
/* eslint-disable no-underscore-dangle */
const chai = require('chai');
const util = require('util');
const assert = chai.assert;
const mockery = require('mockery');
const sinon = require('sinon');
const testConnection = require('./data/testConnection.json');
const testConfig = require('./data/fullConfig.json');
const testPipeline = require('./data/testPipeline.json');
const testJob = require('./data/testJob.json');
const { buildId, jobId, blockedBy } = testConfig;
const partialTestConfig = {
buildId,
jobId,
blockedBy
};
const partialTestConfigToString = Object.assign({}, partialTestConfig, {
blockedBy: blockedBy.toString()
});
const testAdmin = {
username: 'admin'
};
const EventEmitter = require('events').EventEmitter;
sinon.assert.expose(chai.assert, { prefix: '' });
describe('index test', () => {
let Executor;
let executor;
let multiWorker;
let spyMultiWorker;
let scheduler;
let spyScheduler;
let resqueMock;
let queueMock;
let redisMock;
let redisConstructorMock;
let cronMock;
let freezeWindowsMock;
let winstonMock;
let reqMock;
let pipelineMock;
let buildMock;
let pipelineFactoryMock;
let fakeResponse;
let userTokenGen;
let testDelayedConfig;
before(() => {
mockery.enable({
useCleanCache: true,
warnOnUnregistered: false
});
});
beforeEach(() => {
userTokenGen = sinon.stub().returns('admintoken');
testDelayedConfig = {
pipeline: testPipeline,
job: testJob,
apiUri: 'http://localhost',
tokenGen: userTokenGen
};
multiWorker = function () {
this.start = () => { };
this.end = sinon.stub().resolves();
};
scheduler = function () {
this.start = sinon.stub().resolves();
this.connect = sinon.stub().resolves();
this.end = sinon.stub().resolves();
};
util.inherits(multiWorker, EventEmitter);
util.inherits(scheduler, EventEmitter);
queueMock = {
connect: sinon.stub().resolves(),
enqueue: sinon.stub().resolves(),
enqueueAt: sinon.stub().resolves(),
del: sinon.stub().resolves(1),
delDelayed: sinon.stub().resolves(1),
connection: {
connected: false
},
end: sinon.stub().resolves()
};
resqueMock = {
Queue: sinon.stub().returns(queueMock),
MultiWorker: multiWorker,
Scheduler: scheduler
};
spyMultiWorker = sinon.spy(resqueMock, 'MultiWorker');
spyScheduler = sinon.spy(resqueMock, 'Scheduler');
winstonMock = {
info: sinon.stub(),
error: sinon.stub()
};
redisMock = {
hdel: sinon.stub().yieldsAsync(),
hset: sinon.stub().yieldsAsync(),
set: sinon.stub().yieldsAsync(),
expire: sinon.stub().yieldsAsync()
};
redisConstructorMock = sinon.stub().returns(redisMock);
cronMock = {
transform: sinon.stub().returns('H H H H H'),
next: sinon.stub().returns(1500000)
};
freezeWindowsMock = {
timeOutOfWindows: (windows, date) => date
};
fakeResponse = {
statusCode: 201,
body: {
id: '12345'
}
};
reqMock = sinon.stub();
pipelineMock = {
getFirstAdmin: sinon.stub().resolves(testAdmin)
};
pipelineFactoryMock = {
get: sinon.stub().resolves(pipelineMock)
};
buildMock = {
update: sinon.stub().resolves({
id: buildId
})
};
mockery.registerMock('node-resque', resqueMock);
mockery.registerMock('ioredis', redisConstructorMock);
mockery.registerMock('./lib/cron', cronMock);
mockery.registerMock('./lib/freezeWindows', freezeWindowsMock);
mockery.registerMock('winston', winstonMock);
mockery.registerMock('requestretry', reqMock);
/* eslint-disable global-require */
Executor = require('../index');
/* eslint-enable global-require */
executor = new Executor({
redisConnection: testConnection,
breaker: {
retry: {
retries: 1
}
},
pipelineFactory: pipelineFactoryMock
});
});
afterEach(() => {
mockery.deregisterAll();
mockery.resetCache();
});
after(() => {
mockery.disable();
});
describe('construction', () => {
it('constructs the executor', () => {
assert.instanceOf(executor, Executor);
});
it('constructs the multiWorker', () => {
const expectedConfig = {
connection: testConnection,
queues: ['periodicBuilds', 'frozenBuilds'],
minTaskProcessors: 1,
maxTaskProcessors: 10,
checkTimeout: 1000,
maxEventLoopDelay: 10,
toDisconnectProcessors: true
};
assert.calledWith(spyMultiWorker, sinon.match(expectedConfig), sinon.match.any);
});
it('constructs the scheduler', () => {
const expectedConfig = {
connection: testConnection
};
assert.calledWith(spyScheduler, sinon.match(expectedConfig));
});
it('constructs the executor when no breaker config is passed in', () => {
executor = new Executor({
redisConnection: testConnection,
pipelineFactory: pipelineFactoryMock
});
assert.instanceOf(executor, Executor);
});
it('takes in a prefix', () => {
executor = new Executor({
redisConnection: testConnection,
prefix: 'beta_',
pipelineFactory: pipelineFactoryMock
});
assert.instanceOf(executor, Executor);
assert.strictEqual(executor.prefix, 'beta_');
assert.strictEqual(executor.buildQueue, 'beta_builds');
assert.strictEqual(executor.buildConfigTable, 'beta_buildConfigs');
});
it('throws when not given a redis connection', () => {
assert.throws(() => new Executor(), 'No redis connection passed in');
});
it('throws when not given a pipelineFactory', () => {
assert.throws(() => new Executor({
redisConnection: testConnection
}));
});
});
describe('_startPeriodic', () => {
beforeEach(() => {
reqMock.yieldsAsync(null, fakeResponse, fakeResponse.body);
});
it('rejects if it can\'t establish a connection', function () {
queueMock.connect.rejects(new Error('couldn\'t connect'));
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.fail('Should not get here');
}, (err) => {
assert.instanceOf(err, Error);
});
});
it('doesn\'t call connect if there\'s already a connection', () => {
queueMock.connection.connected = true;
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.notCalled(queueMock.connect);
});
});
it('enqueues a new delayed job in the queue', () =>
executor.startPeriodic(testDelayedConfig).then(() => {
assert.calledOnce(queueMock.connect);
assert.calledWith(redisMock.hset, 'periodicBuildConfigs', testJob.id,
JSON.stringify(testDelayedConfig));
assert.calledWith(cronMock.transform, '* * * * *', testJob.id);
assert.calledWith(cronMock.next, 'H H H H H');
assert.calledWith(queueMock.enqueueAt, 1500000, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
}));
it('do not enqueue the same delayed job in the queue', () => {
const err = new Error('Job already enqueued at this time with same arguments');
queueMock.enqueueAt = sinon.stub().rejects(err);
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.calledWith(cronMock.next, 'H H H H H');
assert.calledOnce(queueMock.enqueueAt);
});
});
it('stops and reEnqueues an existing job if isUpdate flag is passed', () => {
testDelayedConfig.isUpdate = true;
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.calledTwice(queueMock.connect);
assert.calledWith(redisMock.hset, 'periodicBuildConfigs', testJob.id,
JSON.stringify(testDelayedConfig));
assert.calledWith(queueMock.enqueueAt, 1500000, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
assert.calledWith(queueMock.delDelayed, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
assert.calledWith(redisMock.hdel, 'periodicBuildConfigs', testJob.id);
});
});
it('stops but does not reEnqueue an existing job if it is disabled', () => {
testDelayedConfig.isUpdate = true;
testDelayedConfig.job.state = 'DISABLED';
testDelayedConfig.job.archived = false;
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.calledOnce(queueMock.connect);
assert.notCalled(redisMock.hset);
assert.notCalled(queueMock.enqueueAt);
assert.calledWith(queueMock.delDelayed, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
assert.calledWith(redisMock.hdel, 'periodicBuildConfigs', testJob.id);
});
});
it('stops but does not reEnqueue an existing job if it is archived', () => {
testDelayedConfig.isUpdate = true;
testDelayedConfig.job.state = 'ENABLED';
testDelayedConfig.job.archived = true;
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.calledOnce(queueMock.connect);
assert.notCalled(redisMock.hset);
assert.notCalled(queueMock.enqueueAt);
assert.calledWith(queueMock.delDelayed, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
assert.calledWith(redisMock.hdel, 'periodicBuildConfigs', testJob.id);
});
});
it('trigger build and do not enqueue next job if archived', () => {
testDelayedConfig.isUpdate = true;
testDelayedConfig.job.state = 'ENABLED';
testDelayedConfig.job.archived = true;
testDelayedConfig.triggerBuild = true;
const options = {
url: 'http://localhost/v4/events',
method: 'POST',
headers: {
Authorization: 'Bearer admintoken',
'Content-Type': 'application/json'
},
json: true,
body: {
causeMessage: 'Started by periodic build scheduler',
creator: { name: 'Screwdriver scheduler', username: 'sd:scheduler' },
pipelineId: testDelayedConfig.pipeline.id,
startFrom: testDelayedConfig.job.name
},
maxAttempts: 3,
retryDelay: 5000,
retryStrategy: executor.requestRetryStrategyPostEvent
};
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.calledOnce(queueMock.connect);
assert.notCalled(redisMock.hset);
assert.notCalled(queueMock.enqueueAt);
assert.calledWith(queueMock.delDelayed, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
assert.calledWith(redisMock.hdel, 'periodicBuildConfigs', testJob.id);
assert.calledOnce(userTokenGen);
assert.calledWith(reqMock, options);
});
});
it('trigger build and enqueue next job', () => {
testDelayedConfig.isUpdate = false;
testDelayedConfig.job.state = 'ENABLED';
testDelayedConfig.job.archived = false;
testDelayedConfig.triggerBuild = true;
const options = {
url: 'http://localhost/v4/events',
method: 'POST',
headers: {
Authorization: 'Bearer admintoken',
'Content-Type': 'application/json'
},
json: true,
body: {
causeMessage: 'Started by periodic build scheduler',
creator: { name: 'Screwdriver scheduler', username: 'sd:scheduler' },
pipelineId: testDelayedConfig.pipeline.id,
startFrom: testDelayedConfig.job.name
},
maxAttempts: 3,
retryDelay: 5000,
retryStrategy: executor.requestRetryStrategyPostEvent
};
return executor.startPeriodic(testDelayedConfig).then(() => {
assert.notCalled(queueMock.delDelayed);
assert.calledOnce(userTokenGen);
assert.calledWith(reqMock, options);
assert.calledOnce(queueMock.connect);
assert.calledWith(redisMock.hset, 'periodicBuildConfigs', testJob.id,
JSON.stringify(testDelayedConfig));
assert.calledWith(cronMock.transform, '* * * * *', testJob.id);
assert.calledWith(cronMock.next, 'H H H H H');
assert.calledWith(queueMock.enqueueAt, 1500000, 'periodicBuilds', 'startDelayed', [{
jobId: testJob.id
}]);
});
});
});
describe('_start', () => {
it('rejects if it can\'t establish a connection', () => {
queueMock.connect.rejects(new Error('couldn\'t connect'));
return executor.start(testConfig).then(() => {
assert.fail('Should not get here');
}, (err) => {
assert.instanceOf(err, Error);
});
});
it('enqueues a build and caches the config', () => {
const dateNow = Date.now();
const isoTime = (new Date(dateNow)).toISOString();
const sandbox = sinon.sandbox.create({
useFakeTimers: false
});
sandbox.useFakeTimers(dateNow);
buildMock.stats = {};
testConfig.build = buildMock;
return executor.start(testConfig).then(() => {
assert.calledTwice(queueMock.connect);
assert.calledWith(redisMock.hset, 'buildConfigs', buildId,
JSON.stringify(testConfig));
assert.calledWith(queueMock.enqueue, 'builds', 'start',
[partialTestConfigToString]);
assert.calledOnce(buildMock.update);
assert.equal(buildMock.stats.queueEnterTime, isoTime);
sandbox.restore();
});
}
);
it('enqueues a build and when force start is on', () => {
const dateNow = Date.now();
const isoTime = (new Date(dateNow)).toISOString();
const sandbox = sinon.sandbox.create({
useFakeTimers: false
});
sandbox.useFakeTimers(dateNow);
buildMock.stats = {};
testConfig.build = buildMock;
testConfig.causeMessage = '[force start] Need to push hotfix';
return executor.start(testConfig).then(() => {
assert.calledTwice(queueMock.connect);
assert.calledWith(redisMock.hset, 'buildConfigs', buildId,
JSON.stringify(testConfig));
assert.calledWith(queueMock.enqueue, 'builds', 'start',
[partialTestConfigToString]);
assert.calledOnce(buildMock.update);
assert.equal(buildMock.stats.queueEnterTime, isoTime);
sandbox.restore();
});
}
);
it('enqueues a build and caches the config', () => executor.start(testConfig).then(() => {
assert.calledTwice(queueMock.connect);
assert.calledWith(redisMock.hset, 'buildConfigs', buildId,
JSON.stringify(testConfig));
assert.calledWith(queueMock.enqueue, 'builds', 'start', [partialTestConfigToString]);
}));
it('doesn\'t call connect if there\'s already a connection', () => {
queueMock.connection.connected = true;
return executor.start(testConfig).then(() => {
assert.notCalled(queueMock.connect);
assert.calledWith(queueMock.enqueue, 'builds', 'start',
[partialTestConfigToString]);
});
});
});
describe('_startFrozen', () => {
it('enqueues a delayed job if in freeze window', () => {
mockery.resetCache();
reqMock.yieldsAsync(null, fakeResponse, fakeResponse.body);
const freezeWindowsMockB = {
timeOutOfWindows: (windows, date) => {
date.setUTCMinutes(date.getUTCMinutes() + 1);
return date;
}
};
mockery.deregisterMock('./lib/freezeWindows');
mockery.registerMock('./lib/freezeWindows', freezeWindowsMockB);
/* eslint-disable global-require */
Executor = require('../index');
/* eslint-enable global-require */
executor = new Executor({
redisConnection: testConnection,
breaker: {
retry: {
retries: 1
}
},
pipelineFactory: pipelineFactoryMock
});
const dateNow = new Date();
const sandbox = sinon.sandbox.create({
useFakeTimers: false
});
sandbox.useFakeTimers(dateNow.getTime());
const options = {
json: true,
method: 'PUT',
uri: `http://api.com/v4/builds/${testConfig.buildId}`,
body: {
status: 'FROZEN',
statusMessage: sinon.match('Blocked by freeze window, re-enqueued to ')
},
headers: {
Authorization: 'Bearer asdf',
'Content-Type': 'application/json'
},
maxAttempts: 3,
retryDelay: 5000,
retryStrategy: executor.requestRetryStrategy
};
return executor.start(testConfig).then(() => {
assert.calledTwice(queueMock.connect);
assert.calledWith(queueMock.delDelayed, 'frozenBuilds', 'startFrozen', [{
jobId
}]);
assert.calledWith(redisMock.hset, 'frozenBuildConfigs', jobId,
JSON.stringify(testConfig));
assert.calledWith(queueMock.enqueueAt, dateNow.getTime() + 60000, 'frozenBuilds',
'startFrozen', [{
jobId
}]);
assert.calledWith(reqMock, options);
sandbox.restore();
});
});
});
describe('_stop', () => {
it('rejects if it can\'t establish a connection', function () {
queueMock.connect.rejects(new Error('couldn\'t connect'));
return executor.stop(partialTestConfig).then(() => {
assert.fail('Should not get here');
}, (err) => {
assert.instanceOf(err, Error);
});
});
it('removes a start event from the queue and the cached buildconfig', () => {
const deleteKey = `deleted_${jobId}_${buildId}`;
const stopConfig = Object.assign({ started: false }, partialTestConfigToString);
return executor.stop(partialTestConfig).then(() => {
assert.calledOnce(queueMock.connect);
assert.calledWith(queueMock.del, 'builds', 'start', [partialTestConfigToString]);
assert.calledWith(redisMock.set, deleteKey, '');
assert.calledWith(redisMock.expire, deleteKey, 1800);
assert.calledWith(queueMock.enqueue, 'builds', 'stop', [stopConfig]);
});
});
it('adds a stop event to the queue if no start events were removed', () => {
queueMock.del.resolves(0);
const stopConfig = Object.assign({ started: true }, partialTestConfigToString);
return executor.stop(partialTestConfig).then(() => {
assert.calledOnce(queueMock.connect);
assert.calledWith(queueMock.del, 'builds', 'start', [partialTestConfigToString]);
assert.calledWith(queueMock.enqueue, 'builds', 'stop', [stopConfig]);
});
});
it('adds a stop event to the queue if it has no blocked job', () => {
queueMock.del.resolves(0);
const partialTestConfigUndefined = Object.assign({}, partialTestConfig, {
blockedBy: undefined
});
const stopConfig = Object.assign({ started: true }, partialTestConfigUndefined);
return executor.stop(partialTestConfigUndefined).then(() => {
assert.calledOnce(queueMock.connect);
assert.calledWith(queueMock.del, 'builds', 'start', [partialTestConfigUndefined]);
assert.calledWith(queueMock.enqueue, 'builds', 'stop', [stopConfig]);
});
});
it('doesn\'t call connect if there\'s already a connection', () => {
queueMock.connection.connected = true;
return executor.stop(Object.assign({}, partialTestConfig, {
annotations: {
'beta.screwdriver.cd/executor': 'screwdriver-executor-k8s'
}
})).then(() => {
assert.notCalled(queueMock.connect);
assert.calledWith(queueMock.del, 'builds', 'start', [partialTestConfigToString]);
});
});
});
describe('cleanUp', () => {
it('worker.end() is called', () => {
executor.cleanUp().then(() => {
assert.called(spyMultiWorker);
assert.called(spyScheduler);
assert.called(queueMock.end);
});
});
});
describe('stats', () => {
it('returns the correct stats', () => {
assert.deepEqual(executor.stats(), {
requests: {
total: 0,
timeouts: 0,
success: 0,
failure: 0,
concurrent: 0,
averageTime: 0
},
breaker: {
isClosed: true
}
});
});
});
});