screwdriver-queue-service 2.0.14 → 2.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -272,3 +272,22 @@ scheduler:
272
272
  vhost: RABBITMQ_VHOST
273
273
  # Connection options
274
274
  connectOptions: RABBITMQ_CONNECT_OPTIONS
275
+ kafka:
276
+ # flag for kafka broker
277
+ enabled: KAFKA_ENABLED
278
+ # kafka brokers list
279
+ hosts: KAFKA_BROKERS_LIST
280
+ # sasl options
281
+ sasl:
282
+ # sasl mechanism
283
+ mechanism: SASL_MECHANISM
284
+ # secret id for sasl/scram
285
+ secretId: SASL_AWS_SECRET_ID
286
+ # client id of the producer
287
+ clientId: KAFKA_CLIENT_ID
288
+ # Amazon access key
289
+ accessKeyId: KAFKA_ACCESS_KEY_ID
290
+ # Amazon secret access key
291
+ secretAccessKey: KAFKA_ACCESS_KEY_SECRET
292
+ # AWS region
293
+ region: AWS_REGION
@@ -202,3 +202,23 @@ scheduler:
202
202
  vhost: /screwdriver
203
203
  # Connect Options
204
204
  connectOptions: { json: true, heartbeatIntervalInSeconds: 20, reconnectTimeInSeconds: 30 }
205
+
206
+ kafka:
207
+ # flag for kafka broker
208
+ enabled: false
209
+ # kafka brokers list
210
+ hosts: KAFKA_BROKERS_LIST
211
+ # sasl options
212
+ sasl:
213
+ # sasl mechanism
214
+ mechanism: scram-sha-512
215
+ # secret id for sasl/scram
216
+ secretId: fake-secret
217
+ # client id of the producer
218
+ clientId: sd-producer
219
+ # Amazon access key
220
+ accessKeyId: KAFKA_ACCESS_KEY_ID
221
+ # Amazon secret access key
222
+ secretAccessKey: KAFKA_ACCESS_KEY_SECRET
223
+ # AWS region
224
+ region: AWS_REGION
package/lib/queue.js CHANGED
@@ -34,6 +34,8 @@ module.exports = class ExecutorQueue {
34
34
  this.userTokenGen = null;
35
35
  this.timeoutQueue = `${this.prefix}timeoutConfigs`;
36
36
  this.cacheQueue = `${this.prefix}cache`;
37
+ this.unzipQueue = `${this.prefix}unzip`;
38
+ this.webhookQueue = `${this.prefix}webhooks`;
37
39
 
38
40
  const redisConnection = { ...config.redisConnection, pkg: 'ioredis' };
39
41
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "screwdriver-queue-service",
3
- "version": "2.0.14",
3
+ "version": "2.0.18",
4
4
  "description": "Screwdriver Queue Service API",
5
5
  "main": "app.js",
6
6
  "directories": {
@@ -28,7 +28,8 @@
28
28
  "node-resque": "^5.5.3",
29
29
  "npm-auto-version": "^1.0.0",
30
30
  "redlock": "^4.2.0",
31
- "screwdriver-data-schema": "^21.2.5",
31
+ "screwdriver-aws-producer-service": "^1.1.0",
32
+ "screwdriver-data-schema": "^21.10.2",
32
33
  "screwdriver-executor-docker": "^5.0.2",
33
34
  "screwdriver-executor-jenkins": "^5.0.1",
34
35
  "screwdriver-executor-k8s": "^14.14.4",
@@ -60,7 +61,8 @@
60
61
  "pretest": "eslint . --quiet",
61
62
  "test": "nyc --report-dir ./artifacts/coverage --reporter=lcov mocha --reporter mocha-multi-reporters --reporter-options configFile=./mocha.config.json --recursive --timeout 4000 --retries 1 --exit --allow-uncaught true --color true",
62
63
  "debug": "node --nolazy ./bin/server",
63
- "functional": "cucumber-js --format=progress --tags 'not @ignore' --retry 2 --fail-fast --exit"
64
+ "functional": "cucumber-js --format=progress --tags 'not @ignore' --retry 2 --fail-fast --exit",
65
+ "semantic-release": "semantic-release"
64
66
  },
65
67
  "repository": {
66
68
  "type": "git",
@@ -85,9 +87,6 @@
85
87
  },
86
88
  "homepage": "https://github.com/screwdriver-cd/screwdriver-queue-service#readme",
87
89
  "release": {
88
- "debug": false,
89
- "verifyConditions": {
90
- "path": "./node_modules/semantic-release/src/lib/plugin-noop.js"
91
- }
90
+ "debug": false
92
91
  }
93
92
  }
