-
Notifications
You must be signed in to change notification settings - Fork 2
/
bootstrap.js
132 lines (83 loc) · 2.92 KB
/
bootstrap.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const url = require("url");
const WebSocket = require("ws");
const request = require("./request.js");
const logger = require("./system/logger.js");
// retry flags
var crashed = false;
var counter = 0;
function bootstrap() {
Promise.all([
// fetch devices from api
new Promise((resolve, reject) => {
request(`${process.env.BACKEND_URL}/api/devices`, (err, data) => {
if (err) {
reject(err);
} else {
let { body } = data;
let map = new Map();
body.filter(({ enabled }) => {
return enabled;
}).forEach(({ _id, interfaces }) => {
interfaces.filter((iface) => {
// filter only for ehternet interfaces
return iface.type === "ETHERNET";
}).forEach((iface) => {
// map ws endpoint with interface obj
map.set(`${process.env.BACKEND_URL}/api/devices/${_id}/interfaces/${iface._id}`, iface);
});
});
resolve(map);
}
});
}),
// connect to websocket events
new Promise((resolve, reject) => {
let uri = new url.URL(process.env.BACKEND_URL);
uri.protocol = (process.env.BACKEND_PROTOCOL === "https" ? "wss" : "ws");
uri.pathname = "/api/events";
uri.search = `x-auth-token=${process.env.AUTH_TOKEN}`;
let ws = new WebSocket(uri);
ws.on("open", () => {
logger.debug(`WebSocket connected to: ${ws.url}`);
resolve(ws);
});
ws.on("error", (err) => {
//console.error("Websocket", err);
reject(err);
});
ws.on("close", (code) => {
if (code === 1006) {
retry();
} else {
console.warn("WebSocket (event) conneciton closed", code);
}
});
})
]).then(([map, ws]) => {
// reset flags
counter = 0;
crashed = false;
logger.debug("Read to bridge traffic");
require("./forwarder.js");
require("./handler.js")(map, ws);
}).catch((err) => {
if (err.code === "ECONNREFUSED") {
retry();
} else {
console.error(err);
process.exit(1);
}
});
}
function retry() {
if (!crashed) {
logger.warn("Backend %s not reachable, retry attempt %d...", process.env.BACKEND_URL, counter + 1);
setTimeout(() => {
counter += 1;
crashed = false;
bootstrap();
}, Number(process.env.RECONNECT_DELAY * 1000) || 3000);
}
crashed = true;
}
bootstrap();