This repository has been archived by the owner on Aug 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlternator.js
76 lines (67 loc) · 1.94 KB
/
Alternator.js
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
// Example usage:
// AWS = require('aws-sdk');
// alternator = require('./Alternator');
// alternator.init(AWS, "http", 8000, ["127.0.0.1"]);
// (...)
// alternator.done();
var AWS = require("aws-sdk");
var http = require("http");
var https = require("https");
var dns = require("dns");
const FAKE_HOST = "dog.scylladb.com";
exports.FAKE_HOST = FAKE_HOST;
var protocol;
var hostIdx = 0;
var hosts;
var port;
var done = false;
var updatePromise;
var agent = new http.Agent;
var oldCreateConnection = agent.createConnection;
agent.createConnection = function(options, callback = null) {
options.lookup = function(hostname, options = null, callback) {
if (hostname == FAKE_HOST) {
var host = hosts[hostIdx];
hostIdx = (hostIdx + 1) % hosts.length;
console.log("Picked", host);
return dns.lookup(host, options, callback);
}
return dns.lookup(hostname, options, callback);
};
return oldCreateConnection(options, callback);
};
exports.agent = agent;
async function updateHosts() {
if (done) {
return;
}
let proto = (protocol == "https") ? https : http;
proto.get(protocol + "://" + hosts[hostIdx] + ":" + 8000 + "/localnodes", (resp) => {
resp.on('data', (payload) => {
payload = JSON.parse(payload);
hosts = payload;
console.log("Hosts updated to", hosts);
});
});
await new Promise(r => setTimeout(r, 1000));
return updateHosts();
}
exports.init = function(AWS, initialProtocol, initialPort, initialHosts) {
protocol = initialProtocol;
hosts = initialHosts;
port = initialPort;
AWS.config.update({
region: "world",
endpoint: protocol + "://" + FAKE_HOST + ":" + initialPort,
httpOptions:{
agent: agent
}
});
done = false;
updatePromise = updateHosts().catch((error) => {
console.error(error);
});;
}
exports.done = function() {
done = true;
}