1 var spawn = require('child_process').spawn;
2 var cluster = require('cluster');
3 var http = require('http');
12 clientConcurrentRequests: 2
15 for (var i = 2; i < process.argv.length; ++i) {
16 var args = process.argv[i].split('=', 2);
22 switch (options.mode) {
23 case 'master': startMaster(); break;
24 case 'server': startServer(); break;
25 case 'client': startClient(); break;
26 default: throw new Error('Bad mode: ' + options.mode);
29 process.title = 'http_bench[' + options.mode + ']';
31 // monkey-patch the log functions so they include name + pid
32 console.log = patch(console.log);
33 console.trace = patch(console.trace);
34 console.error = patch(console.error);
37 var prefix = process.title + '[' + process.pid + '] ';
39 var args = Array.prototype.slice.call(arguments);
40 args[0] = prefix + args[0];
41 return fun.apply(console, args);
45 function startMaster() {
46 if (!cluster.isMaster) return startServer();
50 cluster.on('online', function () {
51 forkCount = forkCount + 1;
52 if (forkCount === ~~options.servers) {
56 'clientConcurrentRequests=' + options.clientConcurrentRequests
58 for (var i = ~~options.clients; i > 0; --i) {
59 var cp = spawn(process.execPath, args);
60 cp.stdout.pipe(process.stdout);
61 cp.stderr.pipe(process.stderr);
66 for (var i = ~~options.servers; i > 0; --i) cluster.fork();
69 function startServer() {
70 http.createServer(onRequest).listen(options.port, options.host);
72 var body = Array(1024).join('x');
73 var headers = {'Content-Length': '' + body.length};
75 function onRequest(req, res) {
76 req.on('error', onError);
77 res.on('error', onError);
78 res.writeHead(200, headers);
82 function onError(err) {
83 console.error(err.stack);
87 function startClient() {
88 // send off a bunch of concurrent requests
89 for (var i = ~~options.clientConcurrentRequests; i > 0; --i) {
93 function sendRequest() {
94 var req = http.request(options, onConnection);
95 req.on('error', onError);
99 // add a little back-off to prevent EADDRNOTAVAIL errors, it's pretty easy
100 // to exhaust the available port range
101 function relaxedSendRequest() {
102 setTimeout(sendRequest, 1);
105 function onConnection(res) {
106 res.on('error', onError);
107 res.on('data', onData);
108 res.on('end', relaxedSendRequest);
111 function onError(err) {
112 console.error(err.stack);
113 relaxedSendRequest();
116 function onData(data) {
117 // this space intentionally left blank