summaryrefslogtreecommitdiff
path: root/src/lib/worker.js
blob: 3a4bb836b6f09d3767306b4a92d60e30324b8788 (plain)
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
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 config = 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'

const JOB_ACCEPTED = 0x01
const JOB_IGNORED  = 0x02
const JOB_NOTFOUND = 0x03

class Worker extends EventEmitter {

    constructor() {
        super()

        /**
         * @type {object.<string, {queue: Queue, paused: boolean}>}
         */
        this.targets = {}

        /**
         * @type {boolean}
         */
        this.polling = false

        /**
         * @type {boolean}
         */
        this.nextpoll = {}

        /**
         * @type {Logger}
         */
        this.logger = getLogger('Worker')
    }

    /**
     * Creates new queue.
     *
     * @param {string} target
     * @param {number} limit
     */
    addTarget(target, limit) {
        this.logger.debug(`addTarget: adding target' ${target}', limit = ${limit}`)

        if (target in this.targets)
            throw new Error(`target '${target}' already added`)

        let queue = Queue({
            concurrency: limit,
            autostart: true
        })
        queue.on('success', this.onJobFinished.bind(this, target))
        queue.on('error', this.onJobFinished.bind(this, target))
        queue.start()

        this.targets[target] = {
            paused: false,
            queue
        }
    }

    /**
     * Deletes a queue.
     *
     * @param {string} target
     */
    removeTarget(target) {
        if (!(target in this.targets))
            throw new Error(`target '${target}' not found`)

        const {queue} = this.targets[target]
        if (queue.length > 0)
            throw new Error(`queue is not empty`)

        this.logger.debug(`deleteTarget: deleting target' ${target}'`)
        queue.removeAllListeners()
        queue.end()
        delete this.targets[target]
    }

    /**
     * @param {string} target
     * @param {number} concurrency
     */
    setTargetConcurrency(target, concurrency) {
        if (!(target in this.targets))
            throw new Error(`target '${target}' not found`)

        this.targets[target].queue.concurrency = concurrency
    }

    /**
     * Stop queues associated with specified targets.
     *
     * @param {null|string[]} targets
     */
    pauseTargets(targets) {
        if (targets === null)
            targets = this.getTargets()

        for (const target of targets) {
            const {queue, paused} = this.targets[target]
            if (paused) {
                this.logger.warn(`pauseTargets: ${target} is already paused`)
                continue
            }

            this.logger.debug(`pauseTargets: stopping ${target}`)
            queue.stop()

            this.targets[target].paused = true
        }
    }

    /**
     * Start queues associated with specified targets.
     *
     * @param {null|string[]} targets
     */
    continueTargets(targets) {
        if (targets === null)
            targets = this.getTargets()

        for (const target of targets) {
            const {queue, paused} = this.targets[target]
            if (!paused) {
                this.logger.warn(`continueTargets: ${target} is not paused`)
                continue
            }

            this.logger.debug(`pauseTargets: starting ${target}`)
            queue.start()

            this.targets[target].paused = false
        }
    }

    /**
     * Checks whether target is being served.
     *
     * @param {string} target
     * @returns {boolean}
     */
    hasTarget(target) {
        return (target in this.targets)
    }

    /**
     * Returns status of all queues.
     *
     * @return {object}
     */
    getStatus() {
        let status = {}
        for (const target in this.targets) {
            if (!this.targets.hasOwnProperty(target))
                continue

            const {queue, paused} = this.targets[target]
            status[target] = {
                paused,
                concurrency: queue.concurrency,
                length: queue.length,
            }
        }
        return status
    }

    /**
     * Returns list of serving targets.
     *
     * @return {string[]}
     */
    getTargets() {
        return Object.keys(this.targets)
    }

