Passed
Push — master ( 08ec9b...e2245b )
by Evgeny
01:36
created

lib/network.js (2 issues)

Severity
1
var IP = null;
2
var args = null;
3
var machine = null;
4
var request = null;
5
6
var get_protocol = function() {
7
	return 'http' + (args.https && 's' || '') + '://';
8
};
9
10
var get_req = function(req, host) {
11
	return new Promise(function(resolve) {
12
		return request({
13
			url: host + req.originalUrl,
14
			headers: Object.assign(req.headers, {'docker-server': 'force', 'content-type': 'application/json'}),
15
			form: req.body,
16
			method: req.method
17
		}, function (err, res, body) {
18
			// console.log('request:', host, err, typeof body, body);
19
			if (err) {
20
				console.error('err:', host, err);
21
				return resolve({'body': [err], 'host': host});
22
			}
23
			
24
			try {
25
				return resolve({'body': typeof body === 'string' && JSON.parse(body) || body, 'host': host});
26
			} catch(e) {
27
				if (body.startsWith('error')) {
28
					body = {'error': body};
29
				} else {
30
					console.error('Error in get_req on', host, ':', e, typeof body, body);
31
				}
32
				
33
				return resolve({'body': [body], 'host': host});
34
			}
35
		});
36
	});
37
};
38
39
var handle_cluster_request = function(req, res, next) {
40
	return function(ip) {
41
		if (ip === IP) {
42
			next();
43
		} else {
44
			get_req(req, ip).then(function(ip_obj) {
45
				res.send(ip_obj.body || null);
46
			});
47
		}
48
	};
49
};
50
51
var handle_cluster = function(req, res, next) {
52
	if (req.method === 'PUT') {
53
		machine.next(IP).then(handle_cluster_request(req, res, next));
54
	} else if(~['GET', 'DELETE', 'POST'].indexOf(req.method)) {
55
		machine.all(IP).then(function(ips) {
56
			var promises = [];
57
			for (var i in ips) {
0 ignored issues
show
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
58
				promises.push(get_req(req, ips[i].host));
59
			}
60
			
61
			return Promise.all(promises).then(function(responses) {
62
				var response = [];
63
				for (var i = 0; i < responses.length; ++i) {
64
					// Add the host to each result for more clearance for the client.
65
					for (var j in responses[i].body) {
0 ignored issues
show
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
66
						responses[i].body[j].host = responses[i].host;
67
					}
68
					response = response.concat(responses[i].body);
69
				}
70
				res.send(response);
71
			});
72
		});
73
	} else {
74
		res.sendStatus(400);
75
	}
76
};
77
78
79
module.exports = function(cli_args) {
80
	args = cli_args;
81
	
82
	return {
83
		'get_protocol': get_protocol,
84
		'check': function(token) {
85
			return function (req, res, next) {
86
				if (req.get('Authorization') === token) {
87
					next();
88
				} else {
89
					res.sendStatus(401);
90
				}
91
			};
92
		},
93
		'protocol': function(app) {
94
			if (args.https) {
95
				const fs = require('fs');
96
				
97
				if (fs.existsSync('/certs/privkey.pem') && fs.existsSync('/certs/cert.pem')) {
98
					try {
99
						return require('https').createServer({
100
							key: fs.readFileSync('/certs/privkey.pem', 'utf8'),
101
							cert: fs.readFileSync('/certs/cert.pem', 'utf8'),
102
							ca: fs.existsSync('/certs/chain.pem') && fs.readFileSync('/certs/chain.pem', 'utf8') || undefined
103
						}, app);
104
					} catch (e) {
105
						console.error('Could not start secure server:', e);
106
						return require('http').createServer(app);
107
					}
108
				}
109
			}
110
			
111
			return require('http').createServer(app);
112
		},
113
		'balance': function(port) {
114
			if (args.cluster) {
115
				IP = get_protocol() + require('ip').address() + ':' + port;
116
				machine = require('./machine.js')(args);
117
				request = require('request');
118
				
119
				machine.cpu(IP);
120
				setInterval(function() { machine.cpu(IP); }, 30000);
121
			}
122
			
123
			return function (req, res, next) {
124
				// console.log('000 ??? body', JSON.stringify(req.body));
125
				if (args.cluster && req.get('docker-server') !== 'force') {
126
					handle_cluster(req, res, next);
127
				} else {
128
					next();
129
				}
130
			};
131
		}
132
	};
133
};