daemon.coffee | |
|---|---|
| A | {EventEmitter} = require "events"
HttpServer = require "./http_server"
DnsServer = require "./dns_server"
fs = require "fs"
path = require "path"
module.exports = class Daemon extends EventEmitter |
| Create a new | constructor: (@configuration) -> |
|
| @httpServer = new HttpServer @configuration
@dnsServer = new DnsServer @configuration |
| The daemon stops in response to | process.on "SIGINT", @stop
process.on "SIGTERM", @stop
process.on "SIGQUIT", @stop |
| Watch for changes to the host root directory once the daemon has
started. When the directory changes and the | hostRoot = @configuration.hostRoot
@restartFilename = path.join hostRoot, "restart.txt"
@on "start", => @watcher = fs.watch hostRoot, persistent: false, @hostRootChanged
@on "close", => @watcher?.close()
hostRootChanged: =>
path.exists @restartFilename, (exists) =>
@restart() if exists |
| Remove the | restart: ->
fs.unlink @restartFilename, (err) =>
@emit "restart" unless err |
| Start the daemon if it's stopped. The process goes like this:
| start: ->
return if @starting or @started
@starting = true
startServer = (server, port, callback) -> process.nextTick ->
try
server.on 'error', callback
server.once 'listening', ->
server.removeListener 'error', callback
callback()
server.listen port
catch err
callback err
pass = =>
@starting = false
@started = true
@emit "start"
flunk = (err) =>
@starting = false
try @httpServer.close()
try @dnsServer.close()
@emit "error", err
{httpPort, dnsPort} = @configuration
startServer @httpServer, httpPort, (err) =>
if err then flunk err
else startServer @dnsServer, dnsPort, (err) =>
if err then flunk err
else pass() |
| Stop the daemon if it's started. This means calling | stop: =>
return if @stopping or !@started
@stopping = true
stopServer = (server, callback) -> process.nextTick ->
try
close = ->
server.removeListener "close", close
callback null
server.on "close", close
server.close()
catch err
callback err
stopServer @httpServer, =>
stopServer @dnsServer, =>
@stopping = false
@started = false
@emit "stop"
|