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

@ -60,9 +60,12 @@ const app = express();
// setup CORS-middleware
const corsOptions = {
methods: ['GET'],
methods: [ 'GET' ],
optionsSuccessStatus: 200,
};
let cronInitialized = false;
app.use(cors(corsOptions));
app.use(favicon(path.join(__dirname + '/..', 'public', 'favicon.ico')));
@ -128,8 +131,8 @@ if (process.env.NODE_ENV === config.test.unit.env || process.env.NODE_ENV === co
const mongoPortAndDB = mongoUri.replace('mongodb://localhost:', '').split('/');
exec(
__dirname + '/apib/dredd/populate-data.sh'
.concat(' -p ').concat(mongoPortAndDB[0])
.concat(' -d ').concat(mongoPortAndDB[1]), (err, stdout, stderr) => {
.concat(' -p ').concat(mongoPortAndDB[ 0 ])
.concat(' -d ').concat(mongoPortAndDB[ 1 ]), (err, stdout, stderr) => {
if (err) {
error(err.message);
} else {
@ -146,25 +149,40 @@ if (process.env.NODE_ENV === config.test.unit.env || process.env.NODE_ENV === co
});
} else {
mongoose.connect(config.database.uri + config.database.db, {useNewUrlParser: true}).then((db) => {
let cronWorkerPID;
if (cluster.isMaster) {
// Fork workers
for (let i = 0; i < numWorkers; i++) {
cluster.fork();
if (i === 0) {
const spawnedWorker = cluster.fork({START_CRON: true});
cronWorkerPID = spawnedWorker.process.pid;
} else {
cluster.fork();
}
}
logger(`Master ${process.pid} is running. Forking ${numWorkers} workers`);
// Check if worker id is died
cluster.on('exit', (worker, code, signal) => {
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 {
app.listen(config.port, (err) => {
if (err !== undefined) {
if (err) {
error(`Error on startup ${err}`);
} else {
logger(`Worker ${process.pid} started. Listening on port ${config.port}`);
signatureCronJob.start();
backupCronJob.start();
if (process.env.START_CRON) {
logger(`Attaching cronJobs to cluster worker ${process.pid}`);
signatureCronJob.start();
backupCronJob.start();
}
}
});
}