Skip to content

Add graceful stop #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: review-branch
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions cluster.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

const cluster = require('cluster');
const { watch } = require('fs');
const { watch, fstat, existsSync } = require('fs');
const path = require('path');

const codeDir = process.env.CODE_DIR || path.join(__dirname, '/');
Expand All @@ -13,6 +13,8 @@ const WORKER_CNT = config.workerVal;
const activeWorkers = [];

const RESTART_FILE = path.join(codeDir, 'tmp/restart.txt');
const STOP_FILE = path.join(codeDir, 'tmp/stop.txt');
let stopCalled = false;

const forceKill = (worker) => {
if (!worker.isDead()) {
Expand Down Expand Up @@ -52,7 +54,15 @@ if (cluster.isMaster) {
logger.info(
`worker ${worker.process.pid} died with signal ${signal} code ${code}`
);
if (activeWorkers.length == 0) spawnNewWorkers();
if (stopCalled) {
if (activeWorkers.length == 0) {
logger.info(
`All workers stopped. Exiting master process ${process.pid}`
);
process.exit(0);
}
}
if (activeWorkers.length == 0 && !stopCalled) spawnNewWorkers();
});

spawnNewWorkers();
Expand All @@ -65,6 +75,18 @@ if (cluster.isMaster) {
spawnNewWorkers();
}
});
if (existsSync(STOP_FILE)) {
watch(STOP_FILE, () => {
logger.info(`Stopping cluster gracefully`)
stopCalled = true;
if (Date.now() > currTime) {
currTime = Date.now();
disconnectOldWorkers();
}
});
} else {
logger.info('Graceful stop is not enabled')
}
} else {
const proxy = new Proxy();
cluster.worker.on('disconnect', () => {
Expand Down
Empty file added tmp/stop.txt
Empty file.