-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdaemonize.js
More file actions
358 lines (276 loc) · 9.77 KB
/
daemonize.js
File metadata and controls
358 lines (276 loc) · 9.77 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
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
// Copyright (c) 2012 Kuba Niegowski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
"use strict";
var fs = require("fs"),
path = require("path"),
util = require("util"),
constants = require("./constants"),
spawn = require("child_process").spawn,
EventEmitter = require("events").EventEmitter;
exports.setup = function(options) {
return new Daemon(options);
};
var Daemon = function(options) {
function find_coffee() {
var file_names = {};
function recursive_search(obj) {
var child, children, found, i, len, pos,
pattern = 'coffee-script/register.js';
if (!file_names[obj.filename]) {
pos = obj.filename.lastIndexOf(pattern);
if (pos === obj.filename.length - pattern.length) {
return obj.filename;
}
file_names[obj.filename] = true;
children = obj.children;
for (i = 0, len = children.length; i < len; i += 1) {
child = children[i];
if (found = recursive_search(child)) {
return found;
}
}
}
}
return recursive_search(process.mainModule);
}
EventEmitter.call(this);
if (!options.main)
throw new Error("Expected 'main' option for daemonize");
var coffeePath,
dir = path.dirname(module.parent.filename),
main = path.resolve(dir, options.main),
name = options.name || path.basename(main, ".js");
if (coffeePath = find_coffee()) {
options.coffeePath = coffeePath;
}
if (!this._isFile(main))
throw new Error("Can't find daemon main module: '" + main + "'");
// normalize options
this._options = {};
// shallow copy
for (var arg in options)
this._options[arg] = options[arg];
this._options.main = main;
this._options.name = this.name = name;
this._options.pidfile = options.pidfile
? path.resolve(dir, options.pidfile)
: path.join("/var/run", name + ".pid");
this._options.user = options.user || "";
this._options.group = options.group || "";
if (typeof options.umask == "undefined")
this._options.umask = 0;
else if (typeof options.umask == "string")
this._options.umask = parseInt(options.umask);
this._options.args = this._makeArray(options.args);
this._options.argv = this._makeArray(options.argv || process.argv.slice(2));
this._stopTimeout = options.stopTimeout || 2000;
this._childExitHandler = null;
this._childDisconnectHandler = null;
this._childDisconnectTimer = null;
if (!options.silent)
this._bindConsole();
};
util.inherits(Daemon, EventEmitter);
Daemon.prototype.start = function(listener) {
// make sure daemon is not running
var pid = this._sendSignal(this._getpid());
if (pid) {
this.emit("running", pid);
if (listener) listener(null, pid);
return this;
}
// callback for started and error
if (listener) {
var errorFunc, startedFunc;
this.once("error", errorFunc = function(err) {
this.removeListener("started", startedFunc);
listener(err, 0);
}.bind(this));
this.once("started", startedFunc = function(pid) {
this.removeListener("error", errorFunc);
listener(null, pid);
}.bind(this));
}
this.emit("starting");
// check whether we have right to write to pid file
var err = this._savepid("");
if (err) {
this.emit("error", new Error("Failed to write pidfile (" + err + ")"));
return this;
}
// spawn child process
var child = spawn(process.execPath, (this._options.args || []).concat([
__dirname + "/wrapper.js"
]).concat(this._options.argv), {
env: process.env,
stdio: ["ignore", "ignore", "ignore", "ipc"],
detached: true
}
);
pid = child.pid;
// save pid
this._savepid(pid);
// rethrow childs's exceptions
child.on("message", function(msg) {
if (msg.type == "error")
throw new Error(msg.error);
});
// wrapper.js will exit with special exit codes
child.once("exit", this._childExitHandler = function(code, signal) {
child.removeListener("disconnect", this._childDisconnectHandler);
clearTimeout(this._childDisconnectTimer);
if (code > 0) {
this.emit("error", new Error(
code > 1
? constants.findExitCode(code)
: "Module '" + this._options.main + "' stopped unexpected"
));
} else {
this.emit("stopped");
}
}.bind(this));
// check if it is still running when ipc closes
child.once("disconnect", this._childDisconnectHandler = function() {
// check it in 100ms in case this is child's exit
this._childDisconnectTimer = setTimeout(function() {
child.removeListener("exit", this._childExitHandler);
if (this._sendSignal(pid)) {
this.emit("started", pid);
} else {
this.emit("error", new Error("Daemon failed to start"));
}
}.bind(this), 100);
}.bind(this));
// trigger child initialization
child.send({type: "init", options: this._options});
// remove child from reference count to make parent process exit
child.unref();
return this;
};
Daemon.prototype.stop = function(listener, signals, timeout) {
return this._kill(signals || ["SIGTERM"], timeout || 0, listener);
};
Daemon.prototype.kill = function(listener, signals, timeout) {
return this._kill(signals || ["SIGTERM", "SIGKILL"], timeout || 0, listener);
};
Daemon.prototype.status = function() {
return this._sendSignal(this._getpid());
};
Daemon.prototype.sendSignal = function(signal) {
return this._sendSignal(this._getpid(), signal);
};
Daemon.prototype._makeArray = function(args) {
if (typeof args == "undefined") return [];
if (typeof args == "string")
return args.trim().split(/\s+/).filter(function(arg) { return !!arg; });
return args;
};
Daemon.prototype._getpid = function() {
try {
return parseInt(fs.readFileSync(this._options.pidfile));
}
catch (err) {
}
return 0;
};
Daemon.prototype._savepid = function(pid) {
try {
fs.writeFileSync(this._options.pidfile, pid + "\n");
}
catch (ex) {
return ex.code;
}
return "";
};
Daemon.prototype._sendSignal = function(pid, signal) {
if (!pid) return 0;
try {
process.kill(pid, signal || 0);
return pid;
}
catch (err) {
}
return 0;
};
Daemon.prototype._kill = function(signals, timeout, listener) {
var pid = this._sendSignal(this._getpid());
if (!pid) {
this.emit("notrunning");
if (listener) listener(null, 0);
return this;
}
if (listener) {
this.once("stopped", function(pid) {
listener(null, pid);
});
}
this.emit("stopping");
this._tryKill(pid, signals, timeout, function(pid) {
// try to remove pid file
try {
fs.unlinkSync(this._options.pidfile);
}
catch (ex) {}
this.emit("stopped", pid);
}.bind(this));
return this;
};
Daemon.prototype._tryKill = function(pid, signals, timeout, callback) {
if (!this._sendSignal(pid, signals.length > 1 ? signals.shift() : signals[0])) {
if (callback) callback(pid);
return true;
}
setTimeout(this._tryKill.bind(this, pid, signals, timeout, callback), timeout || this._stopTimeout);
return false;
};
Daemon.prototype._isFile = function(path) {
try {
var stat = fs.statSync(path);
if (stat && !stat.isDirectory())
return true;
}
catch (err) {
}
return false;
};
Daemon.prototype._bindConsole = function() {
this
.on("starting", function() {
console.log("Starting " + this.name + " daemon...");
})
.on("started", function(pid) {
console.log(this.name + " daemon started. PID: " + pid);
})
.on("stopping", function() {
console.log("Stopping " + this.name + " daemon...");
})
.on("stopped", function(pid) {
console.log(this.name + " daemon stopped.");
})
.on("running", function(pid) {
console.log(this.name + " daemon already running. PID: " + pid);
})
.on("notrunning", function() {
console.log(this.name + " daemon is not running");
})
.on("error", function(err) {
console.log(this.name + " daemon failed to start: " + err.message);
});
};