# Code coverage report for lib/monitor/run.js

## Statements: 49.12% (56 / 114) Branches: 28.57% (20 / 70) Functions: 33.33% (5 / 15) Lines: 50.45% (56 / 111)

All files » lib/monitor/ » run.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    2491
    1

    1
    3

    3

    3
    3

    3

    3
    3

    3

    3
    3
    2

    3
    3

    3

    3

    3

    3

    3

    3
    3
    3
    3

    3

    1
    16

    16
    16

    16
    11

    16
    14

    16

    1
    1

    1

    6
    7
    7

    7

    6
    3

    3

    3
    3
    3
    3

    3

    1

    1

    1

    1

    1

    1'use strict';
    var utils = require('../utils'),
        bus = utils.bus,
        childProcess = require('child_process'),
        spawn = childProcess.spawn,
        exec = childProcess.exec,
        watch = require('./watch'),
        config = require('../config'),
        child = null, // the actual child process we spawn
        killedAfterChange = false,
        // timeout = 1000, // check every 1 second
        noop = function() {},
        restart = null;

    function run(options) {
      var command = run.command(options),
          nodeMajor = parseInt((process.versions.node.split('.') || [null,null])[1] || 0, 10);

      utils.log.status('starting `' + command.executable + (command.args.length ? ' ' + command.args.join(' ') : '') + '`');

      /*jshint validthis:true*/
      restart = run.bind(this, options);
      run.restart = restart;

      config.lastStarted = Date.now();

      Eif (nodeMajor >= 8) {
        child = spawn(command.executable, command.args, {
          env: utils.merge(options.execOptions.env, process.env),
          stdio: ['pipe', 'pipe', 'pipe']
        });
      } else {
        child = spawn(command.executable, command.args);
      }

      bus.emit('start');

      child.stdout.on('data', function (data) {
        if (config.options.stdout) {
          process.stdout.write(data);
        }

        Eif (config.required) {
          bus.emit('stdout', data);
        }
      });

      child.stderr.on('data', function (data) {
        if (config.options.stdout) {
          process.stderr.write(data);
        }

        if (config.required) {
          bus.emit('stderr', data);
        }
      });

      utils.log.detail('child pid: ' + child.pid);

      child.on('error', function (error) {
        if (error.code === 'ENOENT') {
          utils.log.error('unable to run executable: "' + command.executable + '"');
          process.exit(1);
        }
      });

      child.on('exit', function (code, signal) {
        // In case we killed the app ourselves, set the signal thusly
        if (killedAfterChange) {
          killedAfterChange = false;
          signal = 'SIGUSR2';
        }
        // this is nasty, but it gives it windows support
        if (utils.isWindows && signal === 'SIGTERM') {
          signal = 'SIGUSR2';
        }

        if (signal === 'SIGUSR2' || code === 0) {
          // this was a clean exit, so emit exit, rather than crash
          bus.emit('exit');

          // exit the monitor, but do it gracefully
          if (signal === 'SIGUSR2') {
            // restart
            restart();
          } else if (code === 0) { // clean exit - wait until file change to restart
            utils.log.status('clean exit - waiting for changes before restart');
            child = null;
          }
        } else {
          bus.emit('crash');
          if (options.exitcrash) {
            utils.log.fail('app crashed');
            if (!config.required) {
              process.exit(0);
            }
          } else {
            utils.log.fail('app crashed - waiting for file changes before starting...');
            child = null;
          }
        }
      });

      run.kill = function () {
        if (child !== null) {
          // if the stdin piping is on, we need to unpipe, but also close stdin on
          // the child, otherwise linux can throw EPIPE or ECONNRESET errors.
          if (options.stdin) {
            if (process.stdin.unpipe) { // node > 0.8
              process.stdin.unpipe(child.stdin);
            }
            child.stdin.end();
          }

          // When using CoffeeScript under Windows, child's process is not node.exe
          // Instead coffee.cmd is launched, which launches cmd.exe, which starts
          // node.exe as a child process child.kill() would only kill cmd.exe, not
          // node.exe
          // Therefore we use the Windows taskkill utility to kill the process and all
          // its children (/T for tree)
          if (utils.isWindows) {
            // For the on('exit', ...) handler above the following looks like a crash,
            // so we set the killedAfterChange flag
            killedAfterChange = true;
            // Force kill (/F) the whole child tree (/T) by PID (/PID 123)
            exec('taskkill /pid '+ child.pid + ' /T /F');
          } else {
            child.kill('SIGUSR2');
          }
        } else {
          // if there's no child, then we need to manually start the process
          // this is because as there was no child, the child.on('exit') event
          // handler doesn't exist which would normally trigger the restart.
          restart();
        }
      };

      // connect stdin to the child process (options.stdin is on by default)
      Eif (options.stdin) {
        process.stdin.resume();
        process.stdin.setEncoding('utf8');
        process.stdin.pipe(child.stdin);
      }

      watch();
    }

    run.command = function (options) {
      var executable = options.execOptions.exec,
          args = [];

      // after "executable" go the exec args (like --debug, etc)
      Eif (options.execOptions.execArgs) {
        [].push.apply(args, options.execOptions.execArgs);
      }

      // then goes the user's script arguments
      if (options.args) {
        [].push.apply(args, options.args);
      }

      // after the "executable" goes the user's script
      if (options.script) {
        args.splice((options.scriptPosition || 0) + options.execOptions.execArgs.length, 0, options.script);
      }

      return {
        executable: executable,
        args: args
      };
    };

    // stubbed out for now, filled in during run
    run.kill = noop;
    run.restart = noop;

    bus.on('quit', function () {
      // remove event listener
      var exit = function () {
        exit = noop; // null out in case of race condition
        Iif (!config.required) {
          process.exit(0);
        } else {
          bus.emit('exit');
        }
      };

      // if we're not running already, don't bother with trying to kill
      if (config.run === false) {
        return exit();
      }

      // immediately try to stop any polling
      config.run = false;

      Eif (child) {
        child.removeAllListeners('exit');
        child.on('exit', exit);
        child.kill('SIGINT');
        // give up waiting for the kids after 10 seconds
        setTimeout(exit, 10 * 1000);
      } else {
        exit();
      }
    });

    bus.on('restart', function () {
      // run.kill will send a SIGINT to the child process, which will cause it
      // to terminate, which in turn uses the 'exit' event handler to restart
      run.kill();
    });

    // remove the flag file on exit
    process.on('exit', function () {
      utils.log.detail('exiting');
      if (child) { child.kill(); }
    });

    // because windows borks when listening for the SIG* events
    Eif (!utils.isWindows) {
      // usual suspect: ctrl+c exit
      process.on('SIGINT', function () {
        var exit = function () {
              bus.emit('exit');
              exit = noop;
              if (child) { child.kill('SIGINT'); }
              process.exit(0);
            };

        if (child) {
          child.removeAllListeners('exit');
          child.on('exit', exit);
          child.kill('SIGINT');
          // give up waiting for the kids after 10 seconds,
          // this is usually when the child is capturing the SIGINT
          setTimeout(exit, 10 * 1000);
        } else {
          exit();
        }
      });

      process.on('SIGTERM', function () {
        if (child) { child.kill('SIGTERM'); }
        process.exit(0);
      });
    }

    module.exports = run;