-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
73 lines (61 loc) · 2 KB
/
worker.js
File metadata and controls
73 lines (61 loc) · 2 KB
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
const config = require('@cheevr/config');
const fork = require('fork-require');
const shortId = require('shortid');
/**
* The worker class wraps communication with the runner process that will run a task in a separate node instance.
* All method calls on this object are proxied if they don't exist already and sent to the runner process transparently.
*/
class Worker {
/**
* @param {Task} task
* @returns {Proxy}
*/
constructor(task) {
this._id = shortId.generate();
this._task = task;
this._enabled = true;
this.state = {};
// TODO allow to set execArgv (for e.g. memory setting) for forked processes
this._runner = fork('./runner.js', {
args: [process.title, this._id, task.file].concat(process.argv),
execArgv: [ '--max_old_space_size=' + config.tasks.memory ]
});
return new Proxy(this, {
get: (obj, method) => obj[method] ? obj[method] : obj._runner[method]
});
}
setState(jobId, state) {
let job = this.state[jobId] = this.state[jobId] || {};
if (job.state === 'running' && state !== 'running') {
job.finished = Date.now();
job.duration = job.finished - job.started;
}
if (job.state !== 'running' && state === 'running') {
job.started = Date.now();
}
job.state = state;
}
get enabled() {
return this._enabled;
}
set enabled(enabled) {
if (this._enabled !== enabled) {
this._runner.enable(enabled);
}
this._enabled = enabled;
}
get id() {
return this._id;
}
get file() {
return this.task.file;
}
get task() {
return this._task;
}
kill() {
// TODO see if SEGTERM cna be sed instead to allow for graceful shutdown. Maybe by sending a kill signal to the child and let it shut down itself
this._runner._childProcess.kill('SIGHUP');
}
}
module.exports = exports = Worker;