2 var spawn = require('child_process').spawn;
3 var cluster = require('cluster');
4 var http = require('http');
13 clientConcurrentRequests: 2
16 for (var i = 2; i < process.argv.length; ++i) {
17 var args = process.argv[i].split('=', 2);
23 switch (options.mode) {
24 case 'master': startMaster(); break;
25 case 'server': startServer(); break;
26 case 'client': startClient(); break;
27 default: throw new Error('Bad mode: ' + options.mode);
30 process.title = 'http_bench[' + options.mode + ']';
32 // monkey-patch the log functions so they include name + pid
33 console.log = patch(console.log);
34 console.trace = patch(console.trace);
35 console.error = patch(console.error);
38 var prefix = process.title + '[' + process.pid + '] ';
40 var args = Array.prototype.slice.call(arguments);
41 args[0] = prefix + args[0];
42 return fun.apply(console, args);
46 function startMaster() {
47 if (!cluster.isMaster) return startServer();
51 cluster.on('online', function() {
52 forkCount = forkCount + 1;
53 if (forkCount === ~~options.servers) {
57 'clientConcurrentRequests=' + options.clientConcurrentRequests
59 for (var i = ~~options.clients; i > 0; --i) {
60 var cp = spawn(process.execPath, args);
61 cp.stdout.pipe(process.stdout);
62 cp.stderr.pipe(process.stderr);
67 for (var i = ~~options.servers; i > 0; --i) cluster.fork();
70 function startServer() {
71 http.createServer(onRequest).listen(options.port, options.host);
73 var body = Array(1024).join('x');
74 var headers = {'Content-Length': '' + body.length};
76 function onRequest(req, res) {
77 req.on('error', onError);
78 res.on('error', onError);
79 res.writeHead(200, headers);
83 function onError(err) {
84 console.error(err.stack);
88 function startClient() {
89 // send off a bunch of concurrent requests
90 for (var i = ~~options.clientConcurrentRequests; i > 0; --i) {
94 function sendRequest() {
95 var req = http.request(options, onConnection);
96 req.on('error', onError);
100 // add a little back-off to prevent EADDRNOTAVAIL errors, it's pretty easy
101 // to exhaust the available port range
102 function relaxedSendRequest() {
103 setTimeout(sendRequest, 1);
106 function onConnection(res) {
107 res.on('error', onError);
108 res.on('data', onData);
109 res.on('end', relaxedSendRequest);
112 function onError(err) {
113 console.error(err.stack);
114 relaxedSendRequest();
117 function onData(data) {
118 // this space intentionally left blank