• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23const common = require('../common');
24if (common.isWindows)
25  common.skip('This test is disabled on windows.');
26
27const assert = require('assert');
28const http = require('http');
29const net = require('net');
30const spawn = require('child_process').spawn;
31
32switch (process.argv[2]) {
33  case 'child': return child();
34  case 'parent': return parent();
35  default: return test();
36}
37
38// Spawn the parent, and listen for it to tell us the pid of the child.
39// WARNING: This is an example of listening on some arbitrary FD number
40// that has already been bound elsewhere in advance.  However, binding
41// server handles to stdio fd's is NOT a good or reliable way to do
42// concurrency in HTTP servers!  Use the cluster module, or if you want
43// a more low-level approach, use child process IPC manually.
44function test() {
45  const parent = spawn(process.execPath, [__filename, 'parent'], {
46    stdio: [ 0, 'pipe', 2 ]
47  });
48  let json = '';
49  parent.stdout.on('data', function(c) {
50    json += c.toString();
51    if (json.includes('\n')) next();
52  });
53  function next() {
54    console.error('output from parent = %s', json);
55    const child = JSON.parse(json);
56    // Now make sure that we can request to the subprocess, then kill it.
57    http.get({
58      server: 'localhost',
59      port: child.port,
60      path: '/',
61    }).on('response', function(res) {
62      let s = '';
63      res.on('data', function(c) {
64        s += c.toString();
65      });
66      res.on('end', function() {
67        // Kill the subprocess before we start doing asserts.
68        // It's really annoying when tests leave orphans!
69        process.kill(child.pid, 'SIGKILL');
70        try {
71          parent.kill();
72        } catch {}
73
74        assert.strictEqual(s, 'hello from child\n');
75        assert.strictEqual(res.statusCode, 200);
76      });
77    });
78  }
79}
80
81// Listen on port, and then pass the handle to the detached child.
82// Then output the child's pid, and immediately exit.
83function parent() {
84  const server = net.createServer(function(conn) {
85    conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n');
86    throw new Error('Should not see connections on parent');
87  }).listen(0, function() {
88    console.error('server listening on %d', this.address().port);
89
90    const child = spawn(process.execPath, [__filename, 'child'], {
91      stdio: [ 0, 1, 2, server._handle ],
92      detached: true
93    });
94
95    console.log('%j\n', { pid: child.pid, port: this.address().port });
96
97    // Now close the parent, so that the child is the only thing
98    // referencing that handle.  Note that connections will still
99    // be accepted, because the child has the fd open, but the parent
100    // will exit gracefully.
101    server.close();
102    child.unref();
103  });
104}
105
106// Run as a child of the parent() mode.
107function child() {
108  // Start a server on fd=3
109  http.createServer(function(req, res) {
110    console.error('request on child');
111    console.error('%s %s', req.method, req.url, req.headers);
112    res.end('hello from child\n');
113  }).listen({ fd: 3 }, function() {
114    console.error('child listening on fd=3');
115  });
116}
117