-
Notifications
You must be signed in to change notification settings - Fork 24
/
hydra-router.js
359 lines (330 loc) · 11.2 KB
/
hydra-router.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
* @name Service Router
* @description This is the service entry point
*/
'use strict';
if (process.env.HYDRA_ROUTER_ENV) {
require('dotenv').config({path: process.env.HYDRA_ROUTER_ENV});
}
const hydra = require('hydra');
const serviceRouter = require('./lib/servicerouter');
/**
* @name setupExitHandlers
* @description setup exit handlers
* @return {undefined}
*/
let setupExitHandlers = () => {
process.on('cleanup', async() => {
await serviceRouter.shutdown();
await hydra.shutdown();
process.exit(1);
});
process.on('SIGTERM', () => {
hydra.log('fatal', 'Received SIGTERM');
process.emit('cleanup');
});
process.on('SIGINT', () => {
hydra.log('fatal', 'Received SIGINT');
process.emit('cleanup');
});
process.on('unhandledRejection', (reason, _p) => {
hydra.log('fatal', reason);
process.emit('cleanup');
});
process.on('uncaughtException', (err) => {
let stack = err.stack;
delete err.__cached_trace__;
delete err.__previous__;
delete err.domain;
hydra.log('fatal', {
stack
});
process.emit('cleanup');
});
};
/**
* @name displayNetworkInterfaces
* @description display network interaces
* @return {undefined}
*/
let displayNetworkInterfaces = () => {
const os = require('os');
let interfaces = os.networkInterfaces();
console.log('Detected IPv4 IPs:');
Object.keys(interfaces).
forEach((itf) => {
interfaces[itf].forEach((interfaceRecord)=>{
if (interfaceRecord.family === 'IPv4') {
console.log(`* ${itf}: ${interfaceRecord.address} ${interfaceRecord.netmask}`);
}
});
});
console.log('');
};
/**
* @name setupRoutes
* @description setup RESTful API routes
* @param {object} config - config object
* @return {undefined}
*/
let setupRoutes = async(config) => {
let routeList = [
'[get]/',
'[get]/index.css',
'[get]/index.js',
'[get]/fonts/glyphicons-halflings-regular.woff2',
'[get]/fonts/glyphicons-halflings-regular.woff',
'[get]/fonts/glyphicons-halflings-regular.ttf',
'[get]/v1/router/health',
'[get]/v1/router/list/:thing',
'[get]/v1/router/version',
'[get]/v1/router/clear',
'[get]/v1/router/refresh',
'[get]/v1/router/refresh/:service',
'[get]/v1/router/log',
'[get]/v1/router/stats',
'[post]/v1/router/message',
'[post]/v1/router/send',
'[post]/v1/router/queue',
'[post]/v1/router/stream/:name'
];
await hydra.registerRoutes(routeList);
let routesObj = await hydra.getAllServiceRoutes();
routesObj = Object.assign(routesObj, config.externalRoutes);
serviceRouter.init(config, routesObj);
};
/**
* @name setupHydraListeners
* @description setup hydra listeners
* @return {undefined}
*/
let setupHydraListeners = () => {
hydra.on('log', (entry) => {
serviceRouter.log(entry.type, entry);
});
hydra.on('metric', (entry) => {
let type = (entry.indexOf('unavailable') > -1) ? 'error' : 'info';
serviceRouter.log(type, entry);
});
};
/**
* @name setupServer
* @description setup HTTP server
* @param {object} config - config object
* @param {object} serviceInfo - service info object
* @return {object} server - http server object
*/
let setupServer = (config, serviceInfo) => {
const http = require('http');
let server;
try {
server = http.createServer((request, response) => {
serviceRouter.routeRequest(request, response)
.catch((err) => {
hydra.log('fatal', err);
});
});
if (!config.hydra.serviceInterface) {
server.listen(serviceInfo.servicePort);
} else {
server.listen(serviceInfo.servicePort, serviceInfo.serviceIP);
}
} catch (e) {
process.exit(1);
}
return server;
};
/**
* @name setupWebSocketServer
* @description setup websocket server
* @param {object} server - http server to bind to
* @param {object} config - server config
* @return {undefined}
*/
let setupWebSocketServer = (server) => {
const WebSocketServer = require('ws').Server;
let wss = new WebSocketServer({
server,
auth: 'usr:pass#'
});
wss.on('connection', async(ws, req) => {
const config = serviceRouter.getConfig();
if (config.requireWebsocketAuth) {
try {
let auth;
if (req.headers.authorization) {
auth = Buffer.from(req.headers.authorization.slice(6), 'base64').toString();
} else if (req.url && req.url.length > 1) {
auth = req.url;
}
// parse the auth string if provided
if (auth) {
const response = await serviceRouter.wsAuthenticate(auth);
if (response.statusCode !== 200) {
hydra.log('error', 'Invalid auth api response');
serviceRouter.wsDisconnect(ws);
return;
}
ws.authResponse = response.result;
} else {
hydra.log('error', 'Auth must be provided on connection');
serviceRouter.wsDisconnect(ws);
return;
}
} catch (e) {
hydra.log('error', e);
serviceRouter.wsDisconnect(ws);
return;
}
}
serviceRouter.sendConnectMessage(ws, null, req);
ws.on('message', (message) => {
serviceRouter.routeWSMessage(ws, message);
});
ws.on('close', () => {
serviceRouter.wsDisconnect(ws);
});
ws.on('error', (error) => {
try {
hydra.log('info', {
msg: `error detected from client ${ws.id} on ${ws.ipAddr}`
});
hydra.log('fatal', error);
} catch (e) {
hydra.log('fatal', error);
}
});
});
};
let updateConfigWithEnv = async(config) => {
if (process.env.HYDRA_ROUTER_ROUTERTOKEN)
config.routerToken = process.env.HYDRA_ROUTER_ROUTERTOKEN;
if (process.env.HYDRA_ROUTER_ROUTERTOKEN)
config.disableRouterEndpoint = process.env.HYDRA_ROUTER_ROUTERTOKEN;
if (process.env.HYDRA_ROUTER_DEBUGLOGGING)
config.debugLogging = process.env.HYDRA_ROUTER_DEBUGLOGGING;
if (process.env.HYDRA_ROUTER_QUEUERDB)
config.queuerDB = process.env.HYDRA_ROUTER_QUEUERDB;
if (process.env.HYDRA_ROUTER_REQUESTTIMEOUT)
config.requestTimeout = process.env.HYDRA_ROUTER_REQUESTTIMEOUT;
if (process.env.HYDRA_ROUTER_FORCEMESSAGESIGNATURE)
config.forceMessageSignature = process.env.HYDRA_ROUTER_FORCEMESSAGESIGNATURE;
if (process.env.HYDRA_ROUTER_SIGNATURESHAREDSECRET)
config.signatureSharedSecret = process.env.HYDRA_ROUTER_SIGNATURESHAREDSECRET;
if (process.env.HYDRA_ROUTER_CORS) {
if (!config.cors) {
config.cors = {};
}
config.cors['access-control-allow-origin'] = process.env.HYDRA_ROUTER_CORS_ACCESS_CONTROL_ALLOW_ORIGIN || config.cors['access-control-allow-origin'];
config.cors['access-control-allow-methods'] = process.env.HYDRA_ROUTER_CORS_ACCESS_CONTROL_ALLOW_METHODS || config.cors['access-control-allow-methods'];
config.cors['access-control-allow-headers'] = process.env.HYDRA_ROUTER_CORS_ACCESS_CONTROL_ALLOW_HEADERS || config.cors['access-control-allow-headers'];
config.cors['access-control-allow-credentials'] = process.env.HYDRA_ROUTER_CORS_ACCESS_CONTROL_ALLOW_CREDENTIALS || config.cors['access-control-allow-credentials'];
config.cors['access-control-Max-Age'] = process.env.HYDRA_ROUTER_CORS_ACCESS_CONTROL_MAX_AGE || config.cors['access-control-Max-Age'];
}
config.hydra.serviceName = process.env.HYDRA_ROUTER_HYDRA_SERVICENAME || config.hydra.serviceName;
config.hydra.serviceDescription = process.env.HYDRA_ROUTER_HYDRA_SERVICEDESCRIPTION || config.hydra.serviceDescription;
config.hydra.serviceIP = process.env.HYDRA_ROUTER_HYDRA_SERVICEIP || config.hydra.serviceIP;
if (process.env.HYDRA_ROUTER_HYDRA_SERVICEINTERFACE) {
config.hydra.serviceInterface = process.env.HYDRA_ROUTER_HYDRA_SERVICEINTERFACE || config.hydra.serviceInterface;
}
config.hydra.serviceDNS = process.env.HYDRA_ROUTER_HYDRA_SERVICEDNS || config.hydra.serviceDNS;
config.hydra.servicePort = process.env.HYDRA_ROUTER_HYDRA_SERVICEPORT || config.hydra.servicePort;
config.hydra.serviceType = process.env.HYDRA_ROUTER_HYDRA_SERVICETYPE || config.hydra.serviceType;
if (process.env.HYDRA_ROUTER_HYDRA_PLUGINS) {
if (!config.hydra.plugins) {
config.hydra.plugins = {
hydraLogger: {}
};
}
config.hydra.plugins.hydraLogger.logToConsole = process.env.HYDRA_ROUTER_HYDRA_PLUGINS_HYDRALOGGER_LOGTOCONSOLE || config.hydra.hydraLogger.logToConsole;
config.hydra.plugins.hydraLogger.onlyLogLocally = process.env.HYDRA_ROUTER_HYDRA_PLUGINS_HYDRALOGGER_ONLYLOGLOCALLY || config.hydra.hydraLogger.onlyLogLocally;
}
config.hydra.redis.url = process.env.HYDRA_ROUTER_HYDRA_REDIS_URL || config.hydra.redis.url;
return config;
};
/**
* @name displayBanner
* @description display fancy banner
* @return {undefined}
*/
let displayBanner = () => {
let banner = `
_ _ _ ____ _
| | | |_ _ __| |_ __ __ _ | _ \\ ___ _ _| |_ ___ _ __
| |_| | | | |/ _\` | '__/ _\` | | |_) / _ \\| | | | __/ _ \\ '__|
| _ | |_| | (_| | | | (_| | | _ < (_) | |_| | || __/ |
|_| |_|\\__, |\\__,_|_| \\__,_| |_| \\_\\___/ \\__,_|\\__\\___|_|
|___/`;
console.log(banner);
};
/**
* @name main
* @description Load configuration file and initialize hydra app
* @return {undefined}
*/
let main = async() => {
let HydraLogger,
loggerType,
hydraLogger,
config;
try {
config = require('./config/config.json');
if (config.hydra.plugins && config.hydra.plugins.hydraLogger) {
HydraLogger = require('hydra-plugin-hls/hydra');
loggerType = 'hydra';
} else if (config.hydra.plugins && config.hydra.plugins.loggly) {
HydraLogger = require('hydra-plugin-loggly/hydra');
loggerType = 'loggly';
}
hydraLogger = new HydraLogger();
hydra.use(hydraLogger);
let newConfig = '';
if (process.env.HYDRA_ROUTER_ENV) {
newConfig = await updateConfigWithEnv(config);
newConfig = await hydra.init(newConfig, false);
} else {
newConfig = await hydra.init(`${__dirname}/config/config.json`, false);
}
config = newConfig;
} catch (err) {
let stack = err.stack;
console.log(stack); // console log because Logger isn't available in this case.
process.exit(1);
}
try {
let serviceInfo = await hydra.registerService();
let logEntry = `Starting service ${serviceInfo.serviceName}:${hydra.getInstanceVersion()} on ${serviceInfo.serviceIP}:${serviceInfo.servicePort}`;
if (loggerType === 'logger') {
let appLogger = hydraLogger.getLogger();
hydra.log = (type, message) => {
appLogger[type](message);
};
}
if (loggerType === 'loggly') {
hydraLogger.setHydra(hydra);
hydraLogger.setConfig(config.hydra);
hydraLogger.onServiceReady();
}
setupExitHandlers();
displayBanner();
displayNetworkInterfaces();
await setupRoutes(config);
hydra.log('info', {
message: logEntry
});
setupHydraListeners();
let server = await setupServer(config, serviceInfo);
setupWebSocketServer(server);
console.log(logEntry);
if (global.gc) {
global.gc();
} else {
console.warn('No GC hook! Start Hydra-Router using `node --expose-gc hydra-router.js`.');
}
} catch (err) {
let stack = err.stack;
console.log(stack); // console log because Logger isn't available in this case.
process.emit('cleanup');
}
};
main();