All files / lib/internal/cluster child.js

100% Statements 257/257
96.23% Branches 51/53
100% Functions 15/15
100% Lines 257/257

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 249 250 251 252 253 254 255 256 257 258236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 235x 235x 235x 235x 235x 235x 235x 235x 235x 187x 187x 187x 18x 18x 18x 18x 235x 235x 235x 235x 235x 235x 92x 92x 67x 67x 92x 236x 236x 236x 236x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 16x 16x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 103x 99x 99x 99x 99x 99x 65x 99x 103x 103x 103x 88x 88x 88x 88x 88x 103x 236x 236x 236x 34x 34x 34x 34x 34x 34x 34x 28x 28x 28x 28x 34x 34x 34x 34x 34x 236x 236x 65x 65x 65x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 59x 59x 62x 62x 62x 62x 62x 59x 59x 59x 59x 59x 59x 59x 59x 57x 57x 59x 59x 59x 59x 65x 236x 236x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 236x 631x 631x 631x 236x 167x 167x 167x 167x 167x 223x 223x 223x 167x 167x 167x 167x 167x 66x 167x 101x 101x 167x 223x 167x 167x 56x 56x 56x 56x 1x 1x 167x 167x 167x 167x 167x 236x 236x 236x 1528x 101x 101x 101x 1528x 1528x 236x 236x 236x 3x 3x 3x 3x 3x 1x 3x 2x 2x 2x 2x 236x  
'use strict';
 
const {
  ArrayPrototypeJoin,
  FunctionPrototype,
  ObjectAssign,
  ReflectApply,
  SafeMap,
} = primordials;
 
const assert = require('internal/assert');
const path = require('path');
const EventEmitter = require('events');
const { owner_symbol } = require('internal/async_hooks').symbols;
const Worker = require('internal/cluster/worker');
const { internal, sendHelper } = require('internal/cluster/utils');
const cluster = new EventEmitter();
const handles = new SafeMap();
const indexes = new SafeMap();
const noop = FunctionPrototype;
 
module.exports = cluster;
 
cluster.isWorker = true;
cluster.isMaster = false;
cluster.worker = null;
cluster.Worker = Worker;
 
cluster._setupWorker = function() {
  const worker = new Worker({
    id: +process.env.NODE_UNIQUE_ID | 0,
    process: process,
    state: 'online'
  });
 
  cluster.worker = worker;
 
  process.once('disconnect', () => {
    worker.emit('disconnect');
 
    if (!worker.exitedAfterDisconnect) {
      // Unexpected disconnect, master exited, or some such nastiness, so
      // worker exits immediately.
      process.exit(0);
    }
  });
 
  process.on('internalMessage', internal(worker, onmessage));
  send({ act: 'online' });
 
  function onmessage(message, handle) {
    if (message.act === 'newconn')
      onconnection(message, handle);
    else if (message.act === 'disconnect')
      ReflectApply(_disconnect, worker, [true]);
  }
};
 
// `obj` is a net#Server or a dgram#Socket object.
cluster._getServer = function(obj, options, cb) {
  let address = options.address;
 
  // Resolve unix socket paths to absolute paths
  if (options.port < 0 && typeof address === 'string' &&
      process.platform !== 'win32')
    address = path.resolve(address);
 
  const indexesKey = ArrayPrototypeJoin(
    [
      address,
      options.port,
      options.addressType,
      options.fd,
    ], ':');
 
  let index = indexes.get(indexesKey);
 
  if (index === undefined)
    index = 0;
  else
    index++;
 
  indexes.set(indexesKey, index);
 
  const message = {
    act: 'queryServer',
    index,
    data: null,
    ...options
  };
 
  message.address = address;
 
  // Set custom data on handle (i.e. tls tickets key)
  if (obj._getServerData)
    message.data = obj._getServerData();
 
  send(message, (reply, handle) => {
    if (typeof obj._setServerData === 'function')
      obj._setServerData(reply.data);
 
    if (handle)
      shared(reply, handle, indexesKey, cb);  // Shared listen socket.
    else
      rr(reply, indexesKey, cb);              // Round-robin.
  });
 
  obj.once('listening', () => {
    cluster.worker.state = 'listening';
    const address = obj.address();
    message.act = 'listening';
    message.port = (address && address.port) || options.port;
    send(message);
  });
};
 
