diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 2ccbe46..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules/ diff --git a/README.md b/README.md deleted file mode 100644 index a41c8cf..0000000 --- a/README.md +++ /dev/null @@ -1,96 +0,0 @@ -# LoadFire - -LoadFire is an easy to script load balancer and reverse proxy in NodeJS. - -It allows you to write your own pieces of logic as "Patterns" and the core engine takes care of all the proxying logic so you don't have to worry about it. - -**The real power is that all it's behavior is entirely scriptable in JavaScript (NodeJS). :)** - -###This allows for many different use cases, such as: - - Dynamic realtime proxying rules (domain mappings stored in Redis for example). Such things are useful for PaaSs - - Add pieces of middleware to your reverse proxy - - Customizable load balancing patterns (Sticky, RoundRobin, ...) - -###It supports proxying: - - HTTP/HTTPS - - WebSockets - -## Examples: - -### Proxying HTTP traffic using RoundRobin pattern - -```js -var http = require('http'); -var loadfire = require('loadfire'); - - -var EDITOR_PORTS = [7001, 7002, 7003,7004]; - -var EDITOR_SERVERS = EDITOR_PORTS.map(function (x) { - return { - host: 'localhost', - port: x - }; -}); - -// Start all our different http servers -function startEditorServers(ports) { - ports.forEach(function (port) { - // Setup HTTP Server - var httpServer = http.createServer(function(req, res) { - // Output the port number the server is running on - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end(port.toString()); - }); - - // Listen on assigned port - httpServer.listen(port); - }); -} - -// Config for our loadfire server -var CONFIG = { - 'resources': [ - { - // resource is some value identify this resource - // by default it should be the hostname to match - resource: 'localhost:8000', - - // List of backends to hit - backends: EDITOR_SERVERS, - - // Load balancing pattern - // As of now a few are builtin - // random, roundrobin, sticky - pattern: 'roundrobin' - } - ], - - // Server to start loadfire on - port: 8000 -}; - -function main() { - // Start our http servers - startEditorServers(EDITOR_PORTS); - - // Setup our load balancer with the above config - var loadServer = loadfire.createServer(CONFIG); - - // Now start our load balancer - loadServer.run(); - - // Check out localhost:8000 - // Refresh a few times and you'll see different port numbers appear - // depending on which http server the requests are proxied to - // since we are using the roundrobin pattern it will cycle through them -} - -// Run main -main(); -``` - - -It was initially built to satisfy our needs at FriendCode, and we've been using it in product for months without any issues, so it can be considered as stable. - -The API however will be changed soon due to some design decisions aiming to simplify it's API. (Patterns are quite monolithic as of now, they will be split up into different parts: matcher, mapper, balancer, store). diff --git a/bin/loadfire b/bin/loadfire deleted file mode 100644 index 4b0bee4..0000000 --- a/bin/loadfire +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env node - -'use strict'; - -var _ = require('underscore'); -var fs = require('fs'); -var path = require('path'); -var cluster = require('cluster'); -var util = require('util'); -var optimist = require('optimist'); - -var loadfire = require('../index.js'); - -// Constants -var HELP_MSG = [ - 'usage: loadfire [options]', - '', - 'Starts a loadfire server', - '', - 'options:', - ' -c, --config CONFIGFILE Location of the configuration file', - ' -h, --help Display help' -].join('\n'); - - -function LoadFire() { - // Nothing -} - -LoadFire.prototype.help = function() { - util.puts(HELP_MSG); -}; - -LoadFire.prototype.setConfig = function(path) { - var data = fs.readFileSync(path); - this.config = JSON.parse(data); -}; - -LoadFire.prototype.main = function() { - // Run master and worker - this.server = loadfire.createServer(this.config); - this.server.run(); -}; - -LoadFire.prototype.run = function(argv) { - var help = argv.h || argv.help; - var config = argv.c || argv.config; - var is_config = !(_.isUndefined(config)); - var is_help = !(_.isUndefined(help)) || !(is_config); - - if(is_config) { - this.setConfig(config); - this.main(); - } else if(is_help) { - return this.help(); - } else { - return; - } -}; - -function main() { - var argv = optimist.argv; - - var bin = new LoadFire(); - bin.run(argv); -} - -// Run main -main(); \ No newline at end of file diff --git a/images/bkg.png b/images/bkg.png new file mode 100644 index 0000000..fcebb5b Binary files /dev/null and b/images/bkg.png differ diff --git a/images/blacktocat.png b/images/blacktocat.png new file mode 100644 index 0000000..273d571 Binary files /dev/null and b/images/blacktocat.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..d468af1 --- /dev/null +++ b/index.html @@ -0,0 +1,137 @@ + + + + + + + + + + + Loadfire by FriendCode + + + + +
+
+

Loadfire

+

A scriptable Load Balancer & Reverse Proxy in NodeJS

+ +
+ Download as .zip + Download as .tar.gz + View on GitHub +
+
+
+ +
+
+

+LoadFire

+ +

LoadFire is an easy to script load balancer and reverse proxy in NodeJS.

+ +

It allows you to write your own pieces of logic as "Patterns" and the core engine takes care of all the proxying logic so you don't have to worry about it.

+ +

The real power is that all it's behavior is entirely scriptable in JavaScript (NodeJS). :)

+ +

+This allows for many different use cases, such as:

+ +

+It supports proxying:

+ +

+Examples:

+ +

+Proxying HTTP traffic using RoundRobin pattern

