-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
symbot-hub.js
576 lines (379 loc) · 11.7 KB
/
symbot-hub.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
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
'use strict';
/*
SymBot Hub
Copyright © 2023 - 2024 3CQS.com All Rights Reserved
Licensed under Creative Commons Attribution-NonCommerical-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
*/
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const Common = require(__dirname + '/libs/app/Common.js');
const Hub = require(__dirname + '/libs/app/Hub.js');
const WebServer = require(__dirname + '/libs/webserver/hub');
const packageJson = require(__dirname + '/package.json');
let gotSigInt = false;
const shutdownTimeout = 2000;
const hubConfigFile = 'hub.json';
const workerMap = new Map();
let shareData;
function initSignalHandlers() {
process.on('SIGINT', shutDown);
process.on('SIGTERM', shutDown);
process.on('message', function(msg) {
if (msg == 'shutdown') {
shutDown();
}
});
process.on('uncaughtException', function(err) {
let logData = 'Uncaught Exception: ' + JSON.stringify(err.message) + ' Stack: ' + JSON.stringify(err.stack);
Hub.logger('error', logData);
});
}
function startWorker(instanceData) {
const workerId = Common.uuidv4();
const instanceName = instanceData.name;
const currentDate = new Date().toISOString();
instanceData.dateStart = currentDate;
const worker = new Worker(__filename, {
workerData: {
...instanceData,
workerId
}
});
worker.on('message', processWorkerMessageMain(workerId, instanceName));
worker.on('error', (error) => Hub.logger('error', `Instance for ${instanceName} encountered an error:`, error));
worker.on('exit', processWorkerExitMain(workerId));
worker.once('online', () => {
Hub.logger('info', `Instance: ${instanceName} (Worker ID: ${workerId}, Thread ID: ${worker.threadId}) started`);
// Store worker and instanceData in workerMap
workerMap.set(workerId, {
worker,
instance: instanceData,
threadId: worker.threadId
});
});
}
async function startAllWorkers(configs) {
for (const config of configs) {
const serverIdInUse = [...workerMap.values()].some(worker => worker.instance.server_id === (config.overrides.server_id || null));
if (!serverIdInUse) {
const enabled = config['enabled'];
const startBoot = config['start_boot'];
if (enabled && startBoot) {
startWorker({
//instanceId: config.id,
//instanceName: config.name,
...config
});
await Common.delay(1000);
}
}
else {
Hub.logger('info', `Instance for ${config.name} already running.`);
}
}
}
if (isMainThread) {
start();
} else {
// Worker thread logic
async function processWorkerTask(data) {
try {
const instanceName = data.name;
const prefData = `[WORKER-LOG] [${instanceName}] `;
// Override all console methods to send messages back to the main thread
['log', 'error', 'warn', 'info', 'debug'].forEach((method) => {
console[method] = (...args) => parentPort.postMessage({
type: 'log',
level: method, // 'log', 'error', 'warn', etc.
data: prefData + args.join(' ')
});
});
console.log(`Starting Instance: ${instanceName}`);
const SymBot = require(__dirname + '/symbot.js');
SymBot.setInstanceConfig(Object.assign({},
data,
{ shutdownTimeout }
));
SymBot.setInstanceParentPort(parentPort);
await SymBot.start();
console.log(`Finished Starting Instance: ${instanceName}`);
// Listen for command requests from the main thread
parentPort.on('message', (message) => {
processWorkerTaskMessage(SymBot, message);
});
}
catch (error) {
// Log the error and inform the main thread
console.error(`Error performing task for ${data.name}: ${error.message}`);
}
}
processWorkerTask(workerData);
}
async function processWorkerTaskMessage(SymBot, message) {
// Get worker instance memory usage
if (message.type === 'memory') {
const memoryUsage = process.memoryUsage();
parentPort.postMessage({
type: 'memory',
data: memoryUsage
});
}
// Get worker instance active deals
if (message.type === 'deals_active') {
const dealTracker = await SymBot.DCABot.getDealTracker();
const msg = 'Active Deals: ' + Object.keys(dealTracker).length;
parentPort.postMessage({
type: 'deals_active',
data: msg
});
}
// System pause received for SymBot worker
if (message.type === 'system_pause') {
parentPort.postMessage({
type: 'system_pause_received'
});
const data = message.data;
const isPause = data.pause;
const pauseMessage = data.message;
await SymBot.System.pause(isPause, pauseMessage);
}
// Shutdown received for SymBot worker
if (message.type === 'shutdown') {
parentPort.postMessage({
type: 'shutdown_received'
});
SymBot.shutDown();
}
}
function processWorkerMessageMain(workerId, instanceName) {
// Messsages received from worker
return (message) => {
if (message.type === 'log') {
Hub.logger('info', message.data);
}
else if (message.type === 'memory') {
const workerInfo = workerMap.get(workerId);
if (workerInfo) {
let msgObj = {
'instanceId': workerInfo.instance.id,
'instanceName': instanceName,
'workerId': workerId,
'threadId': workerInfo.threadId,
'memoryUsage': {
'rss': message.data.rss,
'heapTotal': message.data.heapTotal,
'heapUsed': message.data.heapUsed
}
};
// Send memory usage to client
Common.sendSocketMsg({
'room': 'memory',
'type': 'log_memory',
'message': msgObj
});
}
else {
Hub.logger('error', `Information for Worker ID ${workerId} not found.`);
}
}
else if (message.type === 'deals_active') {
//console.log(message.data);
}
else if (message.type === 'system_pause_all') {
// Worker sent system pause for all instances
Hub.logger('info', `Worker ID ${workerId} [${instanceName}] requested system pause for all instances`);
// Relay message to all workers
for (const { worker } of workerMap.values()) {
worker.postMessage({
type: 'system_pause',
data: message.data
});
}
}
else if (message.type === 'shutdown_hub') {
// Worker sent global Hub shutdown
Hub.logger('info', `Worker ID ${workerId} [${instanceName}] requested Hub shutdown`);
shutDown();
}
};
}
function processWorkerExitMain(workerId) {
return (code) => {
Hub.logger('info', `Instance exited with code ${code}, Worker ID: ${workerId}`);
const workerInfo = workerMap.get(workerId);
if (workerInfo) {
const { instance } = workerInfo;
const instanceName = instance.name;
workerMap.delete(workerId);
if (code !== 0) {
Hub.logger('error', `Instance for ${instanceName} exited with code ${code}.`);
// Optionally restart the instance
// startWorker(instance);
}
else {
Hub.logger('info', `Instance for ${instanceName} completed successfully.`);
}
}
else {
Hub.logger('error', `Worker ID ${workerId} does not exist in workerMap.`);
}
};
}
async function start() {
let port;
let configs;
let success = true;
initSignalHandlers();
let hubData = await Common.getConfig(hubConfigFile);
if (hubData.success) {
port = hubData.data.port;
configs = hubData.data.instances;
const password = hubData['data']['password'];
if (password == undefined || password == null || password == '') {
// Set default password
const dataPass = await Common.genPasswordHash({ 'data': 'admin' });
hubData['data']['password'] = dataPass['salt'] + ':' + dataPass['hash'];
await Common.saveConfig(hubConfigFile, hubData.data);
}
// Create initial Hub instance
if (configs.length < 1) {
const instanceObj = {
"name": "Instance-1",
"app_config": "app.json",
"bot_config": "bot.json",
"server_config": "server.json",
"server_id": "",
"mongo_db_url": "",
"web_server_port": null,
"enabled": true,
"start_boot": true,
"overrides": { },
"updated": new Date().toISOString()
}
configs.push(instanceObj);
}
}
else {
success = false;
Hub.logger('error', 'Hub Configuration Error: ' + hubData.data);
}
if (success) {
shareData = {
'appData': {
'name': packageJson.description + ' Hub',
'version': packageJson.version,
'password': hubData['data']['password'],
'path_root': __dirname,
'web_server_ports': undefined,
'web_socket_path': 'wsHub_',
'hub_config': hubConfigFile,
'shutdown_timeout': shutdownTimeout,
'sig_int': false,
'started': new Date()
},
'Common': Common,
'WebServer': WebServer,
'Hub': Hub,
'startWorker': startWorker,
'workerMap': workerMap
};
Common.init(shareData);
WebServer.init(shareData);
Hub.init(shareData);
let processData = await Hub.processConfig(configs);
if (!processData.success) {
success = false;
Hub.logger('error', JSON.stringify(processData.error));
}
else {
await Hub.setProxyPorts(processData['web_server_ports']);
let foundMissing = false;
for (let i = 0; i < configs.length; i++) {
const config = configs[i];
let id = config['id'];
if (id == undefined || id == null || id == '') {
foundMissing = true;
config['id'] = Common.uuidv4();
}
}
// Update data if found missing id's
if (foundMissing) {
processData = null;
processData = await Hub.processConfig(configs);
configs = processData.configs;
hubData['data']['instances'] = configs;
await Common.saveConfig(hubConfigFile, hubData.data);
}
configs = processData.configs;
}
}
if (!success) {
Hub.logger('error', 'Aborting due to configuration errors.');
process.exit(1);
}
await WebServer.start(port);
startAllWorkers(configs);
setInterval(() => logMemoryUsage(), 5000);
}
async function logMemoryUsage() {
for (const { worker } of workerMap.values()) {
worker.postMessage({
type: 'memory'
});
}
}
async function shutDown() {
// Perform any post-shutdown processes here
if (!gotSigInt) {
gotSigInt = true;
Hub.logger('info', 'Received kill signal. Shutting down gracefully.');
Hub.logger('info', 'Cleaning up instances...');
const terminationPromises = [];
// Set timer to force shutdown if cleanup takes too long
let timeOutShutdown = setTimeout(() => {
Hub.logger('info', `Cleanup timed out. Forcing shutdown.`);
process.exit(1);
}, (shutdownTimeout + 20000));
for (const [workerId, { worker, instance }] of workerMap.entries()) {
const dateStart = instance.dateStart;
const upTime = Common.timeDiff(new Date(dateStart), new Date());
// Create a promise to track the worker shutdown process
const shutdownPromise = new Promise((resolve, reject) => {
// Wait for the worker to handle the shutdown
worker.on('message', async (message) => {
if (message.type === 'shutdown_received') {
// Wait additional short delay to ensure worker shutdown gracefully
await Common.delay(shutdownTimeout + 3000);
// Once shutdown is complete, terminate the worker
try {
await worker.terminate();
Hub.logger('info', `Worker ${workerId} terminated after ${upTime}.`);
resolve();
}
catch (err) {
Hub.logger('error', `Error terminating instance: ${err}`);
reject(err);
}
}
});
// Send a "shutdown" message to the worker
worker.postMessage({
type: 'shutdown'
});
});
terminationPromises.push(shutdownPromise);
}
// Wait for all workers to finish before starting the shutdown timeout
try {
await Promise.all(terminationPromises);
clearTimeout(timeOutShutdown);
Hub.logger('info', 'All workers have been terminated. Proceeding with shutdown.');
// Start shutdown timeout after all workers are processed
setTimeout(() => {
process.exit(1);
}, (shutdownTimeout + 3000));
}
catch (err) {
Hub.logger('error', `Error during shutdown: ${err}`);
}
}
}