-
Notifications
You must be signed in to change notification settings - Fork 11
/
receiver.js
259 lines (233 loc) · 10.9 KB
/
receiver.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
'use strict';
const amqp = require('amqp-connection-manager');
const threads = require('threads');
const logger = require('screwdriver-logger');
const helper = require('./lib/helper');
const config = require('./lib/config');
const retryQueueLib = require('./lib/retry-queue');
const {
amqpURI,
host,
connectOptions,
queue,
prefetchCount,
messageReprocessLimit,
cacheStrategy,
cachePath,
retryQueue,
retryQueueEnabled
} = config.getConfig();
const { spawn } = threads;
const CACHE_STRATEGY_DISK = 'disk';
let channelWrapper;
/**
* onMessage consume messages in batches, once its available in the queue. channelWrapper has in-built back pressure
* meaning if consumed messages are not ack'd or nack'd, it will not fetch more messages. Definitely need
* to ack or nack messages, otherwise it will halt indefinitely. submit start or stop jobs to build executor
* using threads.
* job = 'start' (or) 'stop' => message is to start or stop build.
* job = 'clear' => message is to clear pipeline or job cache directory.
* clear cache message should be in below json format:
* {"job":"clear","cacheConfig":{"resource":"caches","action":"delete","scope":"pipelines","prefix":"","pipelineId": 1,id":1}}
* scope => "pipelines" (or) jobs; id => based on scope, either pipeline id (or) job id
* @param {Object} data Message from queue with headers, timestamp, and other properties; will be used to ack or nack the message
*/
const onMessage = data => {
try {
const fullBuildConfig = JSON.parse(data.content);
const jobType = fullBuildConfig.job;
const buildConfig = fullBuildConfig.buildConfig || fullBuildConfig.cacheConfig;
if (jobType === 'clear') {
const job = `jobType: ${jobType}, cacheConfig: ${buildConfig}`;
logger.info(`processing ${job}`);
if (
cacheStrategy === CACHE_STRATEGY_DISK &&
cachePath !== '' &&
buildConfig.resource === 'caches' &&
buildConfig.action === 'delete' &&
buildConfig.scope !== '' &&
buildConfig.pipelineId !== '' &&
buildConfig.id !== ''
) {
// eslint-disable-next-line max-len
let dir2Clean = buildConfig.prefix !== '' ? `${cachePath}/${buildConfig.prefix}` : `${cachePath}`;
const threadCache = spawn('./lib/cache.js');
dir2Clean = `${dir2Clean}/${buildConfig.scope}/${buildConfig.pipelineId}`;
if (buildConfig.scope !== 'pipelines') {
dir2Clean = `${dir2Clean}/${buildConfig.id}`;
}
logger.info(`cache directory to clean: ${dir2Clean}`);
threadCache
.send([dir2Clean])
.on('message', () => {
logger.info(`acknowledge, clear cache job completed for ${dir2Clean}`);
channelWrapper.ack(data);
threadCache.kill();
})
.on('error', error => {
logger.info(`acknowledge, clear cache job for ${dir2Clean} - error: ${error} `);
channelWrapper.ack(data);
threadCache.kill();
})
.on('exit', () => {
logger.info(`thread terminated for clear cache job ${dir2Clean}`);
});
} else {
logger.error(
`required conditions not met, cacheStrategy: ${cacheStrategy}, ` +
`cachePath: ${cachePath}, cacheConfig: ${buildConfig}, ` +
`acknowledge data: ${data}, payload: ${data.content} `
);
channelWrapper.ack(data);
}
} else {
const thread = spawn('./lib/jobs.js');
let retryCount = 0;
const { buildId } = buildConfig;
const job = `jobId: ${buildConfig.jobId}, jobType: ${jobType}, buildId: ${buildId}`;
logger.info(`processing ${job}`);
if (typeof data.properties.headers !== 'undefined') {
if (Object.keys(data.properties.headers).length > 0) {
retryCount = data.properties.headers['x-death'][0].count;
logger.info(`retrying ${retryCount}(${messageReprocessLimit}) for ${job}`);
}
}
thread
.send([jobType, buildConfig, job])
.on('message', successful => {
logger.info(`acknowledge, job completed for ${job}, result: ${successful}`);
if (!successful && jobType === 'start') {
// push to retry only for start jobs
retryQueueLib.push(buildConfig, buildId);
}
channelWrapper.ack(data);
thread.kill();
})
.on('error', async error => {
thread.kill();
if (['403', '404'].includes(error.message.substring(0, 3))) {
channelWrapper.ack(data);
return;
}
if (retryCount >= messageReprocessLimit) {
logger.info(`acknowledge, max retries exceeded for ${job}`);
try {
await helper.updateBuildStatusAsync(buildConfig, 'FAILURE', `${error}`);
logger.info(`build status successfully updated for build ${buildId}`);
} catch (err) {
logger.error(`Failed to update build status to FAILURE for build:${buildId}:${err}`);
}
channelWrapper.ack(data);
} else {
logger.info(
`err: ${error}, don't acknowledge, ` +
`retried ${retryCount}(${messageReprocessLimit}) for ${job}`
);
channelWrapper.nack(data, false, false);
}
})
.on('exit', exitCode => {
logger.info(`thread exit code ${exitCode} terminated for ${job}`);
});
}
} catch (err) {
logger.error(`error ${err}, acknowledge data: ${data} payload: ${data.content} `);
channelWrapper.ack(data);
}
};
/**
* onMessage consume messages in batches, once its available in the queue. channelWrapper has in-built back pressure
* meaning if consumed messages are not ack'd or nack'd, it will not fetch more messages. Definitely need
* to ack or nack messages, otherwise it will halt indefinitely. submit start or stop jobs to build executor
* using threads.
* job = 'verify' => message is to verify the build.
* @param {Object} data Message from queue with headers, timestamp, and other properties; will be used to ack or nack the message
*/
const onRetryMessage = async data => {
try {
const parsedData = JSON.parse(data.content);
const { job: jobType, buildConfig } = parsedData;
const thread = spawn('./lib/jobs.js');
let retryCount = 0;
const { buildId } = buildConfig;
const job = `jobId: ${buildConfig.jobId}, jobType: ${jobType}, buildId: ${buildId}`;
logger.info(`processing ${job}`);
if (typeof data.properties.headers !== 'undefined') {
if (Object.keys(data.properties.headers).length > 0) {
retryCount = data.properties.headers['x-death'][0].count;
logger.info(`retrying ${retryCount}(${messageReprocessLimit}) for ${job}`);
}
}
thread
.send([jobType, buildConfig, job])
.on('message', async message => {
logger.info(`acknowledge, job completed for ${job}, result: ${message}`);
if (message) {
try {
await helper.updateBuildStatusAsync(buildConfig, 'FAILURE', message);
logger.info(`build status successfully updated for build ${buildId}`);
} catch (err) {
logger.error(`Failed to update build status to FAILURE for build:${buildId}:${err}`);
}
}
channelWrapper.ack(data);
thread.kill();
})
.on('error', async error => {
if (retryCount >= messageReprocessLimit) {
logger.info(`acknowledge, max retries exceeded for ${job} ${error}`);
try {
await helper.updateBuildStatusAsync(buildConfig, 'FAILURE', error.message);
logger.info(`build status successfully updated for build ${buildId}`);
} catch (err) {
logger.error(`Failed to update build status to FAILURE for build:${buildId}:${err}`);
}
channelWrapper.ack(data);
} else {
logger.info(
`err: ${error}, don't acknowledge, retried ` +
`${retryCount}(${messageReprocessLimit}) for ${job}`
);
channelWrapper.nack(data, false, false);
}
thread.kill();
})
.on('exit', exitCode => {
logger.info(`thread exit code ${exitCode} terminated for ${job}`);
});
} catch (err) {
logger.error(`${retryQueue}: error ${err}, acknowledge data: ${data} payload: ${data.content} `);
channelWrapper.ack(data);
}
};
/**
* Invoke function to start listening for messages
* @returns {Object} Returns the connection obj
*/
const listen = async () => {
const connection = amqp.connect([amqpURI], connectOptions);
connection.on('connect', () => {
logger.info('rabbitmq server connected!');
});
connection.on('disconnect', params => {
logger.info(`server disconnected: ${params.err.stack}. reconnecting rabbitmq server ${host}`);
});
const setup = channel => {
const queueFn = [channel.checkQueue(queue), channel.prefetch(prefetchCount), channel.consume(queue, onMessage)];
if (retryQueueEnabled) {
queueFn.concat([channel.checkQueue(retryQueue), channel.consume(retryQueue, onRetryMessage)]);
}
return Promise.all(queueFn);
};
channelWrapper = connection.createChannel({
setup
});
channelWrapper.waitForConnect().then(() => {
logger.info(`waiting for messages in queues: ${queue}`);
if (retryQueueEnabled) {
logger.info(`waiting for messages in queues: ${retryQueue}`);
}
});
return connection;
};
module.exports.listen = listen;