-
Notifications
You must be signed in to change notification settings - Fork 18
/
server-package.js
101 lines (91 loc) · 2.19 KB
/
server-package.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
var childProcess = require('child_process');
var psTree = require('ps-tree');
var forever = require('forever');
var log = new(require('basic-logger'))({
showTimestamp: true,
prefix: "ServerContainer"
});
var fs = require('fs');
var extend = require('extend');
var server = function (params) {
var that = this;
this.settings = {
forever: {
enabled: false,
options: {
root: './logs',
pidPath: './pids',
sockPath: './sock',
debug: false,
stream: false
}
}
}
extend(true, this.settings, params);
this.start = function() {
if(this.settings.config) {
fs.writeFileSync('./config.hjson', this.settings.config, 'utf8');
}
if (this.settings.forever.enabled) {
forever.load(this.settings.forever.options);
that.pid = forever.start('./start.js');
}
else {
that.proc = runScript('./start.js', function (err) {
if (err) throw err;
});
}
};
this.stop = function() {
stopServer();
};
function stopServer() {
if (that.settings.forever.enabled) {
forever.stop();
}
else {
that.proc.kill('SIGINT');
//kill(that.pid);
}
log.info('Stopping Server Container');
}
}
function runScript(scriptPath, callback) {
var invoked = false;
var proc = childProcess.fork(scriptPath);
proc.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
proc.on('exit', function (code) {
if (invoked) return;
invoked = true;
//var err = code === 0 ? null : new Error('exit code ' + code);
callback();
});
return proc;
}
function kill(pid, signal, callback) {
signal = signal || 'SIGKILL';
callback = callback || function () {};
var killTree = true;
if(killTree) {
psTree(pid, function (err, children) {
[pid].concat(
children.map(function (p) {
return p.PID;
})
).forEach(function (tpid) {
try { process.kill(tpid, signal) }
catch (ex) { }
});
callback();
});
} else {
try { process.kill(pid, signal) }
catch (ex) { }
callback();
}
};
module.exports = server;