package/plugins/helper.js CHANGED
@@ -218,11 +218,34 @@ async function updateBuild(updateConfig, retryStrategyFn) {
218
218
  );
219
219
  }
220
220
 
221
+ /**
222
+ * Post the webhooks process
223
+ * @method processHooks
224
+ * @param {String} apiUri
225
+ * @param {String} token
226
+ * @param {String} webhookConfig as JSON format
227
+ * @param {Function} retryStrategyFn
228
+ * @return {Promise} response or error
229
+ */
230
+ async function processHooks(apiUri, token, webhookConfig, retryStrategyFn) {
231
+ return request(formatOptions('POST', `${apiUri}/v4/processHooks`, token, webhookConfig, retryStrategyFn)).then(
232
+ res => {
233
+ logger.info(`POST /v4/processHooks completed, ${res.statusCode}, ${JSON.stringify(res.body)}`);
234
+ if ([200, 201, 204].includes(res.statusCode)) {
235
+ return res;
236
+ }
237
+
238
+ throw new Error(`Failed to process webhook with ${res.statusCode} code and ${res.body}`);
239
+ }
240
+ );
241
+ }
242
+
221
243
  module.exports = {
222
244
  updateBuildStatus,
223
245
  updateStepStop,
224
246
  getCurrentStep,
225
247
  createBuildEvent,
226
248
  getPipelineAdmin,
227
- updateBuild
249
+ updateBuild,
250
+ processHooks
228
251
  };
