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 cluster = require('cluster');
31
32console.error('Cluster listen fd test', process.argv[2] || 'runner');
33
34// Process relationship is:
35//
36// parent: the test main script
37//   -> primary: the cluster primary
38//        -> worker: the cluster worker
39switch (process.argv[2]) {
40  case 'primary': return primary();
41  case 'worker': return worker();
42}
43
44let ok;
45
46process.on('exit', function() {
47  assert.ok(ok);
48});
49
50// Spawn the parent, and listen for it to tell us the pid of the cluster.
51// WARNING: This is an example of listening on some arbitrary FD number
52// that has already been bound elsewhere in advance.  However, binding
53// server handles to stdio fd's is NOT a good or reliable way to do
54// concurrency in HTTP servers!  Use the cluster module, or if you want
55// a more low-level approach, use child process IPC manually.
56test(function(parent, port) {
57  // Now make sure that we can request to the worker, then kill it.
58  http.get({
59    server: 'localhost',
60    port: port,
61    path: '/',
62  }).on('response', function(res) {
63    let s = '';
64    res.on('data', function(c) {
65      s += c.toString();
66    });
67    res.on('end', function() {
68      // Kill the worker before we start doing asserts.
69      // it's really annoying when tests leave orphans!
70      parent.kill();
71      parent.on('exit', function() {
72        assert.strictEqual(s, 'hello from worker\n');
73        assert.strictEqual(res.statusCode, 200);
74        console.log('ok');
75        ok = true;
76      });
77    });
78  });
79});
80
81function test(cb) {
82  console.error('about to listen in parent');
83  const server = net.createServer(function(conn) {
84    console.error('connection on parent');
85    conn.end('hello from parent\n');
86  }).listen(0, function() {
87    const port = this.address().port;
88    console.error(`server listening on ${port}`);
89
90    const spawn = require('child_process').spawn;
91    const primary = spawn(process.execPath, [__filename, 'primary'], {
92      stdio: [ 0, 'pipe', 2, server._handle, 'ipc' ],
93      detached: true
94    });
95
96    // Now close the parent, so that the primary is the only thing
97    // referencing that handle.  Note that connections will still
98    // be accepted, because the primary has the fd open.
99    server.close();
100
101    primary.on('exit', function(code) {
102      console.error('primary exited', code);
103    });
104
105    primary.on('close', function() {
106      console.error('primary closed');
107    });
108    console.error('primary spawned');
109    primary.on('message', function(msg) {
110      if (msg === 'started worker') {
111        cb(primary, port);
112      }
113    });
114  });
115}
116
117function primary() {
118  console.error('in primary, spawning worker');
119  cluster.setupPrimary({
120    args: [ 'worker' ]
121  });
122  const worker = cluster.fork();
123  worker.on('message', function(msg) {
124    if (msg === 'worker ready') {
125      process.send('started worker');
126    }
127  });
128  // Prevent outliving our parent process in case it is abnormally killed -
129  // under normal conditions our parent kills this process before exiting.
130  process.on('disconnect', function() {
131    console.error('primary exit on disconnect');
132    process.exit(0);
133  });
134}
135
136
137function worker() {
138  console.error('worker, about to create server and listen on fd=3');
139  // Start a server on fd=3
140  http.createServer(function(req, res) {
141    console.error('request on worker');
142    console.error('%s %s', req.method, req.url, req.headers);
143    res.end('hello from worker\n');
144  }).listen({ fd: 3 }, function() {
145    console.error('worker listening on fd=3');
146    process.send('worker ready');
147  });
148}
149