1 # -*- encoding: binary -*-
4 class Rainbows::HttpServer < Unicorn::HttpServer
5 attr_accessor :copy_stream
6 attr_accessor :worker_connections
7 attr_accessor :keepalive_timeout
8 attr_accessor :client_header_buffer_size
9 attr_accessor :client_max_body_size
13 Rainbows.server.instance_eval(&block)
16 def initialize(app, options)
17 Rainbows.server = self
18 @logger = Unicorn::Configurator::DEFAULTS[:logger]
20 defined?(@use) or self.use = Rainbows::Base
21 @worker_connections ||= @use == :Base ? 1 : 50
24 # Add one second to the timeout since our fchmod heartbeat is less
25 # precise (and must be more conservative) than Unicorn does. We
26 # handle many clients per process and can't chmod on every
27 # connection we accept without wasting cycles. That added to the
28 # fact that we let clients keep idle connections open for long
29 # periods of time means we have to chmod at a fixed interval.
36 @worker_connections = 1 if @use == :Base
39 def worker_loop(worker)
40 Rainbows.forked = true
41 orig = method(:worker_loop)
42 extend(Rainbows.const_get(@use))
43 m = method(:worker_loop)
44 orig == m ? super(worker) : worker_loop(worker)
47 def spawn_missing_workers
48 # 5: std{in,out,err} + heartbeat FD + per-process listener
49 nofile = 5 + @worker_connections + LISTENERS.size
50 trysetrlimit(:RLIMIT_NOFILE, nofile)
53 when :ThreadSpawn, :ThreadPool, :ActorSpawn,
54 :CoolioThreadSpawn, :RevThreadSpawn,
55 :XEpollThreadSpawn, :WriterThreadPool, :WriterThreadSpawn
56 trysetrlimit(:RLIMIT_NPROC, @worker_connections + LISTENERS.size + 1)
57 when :XEpollThreadPool, :CoolioThreadPool
58 trysetrlimit(:RLIMIT_NPROC, Rainbows::O[:pool_size] + LISTENERS.size + 1)
63 def trysetrlimit(resource, want)
64 var = Process.const_get(resource)
65 cur, max = Process.getrlimit(var)
66 cur <= want and Process.setrlimit(var, cur = max > want ? max : want)
68 @logger.warn "#{resource} rlim_cur=#{cur} is barely enough"
69 @logger.warn "#{svc} may monopolize resources dictated by #{resource}" \
70 " and leave none for your app"
73 @logger.error e.message
74 @logger.error "#{resource} needs to be increased to >=#{want} before" \
83 @use = mod.to_s.split(/::/)[-1].to_sym
85 'rainbows.model' => @use,
86 'rack.multithread' => !!(mod.to_s =~ /Thread/),
87 'rainbows.autochunk' => [:Coolio,:Rev,:Epoll,:XEpoll,
88 :EventMachine,:NeverBlock].include?(@use),
90 Rainbows::Const::RACK_DEFAULTS.update(new_defaults)
93 def keepalive_requests=(nr)
94 Unicorn::HttpRequest.keepalive_requests = nr
97 def keepalive_requests
98 Unicorn::HttpRequest.keepalive_requests