run.js 16 KB

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