Permalink
Browse files

Code cleaning to follow jshint requirements + got rid of only-one-var…

…-per-function rule for better readability
  • Loading branch information...
1 parent f9cd056 commit fa5402b1b66318df6c8e2a3b7bfe410a5edacac5 @samalba samalba committed Aug 13, 2012
Showing with 85 additions and 128 deletions.
  1. +7 −1 jshint.json
  2. +18 −23 lib/master.js
  3. +16 −25 lib/memorymonitor.js
  4. +34 −75 lib/worker.js
  5. +8 −4 test/proxy.js
  6. +2 −0 test/test_simple.js
View
8 jshint.json
@@ -1,3 +1,9 @@
{
- "node": true
+ "node": true,
+ "strict": true,
+ "curly": true,
+ "newcap": true,
+ "eqeqeq": true,
+ "noempty": true,
+ "white": true
}
View
41 lib/master.js
@@ -7,17 +7,17 @@ var fs = require('fs'),
util = require('util');
var accessLog = function (self, path) {
+ var months = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+ ];
var openStream = function () {
return fs.createWriteStream(path, {
flags: 'a+',
mode: 0x1A4 // 0644
});
- },
- stream = openStream(),
- months = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ];
+ };
+ var stream = openStream();
process.on('SIGUSR1', function () {
// Reload the Stream on signal
@@ -27,16 +27,17 @@ var accessLog = function (self, path) {
self.on('exit', function () {
stream.end();
});
+
// Format log
return function (data) {
+ var line = '',
+ date = new Date(data.currentTime);
var addDigit = function (n) {
if (n < 10) {
return '0' + n;
}
return n;
- },
- line = '',
- date = new Date(data.currentTime);
+ };
// Remote addr
if (data.remoteAddr.slice(0, 2) !== '::') {
line += '::ffff:';
@@ -103,13 +104,9 @@ function Master(config) {
Master.prototype = new events.EventEmitter();
Master.prototype.spawnWorkers = function (number) {
- var self = this,
- workers = [],
- spawnWorker,
- onExit,
- n;
+ var workers = [];
- spawnWorker = function () {
+ var spawnWorker = function () {
var worker = cluster.fork();
worker.on('message', function (message) {
// Gather the logs from the workers
@@ -125,17 +122,15 @@ Master.prototype.spawnWorkers = function (number) {
};
// Spawn all workers
- for (n = 0; n < number; n += 1) {
+ for (var n = 0; n < number; n += 1) {
util.log('Spawning worker #' + n);
spawnWorker();
}
// When one worker is dead, let's respawn one
cluster.on('death', function (worker) {
- var idx = workers.indexOf(worker),
- pid;
-
- pid = (worker.process === undefined) ? worker.pid : worker.process.pid;
+ var idx = workers.indexOf(worker);
+ var pid = (worker.process === undefined) ? worker.pid : worker.process.pid;
if (idx >= 0) {
workers.splice(idx, 1);
}
@@ -144,14 +139,14 @@ Master.prototype.spawnWorkers = function (number) {
});
// Set an exit handler
- onExit = function () {
- self.emit('exit');
+ var onExit = function () {
+ this.emit('exit');
util.log('Exiting, killing the workers');
workers.forEach(function (worker) {
process.kill(worker.pid);
});
process.exit(0);
- };
+ }.bind(this);
process.on('exit', onExit);
process.on('SIGINT', onExit);
process.on('SIGTERM', onExit);
View
41 lib/memorymonitor.js
@@ -11,8 +11,6 @@
*/
function MemoryMonitor(options) {
- var self = this;
-
if (!(this instanceof MemoryMonitor)) {
return new MemoryMonitor(options);
}
@@ -35,14 +33,13 @@ function MemoryMonitor(options) {
this.options.logHandler('MemoryMonitor: ' + msg);
};
setInterval(function () {
- self.tick();
- }, this.options.checkInterval * 1000);
+ this.tick();
+ }.bind(this), this.options.checkInterval * 1000);
}
MemoryMonitor.prototype.tick = function () {
- var memoryLimit = (this.options.memoryLimit * 1024 * 1024),
- currentMemory = process.memoryUsage().rss;
-
+ var memoryLimit = (this.options.memoryLimit * 1024 * 1024);
+ var currentMemory = process.memoryUsage().rss;
if (currentMemory < memoryLimit) {
this.log('Memory usage is OK (' + Math.round(currentMemory / (1024 * 1024)) + 'MB)');
return;
@@ -53,9 +50,7 @@ MemoryMonitor.prototype.tick = function () {
};
MemoryMonitor.prototype.dumpStatistics = function () {
- var uptime;
-
- uptime = (new Date()).getTime() - this.stats.startTime;
+ var uptime = (new Date()).getTime() - this.stats.startTime;
this.log('=== Exceeded memory report ===');
this.log('Gracefully exited: ' + this.stats.gracefullyExited);
this.log('Uptime: ' + Math.round(uptime / 1000 / 60) + ' minutes');
@@ -64,12 +59,10 @@ MemoryMonitor.prototype.dumpStatistics = function () {
};
MemoryMonitor.prototype.exit = function () {
- var self = this,
- n = this._servers.length;
-
+ var n = this._servers.length;
this.log('Waiting for ' + n + ' server handlers...');
if (n === 0) {
- self.dumpStatistics();
+ this.dumpStatistics();
process.exit(1);
}
n -= 1;
@@ -81,30 +74,28 @@ MemoryMonitor.prototype.exit = function () {
this._servers = [];
setTimeout(function () {
this._log(this._closing + ' server handler is stuck, force exiting...');
- self.stats.gracefullyExited = false;
- self.dumpStatistics();
+ this.stats.gracefullyExited = false;
+ this.dumpStatistics();
process.exit(1);
- }, this.options.gracefulWait * 1000);
+ }.bind(this), this.options.gracefulWait * 1000);
};
MemoryMonitor.prototype.addServer = function (server) {
- var self = this;
-
server.on('request', function () {
- self.stats.requests += 1;
- });
+ this.stats.requests += 1;
+ }.bind(this));
server.on('connection', function () {
- self.stats.connections += 1;
- });
+ this.stats.connections += 1;
+ }.bind(this));
server.on('close', function () {
this._closing -= 1;
if (this._closing > 0) {
return;
}
// All servers closed, exiting the current process
- self.dumpStatistics();
+ this.dumpStatistics();
process.exit(1);
- });
+ }.bind(this));
this._servers.push(server);
};
View
109 lib/worker.js
@@ -59,35 +59,16 @@ function Worker(config) {
}
Worker.prototype.runServer = function (config) {
- var proxyErrorHandler,
- startHandler,
- getRemoteAddress,
- errorMessage,
- getDomainName,
- getBackendFromHostHeader,
- httpRequestHandler,
- wsRequestHandler,
- monitor,
- ipv4HttpServer,
- ipv4HttpsServer,
- ipv6HttpServer,
- ipv6HttpsServer,
- options;
-
httpProxy.setMaxSockets(config.maxSockets);
- proxyErrorHandler = function (err, req, res) {
- var frontendKey,
- backendId,
- multi;
-
+ var proxyErrorHandler = function (err, req, res) {
if (err.code === 'ECONNREFUSED' ||
err.code === 'ETIMEDOUT' ||
req.error !== undefined) {
// Store the dead backend ID
- frontendKey = 'dead:' + req.meta.frontend;
- backendId = req.meta.backendId;
- multi = redis.multi();
+ var frontendKey = 'dead:' + req.meta.frontend;
+ var backendId = req.meta.backendId;
+ var multi = redis.multi();
multi.sadd(frontendKey, backendId);
multi.expire(frontendKey, config.deadBackendTTL);
multi.exec();
@@ -111,7 +92,7 @@ Worker.prototype.runServer = function (config) {
req.emit('retry');
};
- startHandler = function (req, res) {
+ var startHandler = function (req, res) {
var remoteAddr = getRemoteAddress(req);
// TCP timeout to 30 sec
@@ -136,7 +117,7 @@ Worker.prototype.runServer = function (config) {
req.headers['x-forwarded-port'] = req.connection.pair ? '443' : '80';
};
- getRemoteAddress = function (req) {
+ var getRemoteAddress = function (req) {
if (req.connection === undefined) {
return null;
}
@@ -149,26 +130,19 @@ Worker.prototype.runServer = function (config) {
return null;
};
- errorMessage = function (res, message, code) {
- var staticPath,
- serve,
- errorPage;
-
+ var errorMessage = function (res, message, code) {
if (message === undefined) {
message = '';
}
code = isNaN(code) ? 400 : parseInt(code, 10);
- staticPath = function (name) {
+ var staticPath = function (name) {
return rootDir + '/static/error_' + name + '.html';
};
- serve = function (filePath) {
- var stream,
- headers;
-
- stream = fs.createReadStream(filePath);
- headers = {
+ var serve = function (filePath) {
+ var stream = fs.createReadStream(filePath);
+ var headers = {
'content-type': 'text/html'
};
if (res.debug === true) {
@@ -186,7 +160,7 @@ Worker.prototype.runServer = function (config) {
});
};
- errorPage = staticPath(code);
+ var errorPage = staticPath(code);
path.exists(errorPage, function (exists) {
if (exists === true) {
return serve(errorPage);
@@ -212,7 +186,7 @@ Worker.prototype.runServer = function (config) {
});
};
- getDomainName = function (hostname) {
+ var getDomainName = function (hostname) {
var idx = hostname.lastIndexOf('.');
if (idx < 0) {
@@ -225,38 +199,29 @@ Worker.prototype.runServer = function (config) {
return hostname.substr(idx);
};
- getBackendFromHostHeader = function (host, callback) {
- var index,
- multi;
-
+ var getBackendFromHostHeader = function (host, callback) {
if (host === undefined) {
return callback('no host header', 400);
}
- index = host.indexOf(':');
+ var index = host.indexOf(':');
if (index > 0) {
host = host.slice(0, index).toLowerCase();
}
- multi = redis.multi();
+ var multi = redis.multi();
multi.lrange('frontend:' + host, 0, -1);
multi.lrange('frontend:*' + getDomainName(host), 0, -1);
multi.smembers('dead:' + host);
multi.exec(function (err, rows) {
- var backends,
- deads,
- virtualHost,
- index,
- backend;
-
- backends = rows[0];
+ var backends = rows[0];
if (backends.length === 0) {
backends = rows[1];
}
- deads = rows[2];
+ var deads = rows[2];
if (backends.length === 0) {
return callback('frontend not found', 400);
}
- virtualHost = backends.shift();
- index = (function () {
+ var virtualHost = backends.shift();
+ var index = (function () {
// Pickup a random backend index
var indexes = [],
i;
@@ -275,7 +240,7 @@ Worker.prototype.runServer = function (config) {
if (index < 0) {
return callback('Cannot find a valid backend', 502);
}
- backend = url.parse(backends[index]);
+ var backend = url.parse(backends[index]);
backend.id = index; // Store the backend index
backend.frontend = host; // Store the associated frontend
backend.virtualHost = virtualHost; // Store the associated vhost
@@ -288,24 +253,18 @@ Worker.prototype.runServer = function (config) {
});
};
- httpRequestHandler = function (req, res) {
- var proxyRequest;
-
+ var httpRequestHandler = function (req, res) {
res.timer = {
start: (new Date()).getTime()
};
// Patch the response object
(function () {
- var resWriteHead,
- resEnd,
- socketBytesWritten;
-
// Enable debug?
- res.debug = !(req.headers['x-debug'] === undefined);
+ res.debug = (req.headers['x-debug'] !== undefined);
// Patch res.writeHead to return debug headers
if (res.debug === true) {
- resWriteHead = res.writeHead;
+ var resWriteHead = res.writeHead;
res.writeHead = function () {
res.timer.end = (new Date()).getTime();
if (req.meta === undefined) {
@@ -321,10 +280,10 @@ Worker.prototype.runServer = function (config) {
};
}
// Patch res.end to log the response stats
- resEnd = res.end;
+ var resEnd = res.end;
res.end = function () {
resEnd.apply(res, arguments);
- socketBytesWritten = res.socket ? res.socket.bytesWritten : 0;
+ var socketBytesWritten = res.socket ? res.socket.bytesWritten : 0;
if (req.meta === undefined ||
req.headers['x-real-ip'] === undefined) {
return; // Nothing to log
@@ -351,7 +310,7 @@ Worker.prototype.runServer = function (config) {
}());
// Proxy the HTTP request
- proxyRequest = function () {
+ var proxyRequest = function () {
var buffer = httpProxy.buffer(req);
getBackendFromHostHeader(req.headers.host, function (err, code, backend) {
@@ -388,7 +347,7 @@ Worker.prototype.runServer = function (config) {
proxyRequest();
};
- wsRequestHandler = function (req, socket, head) {
+ var wsRequestHandler = function (req, socket, head) {
var buffer = httpProxy.buffer(socket);
getBackendFromHostHeader(req.headers.host, function (err, code, backend) {
@@ -409,33 +368,33 @@ Worker.prototype.runServer = function (config) {
});
};
- monitor = memoryMonitor({
+ var monitor = memoryMonitor({
logHandler: log
});
// Ipv4
- ipv4HttpServer = http.createServer(httpRequestHandler);
+ var ipv4HttpServer = http.createServer(httpRequestHandler);
ipv4HttpServer.on('upgrade', wsRequestHandler);
ipv4HttpServer.listen(config.port);
// Ipv6
- ipv6HttpServer = http.createServer(httpRequestHandler);
+ var ipv6HttpServer = http.createServer(httpRequestHandler);
ipv6HttpServer.on('upgrade', wsRequestHandler);
ipv6HttpServer.listen(config.port, '::1');
monitor.addServer(ipv4HttpServer);
monitor.addServer(ipv6HttpServer);
if (config.https) {
- options = config.https;
+ var options = config.https;
options.key = fs.readFileSync(options.key, 'utf8');
options.cert = fs.readFileSync(options.cert, 'utf8');
- ipv4HttpsServer = https.createServer(options, httpRequestHandler);
+ var ipv4HttpsServer = https.createServer(options, httpRequestHandler);
ipv4HttpsServer.on('upgrade', wsRequestHandler);
ipv4HttpsServer.listen(config.https.port);
- ipv6HttpsServer = https.createServer(options, httpRequestHandler);
+ var ipv6HttpsServer = https.createServer(options, httpRequestHandler);
ipv6HttpsServer.on('upgrade', wsRequestHandler);
ipv6HttpsServer.listen(config.https.port, '::1');
View
12 test/proxy.js
@@ -1,4 +1,6 @@
+'use strict';
+
/**
* This module is a helper to setUp and tearDown the tests.
* This is not a Test module.
@@ -14,7 +16,7 @@ var child_process = require('child_process'),
exports.setUp = function () {
redisClient = redis.createClient();
- redisClient.on('error', function () {
+ redisClient.on('error', function (err) {
util.log('RedisError ' + err + ' (is redis-server running?)');
});
count = 0;
@@ -29,8 +31,9 @@ exports.addFrontend = function (frontend, backends, callback) {
exports.removeFrontend(frontend);
backends.splice(0, 0, frontend);
redisClient.rpush('frontend:' + frontend, backends, function () {
- if (callback !== undefined)
+ if (callback !== undefined) {
callback();
+ }
});
};
@@ -60,11 +63,12 @@ exports.requestFrontend = function (testObject, frontend, expectedStatusCode, ca
var req = http.get(opts, function (res) {
testObject.ok(res.statusCode === expectedStatusCode,
'#' + count + ' Expected status code: ' + expectedStatusCode + ' (got: ' + res.statusCode + ' on "' + frontend + '")');
- if (callback !== undefined)
+ if (callback !== undefined) {
callback();
+ }
});
req.on('error', function (error) {
testObject.ok(false, '#' + count + ' Failed to proxify (error: ' + error + ')');
});
count++;
-}
+};
View
2 test/test_simple.js
@@ -1,4 +1,6 @@
+'use strict';
+
var http = require('http'),
proxy = require('./proxy');

0 comments on commit fa5402b

Please sign in to comment.