-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathproxy.js
More file actions
116 lines (78 loc) · 2.08 KB
/
proxy.js
File metadata and controls
116 lines (78 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"use strict";
var debug_log = require('debug')('scluster:log');
debug_log.log = console.log.bind(console);
var debug_error = require('debug')('scluster:error');
var httpProxy = require('http-proxy');
var http = require('http');
var current_proxy = 0;
var total_workers = 0;
function next_proxy() {
var proxy = proxies[current_proxy];
require('util').inspect(proxies, false, null);
current_proxy = (current_proxy + 1) % total_workers;
return proxy;
}
var stickers = {};
var proxies = {};
exports.init = function(workers, first_port, proxy_port, session_hash, no_sockets) {
total_workers = workers;
for (var n = 0; n < total_workers; n++) {
proxies[n] = new httpProxy.createProxyServer({
target : {
host : '127.0.0.1',
port : first_port + n
}
});
proxies[n].on('error', function(error, req, res) {
debug_log('proxy error: ' + error);
if (null != res)
{
try
{
var json;
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = { error: 'proxy_error', reason: error.message };
res.end(JSON.stringify(json))
}
catch (e)
{
}
}
});
}
var server = http.createServer(function(req, res) {
get_proxy(session_hash, req, res).web(req, res);
});
if (!no_sockets)
{
server.on('upgrade', function(req, socket, head) {
get_proxy(session_hash, req).ws(req, socket, head);
});
}
debug_log("main proxy listen on port: " + proxy_port);
server.listen(proxy_port);
}
function get_proxy(session_hash, req, res)
{
var hash = session_hash(req, res);
debug_log('hash: ' + hash);
var proxy = undefined;
if (hash !== undefined) {
if (stickers[hash] !== undefined) {
debug_log('restored proxy.');
proxy = stickers[hash].proxy;
} else {
debug_log('assigned proxy.');
proxy = next_proxy();
stickers[hash] = {
proxy : proxy,
}
}
} else {
debug_log('random proxy.');
proxy = next_proxy();
}
return proxy;
}