net: lazy listen on handler
authorAndreas Madsen <amwebdk@gmail.com>
Tue, 10 Jul 2012 10:06:13 +0000 (12:06 +0200)
committerisaacs <i@izs.me>
Sun, 5 Aug 2012 05:13:07 +0000 (22:13 -0700)
This allow the server to be shared without the need to handle connection
from master

doc/api/child_process.markdown
doc/api/net.markdown
lib/net.js
test/simple/test-net-lazy-listen.js [new file with mode: 0644]

index 3bd79f2..095c42b 100644 (file)
@@ -191,8 +191,9 @@ And the child would the recive the server object as:
       }
     });
 
-Note that the server is now shared between the parent and child, this means
-that some connections will be handled by the parent and some by the child.
+Note that the server is now shared between the parent and child. This means
+that any connections will be load balanced between the servers provided there
+is a `connection` listener.
 
 **send socket object**
 
@@ -357,9 +358,9 @@ index corresponds to a fd in the child.  The value is one of the following:
    ignored node will open `/dev/null` and attach it to the child's fd.
 4. `Stream` object - Share a readable or writable stream that refers to a tty,
    file, socket, or a pipe with the child process. The stream's underlying
-   file descriptor is duplicated in the child process to the fd that 
+   file descriptor is duplicated in the child process to the fd that
    corresponds to the index in the `stdio` array.
-5. Positive integer - The integer value is interpreted as a file descriptor 
+5. Positive integer - The integer value is interpreted as a file descriptor
    that is is currently open in the parent process. It is shared with the child
    process, similar to how `Stream` objects can be shared.
 6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
@@ -388,7 +389,7 @@ Example:
     spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
 
 If the `detached` option is set, the child process will be made the leader of a
-new process group.  This makes it possible for the child to continue running 
+new process group.  This makes it possible for the child to continue running
 after the parent exits.
 
 By default, the parent will wait for the detached child to exit.  To prevent
index f49eb3c..34acc5c 100644 (file)
@@ -10,6 +10,8 @@ this module with `require('net');`
 
 Creates a new TCP server. The `connectionListener` argument is
 automatically set as a listener for the ['connection'][] event.
+If the server has no `connection` listener it will not accept
+connections until it gets one.
 
 `options` is an object with the following defaults:
 
index 10d1f94..30746d4 100644 (file)
@@ -896,18 +896,6 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
   var self = this;
   var r = 0;
 
-  // If there is not yet a handle, we need to create one and bind.
-  // In the case of a server sent via IPC, we don't need to do this.
-  if (!self._handle) {
-    self._handle = createServerHandle(address, port, addressType, fd);
-    if (!self._handle) {
-      process.nextTick(function() {
-        self.emit('error', errnoException(errno, 'listen'));
-      });
-      return;
-    }
-  }
-
   self._handle.onconnection = onconnection;
   self._handle.owner = self;
 
@@ -923,15 +911,13 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
     process.nextTick(function() {
       self.emit('error', ex);
     });
-    return;
+    return r;
   }
 
   // generate connection key, this should be unique to the connection
   this._connectionKey = addressType + ':' + address + ':' + port;
 
-  process.nextTick(function() {
-    self.emit('listening');
-  });
+  return r;
 };
 
 
@@ -941,10 +927,46 @@ function listen(self, address, port, addressType, backlog, fd) {
   if (cluster.isWorker) {
     cluster._getServer(self, address, port, addressType, fd, function(handle) {
       self._handle = handle;
-      self._listen2(address, port, addressType, backlog, fd);
+      var r = self._listen2(address, port, addressType, backlog, fd);
+      if (r === 0) {
+        self.emit('listening');
+      }
     });
   } else {
-    self._listen2(address, port, addressType, backlog, fd);
+    // If there is not yet a handle, we need to create one and bind.
+    // In the case of a server sent via IPC, we don't need to do this.
+    if (!self._handle) {
+      self._handle = createServerHandle(address, port, addressType, fd);
+      if (!self._handle) {
+        process.nextTick(function() {
+          self.emit('error', errnoException(errno, 'listen'));
+        });
+        return;
+      }
+    }
+
+    // self._handle.listen will be called lazy
+    // if there are no connection listeners
+    if (self.listeners('connection').length === 0) {
+      self.on('newListener', function removeme(name) {
+        if (name !== 'connection') return;
+
+        self.removeListener('newListener', removeme);
+        self._listen2(address, port, addressType, backlog, fd);
+      });
+
+      process.nextTick(function() {
+        self.emit('listening');
+      });
+      return;
+    }
+
+    var r = self._listen2(address, port, addressType, backlog, fd);
+    if (r === 0) {
+      process.nextTick(function() {
+        self.emit('listening');
+      });
+    }
   }
 }
 
