1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | var debug = require('debug')('plugin:eurekeclient');
|
8 | var util = require('util');
|
9 | var os = require('os');
|
10 |
|
11 | const port = process.env.PORT || 8000;
|
12 | const Eureka = require('eureka-js-client').Eureka;
|
13 |
|
14 | module.exports.init = function (config, logger, stats) {
|
15 |
|
16 | const lookup = config.servicemap;
|
17 |
|
18 | config.instance.hostName = os.hostname();
|
19 | debug('local hostName: ' + config.instance.hostName);
|
20 | config.instance.ipAddr = getIPAddr();
|
21 | config.instance.port = {};
|
22 | config.instance.port["$"] = port;
|
23 | config.instance.port["@enabled"] = true;
|
24 | config.instance.dataCenterInfo["@class"] = "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo";
|
25 |
|
26 | const client = new Eureka(config);
|
27 |
|
28 | try {
|
29 | client.start();
|
30 | } catch (err) {
|
31 | console.error(err);
|
32 | client.stop();
|
33 | }
|
34 |
|
35 | function getIPAddr() {
|
36 | var interfaces = os.networkInterfaces();
|
37 | var addresses = [];
|
38 | for (var k in interfaces) {
|
39 | for (var k2 in interfaces[k]) {
|
40 | var address = interfaces[k][k2];
|
41 | if (address.family === 'IPv4' && !address.internal) {
|
42 | addresses.push(address.address);
|
43 | }
|
44 | }
|
45 | }
|
46 | debug ('localhost ip: ' + addresses[0]);
|
47 | return addresses[0];
|
48 | }
|
49 |
|
50 | function getAppName(url) {
|
51 | for (var index in config.lookup) {
|
52 | if (url.includes(config.lookup[index].uri) || url == config.lookup[index].uri) {
|
53 | return {
|
54 | app: config.lookup[index].app,
|
55 | secure: config.lookup[index].secure
|
56 | };
|
57 | }
|
58 | }
|
59 | return "";
|
60 | }
|
61 |
|
62 | function getTarget(app, secure) {
|
63 | var instances = client.getInstancesByAppId(app);
|
64 |
|
65 | for (var index in instances) {
|
66 | if (instances[index].status == "UP") {
|
67 | return (secure == true) ? {"hostName": instances[index].hostName, "port": instances[index].securePort["$"]} : {"hostName": instances[index].hostName, "port":instances[index].port["$"]};
|
68 | }
|
69 | }
|
70 | return "";
|
71 | }
|
72 |
|
73 | return {
|
74 | onrequest: function(req, res, next) {
|
75 | var appInfo = getAppName(req.url);
|
76 | var endpoint = getTarget(appInfo.app, appInfo.secure);
|
77 |
|
78 | if (endpoint.hostName) {
|
79 | debug("target hostname: " + endpoint.hostName);
|
80 | req.targetHostname = endpoint.hostName;
|
81 | debug("target port: " + endpoint.port);
|
82 | req.targetPort = endpoint.port;
|
83 | req.targetPath = req.url;
|
84 | if (appInfo.secure) {
|
85 | req.targetSecure = true;
|
86 | } else {
|
87 | req.targetSecure = false;
|
88 | }
|
89 | } else {
|
90 | console.warn("Target enpoint from Eureka not found");
|
91 | }
|
92 | next();
|
93 | }
|
94 | };
|
95 | }
|