public
Created

Node.js v0.8 Cluster Server

  • Download Gist
server-cluster.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
cluster = require "cluster"
log = require "winston"
config = require "config" # Your configuration goes here.
app = require "./server" # Your real server goes here.
 
numCpus = require("os").cpus().length
workers = {}
 
# Helpers.
shutdown = ->
log.warning "Hard shutdown."
for own pid, worker of workers
log.warning "Killing worker: #{pid}"
worker.process.kill()
 
process.exit 0
 
# Start up the cluster.
if cluster.isMaster
# Fork workers.
cluster.fork() for cpu in [0...numCpus]
 
cluster.on "online", (worker) ->
workers[worker.process.pid] = worker
log.info "[#{worker.id}] Worker #{worker.process.pid} came up."
 
cluster.on "exit", (worker, code, signal) ->
log.warning "[#{worker.id}] Worker #{worker.process.pid} died. Restarting."
delete workers[worker.process.pid]
cluster.fork()
 
# Manually shutdown workers on signals.
process.on signal, shutdown for signal in ["SIGINT", "SIGQUIT", "SIGTERM"]
log.info "Master #{process.pid} started."
 
else
# Worker: Start server and message "up".
app.listen config.app.port, config.app.addr
log.info "Worker #{process.pid} started."

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.