Created
May 31, 2017 01:27
-
-
Save JBreit/d85726a49aa8e3575488cd5af5ce24ff to your computer and use it in GitHub Desktop.
Linux Node JS HTTP Daemon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/** | |
* bin/daemon | |
* A simple Linux HTTP Daemon | |
*/ | |
require('daemon')(); | |
const cluster = require('cluster'); | |
const numCPUs = require('os').cpus().length; | |
/** | |
* Creates a new worker when running as cluster master. | |
* Runs the HTTP server otherwise. | |
*/ | |
const createWorker = () => { | |
if(cluster.isMaster) { | |
let child = cluster.fork(); | |
child.on('exit', (code, signal) => { | |
createWorker(); | |
}); | |
} else { | |
require('../app'); | |
} | |
}; | |
/** | |
* Creates the specified number of workers. | |
* @param {Number} n Number of workers to create. | |
*/ | |
const createWorkers = (n) => { | |
while (n-- > 0) { | |
createWorker(); | |
} | |
}; | |
/** | |
* Kills all workers with the given signal. | |
* Also removes all event listeners from workers before sending the signal | |
* to prevent respawning. | |
* @param {Number} signal | |
*/ | |
const killAllWorkers = (signal) => { | |
Object.keys(cluster.workers).forEach((id) => { | |
let worker = cluster.workers[id]; | |
worker.removeListener(); | |
worker.process.kill(signal); | |
}); | |
}; | |
/** | |
* Restarts the workers | |
*/ | |
process.on('SIGHUP', () => { | |
killAllWorkers('SIGTERM'); | |
createWorkers(numCPUs * 2); | |
}); | |
/** | |
* Gracefully shutdown the workers | |
*/ | |
process.on('SIGTERM', () => { | |
killAllWorkers(); | |
}); | |
createWorkers(numCPUs * 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment