-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathlb.ts
223 lines (198 loc) · 6.28 KB
/
lb.ts
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
import express from 'express';
import axios from 'axios';
import { IncomingMessage, Server, ServerResponse } from 'http';
import { BEServerHealth, SchedulingAlgorithm } from './enum';
import { BackendServerDetails, IBackendServerDetails } from './be_details';
export interface ILBServer {
server: Server<typeof IncomingMessage, typeof ServerResponse>;
algo: SchedulingAlgorithm;
backendServers: IBackendServerDetails[];
healthCheckPeriodInSeconds: number;
/**
* Returns the HTTP Server corresponding to the Express app.
*
* @returns {Server<typeof IncomingMessage, typeof ServerResponse>}
*/
getServer(): Server<typeof IncomingMessage, typeof ServerResponse>;
/**
* Closes the express server and returns with the server object.
*
* @returns {Server<typeof IncomingMessage, typeof ServerResponse>}
*/
close(): Server<typeof IncomingMessage, typeof ServerResponse>;
/**
* Start a separate asynchronous health check.
*/
startHealthCheck(): void;
/**
* Stops the Health check
*/
stopHealthCheck(): void;
/**
* This function performs the health check for all BE servers.
*
* @returns {Promise<void>}
*/
performHealthCheck(): Promise<void>;
}
export class LBServer implements ILBServer {
private i = 0;
private port;
algo;
private backendServerUrls = [
'http://localhost:8080/',
'http://localhost:8081/',
'http://localhost:8082/'
];
server;
backendServers;
healthCheckPeriodInSeconds;
private healthCheckTimer!: NodeJS.Timer;
private healthyServers: Array<IBackendServerDetails>;
private controller;
constructor(
port: number = 80,
algo: SchedulingAlgorithm,
healthCheckPeriodInSeconds: number
) {
// Initialize parameters
this.healthyServers = new Array<BackendServerDetails>();
this.backendServers = new Array<BackendServerDetails>();
this.controller = new AbortController();
this.healthCheckPeriodInSeconds = healthCheckPeriodInSeconds;
this.backendServerUrls.forEach((url) => {
const beServer = new BackendServerDetails(url, this.controller);
this.backendServers.push(beServer);
});
this.algo = algo;
this.port = port;
const app = express();
// Attach parsers
app.use(express.text());
app.use(express.json());
app.get('/', async (req, res) => {
const backendServer = this.getBackendServer();
if (this.healthyServers.length === 0) {
res.sendStatus(500);
} else {
this.i = (this.i + 1) % this.healthyServers.length;
try {
const response = await axios.get(backendServer.url);
backendServer.incrementCount();
res.status(200).send(response.data);
} catch (err) {
console.error(err);
res.sendStatus(500);
}
}
});
this.server = app
.listen(this.port, () => {
console.log('LB Server listening on port ' + this.port);
})
.on('error', (err) => {
if (
err.message.toString().indexOf('EADDRINUSE') ||
err.message.toString().indexOf('EACCES')
) {
this.port = 4000;
this.server = app.listen(this.port, () => {
console.log('LB Server listening on port ' + this.port);
});
}
});
this.startHealthCheck();
}
public getServer(): Server<typeof IncomingMessage, typeof ServerResponse> {
return this.server;
}
public close(): Server<typeof IncomingMessage, typeof ServerResponse> {
this.stopHealthCheck();
this.controller.abort();
const server = this.server.close();
console.log('Closed LB Server');
this.printBackendStats();
return server;
}
/**
* This is the scheduling function that returns the Backend Server details
* based on the scheduling algorithm for sending incoming requests.
*
* @private
* @returns {IBackendServerDetails}
*/
private getBackendServer(): IBackendServerDetails {
switch (this.algo) {
case SchedulingAlgorithm.ROUND_ROBIN:
return this.healthyServers[this.i % this.healthyServers.length];
}
}
public startHealthCheck(): void {
this.healthCheckTimer = setInterval(async () => {
await this.performHealthCheck();
}, this.healthCheckPeriodInSeconds * 1000);
}
public async performHealthCheck(): Promise<void> {
// Create Tasks for async operations
const tasks = [];
for (let i = 0; i < this.backendServers.length; i++) {
tasks.push(this.backendServers[i].ping());
}
// Wait for tasks to complete
await Promise.all(tasks).then((values) => {
for (let i = 0; i < values.length; i++) {
const oldStatus = this.backendServers[i].getStatus();
// If BE Server is live
if (values[i] === 200) {
// Update BE Server status if required
if (oldStatus !== BEServerHealth.HEALTHY) {
this.backendServers[i].setStatus(BEServerHealth.HEALTHY);
}
// Add to the list of healthy servers if required
if (
this.healthyServers
.map((server) => server.url)
.indexOf(this.backendServers[i].url) < 0
) {
this.backendServers[i].resetCount();
this.healthyServers.push(this.backendServers[i]);
}
} else {
// Update BE Server status if required
if (oldStatus !== BEServerHealth.UNHEALTHY) {
this.backendServers[i].setStatus(BEServerHealth.UNHEALTHY);
}
// Remove from the list of healthy servers if present
const index = this.healthyServers
.map((server) => server.url)
.indexOf(this.backendServers[i].url);
if (index >= 0) {
this.healthyServers.splice(index, 1);
}
}
}
});
console.log(
`Completed Health Check. Total backend servers online: ${this.healthyServers.length}`
);
}
public stopHealthCheck(): void {
clearInterval(this.healthCheckTimer);
}
/**
* Log the details corresponding to BE Servers.
*
* @private
*/
private printBackendStats(): void {
const status: [string, number, string][] = [];
this.backendServers.forEach((server) => {
status.push([
server.url,
server.count,
BEServerHealth[server.getStatus()]
]);
});
console.log(status);
}
}