run.js 16 KB

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