aboutsummaryrefslogtreecommitdiff
path: root/src/jobd.js
blob: 5dd0d6da592e7d4e9115d34a6db30d9e5a3c93a6 (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
#!/usr/bin/env node
const minimist = require('minimist')
const os = require('os')
const loggerModule = require('./lib/logger')
const config = require('./lib/config')
const db = require('./lib/db')
const {uniq} = require('lodash')
const {createCallablePromise} = require('./lib/util')
const {
    validateInputTargetAndConcurrency,
    validateInputTargets
} = require('./lib/data-validator')
const {RequestHandler} = require('./lib/request-handler')
const {
    Server,
    Connection,
    RequestMessage,
    ResponseMessage
} = require('./lib/server')
const {
    Worker,
    STATUS_MANUAL,
    JOB_NOTFOUND,
    JOB_IGNORED
} = require('./lib/worker')
const package_json = require('../package.json')

const DEFAULT_CONFIG_PATH = "/etc/jobd.conf"

/**
 * @type {Worker}
 */
let worker

/**
 * @type {Logger}
 */
let logger

/**
 * @type {Server}
 */
let server

/**
 * @type {RequestHandler}
 */
let requestHandler

/**
 * @type {object.<string, Promise>}
 */
let jobPromises = {}


main().catch(e => {
    console.error(e)
    process.exit(1)
})


async function main() {
    await initApp('jobd')
    await initDatabase()
    initWorker()
    initRequestHandler()
    initServer()
    connectToMaster()
}

async function initApp(appName) {
    if (process.argv.length < 3) {
        usage()
        process.exit(0)
    }

    process.on('SIGINT', term)
    process.on('SIGTERM', term)

    const argv = minimist(process.argv.slice(2), {
        boolean: ['help', 'version'],
        default: {
            config: DEFAULT_CONFIG_PATH
        }
    })

    if (argv.help) {
        usage()
        process.exit(0)
    }

    if (argv.version) {
        console.log(package_json.version)
        process.exit(0)
    }

    // read config
    try {
        config.parseWorkerConfig(argv.config)
    } catch (e) {
        console.error(`config parsing error: ${e.message}`)
        process.exit(1)
    }

    await loggerModule.init({
        file: config.get('log_file'),
        levelFile: config.get('log_level_file'),
        levelConsole: config.get('log_level_console'),
    })
    logger = loggerModule.getLogger(appName)

    let processTitle = `${appName}`
    if (config.get('name'))
        processTitle += ` ${config.get('name')}`
    process.title = processTitle
}

function initWorker() {
    worker = new Worker()

    const targets = config.get('targets')
    for (const target in targets) {
        let limit = targets[target]
        worker.addTarget(target, limit)
    }

    worker.on('job-done', (data) => {
        if (jobPromises[data.id] !== undefined) {
            const P = jobPromises[data.id]
            delete jobPromises[data.id]

            logger.trace(`job-done: resolving promise of job ${data.id}`)
            P.resolve(data)
        } else {
            // this is not an error, as there will be no promise unless it's a manual job
            // so this is totally normal situation, thus debug() and not warn() or error()
            logger.debug(`job-done: jobPromises[${data.id}] is undefined`)
        }
    })
}

function initRequestHandler() {
    requestHandler = new RequestHandler()
    requestHandler.set('poll', onPollRequest)
    requestHandler.set('status', onStatus)
    requestHandler.set('run-manual', onRunManual)
    requestHandler.set('send-signal', onSendSignal)
    requestHandler.set('pause', onPause)
    requestHandler.set('continue', onContinue)
    requestHandler.set('add-target', onAddTarget)
    requestHandler.set('remove-target', onRemoveTarget)
    requestHandler.set('set-target-concurrency', onSetTargetConcurrency)
}

function initServer() {
    server = new Server()
    server.on('new-connection', (connection) => {
        connection.on('request-message', (message, connection) => {
            requestHandler.process(message, connection)
        })
    })
    server.start(config.get('port'), config.get('host'))
}

async function initDatabase() {
    try {
        await db.init()
    } catch (error) {
        logger.error('failed to connect to MySQL', error)
        process.exit(1)
    }
    logger.info('db initialized')
}

function connectToMaster() {
    const port = config.get('master_port')
    const host = config.get('master_host')

    if (!host || !port) {
        logger.debug('connectToMaster: master host or port is not defined')
        return
    }

    async function connect() {
        const connection = new Connection()
        await connection.connect(host, port)

        try {
            let response = await connection.sendRequest(
                new RequestMessage('register-worker', {
                    name: config.get('name') || os.hostname(),
                    targets: worker.getTargets()
                })
            )
            logger.debug('connectToMaster: response:', response)
        } catch (error) {
            logger.error('connectToMaster: error while awaiting response:', error)
        }

        connection.on('close', () => {
            logger.warn(`connectToMaster: connection closed`)
            tryToConnect()
        })

        connection.on('request-message', (message, connection) => {
            requestHandler.process(message, connection)
        })
    }

    function tryToConnect(now = false) {
        setTimeout(() => {
            connect().catch(error => {
                logger.warn(`connectToMaster: connection failed`, error)
                tryToConnect()
            })
        }, now ? 0 : config.get('master_reconnect_timeout') * 1000)
    }

    tryToConnect(true)
}

function usage() {
    let s = `${process.argv[1]} OPTIONS

Options:
    --config <path>  Path to config. Default: ${DEFAULT_CONFIG_PATH}
    --help           Show this help.
    --version        Print version.`

    console.log(s)
}

async function term() {
    if (logger)
        logger.info('shutdown')

    await loggerModule.shutdown()
    process.exit()
}



/****************************************/
/**                                    **/
/**          Request handlers          **/
/**                                    **/
/****************************************/

/**
 * @param {object} data
 * @return {Promise<string>}
 */
async function onPollRequest(data) {
    let targets = validateInputTargets(data, worker)

    worker.setPollTargets(targets)
    worker.poll()

    return 'ok'
}

/**
 * @param {object} data
 * @return {Promise<object>}
 */
async function onStatus(data) {
    return {
        targets: worker.getStatus(),
        jobPromisesCount: Object.keys(jobPromises).length,
        memoryUsage: process.memoryUsage()
    }
}

/**
 * @param {{ids: number[]}} data
 * @return {Promise}
 */
async function onRunManual(data) {
    let {ids: jobIds} = data
    jobIds = uniq(jobIds)

    for (const id of jobIds) {
        // if at least one item is not a number, reject
        if (typeof id !== 'number')
            throw new Error(`all ids must be numbers, got ${typeof id}`)

        // if at least one of the jobs is already being run, reject
        if (id in jobPromises)
            throw new Error(`another client is already waiting for job ${id}`)
    }

    // create a bunch of promises, one per job
    let promises = []
    for (const id of jobIds) {
        const P = createCallablePromise()
        jobPromises[id] = P
        promises.push(P)
    }

    // get jobs from database and enqueue for execution
    const {results} = await worker.getTasks(null, STATUS_MANUAL, {ids: jobIds})

    // wait till all jobs are done (or failed), then send a response
    const P = Promise.allSettled(promises).then(results => {
        const response = {}

        for (let i = 0; i < results.length; i++) {
            let jobId = jobIds[i]
            let result = results[i]

            if (result.status === 'fulfilled') {
                if (!('jobs' in response))
                    response.jobs = {}

                if (result.value?.id !== undefined)
                    delete result.value.id

                response.jobs[jobId] = result.value
            } else if (result.status === 'rejected') {
                if (!('errors' in response))
                    response.errors = {}

                response.errors[jobId] = result.reason?.message
            }
        }

        return response
    })

    // reject all ignored / non-found jobs
    for (const [id, value] of results.entries()) {
        if (!(id in jobPromises)) {
            this.logger.error(`run-manual: ${id} not found in jobPromises`)
            continue
        }

        if (value.result === JOB_IGNORED || value.result === JOB_NOTFOUND) {
            const P = jobPromises[id]
            delete jobPromises[id]

            if (value.result === JOB_IGNORED)
                P.reject(new Error(value.reason))

            else if (value.result === JOB_NOTFOUND)
                P.reject(new Error(`job ${id} not found`))
        }
    }

    return P
}

async function onSendSignal(data) {
    const {jobs: jobToSignalMap} = data
    const results = {}
    for (const id in jobToSignalMap) {
        if (!jobToSignalMap.hasOwnProperty(id))
            continue
        const signal = jobToSignalMap[id]
        results[id] = worker.killJobProcess(id, signal)
    }
    return results
}

/**
 * @param {{targets: string[]}} data
 */
async function onPause(data) {
    let targets = validateInputTargets(data, worker)
    worker.pauseTargets(targets)
    return 'ok'
}

/**
 * @param {{targets: string[]}} data
 */
async function onContinue(data) {
    let targets
    if ((targets = validateInputTargets(data, worker)) === false)
        return

    // continue queues
    worker.continueTargets(targets)

    // poll just in case
    worker.poll()

    return 'ok'
}

/**
 * @param {{target: string, concurrency: int}} data
 */
async function onAddTarget(data) {
    validateInputTargetAndConcurrency(data)
    worker.addTarget(data.target, data.concurrency)
    return 'ok'
}

/**
 * @param {{target: string}} data
 */
async function onRemoveTarget(data) {
    validateInputTargetAndConcurrency(data, true)
    worker.removeTarget(data.target)
    return 'ok'
}

/**
 * @param {object} data
 */
async function onSetTargetConcurrency(data) {
    validateInputTargetAndConcurrency(data)
    worker.setTargetConcurrency(data.target, data.concurrency)
    return 'ok'
}