run.js 14 KB

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