+ +
var http = require('http');
+var loadfire = require('loadfire');
+
+
+var EDITOR_PORTS = [7001, 7002, 7003,7004];
+
+var EDITOR_SERVERS = EDITOR_PORTS.map(function (x) {
+    return {
+        host: 'localhost',
+        port: x
+    };
+});
+
+// Start all our different http servers
+function startEditorServers(ports) {
+    ports.forEach(function (port) {
+        // Setup HTTP Server
+        var httpServer = http.createServer(function(req, res) {
+            // Output the port number the server is running on
+            res.writeHead(200, {'Content-Type': 'text/plain'});
+            res.end(port.toString());
+        });
+
+        // Listen on assigned port
+        httpServer.listen(port);
+    });
+}
+
+// Config for our loadfire server
+var CONFIG = {
+    'resources': [
+        {
+            // resource is some value identify this resource
+            // by default it should be the hostname to match
+            resource: 'localhost:8000',
+
+            // List of backends to hit
+            backends: EDITOR_SERVERS,
+
+            // Load balancing pattern
+            // As of now a few are builtin
+            // random, roundrobin, sticky
+            pattern: 'roundrobin'
+        }
+    ],
+
+    // Server to start loadfire on
+    port: 8000
+};
+
+function main() {
+    // Start our http servers
+    startEditorServers(EDITOR_PORTS);
+
+    // Setup our load balancer with the above config
+    var loadServer = loadfire.createServer(CONFIG);
+
+    // Now start our load balancer
+    loadServer.run();
+
+    // Check out localhost:8000
+    // Refresh a few times and you'll see different port numbers appear
+    // depending on which http server the requests are proxied to
+    // since we are using the roundrobin pattern it will cycle through them
+}
+
+// Run main
+main();
+
+ +

It was initially built to satisfy our needs at FriendCode, and we've been using it in product for months without any issues, so it can be considered as stable.

+ +

The API however will be changed soon due to some design decisions aiming to simplify it's API. (Patterns are quite monolithic as of now, they will be split up into different parts: matcher, mapper, balancer, store).

