1 # -*- encoding: binary -*-
7 # version of Zbatery, currently 0.5.0
12 # runs the Zbatery HttpServer with +app+ and +options+ and does
13 # not return until the server has exited.
14 def run(app, options = {})
15 Rainbows::HttpServer.new(app, options).start.join
19 Rainbows::Const::RACK_DEFAULTS["SERVER_SOFTWARE"] = "Zbatery #{VERSION}"
21 # we don't actually fork workers, but allow using the
22 # {before,after}_fork hooks found in Unicorn/Rainbows!
24 FORK_HOOK = lambda { |_,_| }
28 # override stuff we don't need or can't use portably
32 # master == worker in our case
33 def init_worker_process(worker)
34 after_fork.call(self, worker)
35 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
36 build_app! unless preload_app
37 Rainbows::Response.setup(self.class)
38 Rainbows::MaxBody.setup
39 Rainbows::ProcessClient.const_set(:APP, @app)
41 logger.info "Zbatery #@use worker_connections=#@worker_connections"
45 # we can't/don't need to do the fchmod heartbeat Unicorn/Rainbows! does
52 # this class is only used to avoid breaking Unicorn user switching
58 # only used if no concurrency model is specified
59 def worker_loop(worker)
60 init_worker_process(worker)
62 ret = IO.select(LISTENERS, nil, nil, nil) and
64 io = sock.kgio_tryaccept and process_client(io)
67 rescue Errno::EBADF, TypeError
70 Rainbows::Error.listen_loop(e)
75 def maintain_worker_count; end
76 def init_self_pipe!; end
78 # can't just do a graceful exit if reopening logs fails, so we just
81 logger.info "reopening logs"
82 Unicorn::Util.reopen_logs
83 logger.info "done reopening logs"
85 logger.error "failed reopening logs #{e.message}"
88 def trap_deferred(sig)
93 trap(:INT) { stop(false) }
94 trap(:TERM) { stop(false) }
96 trap(:USR1) { reopen_logs }
97 trap(:USR2) { reexec }
98 trap(:HUP) { reexec; stop }
100 # technically feasible in some cases, just not sanely supportable:
101 %w(TTIN TTOU WINCH).each do |sig|
102 trap(sig) { logger.info "SIG#{sig} is not handled by Zbatery" }
106 ready_pipe.syswrite($$.to_s)
108 self.ready_pipe = nil
110 extend(Rainbows.const_get(@use))
111 worker = Worker.new(0, DeadIO.new)
112 before_fork.call(self, worker)
113 worker_loop(worker) # runs forever
116 def stop(graceful = true)
118 exit!(0) unless graceful
123 hook == Zbatery::FORK_HOOK or
124 logger.warn "calling before_fork without forking"
130 hook == Zbatery::FORK_HOOK or
131 logger.warn "calling after_fork without having forked"
137 Unicorn::Configurator::DEFAULTS[:before_fork] =
138 Unicorn::Configurator::DEFAULTS[:after_fork] = Zbatery::FORK_HOOK