1 | var fs = require('fs'),
|
2 | path = require('path'),
|
3 | forever = require(path.resolve(__dirname, '..', 'lib', 'forever')),
|
4 | started;
|
5 |
|
6 | //
|
7 | // ### @function (file, pid)
|
8 | // #### @file {string} Location of the pid file.
|
9 | // #### @pid {number} pid to write to disk.
|
10 | // Write the pidFile to disk for later use
|
11 | //
|
12 | function writePid(file, pid) {
|
13 | fs.writeFileSync(file, String(pid), 'utf8');
|
14 | }
|
15 |
|
16 | //
|
17 | // ### @function start (options)
|
18 | // #### @options {Object} Options for the `forever.Monitor` instance.
|
19 | // Starts the child process and disconnects from the IPC channel.
|
20 | //
|
21 | function start(options) {
|
22 | var script = process.argv[2],
|
23 | monitor = new forever.Monitor(script, options);
|
24 |
|
25 | forever.logEvents(monitor);
|
26 | monitor.start();
|
27 |
|
28 | monitor.on('start', function () {
|
29 | //
|
30 | // This starts an nssocket server, which the forever CLI uses to
|
31 | // communicate with this monitor process after it's detached.
|
32 | // Without this, `forever list` won't show the process, even though it
|
33 | // would still be running in the background unaffected.
|
34 | //
|
35 | forever.startServer(monitor);
|
36 |
|
37 | //
|
38 | // Disconnect the IPC channel, letting this monitor's parent process know
|
39 | // that the child has started successfully.
|
40 | //
|
41 | process.disconnect();
|
42 |
|
43 | //
|
44 | // Write the pidFile to disk
|
45 | //
|
46 | writePid(options.pidFile, monitor.child.pid);
|
47 | });
|
48 |
|
49 | //
|
50 | // When the monitor restarts update the pid in the pidFile
|
51 | //
|
52 | monitor.on('restart', function () {
|
53 | writePid(options.pidFile, monitor.child.pid);
|
54 | });
|
55 |
|
56 |
|
57 | //
|
58 | // When the monitor stops or exits, remove the pid and log files
|
59 | //
|
60 | function cleanUp() {
|
61 | try {
|
62 | fs.unlinkSync(options.pidFile);
|
63 | }
|
64 | catch(e) {}
|
65 | }
|
66 | monitor.on('stop', cleanUp);
|
67 | monitor.on('exit', cleanUp);
|
68 | }
|
69 |
|
70 | //
|
71 | // When we receive the first message from the parent process, start
|
72 | // an instance of `forever.Monitor` with the options supplied.
|
73 | //
|
74 | process.on('message', function (data) {
|
75 | //
|
76 | // TODO: Find out if this data will ever get split into two message events.
|
77 | //
|
78 | var options = JSON.parse(data.toString());
|
79 |
|
80 | // inherits configuration from parent process if exists.
|
81 | options && options._loadedOptions && (forever.load(options._loadedOptions), delete options._loadedOptions);
|
82 |
|
83 | if (!started) {
|
84 | started = true;
|
85 | start(options);
|
86 | }
|
87 | });
|