-
Notifications
You must be signed in to change notification settings - Fork 2
/
runner.ts
300 lines (262 loc) · 7.82 KB
/
runner.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
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
import * as utils from './lib/utils';
/* Prometheus client for pushing metrics to the pushgateway */
// import os from 'os';
// import * as promClient from 'prom-client';
// import gcStats from 'prometheus-gc-stats';
// import { nanoid } from 'nanoid';
// import * as url from 'url';
import { Worker } from './lib/worker';
import HawkCatcher from '@hawk.so/nodejs';
import * as dotenv from 'dotenv';
dotenv.config();
if (process.env.HAWK_CATCHER_TOKEN) {
HawkCatcher.init(process.env.HAWK_CATCHER_TOKEN);
}
type WorkerConstructor = new () => Worker;
const BEGINNING_OF_ARGS = 2;
/**
* Get worker name(s) from command line arguments
*
* @example ts-node runner.ts hawk-worker-javascript
* @example ts-node runner.ts hawk-worker-javascript hawk-worker-nodejs
*/
const workerNames = process.argv.slice(BEGINNING_OF_ARGS);
/**
* Workers dispatcher.
* Load, run and finish workers.
*/
class WorkerRunner {
/**
* Dispatched workers list
*/
private workers: Worker[] = [];
// private gateway?: promClient.Pushgateway;
/**
* number returned by setInterval() of metrics push function
*/
private pushIntervalNumber?: ReturnType<typeof setInterval>;
/**
* Create runner instance
*/
constructor() {
/**
* 1. Load workers packages
* 2. Create instances (start)
* 3. Observe process kill and errors to correctly finish workers
*/
this.loadPackages()
.then((workerConstructors) => {
this.constructWorkers(workerConstructors);
})
// .then(() => {
// try {
// this.startMetrics();
// } catch (e) {
// HawkCatcher.send(e);
// console.error(`Metrics not started: ${e}`);
// }
//
// return Promise.resolve();
// })
.then(() => {
return this.startWorkers();
})
.then(() => {
this.observeProcess();
})
.catch((loadingError) => {
HawkCatcher.send(loadingError);
console.error('Worker loading error: ', loadingError);
});
}
/**
* Run metrics exporter
*/
// private startMetrics(): void {
// if (!process.env.PROMETHEUS_PUSHGATEWAY_URL) {
// return;
// }
//
// const PUSH_INTERVAL = parseInt(process.env.PROMETHEUS_PUSHGATEWAY_INTERVAL);
//
// if (isNaN(PUSH_INTERVAL)) {
// throw new Error('PROMETHEUS_PUSHGATEWAY_INTERVAL is invalid or not set');
// }
//
// const collectDefaultMetrics = promClient.collectDefaultMetrics;
// const Registry = promClient.Registry;
//
// const register = new Registry();
// const startGcStats = gcStats(register);
//
// const hostname = os.hostname();
//
// const ID_SIZE = 5;
// const id = nanoid(ID_SIZE);
//
// // eslint-disable-next-line node/no-deprecated-api
// const instance = url.parse(process.env.PROMETHEUS_PUSHGATEWAY_URL).host;
//
// // Initialize metrics for workers
// this.workers.forEach((worker) => {
// // worker.initMetrics();
// worker.getMetrics().forEach((metric: promClient.Counter<string>) => register.registerMetric(metric));
// });
//
// collectDefaultMetrics({ register });
// startGcStats();
//
// this.gateway = new promClient.Pushgateway(process.env.PROMETHEUS_PUSHGATEWAY_URL, null, register);
//
// console.log(`Start pushing metrics to ${process.env.PROMETHEUS_PUSHGATEWAY_URL}`);
//
// // Pushing metrics to the pushgateway every PUSH_INTERVAL
// this.pushIntervalNumber = setInterval(() => {
// this.workers.forEach((worker) => {
// if (!this.gateway || !instance) {
// return;
// }
// // Use pushAdd not to overwrite previous metrics
// this.gateway.pushAdd({
// jobName: 'workers',
// groupings: {
// worker: worker.type.replace('/', '_'),
// host: hostname,
// id,
// },
// }, (err?: Error) => {
// if (err) {
// HawkCatcher.send(err);
// console.log(`Error of pushing metrics to gateway: ${err}`);
// }
// });
// });
// }, PUSH_INTERVAL);
// }
/**
* Dynamically loads workers through the yarn workspaces
*/
private async loadPackages(): Promise<WorkerConstructor[]> {
return workerNames.reduce(async (accumulator, packageName) => {
const workers = await accumulator;
const workerClass = (await import(`${packageName}/src`)) as { default: WorkerConstructor };
workers.push(workerClass.default);
return workers;
}, Promise.resolve([] as WorkerConstructor[]));
}
/**
* Starts worker classes
*
* @param workerConstructors - worker constructors to create new instances
*/
private constructWorkers(workerConstructors: WorkerConstructor[]): void {
return workerConstructors.forEach((WorkerClass) => {
this.workers.push(new WorkerClass());
});
}
/**
* Run workers
*/
private async startWorkers(): Promise<void[]> {
return Promise.all(
this.workers.map(async (worker) => {
try {
await worker.start();
console.log(
'\x1b[32m%s\x1b[0m',
`\n\n( ಠ ͜ʖರೃ) Worker ${worker.constructor.name} started with pid ${process.pid} \n`
);
utils.sendReport(worker.constructor.name + ' started');
} catch (startingError) {
this.exceptionHandler(startingError);
utils.sendReport(worker.constructor.name + ' failed to start');
await this.stopWorker(worker);
}
})
);
}
/**
* - Error on worker starting
* - Uncaught Exception at Runner work
* - Unhandled Promise Rejection at Runner work
*
* @param error - error to handle
*/
private exceptionHandler(error: Error): void {
HawkCatcher.send(error);
console.log(
'\x1b[41m%s\x1b[0m',
'\n\n (▀̿Ĺ̯▀̿ ̿) Hawk Workers Runner: an error has been occurred: \n'
);
console.log(error);
if (error === undefined) {
console.trace();
}
console.log('\n\n');
const workerConstructorNames = this.workers.map(worker => worker.constructor.name).join(', ');
utils.sendReport(`${workerConstructorNames}: Error has been occurred: ${error ? error.message : 'unknown'}`);
}
/**
* Finish workers when something happened with the process
*/
private observeProcess(): void {
process.on('SIGINT', async () => {
console.log('SIGINT');
await this.finishAll();
process.exit(0);
});
process.on('SIGTERM', async () => {
console.log('SIGTERM');
await this.finishAll();
process.exit();
});
process.on('exit', () => {
console.log('exitting...');
process.kill(process.pid, 'SIGTERM');
});
(process as NodeJS.EventEmitter).on(
'uncaughtException',
async (event) => {
this.exceptionHandler(event as Error);
await this.finishAll();
process.exit();
}
);
process.on('unhandledRejection', async (event) => {
this.exceptionHandler(event as Error);
await this.finishAll();
process.exit();
});
}
/**
* Stops one worker
*
* @param worker - worker instance to stop
*/
private async stopWorker(worker: Worker): Promise<void> {
try {
// stop pushing metrics
clearInterval(this.pushIntervalNumber);
await worker.finish();
console.log(
'\x1b[33m%s\x1b[0m',
`\n\n Worker ${worker.constructor.name} stopped \n`
);
} catch (finishingError) {
HawkCatcher.send(finishingError);
console.error('Error while finishing Worker: ', finishingError);
}
}
/**
* Stops all workers
*/
private async finishAll(): Promise<void[]> {
return Promise.all(
this.workers.map(async (worker) => {
return this.stopWorker(worker);
})
);
}
}
// eslint-disable-next-line no-new
new WorkerRunner();