    /**
     *
     */
    poll() {
        const LOGPREFIX = `poll():`

        let targets = this.getPollTargets()
        if (!targets.length) {
            this.logger.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 targets
        // it will be called again from onJobFinished()
        if (!this.hasFreeTargets(targets)) {
            this.logger.debug(`${LOGPREFIX} no free targets`)
            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(({rowsCount}) => {
                let message = `${LOGPREFIX} ${rowsCount} processed`
                if (config.get('mysql_fetch_limit') && rowsCount >= config.get('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
    }

    /**
     * Get new tasks from database.
     *
     * @param {string|null|string[]} target
     * @param {string} neededStatus
     * @param {{ids: number[]}} data
     * @returns
     *  {Promise<{
     *    results: Map<number, {status: number, reason: string, target: string}>,
     *    rowsCount: number
     *  }>}
     */
    async getTasks(target = null, neededStatus = STATUS_WAITING, data = {}) {
        const LOGPREFIX = `getTasks(${JSON.stringify(target)}, '${neededStatus}', ${JSON.stringify(data)}):`

        // get new jobs in transaction
        await db.beginTransaction()

        /**
         * @type {Map<number, {status: number, reason: string, target: string}>}
         */
        const jobsResults = new Map()

        let sqlFields = `id, status, target`
        let sql
        if (data.ids) {
            sql = `SELECT ${sqlFields} FROM ${config.get('mysql_table')} WHERE id IN(`+data.ids.map(db.escape).join(',')+`) 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 = config.get('mysql_fetch_limit') !== 0 ? ` LIMIT 0, ${config.get('mysql_fetch_limit')}` : ''
            let sqlWhere = `status=${db.escape(neededStatus)} AND target IN (`+targets.map(db.escape).join(',')+`)`
            sql = `SELECT ${sqlFields} FROM ${config.get('mysql_table')} WHERE ${sqlWhere} ORDER BY id ${sqlLimit} FOR UPDATE`
        }

        /** @type {object[]} results */
        let rows = await db.query(sql)
        this.logger.trace(`${LOGPREFIX} query result:`, rows)

        for (let result of rows) {
            const id = parseInt(result.id)
            const target = String(result.target)
            const status = String(result.status)

            if (status !== neededStatus) {
                let reason = `status = ${status} != ${neededStatus}`
                jobsResults.set(id, {
                    result: JOB_IGNORED,
                    reason
                })

                this.logger.warn(`${LOGPREFIX} ${reason}`)
                continue
            }

            if (!target || !(target in this.targets)) {
                let reason = `target '${target}' not found (job id=${id})`
                jobsResults.set(id, {
                    result: JOB_IGNORED,
                    reason
                })

                this.logger.error(`${LOGPREFIX} ${reason}`)
                continue
            }

            this.logger.debug(`${LOGPREFIX} accepted target='${target}', id=${id}`)

            jobsResults.set(id, {
                result: JOB_ACCEPTED,
                target
            })
        }

        if (data.ids) {
            for (const id of data.ids) {
                if (!jobsResults.has(id))
                    jobsResults.set(id, {
                        result: JOB_NOTFOUND
                    })
            }
        }

        let accepted = [], ignored = []
        for (const [id, jobResult] of jobsResults.entries()) {
            const {result} = jobResult
            switch (result) {
                case JOB_ACCEPTED:
                    accepted.push(id)
                    break

                case JOB_IGNORED:
                    ignored.push(id)
                    break
            }
        }

        if (accepted.length)
            await db.query(`UPDATE ${config.get('mysql_table')} SET status='accepted' WHERE id IN (`+accepted.join(',')+`)`)

        if (ignored.length)
            await db.query(`UPDATE ${config.get('mysql_table')} SET status='ignored' WHERE id IN (`+ignored.join(',')+`)`)

        await db.commit()

        for (const [id, jobResult] of jobsResults.entries()) {
            const {result} = jobResult
            if (result !== JOB_ACCEPTED)
                continue

            const {target} = jobResult
            this.enqueueJob(id, target)
        }

        return {
            results: jobsResults,
            rowsCount: rows.length,
        }
    }

    /**
     * Enqueue job.
     *
     * @param {int} id
     * @param {string} target
     */
    enqueueJob(id, target) {
        const queue = this.targets[target].queue
        queue.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(`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(`setJobStatus(${id})`, error)
                }

                cb()
            }
        })
    }

    /**
     * Run job.
     *
     * @param {number} id
     */
    async run(id) {
        let command = config.get('launcher').replace(/\{id\}/g, id)
        let cwd = config.get('launcher.cwd')
        let env = Object.assign({}, process.env, config.get('launcher.env'))

        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: config.get('max_output_buffer'),
                cwd,
                env
            })

            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)
            })
        })
    }

    /**
     * Write job status to database.
     *
     * @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 = []
        let argv = []

        for (let field in update) {
            let val = update[field]
            list.push(`${field}=?`)
            argv.push(val)
        }

        argv.push(id)

        await db.query(`UPDATE ${config.get('mysql_table')} SET ${list.join(', ')} WHERE id=?`, argv)
    }

    /**
     * @param {string[]} inTargets
     * @returns {boolean}
     */
    hasFreeTargets(inTargets = []) {
        const LOGPREFIX = `hasFreeTargets(${JSON.stringify(inTargets)}):`

        this.logger.debug(`${LOGPREFIX} entered`)

        for (const target in this.targets) {
            if (!this.targets.hasOwnProperty(target) || !inTargets.includes(target))
                continue

            const {paused, queue} = this.targets[target]
            this.logger.trace(LOGPREFIX, target, queue.concurrency, queue.length)

            if (queue.length < queue.concurrency)
                return true
        }

        return false
    }

    /**
     * @param {string} target
     */
    onJobFinished = (target) => {
        this.logger.debug(`onJobFinished: target=${target}`)

        const {paused, queue} = this.targets[target]
        if (!paused && queue.length < queue.concurrency && this.hasPollTarget(target)) {
            this.logger.debug(`onJobFinished: ${queue.length} < ${queue.concurrency}, calling poll(${target})`)
            this.poll()
        }
    }

}

module.exports = {
    Worker,

    STATUS_WAITING,
    STATUS_MANUAL,
    STATUS_ACCEPTED,
    STATUS_IGNORED,
    STATUS_RUNNING,
    STATUS_DONE,

    JOB_ACCEPTED,
    JOB_IGNORED,
    JOB_NOTFOUND,
}