-
Notifications
You must be signed in to change notification settings - Fork 0
/
spawner.js
124 lines (105 loc) · 2.78 KB
/
spawner.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
var fork = require('child_process').fork;
var config = require('./../config');
/** @type {Logger} */
var logger = require('../../../lib/logger')('Job');
/**
* @callback ForkCallback
* @param {Error} err
* @param {...*} results
*/
/**
* @param {string} jobName
* @param {ForkCallback} result
* @returns {Function}
*/
function OnExit(jobName, result){
return function(code, signal){
var err;
if (code === null) {
err = 'Job "'+ jobName +'" was killed with signal: "'+ signal +'"';
} else if (code > 0) {
err = 'Job "'+ jobName +'" exited with code: "'+ code +'"';
}
if (err) {
logger.error(err);
result(new Error(err), null);
} else {
logger.info('"'+ jobName +'" finished succefully');
}
};
}
/**
* @param {string} jobName
* @param {ForkCallback} result
* @returns {Function}
*/
function OnError(jobName, result){
return function(err){
logger.error('"'+ jobName +'" error: '+ err.message);
result(err, null);
};
}
/**
* @param {string} jobName
* @returns {Function}
*/
function OnData(jobName){
return function(data){
var buffer = new Buffer(data),
log = buffer.toString();
logger.info('"'+ jobName +'": '+ log.trim());
};
}
/**
* @param {string} jobName
* @returns {Function}
*/
function OnErrorData(jobName){
return function(data){
var buffer = new Buffer(data),
log = buffer.toString();
logger.error('"'+ jobName +'": '+ log.trim());
};
}
/**
* @param {ForkCallback} result
* @returns {Function}
*/
function OnMessage(result){
return function(message){
result.apply(null, message);
};
}
/**
* Empty function
*/
function DoNothing(){}
/**
* @param {string} jobName
* @param {...*} [args] - any additional arguments for job
* @param {ForkCallback} [result] - if last argument is function it will be processed as result callback
* @returns {Function}
*/
function GetForkRun(jobName, args, result){
if (!config[jobName]) {
throw new Error('Job "'+ jobName +'" does not exists');
}
args = Array.prototype.slice.call(arguments, 1);
if (typeof(args[args.length - 1]) == 'function') {
result = args.pop();
} else {
result = DoNothing;
}
return function(){
var child = fork(__dirname +'/jobwrapper', [jobName], {silent: true}),
exit = OnExit(jobName, result);
child.on('exit', exit);
// child.on('close', exit);
child.on('error', OnError(jobName, result));
child.on('message', OnMessage(result));
child.stdout.on('data', OnData(jobName));
child.stderr.on('data', OnErrorData(jobName));
child.send(args);
};
}
module.exports = GetForkRun;