Created
January 15, 2015 07:21
-
-
Save lelandcope/cd76bc9a169863ba8fee to your computer and use it in GitHub Desktop.
This file contains 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
# Node Modules | |
cluster = require 'cluster' | |
os = require 'os' | |
### | |
Vars | |
### | |
stopping = false | |
cpus = os.cpus().length | |
workerCount = process.env.WORKER_COUNT or (if cpus > 1 then cpus else 2) | |
workersToStop = [] | |
### | |
Defines what each worker needs to run | |
### | |
cluster.setupMaster { exec: 'server.coffee' } | |
### | |
Functions | |
### | |
### | |
@function: numWorkers | |
@description: Gets the count of active workers. | |
### | |
numWorkers = -> Object.keys(cluster.workers).length | |
### | |
@function: forkNewWorkers | |
@description: Forks off the workers unless the server is stopping. | |
### | |
forkNewWorkers = -> | |
unless stopping | |
cluster.fork() for i in [0...(workerCount-numWorkers())] | |
### | |
@function: stopWorker | |
@description: Stops a single worker. Gives 60 seconds after disconnect before SIGTERM. | |
### | |
stopWorker = (worker)-> | |
console.log 'stopping', worker.process.pid | |
worker.disconnect() | |
killTimer = setTimeout (-> worker.kill()), 60000 | |
killTimer.unref() | |
### | |
@function: stopNextWorker | |
@description: Tell the next worker queued to restart to disconnect. This will allow the | |
process to finish it's work for 60 seconds before sending SIGTERM. | |
### | |
stopNextWorker = -> | |
i = workersToStop.pop() | |
worker = cluster.workers[i] | |
stopWorker(worker) if worker | |
### | |
@function: stopAllWorkers | |
@description: Stops all the works at once. | |
### | |
stopAllWorkers = -> | |
console.log 'stopping all workers' | |
stopping = true | |
stopWorker(cluster.workers[id]) for id in cluster.workers | |
### | |
Event Listeners | |
### | |
cluster.on 'listening', stopNextWorker | |
cluster.on 'disconnect', forkNewWorkers | |
process.on 'SIGTERM', stopAllWorkers | |
process.on 'SIGHUP', -> | |
console.log 'restarting all workers' | |
workersToStop = Object.keys(cluster.workers) | |
stopNextWorker() | |
### | |
Start | |
### | |
forkNewWorkers() | |
console.log 'server master', process.pid, 'started' | |
### | |
Start | |
### | |
forkNewWorkers() | |
console.log 'server master', process.pid, 'started' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment