run.js 16 KB

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