DiskCache fix when using clustering.

This commit is contained in:
softsimon 2020-09-30 00:25:43 +07:00
parent 140fc0c5e1
commit c0ad643d42
No known key found for this signature in database
GPG Key ID: 488D7DCFB5A430D7
2 changed files with 22 additions and 12 deletions

View File

@ -1,5 +1,6 @@
const config = require('../../mempool-config.json');
import * as fs from 'fs'; import * as fs from 'fs';
import * as cluster from 'cluster'; import * as process from 'process';
import memPool from './mempool'; import memPool from './mempool';
import blocks from './blocks'; import blocks from './blocks';
@ -7,15 +8,17 @@ class DiskCache {
static FILE_NAME = './cache.json'; static FILE_NAME = './cache.json';
constructor() { constructor() {
process.on('SIGINT', () => { if (process.env.workerId === '0' || !config.CLUSTER_NUM_CORES || config.CLUSTER_NUM_CORES === 1) {
this.saveCacheToDisk(); process.on('SIGINT', () => {
process.exit(2); this.saveCacheToDisk();
}); process.exit(2);
});
process.on('SIGTERM', () => { process.on('SIGTERM', () => {
this.saveCacheToDisk(); this.saveCacheToDisk();
process.exit(2); process.exit(2);
}); });
}
} }
saveCacheToDisk() { saveCacheToDisk() {

View File

@ -37,12 +37,19 @@ class Server {
const numCPUs = config.CLUSTER_NUM_CORES; const numCPUs = config.CLUSTER_NUM_CORES;
for (let i = 0; i < numCPUs; i++) { for (let i = 0; i < numCPUs; i++) {
cluster.fork(); const env = { workerId: i };
const worker = cluster.fork(env);
worker.process['env'] = env;
} }
cluster.on('exit', (worker, code, signal) => { cluster.on('exit', (worker, code, signal) => {
console.log(`Mempool Worker #${worker.process.pid} died. Restarting in 10 seconds...`, signal || code); const workerId = worker.process['env'].workerId;
setTimeout(() => { cluster.fork(); }, 10000); console.log(`Mempool Worker PID #${worker.process.pid} workerId: ${workerId} died. Restarting in 10 seconds...`, signal || code);
setTimeout(() => {
const env = { workerId: workerId };
const newWorker = cluster.fork(env);
newWorker.process['env'] = env;
}, 10000);
}); });
} else { } else {
this.startServer(true); this.startServer(true);