* Shutdown all worker processes. * From https://medium.com/@gaurav.lahoti/graceful-shutdown-of-node-js-workers-dd58bbff9e30 * @param signal Signal to send to the workers
(signal)
| 67 | * @param signal Signal to send to the workers |
| 68 | */ |
| 69 | function shutdownWorkers (signal) { |
| 70 | return new Promise((resolve) => { |
| 71 | if (!cluster.isMaster) { return resolve() } |
| 72 | const wIds = Object.keys(cluster.workers) |
| 73 | if (wIds.length === 0) { return resolve() } |
| 74 | // Filter all the valid workers |
| 75 | const workers = wIds.map(id => cluster.workers[id]).filter(v => v) |
| 76 | let workersAlive = 0 |
| 77 | let funcRun = 0 |
| 78 | // Count the number of alive workers and keep looping until the number is zero. |
| 79 | const fn = () => { |
| 80 | ++funcRun |
| 81 | workersAlive = 0 |
| 82 | workers.forEach(worker => { |
| 83 | if (!worker.isDead()) { |
| 84 | ++workersAlive |
| 85 | if (funcRun === 1) { |
| 86 | // On the first execution of the function, send the received signal to all the workers |
| 87 | // https://github.com/nodejs/node-v0.x-archive/issues/6042#issuecomment-168677045 |
| 88 | worker.process.kill(signal) |
| 89 | } |
| 90 | } |
| 91 | }) |
| 92 | console.log(workersAlive + ' workers alive') |
| 93 | if (workersAlive === 0) { |
| 94 | // Clear the interval when all workers are dead |
| 95 | clearInterval(interval) |
| 96 | return resolve() |
| 97 | } |
| 98 | } |
| 99 | const interval = setInterval(fn, 1000) |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | // Startup code |
| 104 | // NodeJS is single threaded, how many CPUs/Threads do we want to use? |
no outgoing calls
no test coverage detected
searching dependent graphs…