// Shared listen socket.
function shared(message, handle, indexesKey, cb) {
  const key = message.key;
  // Monkey-patch the close() method so we can keep track of when it's
  // closed. Avoids resource leaks when the handle is short-lived.
  const close = handle.close;
 
  handle.close = function() {
    send({ act: 'close', key });
    handles.delete(key);
    indexes.delete(indexesKey);
    return ReflectApply(close, handle, arguments);
  };
  assert(handles.has(key) === false);
  handles.set(key, handle);
  cb(message.errno, handle);
}
 
// Round-robin. Master distributes handles across workers.
function rr(message, indexesKey, cb) {
  if (message.errno)
    return cb(message.errno, null);
 
  let key = message.key;
 
  function listen(backlog) {
    // TODO(bnoordhuis) Send a message to the master that tells it to
    // update the backlog size. The actual backlog should probably be
    // the largest requested size by any worker.
    return 0;
  }
 
  function close() {
    // lib/net.js treats server._handle.close() as effectively synchronous.
    // That means there is a time window between the call to close() and
    // the ack by the master process in which we can still receive handles.
    // onconnection() below handles that by sending those handles back to
    // the master.
    if (key === undefined)
      return;
 
    send({ act: 'close', key });
    handles.delete(key);
    indexes.delete(indexesKey);
    key = undefined;
  }
 
  function getsockname(out) {
    if (key)
      ObjectAssign(out, message.sockname);
 
    return 0;
  }
 
  // Faux handle. Mimics a TCPWrap with just enough fidelity to get away
  // with it. Fools net.Server into thinking that it's backed by a real
  // handle. Use a noop function for ref() and unref() because the control
  // channel is going to keep the worker alive anyway.
  const handle = { close, listen, ref: noop, unref: noop };
 
  if (message.sockname) {
    handle.getsockname = getsockname;  // TCP handles only.
  }
 
  assert(handles.has(key) === false);
  handles.set(key, handle);
  cb(0, handle);
}
 
// Round-robin connection.
function onconnection(message, handle) {
  const key = message.key;
  const server = handles.get(key);
  const accepted = server !== undefined;
 
  send({ ack: message.seq, accepted });
 
  if (accepted)
    server.onconnection(0, handle);
}
 
function send(message, cb) {
  return sendHelper(process, message, null, cb);
}
 
function _disconnect(masterInitiated) {
  this.exitedAfterDisconnect = true;
  let waitingCount = 1;
 
  function checkWaitingCount() {
    waitingCount--;
 
    if (waitingCount === 0) {
      // If disconnect is worker initiated, wait for ack to be sure
      // exitedAfterDisconnect is properly set in the master, otherwise, if
      // it's master initiated there's no need to send the
      // exitedAfterDisconnect message
      if (masterInitiated) {
        process.disconnect();
      } else {
        send({ act: 'exitedAfterDisconnect' }, () => process.disconnect());
      }
    }
  }
 
  handles.forEach((handle) => {
    waitingCount++;
 
    if (handle[owner_symbol])
      handle[owner_symbol].close(checkWaitingCount);
    else
      handle.close(checkWaitingCount);
  });
 
  handles.clear();
  checkWaitingCount();
}
 
// Extend generic Worker with methods specific to worker processes.
Worker.prototype.disconnect = function() {
  if (this.state !== 'disconnecting' && this.state !== 'destroying') {
    this.state = 'disconnecting';
    ReflectApply(_disconnect, this, []);
  }
 
  return this;
};
 
Worker.prototype.destroy = function() {
  if (this.state === 'destroying')
    return;
 
  this.exitedAfterDisconnect = true;
  if (!this.isConnected()) {
    process.exit(0);
  } else {
    this.state = 'destroying';
    send({ act: 'exitedAfterDisconnect' }, () => process.disconnect());
    process.once('disconnect', () => process.exit(0));
  }
};