writer_thread_spawn: worker_connections limits thread spawned
[rainbows.git] / lib / rainbows.rb
blobdac68c21374403bcfe34480d00dc6e1f155e33f8
1 # -*- encoding: binary -*-
2 require 'unicorn'
3 require 'rainbows/error'
4 require 'fcntl'
6 module Rainbows
8   # global vars because class/instance variables are confusing me :<
9   # this struct is only accessed inside workers and thus private to each
10   # G.cur may not be used in the network concurrency model
11   class State < Struct.new(:alive,:m,:cur,:kato,:server,:tmp,:expire)
12     def tick
13       tmp.chmod(self.m = m == 0 ? 1 : 0)
14       exit!(2) if expire && Time.now >= expire
15       alive && server.master_pid == Process.ppid or quit!
16     end
18     def quit!
19       self.alive = false
20       self.expire ||= Time.now + (server.timeout * 2.0)
21       server.class.const_get(:LISTENERS).map! { |s| s.close rescue nil }
22       false
23     end
24   end
25   # :stopdoc:
26   G = State.new(true, 0, 0, 5)
27   O = {}
28   # :startdoc:
30   require 'rainbows/const'
31   require 'rainbows/http_server'
32   require 'rainbows/http_response'
33   require 'rainbows/base'
34   require 'rainbows/tee_input'
35   autoload :AppPool, 'rainbows/app_pool'
36   autoload :DevFdResponse, 'rainbows/dev_fd_response'
37   autoload :MaxBody, 'rainbows/max_body'
38   autoload :QueuePool, 'rainbows/queue_pool'
40   class << self
42     # Sleeps the current application dispatch.  This will pick the
43     # optimal method to sleep depending on the concurrency model chosen
44     # (which may still suck and block the entire process).  Using this
45     # with the basic :Rev or :EventMachine models is not recommended.
46     # This should be used within your Rack application.
47     def sleep(nr)
48       case G.server.use
49       when :FiberPool, :FiberSpawn
50         Rainbows::Fiber.sleep(nr)
51       when :RevFiberSpawn
52         Rainbows::Fiber::Rev::Sleeper.new(nr)
53       when :Revactor
54         Actor.sleep(nr)
55       else
56         Kernel.sleep(nr)
57       end
58     end
60     # runs the Rainbows! HttpServer with +app+ and +options+ and does
61     # not return until the server has exited.
62     def run(app, options = {})
63       HttpServer.new(app, options).start.join
64     end
66     # returns nil if accept fails
67     def sync_accept(sock)
68       rv = sock.accept
69       rv.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
70       rv
71     rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EINTR
72     end
74     # returns nil if accept fails
75     def accept(sock)
76       rv = sock.accept_nonblock
77       rv.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
78       rv
79     rescue Errno::EAGAIN, Errno::ECONNABORTED
80     end
82     # returns a string representing the address of the given client +io+
83     # For local UNIX domain sockets, this will return a string referred
84     # to by the (non-frozen) Unicorn::HttpRequest::LOCALHOST constant.
85     def addr(io)
86       io.respond_to?(:peeraddr) ?
87                         io.peeraddr.last : Unicorn::HttpRequest::LOCALHOST
88     end
90     # the default max body size is 1 megabyte (1024 * 1024 bytes)
91     @@max_bytes = 1024 * 1024
93     def max_bytes; @@max_bytes; end
94     def max_bytes=(nr); @@max_bytes = nr; end
95   end
97   # configures \Rainbows! with a given concurrency model to +use+ and
98   # a +worker_connections+ upper-bound.  This method may be called
99   # inside a Unicorn/Rainbows configuration file:
100   #
101   #   Rainbows! do
102   #     use :Revactor # this may also be :ThreadSpawn or :ThreadPool
103   #     worker_connections 400
104   #     keepalive_timeout 0 # zero disables keepalives entirely
105   #     client_max_body_size 5*1024*1024 # 5 megabytes
106   #   end
107   #
108   #   # the rest of the Unicorn configuration
109   #   worker_processes 8
110   #
111   # See the documentation for the respective Revactor, ThreadSpawn,
112   # and ThreadPool classes for descriptions and recommendations for
113   # each of them.  The total number of clients we're able to serve is
114   # +worker_processes+ * +worker_connections+, so in the above example
115   # we can serve 8 * 400 = 3200 clients concurrently.
116   #
117   # The default is +keepalive_timeout+ is 5 seconds, which should be
118   # enough under most conditions for browsers to render the page and
119   # start retrieving extra elements for.  Increasing this beyond 5
120   # seconds is not recommended.  Zero disables keepalive entirely
121   # (but pipelining fully-formed requests is still works).
122   #
123   # The default +client_max_body_size+ is 1 megabyte (1024 * 1024 bytes),
124   # setting this to +nil+ will disable body size checks and allow any
125   # size to be specified.
126   def Rainbows!(&block)
127     block_given? or raise ArgumentError, "Rainbows! requires a block"
128     HttpServer.setup(block)
129   end
131   # :stopdoc:
132   # maps models to default worker counts, default worker count numbers are
133   # pretty arbitrary and tuning them to your application and hardware is
134   # highly recommended
135   MODEL_WORKER_CONNECTIONS = {
136     :Base => 1, # this one can't change
137     :WriterThreadPool => 20,
138     :WriterThreadSpawn => 20,
139     :Revactor => 50,
140     :ThreadSpawn => 30,
141     :ThreadPool => 20,
142     :Rev => 50,
143     :RevThreadSpawn => 50,
144     :RevThreadPool => 50,
145     :EventMachine => 50,
146     :FiberSpawn => 50,
147     :FiberPool => 50,
148     :ActorSpawn => 50,
149     :NeverBlock => 50,
150     :RevFiberSpawn => 50,
151   }.each do |model, _|
152     u = model.to_s.gsub(/([a-z0-9])([A-Z0-9])/) { "#{$1}_#{$2.downcase!}" }
153     autoload model, "rainbows/#{u.downcase!}"
154   end
155   # :startdoc:
156   autoload :Fiber, 'rainbows/fiber' # core class
160 # inject the Rainbows! method into Unicorn::Configurator
161 Unicorn::Configurator.class_eval { include Rainbows }