Attach cron job to single cluster worker & ensure it is reassigned on crash (CC-64)

pull/46/head
HardiReady 2018-10-10 23:16:29 +02:00
parent 16fa17a2d4
commit 4a7b1d60d5
1 changed files with 25 additions and 7 deletions

View File

@ -63,6 +63,9 @@ const corsOptions = {
methods: [ 'GET' ], methods: [ 'GET' ],
optionsSuccessStatus: 200, optionsSuccessStatus: 200,
}; };
let cronInitialized = false;
app.use(cors(corsOptions)); app.use(cors(corsOptions));
app.use(favicon(path.join(__dirname + '/..', 'public', 'favicon.ico'))); app.use(favicon(path.join(__dirname + '/..', 'public', 'favicon.ico')));
@ -146,26 +149,41 @@ if (process.env.NODE_ENV === config.test.unit.env || process.env.NODE_ENV === co
}); });
} else { } else {
mongoose.connect(config.database.uri + config.database.db, {useNewUrlParser: true}).then((db) => { mongoose.connect(config.database.uri + config.database.db, {useNewUrlParser: true}).then((db) => {
let cronWorkerPID;
if (cluster.isMaster) { if (cluster.isMaster) {
// Fork workers // Fork workers
for (let i = 0; i < numWorkers; i++) { for (let i = 0; i < numWorkers; i++) {
if (i === 0) {
const spawnedWorker = cluster.fork({START_CRON: true});
cronWorkerPID = spawnedWorker.process.pid;
} else {
cluster.fork(); cluster.fork();
} }
}
logger(`Master ${process.pid} is running. Forking ${numWorkers} workers`); logger(`Master ${process.pid} is running. Forking ${numWorkers} workers`);
// Check if worker id is died // Check if worker id is died
cluster.on('exit', (worker, code, signal) => { cluster.on('exit', (worker, code, signal) => {
logger(`worker ${worker.process.pid} died`); logger(`worker ${worker.process.pid} died`);
if (worker.process.pid === cronWorkerPID) {
const spawnedWorker = cluster.fork({START_CRON: true});
cronWorkerPID = spawnedWorker.process.pid;
} else {
cluster.fork();
}
}); });
} else { } else {
app.listen(config.port, (err) => { app.listen(config.port, (err) => {
if (err !== undefined) { if (err) {
error(`Error on startup ${err}`); error(`Error on startup ${err}`);
} else { } else {
logger(`Worker ${process.pid} started. Listening on port ${config.port}`); logger(`Worker ${process.pid} started. Listening on port ${config.port}`);
if (process.env.START_CRON) {
logger(`Attaching cronJobs to cluster worker ${process.pid}`);
signatureCronJob.start(); signatureCronJob.start();
backupCronJob.start(); backupCronJob.start();
} }
}
}); });
} }
}); });