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 | 1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
167×
167×
161×
1×
167×
167×
161×
6×
6×
1×
5×
1×
84×
84×
84×
84×
84×
84×
84×
84×
83×
83×
83×
75×
75×
75×
12×
75×
3×
72×
74×
15×
1×
14×
1×
13×
89×
89×
3×
3×
3×
3×
2×
2×
1×
2×
2×
2×
2×
3×
3×
1×
2×
3×
2×
2×
2×
1×
1×
1×
1×
305×
7×
83×
80×
76×
75×
74×
76×
1×
6×
6×
6×
6×
6×
6×
3×
3×
3×
3×
2×
2×
1×
4×
4×
4×
2×
2×
2×
2×
1×
1×
1×
1×
1×
2×
1×
3×
3×
2×
2×
1×
1×
1×
1×
1×
2×
1×
3×
1×
2×
2×
1×
2×
1×
3×
1×
2×
2×
1×
2×
9×
9×
4×
5×
5×
5×
5×
3×
3×
3×
1×
2×
2×
2×
2×
1×
1×
1×
4×
4×
4×
2×
2×
2×
2×
1×
1×
1×
1×
2×
1×
1×
1×
1×
5×
1×
4×
3×
3×
2×
3×
1×
3×
1×
10×
5×
12×
5×
5×
1×
39×
1×
26×
1×
25×
1×
7×
7×
7×
8×
3×
3×
2×
1×
21×
21×
21×
21×
22×
22×
21×
16×
21×
21×
21×
21×
20×
1×
3×
3×
3×
3×
3×
1×
3×
3×
1×
2×
2×
2×
2×
2×
2×
2×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
4×
27×
27×
27×
27×
27×
27×
27×
27×
2×
25×
25×
25×
25×
27×
27×
27×
1×
1×
1×
26×
| import request from 'request';
import fs from 'fs';
import yaml from 'js-yaml';
import { merge, findIndex } from 'lodash';
import { normalizeDelta, findInstance } from './deltaUtils';
import path from 'path';
import { series, waterfall } from 'async';
import { EventEmitter } from 'events';
import AwsMetadata from './AwsMetadata';
import ConfigClusterResolver from './ConfigClusterResolver';
import DnsClusterResolver from './DnsClusterResolver';
import Logger from './Logger';
import defaultConfig from './defaultConfig';
function noop() {}
/*
Eureka JS client
This module handles registration with a Eureka server, as well as heartbeats
for reporting instance health.
*/
function fileExists(file) {
try {
return fs.statSync(file);
} catch (e) {
return false;
}
}
function getYaml(file) {
let yml = {};
if (!fileExists(file)) {
return yml; // no configuration file
}
try {
yml = yaml.safeLoad(fs.readFileSync(file, 'utf8'));
} catch (e) {
// configuration file exists but was malformed
throw new Error(`Error loading YAML configuration file: ${file} ${e}`);
}
return yml;
}
export default class Eureka extends EventEmitter {
constructor(config = {}) {
super();
// Allow passing in a custom logger:
this.logger = config.logger || new Logger();
this.logger.debug('initializing eureka client');
// Load up the current working directory and the environment:
const cwd = config.cwd || process.cwd();
const env = process.env.EUREKA_ENV || process.env.NODE_ENV || 'development';
const filename = config.filename || 'eureka-client';
// Load in the configuration files:
const defaultYml = getYaml(path.join(cwd, `${filename}.yml`));
const envYml = getYaml(path.join(cwd, `${filename}-${env}.yml`));
// apply config overrides in appropriate order
this.config = merge({}, defaultConfig, defaultYml, envYml, config);
// Validate the provided the values we need:
this.validateConfig(this.config);
this.requestMiddleware = this.config.requestMiddleware;
this.hasFullRegistry = false;
if (this.amazonDataCenter) {
this.metadataClient = new AwsMetadata({
logger: this.logger,
});
}
if (this.config.eureka.useDns) {
this.clusterResolver = new DnsClusterResolver(this.config, this.logger);
} else {
this.clusterResolver = new ConfigClusterResolver(this.config, this.logger);
}
this.cache = {
app: {},
vip: {},
};
}
/*
Helper method to get the instance ID. If the datacenter is AWS, this will be the
instance-id in the metadata. Else, it's the hostName.
*/
get instanceId() {
if (this.config.instance.instanceId) {
return this.config.instance.instanceId;
} else if (this.amazonDataCenter) {
return this.config.instance.dataCenterInfo.metadata['instance-id'];
}
return this.config.instance.hostName;
}
/*
Helper method to determine if this is an AWS datacenter.
*/
get amazonDataCenter() {
const { dataCenterInfo } = this.config.instance;
return (
dataCenterInfo &&
dataCenterInfo.name &&
dataCenterInfo.name.toLowerCase() === 'amazon'
);
}
/*
Registers instance with Eureka, begins heartbeats, and fetches registry.
*/
start(callback = noop) {
series([
done => {
if (Ithis.metadataClient && this.config.eureka.fetchMetadata) {
return this.addInstanceMetadata(done);
}
done();
},
done => {
if (this.config.eureka.registerWithEureka) {
return this.register(done);
}
done();
},
done => {
if (this.config.eureka.registerWithEureka) {
this.startHeartbeats();
}
if (Ethis.config.eureka.fetchRegistry) {
this.startRegistryFetches();
if (Ithis.config.eureka.waitForRegistry) {
const waitForRegistryUpdate = (cb) => {
this.fetchRegistry(() => {
const instances = this.getInstancesByVipAddress(this.config.instance.vipAddress);
if (instances.length === 0) setTimeout(() => waitForRegistryUpdate(cb), 2000);
else cb();
});
};
return waitForRegistryUpdate(done);
}
this.fetchRegistry(done);
} else {
done();
}
},
], (err, ...rest) => {
if (err) {
this.logger.warn('Error starting the Eureka Client', err);
} else {
this.emit('started');
}
callback(err, ...rest);
});
}
/*
De-registers instance with Eureka, stops heartbeats / registry fetches.
*/
stop(callback = noop) {
clearInterval(this.registryFetch);
if (this.config.eureka.registerWithEureka) {
clearInterval(this.heartbeat);
this.deregister(callback);
} else {
callback();
}
}
/*
Validates client configuration.
*/
validateConfig(config) {
function validate(namespace, key) {
if (!config[namespace][key]) {
throw new TypeError(`Missing "${namespace}.${key}" config value.`);
}
}
if (config.eureka.registerWithEureka) {
validate('instance', 'app');
validate('instance', 'vipAddress');
validate('instance', 'port');
validate('instance', 'dataCenterInfo');
}
if (typeof config.requestMiddleware !== 'function') {
throw new TypeError('requestMiddleware must be a function');
}
}
/*
Registers with the Eureka server and initializes heartbeats on registration success.
*/
register(callback = noop) {
this.config.instance.status = 'UP';
const connectionTimeout = setTimeout(() => {
this.logger.warn('It looks like it\'s taking a while to register with ' +
'Eureka. This usually means there is an issue connecting to the host ' +
'specified. Start application with NODE_DEBUG=request for more logging.');
}, 10000);
this.eurekaRequest({
method: 'POST',
uri: this.config.instance.app,
json: true,
body: { instance: this.config.instance },
}, (error, response, body) => {
clearTimeout(connectionTimeout);
if (!error && response.statusCode === 204) {
this.logger.info(
'registered with eureka: ',
`${this.config.instance.app}/${this.instanceId}`
);
this.emit('registered');
return callback(null);
} else if (error) {
this.logger.warn('Error registering with eureka client.', error);
return callback(error);
}
return callback(
new Error(`eureka registration FAILED: status: ${response.statusCode} body: ${body}`)
);
});
}
/*
De-registers with the Eureka server and stops heartbeats.
*/
deregister(callback = noop) {
this.eurekaRequest({
method: 'DELETE',
uri: `${this.config.instance.app}/${this.instanceId}`,
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
this.logger.info(
`de-registered with eureka: ${this.config.instance.app}/${this.instanceId}`
);
this.emit('deregistered');
return callback(null);
} else if (error) {
this.logger.warn('Error deregistering with eureka', error);
return callback(error);
}
return callback(
new Error(`eureka deregistration FAILED: status: ${response.statusCode} body: ${body}`)
);
});
}
/*
Sets up heartbeats on interval for the life of the application.
Heartbeat interval by setting configuration property: eureka.heartbeatInterval
*/
startHeartbeats() {
this.heartbeat = setInterval(() => {
this.renew();
}, this.config.eureka.heartbeatInterval);
}
renew() {
this.eurekaRequest({
method: 'PUT',
uri: `${this.config.instance.app}/${this.instanceId}`,
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
this.logger.debug('eureka heartbeat success');
this.emit('heartbeat');
} else Eif (!error && response.statusCode === 404) {
this.logger.warn('eureka heartbeat FAILED, Re-registering app');
this.register();
} else {
if (error) {
this.logger.error('An error in the request occured.', error);
}
this.logger.warn(
'eureka heartbeat FAILED, will retry.' +
`statusCode: ${response ? response.statusCode : 'unknown'}` +
`body: ${body} ${error | ''} `
);
}
});
}
/*
Sets up registry fetches on interval for the life of the application.
Registry fetch interval setting configuration property: eureka.registryFetchInterval
*/
startRegistryFetches() {
this.registryFetch = setInterval(() => {
this.fetchRegistry(err => {
if (err) this.logger.warn('Error fetching registry', err);
});
}, this.config.eureka.registryFetchInterval);
}
/*
Retrieves a list of instances from Eureka server given an appId
*/
getInstancesByAppId(appId) {
if (!appId) {
throw new RangeError('Unable to query instances with no appId');
}
const instances = this.cache.app[appId.toUpperCase()] || [];
if (instances.length === 0) {
this.logger.warn(`Unable to retrieve instances for appId: ${appId}`);
}
return instances;
}
/*
Retrieves a list of instances from Eureka server given a vipAddress
*/
getInstancesByVipAddress(vipAddress) {
if (!vipAddress) {
throw new RangeError('Unable to query instances with no vipAddress');
}
const instances = this.cache.vip[vipAddress] || [];
if (instances.length === 0) {
this.logger.warn(`Unable to retrieves instances for vipAddress: ${vipAddress}`);
}
return instances;
}
/*
Orchestrates fetching registry
*/
fetchRegistry(callback = noop) {
if (this.config.shouldUseDelta && this.hasFullRegistry) {
this.fetchDelta(callback);
} else {
this.fetchFullRegistry(callback);
}
}
/*
Retrieves all applications registered with the Eureka server
*/
fetchFullRegistry(callback = noop) {
this.eurekaRequest({
uri: '',
headers: {
Accept: 'application/json',
},
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
this.logger.debug('retrieved full registry successfully');
try {
this.transformRegistry(JSON.parse(body));
} catch (ex) {
return callback(ex);
}
this.emit('registryUpdated');
this.hasFullRegistry = true;
return callback(null);
} else if (error) {
this.logger.warn('Error fetching registry', error);
return callback(error);
}
callback(new Error('Unable to retrieve full registry from Eureka server'));
});
}
/*
Retrieves all applications registered with the Eureka server
*/
fetchDelta(callback = noop) {
this.eurekaRequest({
uri: 'delta',
headers: {
Accept: 'application/json',
},
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
this.logger.debug('retrieved delta successfully');
let applications;
try {
const jsonBody = JSON.parse(body);
applications = jsonBody.applications.application;
this.handleDelta(this.cache, applications);
return callback(null);
} catch (ex) {
return callback(ex);
}
} else if (error) {
this.logger.warn('Error fetching delta registry', error);
return callback(error);
}
callback(new Error('Unable to retrieve delta registry from Eureka server'));
});
}
/*
Transforms the given registry and caches the registry locally
*/
transformRegistry(registry) {
if (!registry) {
this.logger.warn('Unable to transform empty registry');
} else {
if (!registry.applications.application) {
return;
}
const newCache = { app: {}, vip: {} };
if (Array.isArray(registry.applications.application)) {
registry.applications.application.forEach((app) => {
this.transformApp(app, newCache);
});
} else {
this.transformApp(registry.applications.application, newCache);
}
this.cache = newCache;
}
}
/*
Transforms the given application and places in client cache. If an application
has a single instance, the instance is placed into the cache as an array of one
*/
transformApp(app, cache) {
if (app.instance.length) {
app.instance
.filter(this.validateInstance.bind(this))
.forEach((inst) => this.addInstance(cache, inst));
} else Eif (this.validateInstance(app.instance)) {
this.addInstance(cache, app.instance);
}
}
/*
Returns true if instance filtering is disabled, or if the instance is UP
*/
validateInstance(instance) {
return (!this.config.eureka.filterUpInstances || instance.status === 'UP');
}
/*
Returns an array of vipAddresses from string vipAddress given by eureka
*/
splitVipAddress(vipAddress) { // eslint-disable-line
if (typeof vipAddress !== 'string') {
return [];
}
return vipAddress.split(',');
}
handleDelta(cache, appDelta) {
const delta = normalizeDelta(appDelta);
delta.forEach((app) => {
app.instance.forEach((instance) => {
switch (instance.actionType) {
case 'ADDED': this.addInstance(cache, instance); break;
case 'MODIFIED': this.modifyInstance(cache, instance); break;
case 'DELETED': this.deleteInstance(cache, instance); break;
default: this.logger.warn('Unknown delta actionType', instance.actionType); break;
}
});
});
}
addInstance(cache, instance) {
if (I!this.validateInstance(instance)) return;
const vipAddresses = this.splitVipAddress(instance.vipAddress);
const appName = instance.app.toUpperCase();
vipAddresses.forEach((vipAddress) => {
const alreadyContains = findIndex(cache.vip[vipAddress], findInstance(instance)) > -1;
if (alreadyContains) return;
if (!cache.vip[vipAddress]) {
cache.vip[vipAddress] = [];
}
cache.vip[vipAddress].push(instance);
});
if (!cache.app[appName]) cache.app[appName] = [];
const alreadyContains = findIndex(cache.app[appName], findInstance(instance)) > -1;
if (alreadyContains) return;
cache.app[appName].push(instance);
}
modifyInstance(cache, instance) {
const vipAddresses = this.splitVipAddress(instance.vipAddress);
const appName = instance.app.toUpperCase();
vipAddresses.forEach((vipAddress) => {
const index = findIndex(cache.vip[vipAddress], findInstance(instance));
if (index > -1) cache.vip[vipAddress].splice(index, 1, instance);
else this.addInstance(cache, instance);
});
const index = findIndex(cache.app[appName], findInstance(instance));
if (Eindex > -1) cache.app[appName].splice(cache.vip[instance.vipAddress], 1, instance);
else this.addInstance(cache, instance);
}
deleteInstance(cache, instance) {
const vipAddresses = this.splitVipAddress(instance.vipAddress);
const appName = instance.app.toUpperCase();
vipAddresses.forEach((vipAddress) => {
const index = findIndex(cache.vip[vipAddress], findInstance(instance));
if (index > -1) cache.vip[vipAddress].splice(index, 1);
});
const index = findIndex(cache.app[appName], findInstance(instance));
if (index > -1) cache.app[appName].splice(cache.vip[instance.vipAddress], 1);
}
/*
Fetches the metadata using the built-in client and updates the instance
configuration with the hostname and IP address. If the value of the config
option 'eureka.useLocalMetadata' is true, then the local IP address and
hostname is used. Otherwise, the public IP address and hostname is used. If
'eureka.preferIpAddress' is true, the IP address will be used as the hostname.
A string replacement is done on the healthCheckUrl, statusPageUrl and
homePageUrl so that users can define the URLs with a placeholder for the
host ('__HOST__'). This allows flexibility since the host isn't known until
the metadata is fetched. The replaced value respects the config option
'eureka.useLocalMetadata' as described above.
This will only get called when dataCenterInfo.name is Amazon, but you can
set config.eureka.fetchMetadata to false if you want to provide your own
metadata in AWS environments.
*/
addInstanceMetadata(callback = noop) {
this.metadataClient.fetchMetadata(metadataResult => {
this.config.instance.dataCenterInfo.metadata = merge(
this.config.instance.dataCenterInfo.metadata,
metadataResult
);
const useLocal = this.config.eureka.useLocalMetadata;
const preferIpAddress = this.config.eureka.preferIpAddress;
const metadataHostName = metadataResult[useLocal ? 'local-hostname' : 'public-hostname'];
const metadataIpAddress = metadataResult[useLocal ? 'local-ipv4' : 'public-ipv4'];
this.config.instance.hostName = preferIpAddress ? metadataIpAddress : metadataHostName;
this.config.instance.ipAddr = metadataIpAddress;
if (Ethis.config.instance.statusPageUrl) {
const { statusPageUrl } = this.config.instance;
const replacedUrl = statusPageUrl.replace('__HOST__', this.config.instance.hostName);
this.config.instance.statusPageUrl = replacedUrl;
}
if (Ethis.config.instance.healthCheckUrl) {
const { healthCheckUrl } = this.config.instance;
const replacedUrl = healthCheckUrl.replace('__HOST__', this.config.instance.hostName);
this.config.instance.healthCheckUrl = replacedUrl;
}
if (Ethis.config.instance.homePageUrl) {
const { homePageUrl } = this.config.instance;
const replacedUrl = homePageUrl.replace('__HOST__', this.config.instance.hostName);
this.config.instance.homePageUrl = replacedUrl;
}
callback();
});
}
/*
Helper method for making a request to the Eureka server. Handles resolving
the current cluster as well as some default options.
*/
eurekaRequest(opts, callback, retryAttempt = 0) {
waterfall([
/*
Resolve Eureka Clusters
*/
done => {
this.clusterResolver.resolveEurekaUrl((err, eurekaUrl) => {
if (Ierr) return done(err);
const requestOpts = merge({}, opts, {
baseUrl: eurekaUrl,
gzip: true,
});
done(null, requestOpts);
}, retryAttempt);
},
/*
Apply Request Middleware
*/
(requestOpts, done) => {
this.requestMiddleware(requestOpts, (newRequestOpts) => {
if (typeof newRequestOpts !== 'object') {
return done(new Error('requestMiddleware did not return an object'));
}
done(null, newRequestOpts);
});
},
/*
Perform Request
*/
(requestOpts, done) => {
const method = requestOpts.method ? requestOpts.method.toLowerCase() : 'get';
request[method](requestOpts, (error, response, body) => {
done(error, response, body, requestOpts);
});
},
],
/*
Handle Final Output.
*/
(error, response, body, requestOpts) => {
if (error) this.logger.error('Problem making eureka request', error);
// Perform retry if request failed and we have attempts left
const responseInvalid = response
&& response.statusCode
&& String(response.statusCode)[0] === '5';
if ((error || responseInvalid) && retryAttempt < this.config.eureka.maxRetries) {
const nextRetryDelay = this.config.eureka.requestRetryDelay * (retryAttempt + 1);
this.logger.warn(`Eureka request failed to endpoint ${requestOpts.baseUrl}, ` +
`next server retry in ${nextRetryDelay}ms`);
setTimeout(() => this.eurekaRequest(opts, callback, retryAttempt + 1),
nextRetryDelay);
return;
}
callback(error, response, body);
});
}
}
|