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
|
const Queue = require('queue')
const child_process = require('child_process')
const db = require('./db')
const {timestamp} = require('./util')
const {getLogger} = require('./logger')
const EventEmitter = require('events')
const {workerConfig} = require('./config')
const STATUS_WAITING = 'waiting'
const STATUS_MANUAL = 'manual'
const STATUS_ACCEPTED = 'accepted'
const STATUS_IGNORED = 'ignored'
const STATUS_RUNNING = 'running'
const STATUS_DONE = 'done'
const RESULT_OK = 'ok'
const RESULT_FAIL = 'fail'
class Worker extends EventEmitter {
constructor() {
super()
/**
* @type {object.<string, {slots: object.<string, {limit: number, queue: Queue}>}>}
*/
this.targets = {}
/**
* @type {boolean}
*/
this.polling = false
/**
* @type {boolean}
*/
this.nextpoll = {}
/**
* @type {Logger}
*/
this.logger = getLogger('Worker')
}
/**
* @param {string} target
* @param {string} slot
* @param {number} limit
*/
addSlot(target, slot, limit) {
this.logger.debug(`addSlot: adding slot '${slot}' for target' ${target}' (limit: ${limit})`)
if (this.targets[target] === undefined)
this.targets[target] = {slots: {}}
if (this.targets[target].slots[slot] !== undefined)
throw new Error(`slot ${slot} for target ${target} has already been added`)
let queue = Queue({
concurrency: limit,
autostart: true
})
queue.on('success', this.onJobFinished.bind(this, target, slot))
queue.on('error', this.onJobFinished.bind(this, target, slot))
queue.start()
this.targets[target].slots[slot] = {limit, queue}
}
/**
* @param {string} target
* @returns {boolean}
*/
hasTarget(target) {
return (target in this.targets)
}
/**
* Returns status of all queues.
*
* @return {object}
*/
getStatus() {
let status = {targets: {}}
for (const targetName in this.targets) {
let target = this.targets[targetName]
status.targets[targetName] = {}
for (const slotName in target.slots) {
const {queue, limit} = target.slots[slotName]
status.targets[targetName][slotName] = {
concurrency: queue.concurrency,
limit,
length: queue.length,
}
}
}
return status
}
/**
* @return {string[]}
*/
getTargets() {
return Object.keys(this.targets)
}
/**
*
*/
poll() {
const LOGPREFIX = `poll():`
let targets = this.getPollTargets()
if (!targets.length) {
this.poller.warn(`${LOGPREFIX} no targets`)
return
}
// skip and postpone the poll, if we're in the middle on another poll
// it will be called again from the last .then() at the end of this method
if (this.polling) {
this.logger.debug(`${LOGPREFIX} already polling`)
return
}
// skip and postpone the poll, if no free slots
// it will be called again from onJobFinished()
if (!this.hasFreeSlots(targets)) {
this.logger.debug(`${LOGPREFIX} no free slots`)
return
}
// set polling flag
this.polling = true
// clear postponed polls target list
this.setPollTargets()
this.logger.debug(`${LOGPREFIX} calling getTasks(${JSON.stringify(targets)})`)
this.getTasks(targets)
.then(({rows}) => {
let message = `${LOGPREFIX} ${rows} processed`
if (workerConfig.mysql_fetch_limit && rows >= workerConfig.mysql_fetch_limit) {
// it seems, there are more, so we'll need to perform another query
this.setPollTargets(targets)
message += `, scheduling more polls (targets: ${JSON.stringify(this.getPollTargets())})`
}
this.logger.debug(message)
})
.catch((error) => {
this.logger.error(`${LOGPREFIX}`, error)
//this.setPollTargets(targets)
})
.then(() => {
// unset polling flag
this.polling = false
// perform another poll, if needed
if (this.getPollTargets().length > 0) {
this.logger.debug(`${LOGPREFIX} next poll scheduled, calling poll() again`)
this.poll()
}
})
}
/**
* @param {string|string[]|null} target
*/
setPollTargets(target) {
// when called without parameter, remove all targets
if (target === undefined) {
this.nextpoll = {}
return
}
// just a fix
if (target === 'null')
target = null
if (Array.isArray(target)) {
target.forEach(t => {
this.nextpoll[t] = true
})
} else {
if (target === null)
this.nextpoll = {}
this.nextpoll[target] = true
}
}
/**
* @return {string[]}
*/
getPollTargets() {
if (null in this.nextpoll)
return Object.keys(this.targets)
return Object.keys(this.nextpoll)
}
/**
* @param {string} target
* @return {boolean}
*/
hasPollTarget(target) {
return target in this.nextpoll || null in this.nextpoll
}
/**
* @param {string|null|string[]} target
* @param {string} reqstatus
* @param {object} data
* @returns {Promise<{ignored: number, accepted: number, rows: number}>}
*/
async getTasks(target = null, reqstatus = STATUS_WAITING, data = {}) {
const LOGPREFIX = `getTasks(${JSON.stringify(target)}, '${reqstatus}', ${JSON.stringify(data)}):`
// get new jobs in transaction
await db.beginTransaction()
let error = null
let sqlFields = `id, status, target, slot`
let sql
if (data.id) {
sql = `SELECT ${sqlFields} FROM ${workerConfig.mysql_table} WHERE id=${db.escape(data.id)} FOR UPDATE`
} else {
let targets
if (target === null) {
targets = Object.keys(this.targets)
} else if (!Array.isArray(target)) {
targets = [target]
} else {
targets = target
}
let sqlLimit = workerConfig.mysql_fetch_limit !== 0 ? ` LIMIT 0, ${workerConfig.mysql_fetch_limit}` : ''
let sqlWhere = `status=${db.escape(reqstatus)} AND target IN (`+targets.map(db.escape).join(',')+`)`
sql = `SELECT ${sqlFields} FROM ${workerConfig.mysql_table} WHERE ${sqlWhere} ORDER BY id ${sqlLimit} FOR UPDATE`
}
/** @type {object[]} results */
let results = await db.query(sql)
this.logger.trace(`${LOGPREFIX} query result:`, results)
/**
* @type {{target: string, slot: string, id: number}[]}
*/
let accepted = []
/**
* @type {number[]}
*/
let ignored = []
for (let result of results) {
let {id, slot, target, status} = result
id = parseInt(id)
if (status !== reqstatus) {
error = `status = ${status} != ${reqstatus}`
this.logger.warn(`${LOGPREFIX} ${error}`)
ignored.push(id)
continue
}
if (!target || this.targets[target] === undefined) {
error = `target '${target}' not found (job id=${id})`
this.logger.error(`${LOGPREFIX} ${error}`)
ignored.push(id)
continue
}
if (!slot || this.targets[target].slots[slot] === undefined) {
error = `slot '${slot}' of target '${target}' not found (job id=${id})`
this.logger.error(`${LOGPREFIX} ${error}`)
ignored.push(id)
continue
}
this.logger.debug(`${LOGPREFIX} accepted target='${target}', slot='${slot}', id=${id}`)
accepted.push({target, slot, id})
}
if (accepted.length)
await db.query(`UPDATE ${workerConfig.mysql_table} SET status='accepted' WHERE id IN (`+accepted.map(j => j.id).join(',')+`)`)
if (ignored.length)
await db.query(`UPDATE ${workerConfig.mysql_table} SET status='ignored' WHERE id IN (`+ignored.join(',')+`)`)
await db.commit()
accepted.forEach(({id, target, slot}) => {
let q = this.targets[target].slots[slot].queue
q.push(async (cb) => {
let data = {
code: null,
signal: null,
stdout: '',
stderr: ''
}
let result = RESULT_OK
try {
await this.setJobStatus(id, STATUS_RUNNING)
Object.assign(data, (await this.run(id)))
if (data.code !== 0)
result = RESULT_FAIL
} catch (error) {
this.logger.error(`${LOGPREFIX} job ${id}: error while run():`, error)
result = RESULT_FAIL
data.stderr = (error instanceof Error) ? (error.message + '\n' + error.stack) : (error + '')
} finally {
this.emit('job-done', {
id,
result,
...data
})
try {
await this.setJobStatus(id, STATUS_DONE, result, data)
} catch (error) {
this.logger.error(`${LOGPREFIX} setJobStatus(${id})`, error)
}
cb()
}
})
})
return {
error,
rows: results.length,
accepted: accepted.length,
ignored: ignored.length,
}
}
/**
* @param {number} id
*/
async run(id) {
let command = workerConfig.launcher.replace(/\{id\}/g, id)
let args = command.split(/ +/)
return new Promise((resolve, reject) => {
this.logger.info(`run(${id}): launching`, args)
let process = child_process.spawn(args[0], args.slice(1), {
maxBuffer: workerConfig.max_output_buffer
})
let stdoutChunks = []
let stderrChunks = []
process.on('exit',
/**
* @param {null|number} code
* @param {null|string} signal
*/
(code, signal) => {
let stdout = stdoutChunks.join('')
let stderr = stderrChunks.join('')
stdoutChunks = undefined
stderrChunks = undefined
resolve({
code,
signal,
stdout,
stderr
})
})
process.on('error', (error) => {
reject(error)
})
process.stdout.on('data', (data) => {
if (data instanceof Buffer)
data = data.toString('utf-8')
stdoutChunks.push(data)
})
process.stderr.on('data', (data) => {
if (data instanceof Buffer)
data = data.toString('utf-8')
stderrChunks.push(data)
})
})
}
/**
* @param {number} id
* @param {string} status
* @param {string} result
* @param {object} data
* @return {Promise<void>}
*/
async setJobStatus(id, status, result = RESULT_OK, data = {}) {
let update = {
status,
result
}
switch (status) {
case STATUS_RUNNING:
case STATUS_DONE:
update[status === STATUS_RUNNING ? 'time_started' : 'time_finished'] = timestamp()
break
}
if (data.code !== undefined)
update.return_code = data.code
if (data.signal !== undefined)
update.sig = data.signal
if (data.stderr !== undefined)
update.stderr = data.stderr
if (data.stdout !== undefined)
update.stdout = data.stdout
let list = []
for (let field in update) {
let val = update[field]
if (val !== null)
val = db.escape(val)
list.push(`${field}=${val}`)
}
await db.query(`UPDATE ${workerConfig.mysql_table} SET ${list.join(', ')} WHERE id=?`, [id])
}
/**
* @param {string[]} inTargets
* @returns {boolean}
*/
hasFreeSlots(inTargets = []) {
const LOGPREFIX = `hasFreeSlots(${JSON.stringify(inTargets)}):`
this.logger.debug(`${LOGPREFIX} entered`)
for (const target in this.targets) {
if (!inTargets.includes(target))
continue
for (const slot in this.targets[target].slots) {
const {limit, queue} = this.targets[target].slots[slot]
this.logger.debug(LOGPREFIX, limit, queue.length)
if (queue.length < limit)
return true
}
}
return false
}
/**
* @param {string} target
* @param {string} slot
*/
onJobFinished = (target, slot) => {
this.logger.debug(`onJobFinished: target=${target}, slot=${slot}`)
const {queue, limit} = this.targets[target].slots[slot]
if (queue.length < limit && this.hasPollTarget(target)) {
this.logger.debug(`onJobFinished: ${queue.length} < ${limit}, calling poll(${target})`)
this.poll()
}
}
}
module.exports = {
Worker,
STATUS_WAITING,
STATUS_MANUAL,
STATUS_ACCEPTED,
STATUS_IGNORED,
STATUS_RUNNING,
STATUS_DONE,
}
|