@@ -33,6 +33,12 @@ module.exports = () => ({
33
33
  case 'cache':
34
34
  await scheduler.clearCache(executor, request.payload);
35
35
  break;
36
+ case 'unzip':
37
+ await scheduler.unzipArtifacts(executor, request.payload);
38
+ break;
39
+ case 'webhook':
40
+ await scheduler.queueWebhook(executor, request.payload);
41
+ break;
36
42
  default:
37
43
  await scheduler.start(executor, request.payload);
38
44
  break;
@@ -13,6 +13,7 @@ const RETRY_LIMIT = 3;
13
13
  const RETRY_DELAY = 5;
14
14
  const EXPIRE_TIME = 1800; // 30 mins
15
15
  const TEMPORAL_TOKEN_TIMEOUT = 12 * 60; // 12 hours in minutes
16
+ const TEMPORAL_UNZIP_TOKEN_TIMEOUT = 2 * 60; // 2 hours in minutes
16
17
 
17
18
  /**
18
19
  * Posts a new build event to the API
@@ -651,7 +652,7 @@ async function stop(executor, config) {
651
652
  }
652
653
 
653
654
  /**
654
- * Cleanup any reladed processing
655
+ * Cleanup any related processing
655
656
  */
656
657
  async function cleanUp(executor) {
657
658
  try {
@@ -688,6 +689,51 @@ async function clearCache(executor, config) {
688
689
  }
689
690
  }
690
691
 
692
+ /**
693
+ * Pushes a message to unzip artifacts
694
+ * @async unzipArtifacts
695
+ * @param {Object} executor
696
+ * @param {Object} config Configuration
697
+ * @param {String} config.buildId Unique ID for a build
698
+ * @return {Promise}
699
+ */
700
+ async function unzipArtifacts(executor, config) {
701
+ await executor.connect();
702
+ const { buildId } = config;
703
+ const tokenConfig = {
704
+ username: buildId,
705
+ scope: 'unzip_worker'
706
+ };
707
+ const token = executor.tokenGen(tokenConfig, TEMPORAL_UNZIP_TOKEN_TIMEOUT);
708
+
709
+ const enq = await executor.queueBreaker.runCommand('enqueue', executor.unzipQueue, 'start', [
710
+ {
711
+ buildId,
712
+ token
713
+ }
714
+ ]);
715
+
716
+ return enq;
717
+ }
718
+
719
+ /**
720
+ * Pushes webhooks to redis
721
+ * @async queueWebhook
722
+ * @param {Object} executor
723
+ * @param {Object} webhookConfig
724
+ * @return {Promise}
725
+ */
726
+ async function queueWebhook(executor, webhookConfig) {
727
+ await executor.connect();
728
+
729
+ return executor.queueBreaker.runCommand(
730
+ 'enqueue',
731
+ executor.webhookQueue,
732
+ 'sendWebhook',
733
+ JSON.stringify(webhookConfig)
734
+ );
735
+ }
736
+
691
737
  module.exports = {
692
738
  init,
693
739
  start,
@@ -699,5 +745,7 @@ module.exports = {
699
745
  startTimer,
700
746
  stopTimer,
701
747
  cleanUp,
702
- clearCache
748
+ clearCache,
749
+ unzipArtifacts,
750
+ queueWebhook
703
751
  };
@@ -6,6 +6,8 @@ const config = require('config');
6
6
  const hoek = require('@hapi/hoek');
7
7
  const ExecutorRouter = require('screwdriver-executor-router');
8
8
  const logger = require('screwdriver-logger');
9
+ const AWSProducer = require('screwdriver-aws-producer-service');
10
+ const helper = require('../../helper');
9
11
  const { BlockedBy } = require('./BlockedBy');
10
12
  const { Filter } = require('./Filter');
11
13
  const { CacheFilter } = require('./CacheFilter');
@@ -13,9 +15,10 @@ const blockedByConfig = config.get('plugins').blockedBy;
13
15
  const { connectionDetails, queuePrefix, runningJobsPrefix, waitingJobsPrefix } = require('../../../config/redis');
14
16
  const rabbitmqConf = require('../../../config/rabbitmq');
15
17
  const { amqpURI, exchange, connectOptions } = rabbitmqConf.getConfig();
18
+ const kafkaEnabled = config.get('kafka').enabled === 'true';
16
19
 
17
20
  const RETRY_LIMIT = 3;
18
- // This is in milliseconds, reference: https://github.com/taskrabbit/node-resque/blob/master/lib/plugins/Retry.js#L12
21
+ // This is in milliseconds, reference: https://github.com/actionhero/node-resque/blob/2ffdf0/lib/plugins/Retry.js#L12
19
22
  const RETRY_DELAY = 5 * 1000;
20
23
  const redis = new Redis(connectionDetails.port, connectionDetails.host, connectionDetails.options);
21
24
 
@@ -72,7 +75,7 @@ function getRabbitmqConn() {
72
75
  logger.info('Creating new rabbitmq connection.');
73
76
 
74
77
  rabbitmqConn.on('connect', () => logger.info('Connected to rabbitmq!'));
75
- rabbitmqConn.on('disconnect', params => logger.info('Disconnected from rabbitmq.', params.err.stack));
78
+ rabbitmqConn.on('disconnect', params => logger.info(`Disconnected from rabbitmq: ${params.err.stack}`));
76
79
 
77
80
  return rabbitmqConn;
78
81
  }
@@ -83,17 +86,23 @@ function getRabbitmqConn() {
83
86
  * @param {String} queue
84
87
  * @param {String} messageId
85
88
  */
86
- function pushToRabbitMq(message, queue, messageId) {
89
+ async function pushToRabbitMq(message, queue, messageId) {
87
90
  if (!rabbitmqConf.getConfig().schedulerMode) {
88
91
  return Promise.resolve();
89
92
  }
90
- const channelWrapper = getRabbitmqConn().createChannel({
93
+
94
+ const conn = getRabbitmqConn();
95
+ const channelWrapper = conn.createChannel({
91
96
  json: true,
92
97
  setup: channel => channel.checkExchange(exchange)
93
98
  });
94
99
 
95
100
  logger.info('publishing msg to rabbitmq: %s', messageId);
96
101
 
102
+ channelWrapper.on('error', (error, { name }) => {
103
+ logger.error(`channel wrapper error ${error}:${name}`);
104
+ });
105
+
97
106
  return channelWrapper
98
107
  .publish(exchange, queue, message, {
99
108
  contentType: 'application/json',
@@ -107,11 +116,24 @@ function pushToRabbitMq(message, queue, messageId) {
107
116
  .catch(err => {
108
117
  logger.error('publishing failed to rabbitmq: %s', err.message);
109
118
  channelWrapper.close();
110
-
119
+ conn.close();
111
120
  throw err;
112
121
  });
113
122
  }
114
123
 
124
+ /**
125
+ * Push message to Kafka topic
126
+ * @param {Object} message Job and build config metadata
127
+ * @param {String} topic Topic name
128
+ */
129
+ async function pushToKafka(message, topic) {
130
+ const conn = await AWSProducer.connect();
131
+
132
+ if (conn) {
133
+ await AWSProducer.sendMessage(message, topic);
134
+ }
135
+ }
136
+
115
137
  /**
116
138
  * Schedule a job based on mode
117
139
  * @method schedule
@@ -119,7 +141,7 @@ function pushToRabbitMq(message, queue, messageId) {
119
141
  * @param {Object} buildConfig build config
120
142
  * @return {Promise}
121
143
  */
122
- function schedule(job, buildConfig) {
144
+ async function schedule(job, buildConfig) {
123
145
  const buildCluster = buildConfig.buildClusterName;
124
146
 
125
147
  delete buildConfig.buildClusterName;
@@ -129,8 +151,20 @@ function schedule(job, buildConfig) {
129
151
  buildConfig
130
152
  };
131
153
 
154
+ if (kafkaEnabled && buildConfig.provider) {
155
+ const { accountId, region } = buildConfig.provider;
156
+ const topic = `builds-${accountId}-${region}`;
157
+
158
+ return pushToKafka(msg, topic);
159
+ }
160
+
132
161
  if (rabbitmqConf.getConfig().schedulerMode) {
133
- return pushToRabbitMq(msg, buildCluster, buildConfig.buildId);
162
+ try {
163
+ return await pushToRabbitMq(msg, buildCluster, buildConfig.buildId);
164
+ } catch (err) {
165
+ logger.error(`err in pushing to rabbitmq: ${err}`);
166
+ throw err;
167
+ }
134
168
  }
135
169
 
136
170
  // token is not allowed in executor.stop
@@ -150,15 +184,17 @@ function schedule(job, buildConfig) {
150
184
  * @param {String} buildConfig.blockedBy Jobs that are blocking this job
151
185
  * @return {Promise}
152
186
  */
153
- function start(buildConfig) {
154
- return redis
155
- .hget(`${queuePrefix}buildConfigs`, buildConfig.buildId)
156
- .then(fullBuildConfig => schedule('start', JSON.parse(fullBuildConfig)))
157
- .catch(err => {
158
- logger.error(`err in start job: ${err}`);
187
+ async function start(buildConfig) {
188
+ try {
189
+ const fullBuildConfig = await redis.hget(`${queuePrefix}buildConfigs`, buildConfig.buildId);
159
190
 
160
- return Promise.reject(err);
161
- });
191
+ await schedule('start', JSON.parse(fullBuildConfig));
192
+
193
+ return null;
194
+ } catch (err) {
195
+ logger.error(`err in start job: ${err}`);
196
+ throw err;
197
+ }
162
198
  }
163
199
 
164
200
  /**
@@ -169,79 +205,91 @@ function start(buildConfig) {
169
205
  * @param {String} buildConfig.jobId Job that this build belongs to
170
206
  * @param {String} buildConfig.blockedBy Jobs that are blocking this job
171
207
  * @param {String} buildConfig.started Whether job has started
208
+ * @param {String} buildConfig.jobName Job name
172
209
  * @return {Promise}
173
210
  */
174
- function stop(buildConfig) {
211
+ async function stop(buildConfig) {
175
212
  const started = hoek.reach(buildConfig, 'started', { default: true }); // default value for backward compatibility
176
- const { buildId, jobId } = buildConfig;
177
- const stopConfig = { buildId };
213
+ const { buildId, jobId, jobName } = buildConfig;
214
+ let stopConfig = { buildId, jobId, jobName };
178
215
  const runningKey = `${runningJobsPrefix}${jobId}`;
179
216
 
180
- return (
181
- redis
182
- .hget(`${queuePrefix}buildConfigs`, buildId)
183
- .then(fullBuildConfig => {
184
- const parsedConfig = JSON.parse(fullBuildConfig);
217
+ try {
218
+ const fullBuildConfig = await redis.hget(`${queuePrefix}buildConfigs`, buildId);
219
+ const parsedConfig = JSON.parse(fullBuildConfig);
220
+
221
+ if (parsedConfig) {
222
+ stopConfig = {
223
+ buildId,
224
+ ...parsedConfig
225
+ };
226
+ }
227
+ } catch (err) {
228
+ logger.error(`[Stop Build] failed to get config for build ${buildId}: ${err.message}`);
229
+ }
185
230
 
186
- if (parsedConfig && parsedConfig.annotations) {
187
- stopConfig.annotations = parsedConfig.annotations;
188
- }
231
+ await redis.hdel(`${queuePrefix}buildConfigs`, buildId);
232
+ // If this is a running job
233
+ const runningBuildId = await redis.get(runningKey);
189
234
 
190
- if (parsedConfig && parsedConfig.buildClusterName) {
191
- stopConfig.buildClusterName = parsedConfig.buildClusterName;
192
- }
235
+ if (parseInt(runningBuildId, 10) === buildId) {
236
+ await redis.del(runningKey);
237
+ }
238
+ // If this is a waiting job
239
+ await redis.lrem(`${waitingJobsPrefix}${jobId}`, 0, buildId);
193
240
 
194
- stopConfig.token = parsedConfig.token;
195
- })
196
- .catch(err => {
197
- logger.error(`[Stop Build] failed to get config for build ${buildId}: ${err.message}`);
198
- })
199
- .then(() => redis.hdel(`${queuePrefix}buildConfigs`, buildId))
200
- // If this is a running job
201
- .then(() => redis.get(runningKey))
202
- .then(runningBuildId => {
203
- if (parseInt(runningBuildId, 10) === buildId) {
204
- return redis.del(runningKey);
205
- }
206
-
207
- return null;
208
- })
209
- // If this is a waiting job
210
- .then(() => redis.lrem(`${waitingJobsPrefix}${jobId}`, 0, buildId))
211
- .then(() => (started ? schedule('stop', stopConfig) : null))
212
- );
241
+ if (started) {
242
+ await schedule('stop', stopConfig);
243
+ }
244
+
245
+ return null;
213
246
  }
214
247
 
215
248
  /**
216
249
  * Send message to clear cache from disk
217
250
  * @param {Object} cacheConfig
218
251
  */
219
- function clear(cacheConfig) {
252
+ async function clear(cacheConfig) {
220
253
  const { id, buildClusters } = cacheConfig;
221
- let queueName;
254
+ const data = await redis.hget(`${queuePrefix}buildConfigs`, id);
222
255
 
223
- return redis
224
- .hget(`${queuePrefix}buildConfigs`, id)
225
- .then(data => {
226
- if (data) {
227
- const buildConfig = JSON.parse(data);
256
+ if (data) {
257
+ const buildConfig = JSON.parse(data);
228
258
 
229
- queueName = buildConfig.buildClusterName;
230
- }
231
- })
232
- .then(() => {
233
- if (queueName) {
234
- return pushToRabbitMq({ job: 'clear', cacheConfig }, queueName, id);
235
- }
259
+ const queueName = buildConfig.buildClusterName;
236
260
 
237
- if (buildClusters) {
238
- return Promise.all(
239
- buildClusters.map(cluster => pushToRabbitMq({ job: 'clear', cacheConfig }, cluster, id))
240
- );
241
- }
261
+ if (queueName) {
262
+ await pushToRabbitMq({ job: 'clear', cacheConfig }, queueName, id);
263
+ }
264
+ }
242
265
 
243
- return null;
244
- });
266
+ if (buildClusters) {
267
+ await Promise.all(
268
+ buildClusters.map(async cluster => {
269
+ return pushToRabbitMq({ job: 'clear', cacheConfig }, cluster, id);
270
+ })
271
+ );
272
+ }
273
+
274
+ return null;
275
+ }
276
+
277
+ /**
278
+ * Send message to processHooks API
279
+ * @param {String} webhookConfig as String
280
+ */
281
+ async function sendWebhook(webhookConfig) {
282
+ const parsedConfig = JSON.parse(webhookConfig);
283
+ const apiUri = ecosystem.api;
284
+ const token = executor.tokenGen({
285
+ service: 'queue',
286
+ scope: ['webhook_worker']
287
+ });
288
+ const retryFn = executor.requestRetryStrategyPostEvent;
289
+
290
+ await helper.processHooks(apiUri, token, parsedConfig, retryFn);
291
+
292
+ return null;
245
293
  }
246
294
 
247
295
  module.exports = {
@@ -266,5 +314,12 @@ module.exports = {
266
314
  Retry: retryOptions
267
315
  },
268
316
  perform: clear
317
+ },
318
+ sendWebhook: {
319
+ plugins: ['Retry'],
320
+ pluginOptions: {
321
+ Retry: retryOptions
322
+ },
323
+ perform: sendWebhook
269
324
  }
270
325
  };
@@ -42,7 +42,7 @@ async function shutDownAll(worker, scheduler) {
42
42
  const multiWorker = new NodeResque.MultiWorker(
43
43
  {
44
44
  connection: connectionDetails,
45
- queues: [`${queuePrefix}builds`, `${queuePrefix}cache`],
45
+ queues: [`${queuePrefix}builds`, `${queuePrefix}cache`, `${queuePrefix}webhooks`],
46
46
  minTaskProcessors: workerConfig.minTaskProcessors,
47
47
  maxTaskProcessors: workerConfig.maxTaskProcessors,
48
48
  checkTimeout: workerConfig.checkTimeout,