+
+
+ + + + \ No newline at end of file diff --git a/index.js b/index.js deleted file mode 100644 index 46b6cb8..0000000 --- a/index.js +++ /dev/null @@ -1,27 +0,0 @@ -// Requires -var server = require('./lib/server'); - -var selectors = require('./lib/selectors/'); -var balancers = require('./lib/balancers/'); - -var groupBalancer = require('./lib/groupbalancer'); -var config = require('./lib/config'); - - -function createServer(config) { - var newServer = new server.Server(config); - return newServer; -} - -// Exports -exports.createServer = createServer; -exports.Server = server.Server; - -// Aliasing -exports.server = server; - -exports.selectors = selectors; -exports.balancers = balancers; - -exports.groupBalancer = groupBalancer; -exports.config = config; diff --git a/javascripts/main.js b/javascripts/main.js new file mode 100644 index 0000000..d8135d3 --- /dev/null +++ b/javascripts/main.js @@ -0,0 +1 @@ +console.log('This would be the main JS file.'); diff --git a/lib/balancers/index.js b/lib/balancers/index.js deleted file mode 100644 index e72edb9..0000000 --- a/lib/balancers/index.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - random: require('./random'), - roundrobin: require('./roundrobin'), -}; diff --git a/lib/balancers/random.js b/lib/balancers/random.js deleted file mode 100644 index 6122f33..0000000 --- a/lib/balancers/random.js +++ /dev/null @@ -1,12 +0,0 @@ - // Requires -var _ = require('underscore'); - - -// Random Pattern -function random(backends, req, cb) { - return cb(null, _.sample(backends)); -} - - -// Exports -module.exports = random; diff --git a/lib/balancers/roundrobin.js b/lib/balancers/roundrobin.js deleted file mode 100644 index 799f001..0000000 --- a/lib/balancers/roundrobin.js +++ /dev/null @@ -1,12 +0,0 @@ -// Roundrobin Pattern -function roundrobin(backends, req, cb) { - // Rotate backends - var x = backends.shift(); - backends.push(x); - - return cb(null, x); -} - - -// Exports -module.exports = roundrobin; diff --git a/lib/config.js b/lib/config.js deleted file mode 100644 index 446ebd4..0000000 --- a/lib/config.js +++ /dev/null @@ -1,113 +0,0 @@ -// Requires -var _ = require('underscore'); - -var connect = require('connect'); - -// Constants -var REQUIRED_FIELDS = ['resources']; -var DEFAULTS = { - 'port': 8484, - 'bind': '0.0.0.0', - 'tcpTimeout': 600, - 'retries': 50, - 'retryTimeout': 100, -}; - -function ConfigLoader(rawConfig) { - // This should not be modified - this.rawConfig = rawConfig; - - // This will be modified (updated) - this.config = _.clone(rawConfig); -} - -ConfigLoader.prototype.isValid = function() { - var that = this; - var fields = REQUIRED_FIELDS.map(function(x) { - return that.config[x]; - }); - - // Check that they exist - var exist = _.all(fields.map(function(x) { - return !_.isUndefined(x); - })); - - return exist; -}; - -ConfigLoader.prototype.resolveBackends = function(backends) { - return backends.map(function(x) { - x.port = Number(x.port); - return x; - }); -}; - - -ConfigLoader.prototype.resolveResources = function(resources) { - var that = this; - var newResources = resources.map(function(x) { - var y = _.clone(x); - - y.backends = that.resolveBackends(y.backends); - - y.middleware = y.middleware || []; - - // Setup connect middleware handler - var app = connect(); - _.each(y.middleware, function(middleware) { - app.use(middleware); - }); - - y.middlewareHandler = app.handle.bind(app); - - // Bind methods to resource - _.bindAll(y); - - return y; - }); - return newResources; -}; - -ConfigLoader.prototype.resolve = function() { - // Resolve patterns and what not - var resources = this.resolveResources(this.config.resources); - - var newConfig = _.clone(this.config); - - // Update copied config - newConfig.resources = resources; - newConfig.port = Number(this.config.port); - - return newConfig; -}; - -ConfigLoader.prototype.setDefaults = function() { - for(var key in DEFAULTS) { - this.config[key] = this.rawConfig[key] || DEFAULTS[key]; - } -}; - -ConfigLoader.prototype.load = function() { - // Set defaults - this.setDefaults(); - - // Validate - var valid = this.isValid(); - if(!valid) { - throw Error("Invalid Config"); - } - - // Resolve patterns etc ... - return this.resolve(); -}; - -function resolveConfig(config) { - var loader = new ConfigLoader(config); - var newConfig = loader.load(); - return newConfig; -} - -// Exports -module.exports.ConfigLoader = ConfigLoader; -module.exports.resolveConfig = resolveConfig; - diff --git a/lib/groupbalancer.js b/lib/groupbalancer.js deleted file mode 100644 index 23e5ff2..0000000 --- a/lib/groupbalancer.js +++ /dev/null @@ -1,307 +0,0 @@ -// Requires -var Q = require('q'); -var _ = require('underscore'); -var es = require('event-stream'); - -var util = require('util'); -var events = require('events'); - -var retry = require('qplus').retry; - -var httpProxy = require('http-proxy'); - - -// Returns only fulfilled value in a list of results -function fulfilled(results) { - return (results || []) - .filter(function(result) { - return result.state === "fulfilled"; - }) - .map(function(result) { - return result.value; - }); -} - -function GroupBalancer(config, resources) { - // Bind methods to resource - this.resources = resources; - - this.config = config; - - // Bind methods - _.bindAll(this); -} -util.inherits(GroupBalancer, events.EventEmitter); - - -GroupBalancer.prototype.selectResource = function(req) { - var resources = this.resources; - - return Q.allSettled( - // Array of booleans saying if the resource can handle - this.resources.map(function(resource) { - // Should handle ? - return Q.nfcall(resource.selector, req); - }) - ) - .then(fulfilled) - .then(function (results) { - // Associate resources with their respective results - return _.first(_.map( - _.filter( - _.zip(resources, results), - _.last - ), - _.first - )); - }) - .then(function(resource) { - if(!resource) { - throw new Error("No resource can handle the request"); - } - return resource; - }); -}; - -GroupBalancer.prototype.selectBackend = function(req, resource) { - return Q.nfcall(resource.balancer, resource.backends, req) - .then(function(backend) { - if(!backend) { - throw new Error("Balancer could not give a valid backend to route to"); - } - return [backend, resource]; - }); -}; - -// selectResource then selectBackend -GroupBalancer.prototype.grabBackend = function(req) { - return this.selectResource(req) - .then(_.partial(this.selectBackend, req)); -}; - -GroupBalancer.prototype.applyMiddleware = function(resource, req, res) { - return Q.nfcall(resource.middlewareHandler, req, res); -}; - -// Handle an error when routing a HTTP request -// Terminate request/response -GroupBalancer.prototype.handleError = function(err, req, res, backend) { - var target = !backend ? null : [backend.host, backend.port].join(':') + req.url; - - // Emit handling error - this.emit('httpError', err, target); - - // Terminate request - res.writeHead(500, { 'Content-Type': 'text/plain' }); - - if (req.method !== 'HEAD') { - // - // This NODE_ENV=production behavior is mimics Express and - // Connect. - // - if (process.env.NODE_ENV === 'production') { - res.write('Internal Server Error'); - } - else { - res.write('An error has occurred:\n' + err ? err.stack : err); - } - } - - // End - try { res.end(); } - catch (ex) { console.error("res.end error: %s", ex.message); } -}; - -GroupBalancer.prototype._proxyToBackend = function(req, res, backend, dataArray) { - // this will be resolved/rejected on request completion - var d = Q.defer(); - - // Create a readable stream - // from all the data of our request that we stored - var buffer = es.readArray(dataArray); - - // Build proxy - var proxy = httpProxy.createProxyServer({ - target: _.clone(backend), - buffer: buffer - }); - - function cleanup() { - req.removeAllListeners(); - } - - // Failure - proxy.once('error', function(err) { - cleanup(); - d.reject(err); - }); - - // Success - proxy.once('proxyRes', function() { - cleanup(); - d.resolve(); - }); - - // Handle (actual proxying) - proxy.proxyRequest(req, res); - - return d.promise; -}; - -GroupBalancer.prototype._handleHttp = function(req, res, backend, dataArray) { - var self = this; - - // Try 5 times, 50ms apart - return retry( - self._proxyToBackend, - this.config.retries, - this.config.retryTimeout, - function canContinue(err, nTries) { - // Only continue if headers are not sent - return res.headersSent === false; - } - )(req, res, backend, dataArray); -}; - -GroupBalancer.prototype.handle = function(req, res, _proxy) { - var self = this; - - // Pause req for middleware (async work) - req.pause(); - - return this.selectResource(req) - .then(function(resource) { - // Apply middleware and return backend - return self.applyMiddleware(resource, req, res) - .then(_.partial(_.identity, resource)); - }) - .then(function(resource) { - // Middleware handled response so lets exit - if(res.headersSent) { - return; - } - - return self.selectBackend(req, resource) - .spread(function(backend, resource) { - var d = Q.defer(); - - // Resume request (after applying middleware) - req.resume(); - - // We need to log all the req's events to a buffer - // so that we can replay them when retrying - var writer = es.writeArray(function(err, dataArray) { - if(err) { - return d.reject(err); - } - - return d.resolve([backend, dataArray]); - }); - - // Pipe to the array - req.pipe(writer); - - return d.promise; - }) - .spread(function(backend, dataArray) { - return self._handleHttp(req, res, backend, dataArray); - }) - .fail(function(err) { - // Use custom resource error handler if it exists - if(_.isFunction(resource.error)) { - return resource.error(err, req, res); - } - return self.handleError(err, req, res); - }); - }, function(err) { - return self.handleError(err, req, res); - }); -}; - - - -GroupBalancer.prototype.handleWs = function(req, socket, head) { - var self = this; - - // Pause request stream - req.pause(); - - return this.grabBackend(req) - .spread(function(backend, resource) { - var d = Q.defer(); - - // Log - self.emit('wsHandle', req.headers.host+req.url); - - // Build proxy - var proxy = httpProxy.createProxyServer({ - target: _.clone(backend) - }); - - // Handle errors - proxy.once('error', function(err, req, socket) { - return d.reject(err); - }); - - // Handle success/termination - socket.once('end', function() { - return d.resolve(); - }); - - // Actual proxying - proxy.proxyWebsocketRequest(req, socket, head); - - // Resume request - req.resume(); - - return d.promise; - }) - .fail(function(err) { - req.resume(); - - console.log('WS Error:', err && err.stack); - - self.emit('wsError', err); - - // Write error and close - socket.write('ERROR: Loadfire does not know how to handle that request\n'); - socket.end(err.toString()); - - }); -}; - - -// TCP Handler, just keep the connection alive -// do nothing special besides some logging -GroupBalancer.prototype.tcpConnectionHandler = function (connection) { - var self = this; - - var remoteAddress = connection.remoteAddress, - remotePort = connection.remotePort, - start = Date.now(); - - var getSocketInfo = function () { - return JSON.stringify({ - remoteAddress: remoteAddress, - remotePort: remotePort, - bytesWritten: connection.bytesWritten, - bytesRead: connection.bytesRead, - elapsed: (Date.now() - start) / 1000 - }); - }; - - connection.setKeepAlive(false); - connection.setTimeout(this.config.tcpTimeout * 1000); - - - connection.on('error', function (err) { - self.emit('tcpError', err, getSocketInfo()); - }); - connection.on('timeout', function () { - self.emit('tcpTimeout', getSocketInfo()); - connection.destroy(); - }); -}; - -// Exports -module.exports.GroupBalancer = GroupBalancer; \ No newline at end of file diff --git a/lib/selectors/host.js b/lib/selectors/host.js deleted file mode 100644 index 677b6ff..0000000 --- a/lib/selectors/host.js +++ /dev/null @@ -1,14 +0,0 @@ -// Host selector -function host(hostRegex) { - var regex = new RegExp(hostRegex); - return function _host_selector(req, cb) { - return cb( - null, - req.headers.host.match(regex) !== null - ); - }; -} - - -// Exports -module.exports = host; diff --git a/lib/selectors/index.js b/lib/selectors/index.js deleted file mode 100644 index 6872b79..0000000 --- a/lib/selectors/index.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - url: require('./url'), - host: require('./host') -}; \ No newline at end of file diff --git a/lib/selectors/url.js b/lib/selectors/url.js deleted file mode 100644 index 4e1c7e5..0000000 --- a/lib/selectors/url.js +++ /dev/null @@ -1,14 +0,0 @@ -// Url selector -function url(urlRegex) { - var regex = new RegExp(urlRegex); - return function _url_selector(req, cb) { - return cb( - null, - req.url.match(regex) !== null - ); - }; -} - - -// Exports -module.exports = url; diff --git a/lib/server.js b/lib/server.js deleted file mode 100644 index c3ff38e..0000000 --- a/lib/server.js +++ /dev/null @@ -1,50 +0,0 @@ -// Requires -var _ = require('underscore'); - -var http = require('http'); - -var config = require('./config'); -var GroupBalancer = require('./groupbalancer').GroupBalancer; - - -function Server(_config) { - // Validate and Resolve our configuration - this.config = config.resolveConfig(_config); - - // Get the group balancer - this.balancer = new GroupBalancer(this.config, this.config.resources); - - // Setup server and the different handlers - this.setupServer(); - - // Bind methods - _.bindAll(this); -} - -// Setup our handlers -Server.prototype.setupServer = function () { - // Create server and handle usual HTTP Connections - this.server = http.createServer(this.balancer.handle); - - // Handle TCP connections - this.server.on('connection', this.balancer.tcpConnectionHandler); - - // Handle websocket upgrades - this.server.on('upgrade', this.balancer.handleWs); -}; - -// Server listen -Server.prototype.listen = function () { - var args = _.isEmpty(arguments) ? [this.config.port] : _.toArray(arguments); - // List on port - this.server.listen.apply(this.server, args); - - return this; -}; - -// Alias -Server.prototype.run = Server.prototype.listen; - - -// Exports -module.exports.Server = Server; \ No newline at end of file diff --git a/package.json b/package.json deleted file mode 100644 index 1be3a31..0000000 --- a/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name" : "loadfire", - "version" : "3.0.1", - "description" : "A clean and simple load balancer", - "keywords": [ - "reverse", - "proxy", - "http", - "http-proxy", - "load", - "balancer", - "load-balancer" - ], - "main" : "./index.js", - "bin": { - "loadfire": "./bin/loadfire" - }, - "directories" : { - "lib" : "./lib" - }, - "dependencies" : { - "connect": "2.11.0", - "http-proxy" : "1.0.2", - "optimist": "0.3.0", - "underscore": "1.4.4", - "q": "0.9.6", - "event-stream": "3.1.0", - "qplus": "0.1.0" - }, - "scripts" : { - "start" : "node bin/loadfire" - }, - "engines" : { - "node" : ">=0.8.0" - }, - "engineStrict": true, - "license": "MIT", - "author" : { - "name" : "Aaron O'Mullan", - "email" : "aaron.omullan@friendco.de", - "url" : "https://friendco.de" - }, - "maintainer" : [ - "Aaron O'Mullan " - ], - "repository": { - "type": "git", - "url": "https://github.com/FriendCode/loadfire.git" - } -} diff --git a/params.json b/params.json new file mode 100644 index 0000000..e95c302 --- /dev/null +++ b/params.json @@ -0,0 +1 @@ +{"name":"Loadfire","tagline":"A scriptable Load Balancer & Reverse Proxy in NodeJS","body":"# LoadFire\r\n\r\nLoadFire is an easy to script load balancer and reverse proxy in NodeJS.\r\n\r\nIt allows you to write your own pieces of logic as \"Patterns\" and the core engine takes care of all the proxying logic so you don't have to worry about it.\r\n\r\n**The real power is that all it's behavior is entirely scriptable in JavaScript (NodeJS). :)**\r\n\r\n###This allows for many different use cases, such as:\r\n - Dynamic realtime proxying rules (domain mappings stored in Redis for example). Such things are useful for PaaSs \r\n - Add pieces of middleware to your reverse proxy\r\n - Customizable load balancing patterns (Sticky, RoundRobin, ...)\r\n\r\n###It supports proxying:\r\n - HTTP/HTTPS\r\n - WebSockets\r\n\r\n## Examples:\r\n\r\n### Proxying HTTP traffic using RoundRobin pattern\r\n\r\n```js\r\nvar http = require('http');\r\nvar loadfire = require('loadfire');\r\n\r\n\r\nvar EDITOR_PORTS = [7001, 7002, 7003,7004];\r\n\r\nvar EDITOR_SERVERS = EDITOR_PORTS.map(function (x) {\r\n return {\r\n host: 'localhost',\r\n port: x\r\n };\r\n});\r\n\r\n// Start all our different http servers\r\nfunction startEditorServers(ports) {\r\n ports.forEach(function (port) {\r\n // Setup HTTP Server\r\n var httpServer = http.createServer(function(req, res) {\r\n // Output the port number the server is running on\r\n res.writeHead(200, {'Content-Type': 'text/plain'});\r\n res.end(port.toString());\r\n });\r\n\r\n // Listen on assigned port\r\n httpServer.listen(port);\r\n });\r\n}\r\n\r\n// Config for our loadfire server\r\nvar CONFIG = {\r\n 'resources': [\r\n {\r\n // resource is some value identify this resource\r\n // by default it should be the hostname to match\r\n resource: 'localhost:8000',\r\n\r\n // List of backends to hit\r\n backends: EDITOR_SERVERS,\r\n\r\n // Load balancing pattern\r\n // As of now a few are builtin\r\n // random, roundrobin, sticky\r\n pattern: 'roundrobin'\r\n }\r\n ],\r\n\r\n // Server to start loadfire on\r\n port: 8000\r\n};\r\n\r\nfunction main() {\r\n // Start our http servers\r\n startEditorServers(EDITOR_PORTS);\r\n\r\n // Setup our load balancer with the above config\r\n var loadServer = loadfire.createServer(CONFIG);\r\n\r\n // Now start our load balancer\r\n loadServer.run();\r\n\r\n // Check out localhost:8000\r\n // Refresh a few times and you'll see different port numbers appear\r\n // depending on which http server the requests are proxied to\r\n // since we are using the roundrobin pattern it will cycle through them\r\n}\r\n\r\n// Run main\r\nmain();\r\n```\r\n\r\n\r\nIt was initially built to satisfy our needs at FriendCode, and we've been using it in product for months without any issues, so it can be considered as stable.\r\n\r\nThe API however will be changed soon due to some design decisions aiming to simplify it's API. (Patterns are quite monolithic as of now, they will be split up into different parts: matcher, mapper, balancer, store).\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."} \ No newline at end of file diff --git a/stylesheets/pygment_trac.css b/stylesheets/pygment_trac.css new file mode 100644 index 0000000..d1df6a2 --- /dev/null +++ b/stylesheets/pygment_trac.css @@ -0,0 +1,68 @@ +.highlight .c { color: #999988; font-style: italic } /* Comment */ +.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ +.highlight .k { font-weight: bold } /* Keyword */ +.highlight .o { font-weight: bold } /* Operator */ +.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ +.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ +.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ +.highlight .gd .x { color: #000000; background-color: #ffaaaa } /* Generic.Deleted.Specific */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #aa0000 } /* Generic.Error */ +.highlight .gh { color: #999999 } /* Generic.Heading */ +.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ +.highlight .gi .x { color: #000000; background-color: #aaffaa } /* Generic.Inserted.Specific */ +.highlight .go { color: #888888 } /* Generic.Output */ +.highlight .gp { color: #555555 } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold; } /* Generic.Subheading */ +.highlight .gt { color: #aa0000 } /* Generic.Traceback */ +.highlight .kc { font-weight: bold } /* Keyword.Constant */ +.highlight .kd { font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ +.highlight .kr { font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ +.highlight .m { color: #009999 } /* Literal.Number */ +.highlight .s { color: #d14 } /* Literal.String */ +.highlight .na { color: #008080 } /* Name.Attribute */ +.highlight .nb { color: #0086B3 } /* Name.Builtin */ +.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ +.highlight .no { color: #008080 } /* Name.Constant */ +.highlight .ni { color: #800080 } /* Name.Entity */ +.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ +.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ +.highlight .nn { color: #555555 } /* Name.Namespace */ +.highlight .nt { color: #CBDFFF } /* Name.Tag */ +.highlight .nv { color: #008080 } /* Name.Variable */ +.highlight .ow { font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mf { color: #009999 } /* Literal.Number.Float */ +.highlight .mh { color: #009999 } /* Literal.Number.Hex */ +.highlight .mi { color: #009999 } /* Literal.Number.Integer */ +.highlight .mo { color: #009999 } /* Literal.Number.Oct */ +.highlight .sb { color: #d14 } /* Literal.String.Backtick */ +.highlight .sc { color: #d14 } /* Literal.String.Char */ +.highlight .sd { color: #d14 } /* Literal.String.Doc */ +.highlight .s2 { color: #d14 } /* Literal.String.Double */ +.highlight .se { color: #d14 } /* Literal.String.Escape */ +.highlight .sh { color: #d14 } /* Literal.String.Heredoc */ +.highlight .si { color: #d14 } /* Literal.String.Interpol */ +.highlight .sx { color: #d14 } /* Literal.String.Other */ +.highlight .sr { color: #009926 } /* Literal.String.Regex */ +.highlight .s1 { color: #d14 } /* Literal.String.Single */ +.highlight .ss { color: #990073 } /* Literal.String.Symbol */ +.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ +.highlight .vc { color: #008080 } /* Name.Variable.Class */ +.highlight .vg { color: #008080 } /* Name.Variable.Global */ +.highlight .vi { color: #008080 } /* Name.Variable.Instance */ +.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ + +.type-csharp .highlight .k { color: #0000FF } +.type-csharp .highlight .kt { color: #0000FF } +.type-csharp .highlight .nf { color: #000000; font-weight: normal } +.type-csharp .highlight .nc { color: #2B91AF } +.type-csharp .highlight .nn { color: #000000 } +.type-csharp .highlight .s { color: #A31515 } +.type-csharp .highlight .sc { color: #A31515 } diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css new file mode 100644 index 0000000..a54a639 --- /dev/null +++ b/stylesheets/stylesheet.css @@ -0,0 +1,247 @@ +body { + margin: 0; + padding: 0; + background: #151515 url("../images/bkg.png") 0 0; + color: #eaeaea; + font: 16px; + line-height: 1.5; + font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; +} + +/* General & 'Reset' Stuff */ + +.container { + width: 90%; + max-width: 600px; + margin: 0 auto; +} + +section { + display: block; + margin: 0 0 20px 0; +} + +h1, h2, h3, h4, h5, h6 { + margin: 0 0 20px; +} + +li { + line-height: 1.4 ; +} + +/* Header,
+ header - container + h1 - project name + h2 - project description +*/ + +header { + background: rgba(0, 0, 0, 0.1); + width: 100%; + border-bottom: 1px dashed #b5e853; + padding: 20px 0; + margin: 0 0 40px 0; +} + +header h1 { + font-size: 30px; + line-height: 1.5; + margin: 0 0 0 -40px; + font-weight: bold; + font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; + color: #b5e853; + text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1), + 0 0 5px rgba(181, 232, 83, 0.1), + 0 0 10px rgba(181, 232, 83, 0.1); + letter-spacing: -1px; + -webkit-font-smoothing: antialiased; +} + +header h1:before { + content: "./ "; + font-size: 24px; +} + +header h2 { + font-size: 18px; + font-weight: 300; + color: #666; +} + +#downloads .btn { + display: inline-block; + text-align: center; + margin: 0; +} + +/* Main Content +*/ + +#main_content { + width: 100%; + -webkit-font-smoothing: antialiased; +} +section img { + max-width: 100% +} + +h1, h2, h3, h4, h5, h6 { + font-weight: normal; + font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; + color: #b5e853; + letter-spacing: -0.03em; + text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1), + 0 0 5px rgba(181, 232, 83, 0.1), + 0 0 10px rgba(181, 232, 83, 0.1); +} + +#main_content h1 { + font-size: 30px; +} + +#main_content h2 { + font-size: 24px; +} + +#main_content h3 { + font-size: 18px; +} + +#main_content h4 { + font-size: 14px; +} + +#main_content h5 { + font-size: 12px; + text-transform: uppercase; + margin: 0 0 5px 0; +} + +#main_content h6 { + font-size: 12px; + text-transform: uppercase; + color: #999; + margin: 0 0 5px 0; +} + +dt { + font-style: italic; + font-weight: bold; +} + +ul li { + list-style: none; +} + +ul li:before { + content: ">>"; + font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; + font-size: 13px; + color: #b5e853; + margin-left: -37px; + margin-right: 21px; + line-height: 16px; +} + +blockquote { + color: #aaa; + padding-left: 10px; + border-left: 1px dotted #666; +} + +pre { + background: rgba(0, 0, 0, 0.9); + border: 1px solid rgba(255, 255, 255, 0.15); + padding: 10px; + font-size: 14px; + color: #b5e853; + border-radius: 2px; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + text-wrap: normal; + overflow: auto; + overflow-y: hidden; +} + +table { + width: 100%; + margin: 0 0 20px 0; +} + +th { + text-align: left; + border-bottom: 1px dashed #b5e853; + padding: 5px 10px; +} + +td { + padding: 5px 10px; +} + +hr { + height: 0; + border: 0; + border-bottom: 1px dashed #b5e853; + color: #b5e853; +} + +/* Buttons +*/ + +.btn { + display: inline-block; + background: -webkit-linear-gradient(top, rgba(40, 40, 40, 0.3), rgba(35, 35, 35, 0.3) 50%, rgba(10, 10, 10, 0.3) 50%, rgba(0, 0, 0, 0.3)); + padding: 8px 18px; + border-radius: 50px; + border: 2px solid rgba(0, 0, 0, 0.7); + border-bottom: 2px solid rgba(0, 0, 0, 0.7); + border-top: 2px solid rgba(0, 0, 0, 1); + color: rgba(255, 255, 255, 0.8); + font-family: Helvetica, Arial, sans-serif; + font-weight: bold; + font-size: 13px; + text-decoration: none; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.75); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.btn:hover { + background: -webkit-linear-gradient(top, rgba(40, 40, 40, 0.6), rgba(35, 35, 35, 0.6) 50%, rgba(10, 10, 10, 0.8) 50%, rgba(0, 0, 0, 0.8)); +} + +.btn .icon { + display: inline-block; + width: 16px; + height: 16px; + margin: 1px 8px 0 0; + float: left; +} + +.btn-github .icon { + opacity: 0.6; + background: url("../images/blacktocat.png") 0 0 no-repeat; +} + +/* Links + a, a:hover, a:visited +*/ + +a { + color: #63c0f5; + text-shadow: 0 0 5px rgba(104, 182, 255, 0.5); +} + +/* Clearfix */ + +.cf:before, .cf:after { + content:""; + display:table; +} + +.cf:after { + clear:both; +} + +.cf { + zoom:1; +} \ No newline at end of file diff --git a/test/balance-ws.js b/test/balance-ws.js deleted file mode 100644 index 1e08ffd..0000000 --- a/test/balance-ws.js +++ /dev/null @@ -1,80 +0,0 @@ - -var http = require('http'); -var httpProxy = require('http-proxy'); - -var WebSocketServer = require('ws').Server; -var wss = new WebSocketServer({port: 8080}); -wss.on('connection', function(ws) { - console.log('CLIENT CONNECTED'); - ws.on('message', function(message) { - console.log('received: %s', message); - }); - ws.send('something'); -}); - - -var WebSocketServer = require('ws').Server; -var wss = new WebSocketServer({port: 8081}); -wss.on('connection', function(ws) { - console.log('CLIENT CONNECTED 22'); - ws.on('message', function(message) { - console.log('received other: %s', message); - }); - ws.send('something else'); -}); - - -// -// A simple round-robin load balancing strategy. -// -// First, list the servers you want to use in your rotation. -// -var addresses = [ - { - host: 'localhost', - port: 8080 - }, - { - host: 'localhost', - port: 8081 - } -]; - -// -// Create a HttpProxy object for each target -// - -var proxies = addresses.map(function (target) { - return new httpProxy.createProxyServer({ - target: target - }); -}); - -// -// Get the proxy at the front of the array, put it at the end and return it -// If you want a fancier balancer, put your code here -// - -function nextProxy() { - var proxy = proxies.shift(); - proxies.push(proxy); - return proxy; -} - -// -// Get the 'next' proxy and send the http request -// - -var server = http.createServer(function (req, res) { - nextProxy().web(req, res); -}); - -// -// Get the 'next' proxy and send the upgrade request -// - -server.on('upgrade', function (req, socket, head) { - nextProxy().ws(req, socket, head); -}); - -server.listen(8000); diff --git a/test/balancer-error.js b/test/balancer-error.js deleted file mode 100644 index 03b7f33..0000000 --- a/test/balancer-error.js +++ /dev/null @@ -1,90 +0,0 @@ -var http = require('http'); -var loadfire = require('../'); - - -var EDITOR_PORTS = [6001, 6002]; - -var EDITOR_SERVERS = EDITOR_PORTS.map(function (x) { - return { - host: 'localhost', - port: x - }; -}); - -// Start all our different http servers -function startEditorServers(ports) { - ports.forEach(function (port) { - // Setup HTTP Server - var httpServer = http.createServer(function(req, res) { - // Output the port number the server is running on - console.log('responding'); - res.writeHead(200, {'Content-Type': 'text/plain'}); - console.log('URL =', req.url); - req.on('data', function(data) { - console.log("EDITOR DATA =", data.toString()); - }); - res.end(port.toString()); - }); - - // Listen on assigned port - httpServer.listen(port); - }); -} - -// Config for our loadfire server -var CONFIG = { - 'resources': [ - { - // resource is some value identify this resource - // by default it should be the hostname to match - selector: loadfire.selectors.host('localhost:8000'), - - // List of backends to hit - backends: EDITOR_SERVERS, - - // Load balancing pattern - // As of now a few are builtin - // random, roundrobin, sticky - balancer: function(backends, req, cb) { - // Fail first - cb(new Error('Failed balancing because of whatever')); - - return loadfire.balancers.roundrobin(backends, req, cb); - }, - - - middleware: [ - function(req, res, next) { - console.log('heelo'); - next(); - } - ], - } - ], - - // Server to start loadfire on - port: 8000 -}; - -function main() { - // Start our http servers - setTimeout(function() { - startEditorServers(EDITOR_PORTS); - console.log('Started editors'); - }, 3000); - - - // Setup our load balancer with the above config - var loadServer = loadfire.createServer(CONFIG); - - // Now start our load balancer - loadServer.run(); - - // Check out localhost:8000 - // Refresh a few times and you'll see different port numbers appear - // depending on which http server the requests are proxied to - // since we are using the roundrobin pattern it will cycle through them -} - -// Run main -main(); \ No newline at end of file diff --git a/test/basic.js b/test/basic.js deleted file mode 100644 index b28d2b3..0000000 --- a/test/basic.js +++ /dev/null @@ -1,84 +0,0 @@ -var http = require('http'); -var loadfire = require('../'); - - -var EDITOR_PORTS = [7001, 7002, 7003,7004]; - -var EDITOR_SERVERS = EDITOR_PORTS.map(function (x) { - return { - host: 'localhost', - port: x - }; -}); - -// Start all our different http servers -function startEditorServers(ports) { - ports.forEach(function (port) { - // Setup HTTP Server - var httpServer = http.createServer(function(req, res) { - // Output the port number the server is running on - console.log('responding'); - res.writeHead(200, {'Content-Type': 'text/plain'}); - console.log('URL =', req.url); - req.on('data', function(data) { - console.log("EDITOR DATA =", data.toString()); - }); - res.end(port.toString()); - }); - - // Listen on assigned port - httpServer.listen(port); - }); -} - -// Config for our loadfire server -var CONFIG = { - 'resources': [ - { - // resource is some value identify this resource - // by default it should be the hostname to match - selector: loadfire.selectors.host('localhost:8000'), - - // List of backends to hit - backends: EDITOR_SERVERS, - - // Load balancing pattern - // As of now a few are builtin - // random, roundrobin, sticky - balancer: loadfire.balancers.roundrobin, - - middleware: [ - function(req, res, next) { - console.log('heelo'); - next(); - } - ], - } - ], - - // Server to start loadfire on - port: 8000 -}; - -function main() { - // Start our http servers - setTimeout(function() { - startEditorServers(EDITOR_PORTS); - console.log('Started editors'); - }, 3000); - - - // Setup our load balancer with the above config - var loadServer = loadfire.createServer(CONFIG); - - // Now start our load balancer - loadServer.run(); - - // Check out localhost:8000 - // Refresh a few times and you'll see different port numbers appear - // depending on which http server the requests are proxied to - // since we are using the roundrobin pattern it will cycle through them -} - -// Run main -main(); \ No newline at end of file diff --git a/test/middleware.js b/test/middleware.js deleted file mode 100644 index 999582d..0000000 --- a/test/middleware.js +++ /dev/null @@ -1,105 +0,0 @@ -var http = require('http'); -var loadfire = require('../'); - - -var EDITOR_PORTS = [7001, 7002, 7003,7004]; - -var EDITOR_SERVERS = EDITOR_PORTS.map(function (x) { - return { - host: 'localhost', - port: x - }; -}); - -// Start all our different http servers -function startEditorServers(ports) { - ports.forEach(function (port) { - // Setup HTTP Server - var httpServer = http.createServer(function(req, res) { - // Output the port number the server is running on - console.log('responding'); - res.writeHead(200, {'Content-Type': 'text/plain'}); - console.log('URL =', req.url); - req.on('data', function(data) { - console.log("EDITOR DATA =", data.toString()); - }); - res.end(port.toString()); - }); - - // Listen on assigned port - httpServer.listen(port); - }); -} - -// Config for our loadfire server -var CONFIG = { - 'resources': [ - { - selector: loadfire.selectors.url('/redirect'), - - backends: [], - - balancer: loadfire.balancers.roundrobin, - - middleware: [ - function(req, res, next) { - var dest = 'http://www.google.com'; - console.log('Redirecting to Google'); - //res.redirect(dest); - res.writeHead(302, { - 'Location': dest - }); - res.end(); - console.log('Redirected to Google'); - next(); - } - ] - }, - { - // resource is some value identify this resource - // by default it should be the hostname to match - selector: loadfire.selectors.host('localhost:8000'), - - // List of backends to hit - backends: EDITOR_SERVERS, - - // Load balancing pattern - // As of now a few are builtin - // random, roundrobin, sticky - balancer: loadfire.balancers.roundrobin, - - middleware: [ - function(req, res, next) { - console.log('heelo'); - next(); - } - ], - } - ], - - // Server to start loadfire on - port: 8000 -}; - -function main() { - // Start our http servers - setTimeout(function() { - startEditorServers(EDITOR_PORTS); - console.log('Started editors'); - }, 3000); - - - // Setup our load balancer with the above config - var loadServer = loadfire.createServer(CONFIG); - - // Now start our load balancer - loadServer.run(); - - // Check out localhost:8000 - // Refresh a few times and you'll see different port numbers appear - // depending on which http server the requests are proxied to - // since we are using the roundrobin pattern it will cycle through them -} - -// Run main -main(); \ No newline at end of file diff --git a/test/websocket-proxy.js b/test/websocket-proxy.js deleted file mode 100644 index a013847..0000000 --- a/test/websocket-proxy.js +++ /dev/null @@ -1,42 +0,0 @@ -var util = require('util'), - http = require('http'), - httpProxy = require('http-proxy'); - -// -// Create the target HTTP server and setup -// socket.io on it. -// -var WebSocketServer = require('ws').Server; -var wss = new WebSocketServer({port: 8080}); -wss.on('connection', function(ws) { - console.log('CLIENT CONNECTED'); - ws.on('message', function(message) { - console.log('received: %s', message); - }); - ws.send('something'); -}); - -// -// Create a proxy server with node-http-proxy -// -httpProxy.createServer({target: { - host: 'localhost', - port:8080 -}, ws:true}).listen(8000); - -var WebSocket = require('ws'); -var ws = new WebSocket('ws://localhost:8000/'); -ws.on('open', function() { - console.log('connected'); - ws.send(Date.now().toString(), {mask: true}); -}); -ws.on('close', function() { - console.log('disconnected'); -}); -ws.on('message', function(data, flags) { - console.log('CLIENT GOT', data); - console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags); - setTimeout(function() { - ws.send(Date.now().toString(), {mask: true}); - }, 500); -}); \ No newline at end of file diff --git a/test/ws.js b/test/ws.js deleted file mode 100644 index 02438f7..0000000 --- a/test/ws.js +++ /dev/null @@ -1,60 +0,0 @@ -var loadfire = require('../'); - -var WebSocketServer = require('ws').Server; -var wss = new WebSocketServer({port: 8080}); -wss.on('connection', function(ws) { - console.log('CLIENT CONNECTED'); - ws.on('message', function(message) { - console.log('received: %s', message); - }); - ws.send('something'); -}); - -// Config for our loadfire server -var CONFIG = { - 'resources': [ - { - selector: function(req, cb) { - return cb(null, true); - }, - - // resource is some value identify this resource - // by default it should be the hostname to match - //selector: loadfire.selectors.host('localhost:8000'), - backends: [], - - // Load balancing pattern - // As of now a few are builtin - // random, roundrobin, sticky - balancer: function(backends, req, cb) { - return cb(null, { - host: 'localhost', - port: 8081 - }); - }, - -/* - middleware: [ - function(req, res, next) { - console.log('heelo'); - next(); - } - ], -*/ - } - ], - - // Server to start loadfire on - port: 8000 -}; - -function main() { - // Setup our load balancer with the above config - var loadServer = loadfire.createServer(CONFIG); - - // Now start our load balancer - loadServer.run(); -} - -// Run main -main(); \ No newline at end of file