-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.js
executable file
·2315 lines (2175 loc) · 75.6 KB
/
index.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const debug = require('debug')('hydra');
const Promise = require('bluebird');
Promise.series = (iterable, action) => {
return Promise.mapSeries(
iterable.map(action),
(value, index, _length) => value || iterable[index].name || null
);
};
const EventEmitter = require('events');
const util = require('util');
const uuid = require('uuid');
const Route = require('route-parser');
const net = require('net');
const dns = require('dns');
const os = require('os');
const Utils = require('./lib/utils');
const UMFMessage = require('./lib/umfmessage');
const RedisConnection = require('./lib/redis-connection');
const ServerResponse = require('./lib/server-response');
let serverResponse = new ServerResponse();
const ServerRequest = require('./lib/server-request');
let serverRequest = new ServerRequest();
const Cache = require('./lib/cache');
let HYDRA_REDIS_DB = 0;
const redisPreKey = 'hydra:service';
const mcMessageKey = 'hydra:service:mc';
const MAX_ENTRIES_IN_HEALTH_LOG = 64;
const ONE_SECOND = 1000; // milliseconds
const ONE_WEEK_IN_SECONDS = 604800;
const PRESENCE_UPDATE_INTERVAL = ONE_SECOND;
const HEALTH_UPDATE_INTERVAL = ONE_SECOND * 5;
const KEY_EXPIRATION_TTL = 3; // three seconds
const KEYS_PER_SCAN = '100';
const UMF_INVALID_MESSAGE = 'UMF message requires "to", "from" and "body" fields';
const INSTANCE_ID_NOT_SET = 'not set';
/**
* @name Hydra
* @summary Base class for Hydra.
* @fires Hydra#log
* @fires Hydra#message
*/
class Hydra extends EventEmitter {
/**
* @name constructor
* @return {undefined}
*/
constructor() {
super();
this.instanceID = INSTANCE_ID_NOT_SET;
this.mcMessageChannelClient;
this.mcDirectMessageChannelClient;
this.publishChannel = null;
this.config = null;
this.serviceName = '';
this.serviceDescription = '';
this.serviceVersion = '';
this.isService = false;
this.redisdb = null;
this._updatePresence = this._updatePresence.bind(this);
this._updateHealthCheck = this._updateHealthCheck.bind(this);
this.registeredRoutes = [];
this.registeredPlugins = [];
this.presenceTimerInteval = null;
this.healthTimerInterval = null;
this.initialized = false;
this.hostName = os.hostname();
this.internalCache = new Cache();
this.ready = () => Promise.reject(new Error('You must call hydra.init() before invoking hydra.ready()'));
}
/**
* @name use
* @summary Adds plugins to Hydra
* @param {...object} plugins - plugins to register
* @return {object} - Promise which will resolve when all plugins are registered
*/
use(...plugins) {
return Promise.series(plugins, (plugin) => this._registerPlugin(plugin));
}
/**
* @name _registerPlugin
* @summary Registers a plugin with Hydra
* @param {object} plugin - HydraPlugin to use
* @return {object} Promise or value
*/
_registerPlugin(plugin) {
this.registeredPlugins.push(plugin);
return plugin.setHydra(this);
}
/**
* @name init
* @summary Register plugins then continue initialization
* @param {mixed} config - a string with a path to a configuration file or an
* object containing hydra specific keys/values
* @param {boolean} testMode - whether hydra is being started in unit test mode
* @return {object} promise - resolves with this._init or rejects with an appropriate
* error if something went wrong
*/
init(config, testMode) {
// Reject() if we've already been called successfully
if (INSTANCE_ID_NOT_SET !== this.instanceID) {
return Promise.reject(new Error('Hydra.init() already invoked'));
}
this.testMode = testMode;
if (typeof config === 'string') {
const configHelper = require('./lib/config');
return configHelper.init(config)
.then(() => {
return this.init(configHelper.getObject(), testMode);
});
}
const initPromise = new Promise((resolve, reject) => {
let loader = (newConfig) => {
return Promise.series(this.registeredPlugins, (plugin) => plugin.setConfig(newConfig.hydra))
.then((..._results) => {
return this._init(newConfig.hydra);
})
.then(() => {
resolve(newConfig);
return 0;
})
.catch((err) => {
this._logMessage('error', err.toString());
reject(err);
});
};
if (!config || !config.hydra) {
config = Object.assign({
'hydra': {
'serviceIP': '',
'servicePort': 0,
'serviceType': '',
'serviceDescription': '',
'redis': {
'url': 'redis://127.0.0.1:6379/15'
}
}
});
}
if (!config.hydra.redis) {
config.hydra = Object.assign(config.hydra, {
'redis': {
'url': 'redis://127.0.0.1:6379/15'
}
});
}
if (process.env.HYDRA_REDIS_URL) {
Object.assign(config.hydra, {
redis: {
url: process.env.HYDRA_REDIS_URL
}
});
}
let partialConfig = true;
if (process.env.HYDRA_SERVICE) {
let hydraService = process.env.HYDRA_SERVICE.trim();
if (hydraService[0] === '{') {
let newHydraBranch = Utils.safeJSONParse(hydraService);
Object.assign(config.hydra, newHydraBranch);
partialConfig = false;
}
if (hydraService.includes('|')) {
hydraService = hydraService.replace(/(\r\n|\r|\n)/g, '');
let newHydraBranch = {};
let key = '';
let val = '';
let segs = hydraService.split('|');
segs.forEach((segment) => {
segment = segment.trim();
[key, val] = segment.split('=');
newHydraBranch[key] = val;
});
Object.assign(config.hydra, newHydraBranch);
partialConfig = false;
}
}
if (!config.hydra.serviceName || (!config.hydra.servicePort && !config.hydra.servicePort === 0)) {
reject(new Error('Config missing serviceName or servicePort'));
return;
}
if (config.hydra.serviceName.includes(':')) {
reject(new Error('serviceName can not have a colon character in its name'));
return;
}
if (config.hydra.serviceName.includes(' ')) {
reject(new Error('serviceName can not have a space character in its name'));
return;
}
if (partialConfig && process.env.HYDRA_REDIS_URL && process.env.HYDRA_SERVICE) {
this._connectToRedis({redis: {url: process.env.HYDRA_REDIS_URL}})
.then(() => {
if (!this.redisdb) {
reject(new Error('No Redis connection'));
return;
}
this.redisdb.select(HYDRA_REDIS_DB, (err, _result) => {
if (!err) {
this._getConfig(process.env.HYDRA_SERVICE)
.then((storedConfig) => {
this.redisdb.quit();
if (!storedConfig) {
reject(new Error('Invalid service stored config'));
} else {
return loader(storedConfig);
}
})
.catch((err) => reject(err));
} else {
reject(new Error('Invalid service stored config'));
}
});
});
} else {
return loader(config);
}
});
this.ready = () => initPromise;
return initPromise;
}
/**
* @name _init
* @summary Initialize Hydra with config object.
* @param {object} config - configuration object containing hydra specific keys/values
* @return {object} promise - resolving if init success or rejecting otherwise
*/
_init(config) {
return new Promise((resolve, reject) => {
let ready = () => {
Promise.series(this.registeredPlugins, (plugin) => plugin.onServiceReady()).then((..._results) => {
resolve();
}).catch((err) => {
this._logMessage('error', err.toString());
reject(err);
});
};
this.config = config;
this._connectToRedis(this.config).then(() => {
if (!this.redisdb) {
reject(new Error('No Redis connection'));
return;
}
let p = this._parseServicePortConfig(this.config.servicePort);
p.then((port) => {
this.config.servicePort = port;
this.serviceName = config.serviceName;
if (this.serviceName && this.serviceName.length > 0) {
this.serviceName = this.serviceName.toLowerCase();
}
this.serviceDescription = this.config.serviceDescription || 'not specified';
this.config.serviceVersion = this.serviceVersion = this.config.serviceVersion || this._getParentPackageJSONVersion();
/**
* Check if serviceIP has a wildcard character.
* If so, use the wildcard to mean the IP address pattern up to the wildcard.
* Use the pattern to search for an IP address that matches the pattern.
* If found, use the first matchin IP address as the serviceIP.
* This is useful in docker containers with multiple network interfaces and now way of choosing which one to use.
*/
if (this.config.serviceIP !== '' && this.config.serviceIP.indexOf('*') > -1) {
let starPoint = this.config.serviceIP.indexOf('*');
let pattern = this.config.serviceIP.substring(0, starPoint);
let firstSelected = false;
let interfaces = os.networkInterfaces();
Object.keys(interfaces).
forEach((itf) => {
interfaces[itf].forEach((interfaceRecord)=>{
if (!firstSelected && interfaceRecord.family === 'IPv4' && interfaceRecord.address.indexOf(pattern) === 0) {
this.config.serviceIP = interfaceRecord.address;
firstSelected = true;
}
});
});
this._updateInstanceData();
ready();
}
/**
* Determine network DNS/IP for this service.
* - First check whether serviceDNS is defined. If so, this is expected to be a DNS entry.
* - Else check whether serviceIP exists and is not empty ('') and is not an segemented IP
* such as 192.168.100.106 If so, then use DNS lookup to determine an actual dotted IP address.
* - Else check whether serviceIP exists and *IS* set to '' - that means the service author is
* asking Hydra to determine the machine's IP address.
* - And final else - the serviceIP is expected to be populated with an actual dotted IP address
* or serviceDNS contains a valid DNS entry.
*/
else if (this.config.serviceDNS && this.config.serviceDNS !== '') {
this.config.serviceIP = this.config.serviceDNS;
this._updateInstanceData();
ready();
} else {
if (this.config.serviceIP && this.config.serviceIP !== '' && net.isIP(this.config.serviceIP) === 0) {
dns.lookup(this.config.serviceIP, (err, result) => {
this.config.serviceIP = result;
this._updateInstanceData();
ready();
});
} else if (!this.config.serviceIP || this.config.serviceIP === '') {
// handle IP selection
let interfaces = os.networkInterfaces();
if (this.config.serviceInterface && this.config.serviceInterface !== '') {
let segments = this.config.serviceInterface.split('/');
if (segments && segments.length === 2) {
let interfaceName = segments[0];
let interfaceMask = segments[1];
Object.keys(interfaces).
forEach((itf) => {
interfaces[itf].forEach((interfaceRecord)=>{
if (itf === interfaceName && interfaceRecord.netmask === interfaceMask && interfaceRecord.family === 'IPv4') {
this.config.serviceIP = interfaceRecord.address;
}
});
});
} else {
throw new Error('config serviceInterface is not a valid format');
}
} else {
// not using serviceInterface - just select first eth0 entry.
let firstSelected = false;
Object.keys(interfaces).
forEach((itf) => {
interfaces[itf].forEach((interfaceRecord)=>{
if (!firstSelected && interfaceRecord.family === 'IPv4' && interfaceRecord.address !== '127.0.0.1') {
this.config.serviceIP = interfaceRecord.address;
firstSelected = true;
}
});
});
}
this._updateInstanceData();
ready();
} else {
this._updateInstanceData();
ready();
}
}
return 0;
}).catch((err) => reject(err));
return p;
}).catch((err) => reject(err));
});
}
/**
* @name _updateInstanceData
* @summary Update instance id and direct message key
* @return {undefined}
*/
_updateInstanceData() {
this.instanceID = this._serverInstanceID();
this.initialized = true;
}
/**
* @name _shutdown
* @summary Shutdown hydra safely.
* @return {undefined}
*/
_shutdown() {
return new Promise((resolve) => {
clearInterval(this.presenceTimerInteval);
clearInterval(this.healthTimerInterval);
const promises = [];
if (!this.testMode) {
this._logMessage('error', 'Service is shutting down.');
this.redisdb.batch()
.expire(`${redisPreKey}:${this.serviceName}:${this.instanceID}:health`, KEY_EXPIRATION_TTL)
.expire(`${redisPreKey}:${this.serviceName}:${this.instanceID}:health:log`, ONE_WEEK_IN_SECONDS)
.exec();
if (this.mcMessageChannelClient) {
promises.push(this.mcMessageChannelClient.quitAsync());
}
if (this.mcDirectMessageChannelClient) {
promises.push(this.mcDirectMessageChannelClient.quitAsync());
}
if (this.publishChannel) {
promises.push(this.publishChannel.quitAsync());
}
}
if (this.redisdb) {
this.redisdb.del(`${redisPreKey}:${this.serviceName}:${this.instanceID}:presence`, () => {
this.redisdb.quit();
Promise.all(promises).then(resolve);
});
this.redisdb.quit();
Promise.all(promises).then(resolve);
} else {
Promise.all(promises).then(resolve);
}
this.initialized = false;
this.instanceID = INSTANCE_ID_NOT_SET;
});
}
/**
* @name _connectToRedis
* @summary Configure access to Redis and monitor emitted events.
* @private
* @param {object} config - Redis client configuration
* @return {object} promise - resolves or reject
*/
_connectToRedis(config) {
let retryStrategy = config.redis.retry_strategy;
delete config.redis.retry_strategy;
let redisConnection = new RedisConnection(config.redis, 0, this.testMode);
HYDRA_REDIS_DB = redisConnection.redisConfig.db;
return redisConnection.connect(retryStrategy)
.then((client) => {
this.redisdb = client;
client
.on('reconnecting', () => {
this._logMessage('error', 'Reconnecting to Redis server...');
})
.on('warning', (warning) => {
this._logMessage('error', `Redis warning: ${warning}`);
})
.on('end', () => {
this._logMessage('error', 'Established Redis server connection has closed');
})
.on('error', (err) => {
this._logMessage('error', `Redis error: ${err}`);
});
return client;
});
}
/**
* @name _getKeys
* @summary Retrieves a list of Redis keys based on pattern.
* @param {string} pattern - pattern to filter with
* @return {object} promise - promise resolving to array of keys or or empty array
*/
_getKeys(pattern) {
return new Promise((resolve, _reject) => {
if (this.testMode) {
this.redisdb.keys(pattern, (err, result) => {
if (err) {
resolve([]);
} else {
resolve(result);
}
});
} else {
let doScan = (cursor, pattern, retSet) => {
this.redisdb.scan(cursor, 'MATCH', pattern, 'COUNT', KEYS_PER_SCAN, (err, result) => {
if (!err) {
cursor = result[0];
let keys = result[1];
keys.forEach((key, _i) => {
retSet.add(key);
});
if (cursor === '0') {
resolve(Array.from(retSet));
} else {
doScan(cursor, pattern, retSet);
}
} else {
resolve([]);
}
});
};
let results = new Set();
doScan('0', pattern, results);
}
});
}
/**
* @name _getServiceName
* @summary Retrieves the service name of the current instance.
* @private
* @throws Throws an error if this machine isn't an instance.
* @return {string} serviceName - returns the service name.
*/
_getServiceName() {
if (!this.initialized) {
let msg = 'init() not called, Hydra requires a configuration object.';
this._logMessage('error', msg);
throw new Error(msg);
}
return this.serviceName;
}
/**
* @name _serverInstanceID
* @summary Returns the server instance ID.
* @private
* @return {string} instance id
*/
_serverInstanceID() {
return uuid.
v4().
replace(RegExp('-', 'g'), '');
}
/**
* @name _registerService
* @summary Registers this machine as a Hydra instance.
* @description This is an optional call as this module might just be used to monitor and query instances.
* @private
* @return {object} promise - resolving if registration success or rejecting otherwise
*/
_registerService() {
return new Promise((resolve, reject) => {
if (!this.initialized) {
let msg = 'init() not called, Hydra requires a configuration object.';
this._logMessage('error', msg);
reject(new Error(msg));
return;
}
if (!this.redisdb) {
let msg = 'No Redis connection';
this._logMessage('error', msg);
reject(new Error(msg));
return;
}
this.isService = true;
let serviceName = this.serviceName;
let serviceEntry = Utils.safeJSONStringify({
serviceName,
type: this.config.serviceType,
registeredOn: this._getTimeStamp()
});
this.redisdb.set(`${redisPreKey}:${serviceName}:service`, serviceEntry, (err, _result) => {
if (err) {
let msg = 'Unable to set :service key in Redis db.';
this._logMessage('error', msg);
reject(new Error(msg));
} else {
let testRedis;
if (this.testMode) {
let redisConnection;
redisConnection = new RedisConnection(this.config.redis, 0, this.testMode);
testRedis = redisConnection.getRedis();
}
// Setup service message courier channels
this.mcMessageChannelClient = this.testMode ? testRedis.createClient() : this.redisdb.duplicate();
this.mcMessageChannelClient.subscribe(`${mcMessageKey}:${serviceName}`);
this.mcMessageChannelClient.on('message', (channel, message) => {
let msg = Utils.safeJSONParse(message);
if (msg) {
let umfMsg = UMFMessage.createMessage(msg);
this.emit('message', umfMsg.toShort());
}
});
this.mcDirectMessageChannelClient = this.testMode ? testRedis.createClient() : this.redisdb.duplicate();
this.mcDirectMessageChannelClient.subscribe(`${mcMessageKey}:${serviceName}:${this.instanceID}`);
this.mcDirectMessageChannelClient.on('message', (channel, message) => {
let msg = Utils.safeJSONParse(message);
if (msg) {
let umfMsg = UMFMessage.createMessage(msg);
this.emit('message', umfMsg.toShort());
}
});
// Schedule periodic updates
this.presenceTimerInteval = setInterval(this._updatePresence, PRESENCE_UPDATE_INTERVAL);
this.healthTimerInterval = setInterval(this._updateHealthCheck, HEALTH_UPDATE_INTERVAL);
// Update presence immediately without waiting for next update interval.
this._updatePresence();
resolve({
serviceName: this.serviceName,
serviceIP: this.config.serviceIP,
servicePort: this.config.servicePort
});
}
});
});
}
/**
* @name _registerRoutes
* @summary Register routes
* @description Routes must be formatted as UMF To routes. https://github.com/cjus/umf#%20To%20field%20(routing)
* @private
* @param {array} routes - array of routes
* @return {object} Promise - resolving or rejecting
*/
_registerRoutes(routes) {
return new Promise((resolve, reject) => {
if (!this.redisdb) {
reject(new Error('No Redis connection'));
return;
}
this._flushRoutes().then(() => {
let routesKey = `${redisPreKey}:${this.serviceName}:service:routes`;
let trans = this.redisdb.multi();
[
`[get]/${this.serviceName}`,
`[get]/${this.serviceName}/`,
`[get]/${this.serviceName}/:rest`
].forEach((pattern) => {
routes.push(pattern);
});
routes.forEach((route) => {
trans.sadd(routesKey, route);
});
trans.exec((err, _result) => {
if (err) {
reject(err);
} else {
return this._getRoutes()
.then((routeList) => {
if (routeList.length) {
this.registeredRoutes = [];
routeList.forEach((route) => {
this.registeredRoutes.push(new Route(route));
});
if (this.serviceName !== 'hydra-router') {
// let routers know that a new service route was registered
resolve();
return this._sendBroadcastMessage(UMFMessage.createMessage({
to: 'hydra-router:/refresh',
from: `${this.serviceName}:/`,
body: {
action: 'refresh',
serviceName: this.serviceName
}
}));
} else {
resolve();
}
} else {
resolve();
}
})
.catch(reject);
}
});
}).catch(reject);
});
}
/**
* @name _getRoutes
* @summary Retrieves a array list of routes
* @param {string} serviceName - name of service to retrieve list of routes.
* If param is undefined, then the current serviceName is used.
* @return {object} Promise - resolving to array of routes or rejection
*/
_getRoutes(serviceName) {
if (serviceName === undefined) {
serviceName = this.serviceName;
}
return new Promise((resolve, reject) => {
let routesKey = `${redisPreKey}:${serviceName}:service:routes`;
this.redisdb.smembers(routesKey, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
/**
* @name _getAllServiceRoutes
* @summary Retrieve all service routes.
* @return {object} Promise - resolving to an object with keys and arrays of routes
*/
_getAllServiceRoutes() {
return new Promise((resolve, reject) => {
if (!this.redisdb) {
let msg = 'No Redis connection';
this._logMessage('error', msg);
reject(new Error(msg));
return;
}
let promises = [];
let serviceNames = [];
this._getKeys('*:routes')
.then((serviceRoutes) => {
serviceRoutes.forEach((service) => {
let segments = service.split(':');
let serviceName = segments[2];
serviceNames.push(serviceName);
promises.push(this._getRoutes(serviceName));
});
return Promise.all(promises);
})
.then((routes) => {
let resObj = {};
let idx = 0;
routes.forEach((routesList) => {
resObj[serviceNames[idx]] = routesList;
idx += 1;
});
resolve(resObj);
})
.catch((err) => {
reject(err);
});
});
}
/**
* @name _matchRoute
* @summary Matches a route path to a list of registered routes
* @private
* @param {string} routePath - a URL path to match
* @return {boolean} match - true if match, false if not
*/
_matchRoute(routePath) {
let ret = false;
for (let route of this.registeredRoutes) {
if (route.match(routePath)) {
ret = true;
break;
}
}
return ret;
}
/**
* @name _flushRoutes
* @summary Delete's the services routes.
* @return {object} Promise - resolving or rejection
*/
_flushRoutes() {
return new Promise((resolve, reject) => {
let routesKey = `${redisPreKey}:${this.serviceName}:service:routes`;
this.redisdb.del(routesKey, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
/**
* @name _updatePresence
* @summary Update service presence.
* @private
* @return {undefined}
*/
_updatePresence() {
let entry = Utils.safeJSONStringify({
serviceName: this.serviceName,
serviceDescription: this.serviceDescription,
version: this.serviceVersion,
instanceID: this.instanceID,
updatedOn: this._getTimeStamp(),
processID: process.pid,
ip: this.config.serviceIP,
port: this.config.servicePort,
hostName: this.hostName
});
if (entry && !this.redisdb.closing) {
let cmd = (this.testMode) ? 'multi' : 'batch';
this.redisdb[cmd]()
.setex(`${redisPreKey}:${this.serviceName}:${this.instanceID}:presence`, KEY_EXPIRATION_TTL, this.instanceID)
.hset(`${redisPreKey}:nodes`, this.instanceID, entry)
.exec();
}
}
/**
* @name _updateHealthCheck
* @summary Update service heath.
* @private
* @return {undefined}
*/
_updateHealthCheck() {
let entry = Object.assign({
updatedOn: this._getTimeStamp()
}, this._getHealth());
let cmd = (this.testMode) ? 'multi' : 'batch';
this.redisdb[cmd]()
.setex(`${redisPreKey}:${this.serviceName}:${this.instanceID}:health`, KEY_EXPIRATION_TTL, Utils.safeJSONStringify(entry))
.expire(`${redisPreKey}:${this.serviceName}:${this.instanceID}:health:log`, ONE_WEEK_IN_SECONDS)
.exec();
}
/**
* @name _getHealth
* @summary Retrieve server health info.
* @private
* @return {object} obj - object containing server info
*/
_getHealth() {
let lines = [];
let keyval = [];
let map = {};
let memory = util.inspect(process.memoryUsage());
memory = memory.replace(/[\ \{\}.|\n]/g, '');
lines = memory.split(',');
lines.forEach((line) => {
keyval = line.split(':');
map[keyval[0]] = Number(keyval[1]);
});
let uptimeInSeconds = process.uptime();
return {
serviceName: this.serviceName,
instanceID: this.instanceID,
hostName: this.hostName,
sampledOn: this._getTimeStamp(),
processID: process.pid,
architecture: process.arch,
platform: process.platform,
nodeVersion: process.version,
memory: map,
uptimeSeconds: uptimeInSeconds
};
}
/**
* @name _logMessage
* @summary Log a message to the service's health log queue.
* @private
* @throws Throws an error if this machine isn't an instance.
* @event Hydra#log
* @param {string} type - type of message ('error', 'info', 'debug' or user defined)
* @param {string} message - message to log
* @param {boolean} suppressEmit - false by default. If true then suppress log emit
* @return {undefined}
*/
_logMessage(type, message, suppressEmit) {
let errMessage = {
ts: this._getTimeStamp(),
serviceName: this.serviceName || 'not a service',
type,
processID: process.pid,
msg: message
};
let entry = Utils.safeJSONStringify(errMessage);
debug(entry);
if (!suppressEmit) {
this.emit('log', errMessage);
}
if (entry) {
// If issue is with Redis we can't use Redis to log this error.
// however the above call to the application logger would be one way of detecting the issue.
if (this.isService) {
if (entry.toLowerCase().indexOf('redis') === -1) {
if (!this.redisdb.closing) {
let key = `${redisPreKey}:${this.serviceName}:${this.instanceID}:health:log`;
this.redisdb.multi()
.select(HYDRA_REDIS_DB)
.lpush(key, entry)
.ltrim(key, 0, MAX_ENTRIES_IN_HEALTH_LOG - 1)
.exec();
}
}
}
} else {
console.log('Unable to log this message', type, message);
}
}
/**
* @name _getServices
* @summary Retrieve a list of available services.
* @private
* @return {promise} promise - returns a promise
*/
_getServices() {
return new Promise((resolve, reject) => {
if (!this.redisdb) {
reject(new Error('No Redis connection'));
return;
}
this._getKeys('*:service')
.then((services) => {
let trans = this.redisdb.multi();
services.forEach((service) => {
trans.get(service);
});
trans.exec((err, result) => {
if (err) {
reject(err);
} else {
let serviceList = result.map((service) => {
return Utils.safeJSONParse(service);
});
resolve(serviceList);
}
});
});
});
}
/**
* @name _getServiceNodes
* @summary Retrieve a list of services even if inactive.
* @private
* @return {promise} promise - returns a promise
*/
_getServiceNodes() {
return new Promise((resolve, reject) => {
if (!this.redisdb) {
reject(new Error('No Redis connection'));
return;
}
let now = (new Date()).getTime();
this.redisdb.hgetall(`${redisPreKey}:nodes`, (err, data) => {
if (err) {
reject(err);
} else {
let nodes = [];
if (data) {
Object.keys(data).forEach((entry) => {
let item = Utils.safeJSONParse(data[entry]);
item.elapsed = parseInt((now - (new Date(item.updatedOn)).getTime()) / ONE_SECOND);
nodes.push(item);
});
}
resolve(nodes);
}
});
});
}
/**
* @name _findService
* @summary Find a service.
* @private
* @param {string} name - service name - note service name is case insensitive
* @return {promise} promise - which resolves with service
*/
_findService(name) {
return new Promise((resolve, reject) => {
if (!this.redisdb) {
reject(new Error('No Redis connection'));
return;
}
this.redisdb.get(`${redisPreKey}:${name}:service`, (err, result) => {
if (err) {
reject(err);
} else {
if (!result) {
reject(new Error(`Can't find ${name} service`));
} else {
let js = Utils.safeJSONParse(result);
resolve(js);
}
}
});
});
}
/**
* @name _checkServicePresence
* @summary Retrieves all the "present" service instances information.
* @description Differs from getServicePresence (which calls this one)
* in that this performs only bare minimum fatal error checking that
* would throw a reject(). This is useful when it's expected to perhaps
* have some dead serivces, etc. as used in getServiceHealthAll()
* for example.
* @param {string} [name=our service name] - service name - note service name is case insensitive
* @return {promise} promise - which resolves with a randomized service presence array or else
* a reject() if a "fatal" error occured (Redis error for example)
*/
_checkServicePresence(name) {
name = name || this._getServiceName();
return new Promise((resolve, reject) => {
let cacheKey = `checkServicePresence:${name}`;
let cachedValue = this.internalCache.get(cacheKey);
if (cachedValue) {
// Re-randomized the array each call to make sure we return a good
// random set each time we access the cache... no need to store
// the new random array again since it will just be randomzied again next call
Utils.shuffleArray(cachedValue);
resolve(cachedValue);
return;
}