diff --git a/test/simple/test-net-lazy-listen.js b/test/simple/test-net-lazy-listen.js
new file mode 100644 (file)
index 0000000..f6eb5b6
--- /dev/null
@@ -0,0 +1,182 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('../common');
+var net = require('net');
+var fork = require('child_process').fork;
+
+if (process.argv[2] === 'worker') {
+  process.once('disconnect', function () {
+    process.exit(0);
+  });
+
+  process.on('message', function (msg, server) {
+    if (msg !== 'server') return;
+
+    server.on('connection', function (socket) {
+      socket.end(process.argv[3]);
+    });
+
+    process.send('listen');
+  });
+
+  process.send('online');
+  return;
+}
+
+var workers = [];
+
+function spawn(server, id, cb) {
+ // create a worker
+  var worker = fork(__filename, ['worker', id]);
+  workers[id] = worker;
+
+  // wait for ready
+  worker.on('message', function (msg) {
+    switch (msg) {
+      case 'online':
+        worker.send('server', server);
+        break;
+      case 'listen':
+        cb(worker);
+        break;
+      default:
+        throw new Error('got wrong message' + msg);
+    }
+  });
+
+  return worker;
+}
+
+// create a server instance there don't take connections
+var server = net.createServer().listen(common.PORT, function () {
+
+  setTimeout(function() {
+      console.log('spawn worker#0');
+      spawn(server, 0, function () {
+        console.log('worker#0 spawned');
+      });
+  }, 250);
+
+  console.log('testing for standby, expect id 0');
+  testResponse([0], function () {
+
+    // test with two worker, expect id response to be 0 or 1
+    testNewWorker(1, [0, 1], function () {
+
+      // kill worker#0, expect id response to be 1
+      testWorkerDeath(0, [1], function () {
+
+        // close server, expect all connections to continue
+        testServerClose(server, [1], function () {
+
+          // killing worker#1, expect all connections to fail
+          testWorkerDeath(1, [], function () {
+            console.log('test complete');
+          });
+        });
+      });
+    });
+  });
+});
+
+function testServerClose(server, expect, cb) {
+  console.log('closeing server');
+  server.close(function () {
+    testResponse(expect, cb);
+  });
+}
+
+function testNewWorker(workerId, exptect, cb) {
+  console.log('spawning worker#' + workerId);
+  spawn(server, 1, function () {
+    testResponse(exptect, cb);
+  });
+}
+
+function testWorkerDeath(workerID, exptect, cb) {
+  // killing worker#1, expect all connections to fail
+  console.log('killing worker#' + workerID);
+  workers[workerID].kill();
+  workers[workerID].once('exit', function () {
+    testResponse(exptect, cb);
+  });
+}
+
+function testResponse(expect, cb) {
+  // make 25 connections
+  var count = 25;
+  var missing = expect.slice(0);
+
+  var i = count;
+  while (i--) {
+    makeConnection(function (error, id) {
+      if (expect.length === 0) {
+        if (error === null) {
+          throw new Error('connect should not be possible');
+        }
+      } else {
+        if (expect.indexOf(id) === -1) {
+          throw new Error('got unexpected response: ' + id +
+                          ', expected: ' + expect.join(', '));
+        }
+
+        var index = missing.indexOf(id);
+        if (index !== -1) missing.splice(index, 1);
+      }
+
+      count -= 1;
+      if (count === 0) {
+        if (missing.length !== 0) {
+          throw new Error('no connection responsed with the following id: ' +
+                          missing.join(', '));
+        }
+        cb();
+      }
+    });
+  }
+}
+
+function makeConnection(cb) {
+  var client = net.connect({ port: common.PORT });
+
+  var id = null;
+  client.once('data', function(data) {
+    id = parseInt(data, 10);
+  });
+
+  var error = null;
+  client.once('error', function (e) {
+    error = e;
+  });
+
+  client.setTimeout(500);
+
+  client.on('close', function () {
+    cb(error, id);
+  });
+}
+
+process.on('exit', function () {
+  workers.forEach(function (worker) {
+    try { worker.kill(); } catch(e) {}
+  });
+});