You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

run.js 16KB

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