run.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. var debug = require('debug')('nodemon:run');
  2. const statSync = require('fs').statSync;
  3. var utils = require('../utils');
  4. var bus = utils.bus;
  5. var childProcess = require('child_process');
  6. var spawn = childProcess.spawn;
  7. var exec = childProcess.exec;
  8. var fork = childProcess.fork;
  9. var watch = require('./watch').watch;
  10. var config = require('../config');
  11. var child = null; // the actual child process we spawn
  12. var killedAfterChange = false;
  13. var noop = () => {};
  14. var restart = null;
  15. var psTree = require('pstree.remy');
  16. var path = require('path');
  17. var signals = require('./signals');
  18. function run(options) {
  19. var cmd = config.command.raw;
  20. var runCmd = !options.runOnChangeOnly || config.lastStarted !== 0;
  21. if (runCmd) {
  22. utils.log.status('starting `' + config.command.string + '`');
  23. }
  24. /*jshint validthis:true*/
  25. restart = run.bind(this, options);
  26. run.restart = restart;
  27. config.lastStarted = Date.now();
  28. var stdio = ['pipe', 'pipe', 'pipe'];
  29. if (config.options.stdout) {
  30. stdio = ['pipe', process.stdout, process.stderr];
  31. }
  32. if (config.options.stdin === false) {
  33. stdio = [process.stdin, process.stdout, process.stderr];
  34. }
  35. var sh = 'sh';
  36. var shFlag = '-c';
  37. const binPath = process.cwd() + '/node_modules/.bin';
  38. const spawnOptions = {
  39. env: Object.assign({}, process.env, options.execOptions.env, {
  40. PATH: binPath + ':' + process.env.PATH,
  41. }),
  42. stdio: stdio,
  43. }
  44. var executable = cmd.executable;
  45. if (utils.isWindows) {
  46. // if the exec includes a forward slash, reverse it for windows compat
  47. // but *only* apply to the first command, and none of the arguments.
  48. // ref #1251 and #1236
  49. if (executable.indexOf('/') !== -1) {
  50. executable = executable.split(' ').map((e, i) => {
  51. if (i === 0) {
  52. return path.normalize(e);
  53. }
  54. return e;
  55. }).join(' ');
  56. }
  57. // taken from npm's cli: https://git.io/vNFD4
  58. sh = process.env.comspec || 'cmd';
  59. shFlag = '/d /s /c';
  60. spawnOptions.windowsVerbatimArguments = true;
  61. }
  62. var args = runCmd ? utils.stringify(executable, cmd.args) : ':';
  63. var spawnArgs = [sh, [shFlag, args], spawnOptions];
  64. const firstArg = cmd.args[0] || '';
  65. var inBinPath = false;
  66. try {
  67. inBinPath = statSync(`${binPath}/${executable}`).isFile();
  68. } catch (e) {}
  69. // hasStdio allows us to correctly handle stdin piping
  70. // see: https://git.io/vNtX3
  71. const hasStdio = utils.satisfies('>= 6.4.0 || < 5');
  72. // forking helps with sub-process handling and tends to clean up better
  73. // than spawning, but it should only be used under specific conditions
  74. const shouldFork =
  75. !config.options.spawn &&
  76. !inBinPath &&
  77. !(firstArg.indexOf('-') === 0) && // don't fork if there's a node exec arg
  78. firstArg !== 'inspect' && // don't fork it's `inspect` debugger
  79. executable === 'node' && // only fork if node
  80. utils.version.major > 4 // only fork if node version > 4
  81. if (shouldFork) {
  82. var forkArgs = cmd.args.slice(1);
  83. var env = utils.merge(options.execOptions.env, process.env);
  84. stdio.push('ipc');
  85. child = fork(options.execOptions.script, forkArgs, {
  86. env: env,
  87. stdio: stdio,
  88. silent: !hasStdio,
  89. });
  90. utils.log.detail('forking');
  91. debug('fork', sh, shFlag, args)
  92. } else {
  93. utils.log.detail('spawning');
  94. child = spawn.apply(null, spawnArgs);
  95. debug('spawn', sh, shFlag, args);
  96. }
  97. if (config.required) {
  98. var emit = {
  99. stdout: function (data) {
  100. bus.emit('stdout', data);
  101. },
  102. stderr: function (data) {
  103. bus.emit('stderr', data);
  104. },
  105. };
  106. // now work out what to bind to...
  107. if (config.options.stdout) {
  108. child.on('stdout', emit.stdout).on('stderr', emit.stderr);
  109. } else {
  110. child.stdout.on('data', emit.stdout);
  111. child.stderr.on('data', emit.stderr);
  112. bus.stdout = child.stdout;
  113. bus.stderr = child.stderr;
  114. }
  115. if (shouldFork) {
  116. child.on('message', function (message, sendHandle) {
  117. bus.emit('message', message, sendHandle);
  118. });
  119. }
  120. }
  121. bus.emit('start');
  122. utils.log.detail('child pid: ' + child.pid);
  123. child.on('error', function (error) {
  124. bus.emit('error', error);
  125. if (error.code === 'ENOENT') {
  126. utils.log.error('unable to run executable: "' + cmd.executable + '"');
  127. process.exit(1);
  128. } else {
  129. utils.log.error('failed to start child process: ' + error.code);
  130. throw error;
  131. }
  132. });
  133. child.on('exit', function (code, signal) {
  134. if (child && child.stdin) {
  135. process.stdin.unpipe(child.stdin);
  136. }
  137. if (code === 127) {
  138. utils.log.error('failed to start process, "' + cmd.executable +
  139. '" exec not found');
  140. bus.emit('error', code);
  141. process.exit();
  142. }
  143. // If the command failed with code 2, it may or may not be a syntax error
  144. // See: http://git.io/fNOAR
  145. // We will only assume a parse error, if the child failed quickly
  146. if (code === 2 && Date.now() < config.lastStarted + 500) {
  147. utils.log.error('process failed, unhandled exit code (2)');
  148. utils.log.error('');
  149. utils.log.error('Either the command has a syntax error,');
  150. utils.log.error('or it is exiting with reserved code 2.');
  151. utils.log.error('');
  152. utils.log.error('To keep nodemon running even after a code 2,');
  153. utils.log.error('add this to the end of your command: || exit 1');
  154. utils.log.error('');
  155. utils.log.error('Read more here: https://git.io/fNOAG');
  156. utils.log.error('');
  157. utils.log.error('nodemon will stop now so that you can fix the command.');
  158. utils.log.error('');
  159. bus.emit('error', code);
  160. process.exit();
  161. }
  162. // In case we killed the app ourselves, set the signal thusly
  163. if (killedAfterChange) {
  164. killedAfterChange = false;
  165. signal = config.signal;
  166. }
  167. // this is nasty, but it gives it windows support
  168. if (utils.isWindows && signal === 'SIGTERM') {
  169. signal = config.signal;
  170. }
  171. if (signal === config.signal || code === 0) {
  172. // this was a clean exit, so emit exit, rather than crash
  173. debug('bus.emit(exit) via ' + config.signal);
  174. bus.emit('exit', signal);
  175. // exit the monitor, but do it gracefully
  176. if (signal === config.signal) {
  177. return restart();
  178. }
  179. if (code === 0) { // clean exit - wait until file change to restart
  180. if (runCmd) {
  181. utils.log.status('clean exit - waiting for changes before restart');
  182. }
  183. child = null;
  184. }
  185. } else {
  186. bus.emit('crash');
  187. if (options.exitcrash) {
  188. utils.log.fail('app crashed');
  189. if (!config.required) {
  190. process.exit(1);
  191. }
  192. } else {
  193. utils.log.fail('app crashed - waiting for file changes before' +
  194. ' starting...');
  195. child = null;
  196. }
  197. }
  198. if (config.options.restartable) {
  199. // stdin needs to kick in again to be able to listen to the
  200. // restart command
  201. process.stdin.resume();
  202. }
  203. });
  204. run.kill = function (noRestart, callback) {
  205. // I hate code like this :( - Remy (author of said code)
  206. if (typeof noRestart === 'function') {
  207. callback = noRestart;
  208. noRestart = false;
  209. }
  210. if (!callback) {
  211. callback = noop;
  212. }
  213. if (child !== null) {
  214. // if the stdin piping is on, we need to unpipe, but also close stdin on
  215. // the child, otherwise linux can throw EPIPE or ECONNRESET errors.
  216. if (options.stdin) {
  217. process.stdin.unpipe(child.stdin);
  218. }
  219. // For the on('exit', ...) handler above the following looks like a
  220. // crash, so we set the killedAfterChange flag if a restart is planned
  221. if (!noRestart) {
  222. killedAfterChange = true;
  223. }
  224. /* Now kill the entire subtree of processes belonging to nodemon */
  225. var oldPid = child.pid;
  226. if (child) {
  227. kill(child, config.signal, function () {
  228. // this seems to fix the 0.11.x issue with the "rs" restart command,
  229. // though I'm unsure why. it seems like more data is streamed in to
  230. // stdin after we close.
  231. if (child && options.stdin && child.stdin && oldPid === child.pid) {
  232. child.stdin.end();
  233. }
  234. callback();
  235. });
  236. }
  237. } else if (!noRestart) {
  238. // if there's no child, then we need to manually start the process
  239. // this is because as there was no child, the child.on('exit') event
  240. // handler doesn't exist which would normally trigger the restart.
  241. bus.once('start', callback);
  242. restart();
  243. } else {
  244. callback();
  245. }
  246. };
  247. // connect stdin to the child process (options.stdin is on by default)
  248. if (options.stdin) {
  249. process.stdin.resume();
  250. // FIXME decide whether or not we need to decide the encoding
  251. // process.stdin.setEncoding('utf8');
  252. // swallow the stdin error if it happens
  253. // ref: https://github.com/remy/nodemon/issues/1195
  254. if (hasStdio) {
  255. child.stdin.on('error', () => { });
  256. process.stdin.pipe(child.stdin);
  257. } else {
  258. if (child.stdout) {
  259. child.stdout.pipe(process.stdout);
  260. } else {
  261. utils.log.error('running an unsupported version of node ' +
  262. process.version);
  263. utils.log.error('nodemon may not work as expected - ' +
  264. 'please consider upgrading to LTS');
  265. }
  266. }
  267. bus.once('exit', function () {
  268. if (child && process.stdin.unpipe) { // node > 0.8
  269. process.stdin.unpipe(child.stdin);
  270. }
  271. });
  272. }
  273. debug('start watch on: %s', config.options.watch);
  274. if (config.options.watch !== false) {
  275. watch();
  276. }
  277. }
  278. function waitForSubProcesses(pid, callback) {
  279. debug('checking ps tree for pids of ' + pid);
  280. psTree(pid, (err, pids) => {
  281. if (!pids.length) {
  282. return callback();
  283. }
  284. utils.log.status(`still waiting for ${pids.length} sub-process${
  285. pids.length > 2 ? 'es' : ''} to finish...`);
  286. setTimeout(() => waitForSubProcesses(pid, callback), 1000);
  287. });
  288. }
  289. function kill(child, signal, callback) {
  290. if (!callback) {
  291. callback = function () { };
  292. }
  293. if (utils.isWindows) {
  294. // When using CoffeeScript under Windows, child's process is not node.exe
  295. // Instead coffee.cmd is launched, which launches cmd.exe, which starts
  296. // node.exe as a child process child.kill() would only kill cmd.exe, not
  297. // node.exe
  298. // Therefore we use the Windows taskkill utility to kill the process and all
  299. // its children (/T for tree).
  300. // Force kill (/F) the whole child tree (/T) by PID (/PID 123)
  301. exec('taskkill /pid ' + child.pid + ' /T /F');
  302. callback();
  303. } else {
  304. // we use psTree to kill the full subtree of nodemon, because when
  305. // spawning processes like `coffee` under the `--debug` flag, it'll spawn
  306. // it's own child, and that can't be killed by nodemon, so psTree gives us
  307. // an array of PIDs that have spawned under nodemon, and we send each the
  308. // configured signal (default: SIGUSR2) signal, which fixes #335
  309. // note that psTree also works if `ps` is missing by looking in /proc
  310. let sig = signal.replace('SIG', '');
  311. psTree(child.pid, function (err, pids) {
  312. // if ps isn't native to the OS, then we need to send the numeric value
  313. // for the signal during the kill, `signals` is a lookup table for that.
  314. if (!psTree.hasPS) {
  315. sig = signals[signal];
  316. }
  317. // the sub processes need to be killed from smallest to largest
  318. debug('sending kill signal to ' + pids.join(', '));
  319. child.kill(signal);
  320. pids.sort().forEach(pid => exec(`kill -${sig} ${pid}`, noop));
  321. waitForSubProcesses(child.pid, () => {
  322. // finally kill the main user process
  323. exec(`kill -${sig} ${child.pid}`, callback);
  324. });
  325. });
  326. }
  327. }
  328. // stubbed out for now, filled in during run
  329. run.kill = function (flag, callback) {
  330. if (callback) {
  331. callback();
  332. }
  333. };
  334. run.restart = noop;
  335. bus.on('quit', function onQuit(code) {
  336. if (code === undefined) {
  337. code = 0;
  338. }
  339. // remove event listener
  340. var exitTimer = null;
  341. var exit = function () {
  342. clearTimeout(exitTimer);
  343. exit = noop; // null out in case of race condition
  344. child = null;
  345. if (!config.required) {
  346. // Execute all other quit listeners.
  347. bus.listeners('quit').forEach(function (listener) {
  348. if (listener !== onQuit) {
  349. listener();
  350. }
  351. });
  352. process.exit(code);
  353. } else {
  354. bus.emit('exit');
  355. }
  356. };
  357. // if we're not running already, don't bother with trying to kill
  358. if (config.run === false) {
  359. return exit();
  360. }
  361. // immediately try to stop any polling
  362. config.run = false;
  363. if (child) {
  364. // give up waiting for the kids after 10 seconds
  365. exitTimer = setTimeout(exit, 10 * 1000);
  366. child.removeAllListeners('exit');
  367. child.once('exit', exit);
  368. kill(child, 'SIGINT');
  369. } else {
  370. exit();
  371. }
  372. });
  373. bus.on('restart', function () {
  374. // run.kill will send a SIGINT to the child process, which will cause it
  375. // to terminate, which in turn uses the 'exit' event handler to restart
  376. run.kill();
  377. });
  378. // remove the child file on exit
  379. process.on('exit', function () {
  380. utils.log.detail('exiting');
  381. if (child) { child.kill(); }
  382. });
  383. // because windows borks when listening for the SIG* events
  384. if (!utils.isWindows) {
  385. bus.once('boot', () => {
  386. // usual suspect: ctrl+c exit
  387. process.once('SIGINT', () => bus.emit('quit', 130));
  388. process.once('SIGTERM', () => {
  389. bus.emit('quit', 143);
  390. if (child) { child.kill('SIGTERM'); }
  391. });
  392. })
  393. }
  394. module.exports = run;