-
Notifications
You must be signed in to change notification settings - Fork 245
/
cache.js
233 lines (210 loc) · 7.48 KB
/
cache.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
'use strict';
/*
* This module handles all IO called on the cache (currently Redis)
*/
var url = require('url'),
redis = require('redis'),
lruCache = require('lru-cache');
function Cache(config, handlers) {
if (!(this instanceof Cache)) {
return new Cache(config, handlers);
}
var logHandler = handlers.logHandler || console.log,
debugHandler = handlers.debugHandler || console.log;
this.config = config;
this.log = function (msg) {
logHandler('Cache: ' + msg);
};
this.debug = function (msg) {
debugHandler('Cache: ' + msg);
};
// Passive check enabled means: there is no active checks running
this.passiveCheck = true;
// Configure Redis
this.redisClient = redis.createClient(
this.config.redisPort,
this.config.redisHost
);
if (this.config.redisMasterPort && this.config.redisMasterHost) {
this.redisMasterClient = redis.createClient(
this.config.redisMasterPort,
this.config.redisMasterHost
);
}
//select database
if (this.config.redisDatabase) {
this.redisClient.select(this.config.redisDatabase);
if (this.redisMasterClient) {
this.redisMasterClient.select(this.config.redisDatabase);
}
}
//auth redis
if (this.config.redisPassword) {
this.redisClient.auth(this.config.redisPassword);
if (this.config.redisMasterPassword) {
this.redisMasterClient.auth(this.config.redisMasterPassword);
}
}
this.redisClient.on('error', function (err) {
this.log('RedisError ' + err);
}.bind(this));
if (this.redisMasterClient) {
this.redisMasterClient.on('error', function (err) {
this.log('RedisMasterError ' + err);
}.bind(this));
}
// Monitor active checker every 30 seconds
this.monitorActiveChecker();
setInterval(this.monitorActiveChecker.bind(this), 30 * 1000);
// LRU cache for Redis lookups
if (this.config.server.lruCache === undefined) {
this.debug('LRU cache is disabled');
this.lru = {
set: function () {},
get: function () {},
del: function () {}
};
} else {
this.debug('LRU cache is enabled');
this.lru = lruCache({
max: this.config.server.lruCache.Size,
maxAge: this.config.server.lruCache.ttl * 1000
});
}
}
/*
* This method monitor if there is a active-health-checker. If there is one
* running, it disables passive-health-checks and vice-versa.
*/
Cache.prototype.monitorActiveChecker = function () {
this.redisClient.get('hchecker_ping', function (err, reply) {
var newStatus = ((Math.floor(Date.now() / 1000) - reply) > 30);
if (newStatus !== this.passiveCheck) {
if (newStatus === false) {
this.log("Disabling passive checks (active hchecker detected).");
} else {
this.log("Enabling passive checks (active hchecker stopped).");
}
this.passiveCheck = newStatus;
}
}.bind(this));
};
/*
* This method mark a dead backend in the cache by its backend id
*/
Cache.prototype.markDeadBackend = function (backendInfo) {
var multi;
var frontendKey = 'dead:' + backendInfo.frontend;
if (this.redisMasterClient) {
multi = this.redisMasterClient.multi();
} else {
multi = this.redisClient.multi();
}
// Update the Redis only if passive checks are enabled
if (this.passiveCheck === true) {
multi.sadd(frontendKey, backendInfo.backendId);
multi.expire(frontendKey, this.config.server.deadBackendTTL);
}
// Announce the dead backend on the "dead" channel
multi.publish('dead', backendInfo.frontend + ';' +
backendInfo.backendUrl + ';' + backendInfo.backendId + ';' +
backendInfo.backendLen);
multi.exec();
// A dead backend invalidates the LRU
this.lru.del(backendInfo.frontend);
};
/*
* This method is an helper to get the domain name (without the subdomain)
*/
Cache.prototype.getDomainName = function (hostname) {
var idx = hostname.lastIndexOf('.');
if (idx < 0) {
return hostname;
}
idx = hostname.lastIndexOf('.', idx - 1);
if (idx < 0) {
return hostname;
}
return hostname.substr(idx);
};
/*
* This method picks up a backend randomly and ignore dead ones.
* The parsed URL of the chosen backend is returned.
* The method also decides which HTTP error code to return according to the
* error.
*/
Cache.prototype.getBackendFromHostHeader = function (host, callback) {
if (host === undefined) {
return callback('no host header', 400);
}
if (host === '__ping__') {
return callback('ok', 200);
}
var index = host.indexOf(':');
if (index > 0) {
host = host.slice(0, index).toLowerCase();
}
var readFromCache = function (hostKey, cb) {
// Let's try the LRU cache first
var rows = this.lru.get(hostKey);
if (rows !== undefined) {
return cb(rows);
}
// The entry is not in the LRU cache, let's do a request on Redis
var multi = this.redisClient.multi();
multi.lrange('frontend:' + hostKey, 0, -1);
multi.lrange('frontend:*' + this.getDomainName(hostKey), 0, -1);
multi.lrange('frontend:*', 0, -1);
multi.smembers('dead:' + hostKey);
multi.exec(function (err, rows) {
this.lru.set(hostKey, rows);
cb(rows);
}.bind(this));
}.bind(this);
readFromCache(host, function (rows) {
var backends = rows[0];
if (backends.length === 0) {
// The frontend does not exist, let's try the wildcard entry?
backends = rows[1];
if (backends.length === 0) {
// Final attempt, the catch-all wildcard.
backends = rows[2];
}
}
var deads = rows[3];
if (backends.length === 0) {
return callback('frontend not found', 400);
}
var virtualHost = backends[0];
backends = backends.slice(1); // copy to not modify the lru in place
var index = (function () {
// Pickup a random backend index
var indexes = [];
for (var i = 0; i < backends.length; i += 1) {
if (deads.indexOf(i.toString()) >= 0) {
continue; // Ignoring dead backends
}
indexes.push(i); // Keeping only the valid backend indexes
}
if (indexes.length < 2) {
return (indexes.length === 1) ? indexes[0] : -1;
}
return indexes[Math.floor(Math.random() * indexes.length)];
}());
if (index < 0) {
return callback('Cannot find a valid backend', 502);
}
var backend = url.parse(backends[index]);
backend.id = index; // Store the backend index
backend.frontend = host; // Store the associated frontend
backend.virtualHost = virtualHost; // Store the associated vhost
backend.len = backends.length;
if (backend.hostname === undefined) {
return callback('backend is invalid', 502);
}
backend.port = (backend.port === undefined) ? 80 : parseInt(backend.port, 10);
this.debug('Proxying: ' + host + ' -> ' + backend.hostname + ':' + backend.port);
callback(false, 0, backend);
}.bind(this));
};
module.exports = Cache;