unicorn-camilo 4.8.2.5.g0b28.dirty

Sign up to get free protection for your applications and to get access to all the features.
Files changed (166) hide show
  1. checksums.yaml +7 -0
  2. data/.CHANGELOG.old +25 -0
  3. data/.document +29 -0
  4. data/.gitignore +25 -0
  5. data/.mailmap +26 -0
  6. data/.manifest +164 -0
  7. data/.wrongdoc.yml +10 -0
  8. data/Application_Timeouts +77 -0
  9. data/CONTRIBUTORS +35 -0
  10. data/COPYING +674 -0
  11. data/ChangeLog +4919 -0
  12. data/DESIGN +97 -0
  13. data/Documentation/.gitignore +5 -0
  14. data/Documentation/GNUmakefile +30 -0
  15. data/Documentation/unicorn.1.txt +178 -0
  16. data/Documentation/unicorn_rails.1.txt +175 -0
  17. data/FAQ +53 -0
  18. data/GIT-VERSION-FILE +1 -0
  19. data/GIT-VERSION-GEN +39 -0
  20. data/GNUmakefile +268 -0
  21. data/HACKING +134 -0
  22. data/ISSUES +36 -0
  23. data/KNOWN_ISSUES +79 -0
  24. data/LATEST +6 -0
  25. data/LICENSE +67 -0
  26. data/Links +56 -0
  27. data/NEWS +2089 -0
  28. data/PHILOSOPHY +145 -0
  29. data/README +150 -0
  30. data/Rakefile +60 -0
  31. data/SIGNALS +123 -0
  32. data/Sandbox +103 -0
  33. data/TODO +5 -0
  34. data/TUNING +98 -0
  35. data/bin/unicorn +126 -0
  36. data/bin/unicorn_rails +209 -0
  37. data/examples/big_app_gc.rb +2 -0
  38. data/examples/echo.ru +27 -0
  39. data/examples/git.ru +13 -0
  40. data/examples/init.sh +74 -0
  41. data/examples/logger_mp_safe.rb +25 -0
  42. data/examples/logrotate.conf +29 -0
  43. data/examples/nginx.conf +156 -0
  44. data/examples/unicorn.conf.minimal.rb +13 -0
  45. data/examples/unicorn.conf.rb +102 -0
  46. data/ext/unicorn_http/CFLAGS +13 -0
  47. data/ext/unicorn_http/c_util.h +124 -0
  48. data/ext/unicorn_http/common_field_optimization.h +111 -0
  49. data/ext/unicorn_http/ext_help.h +82 -0
  50. data/ext/unicorn_http/extconf.rb +10 -0
  51. data/ext/unicorn_http/global_variables.h +97 -0
  52. data/ext/unicorn_http/httpdate.c +78 -0
  53. data/ext/unicorn_http/unicorn_http.c +4031 -0
  54. data/ext/unicorn_http/unicorn_http.rl +1036 -0
  55. data/ext/unicorn_http/unicorn_http_common.rl +76 -0
  56. data/lib/unicorn/app/exec_cgi.rb +154 -0
  57. data/lib/unicorn/app/inetd.rb +109 -0
  58. data/lib/unicorn/app/old_rails/static.rb +59 -0
  59. data/lib/unicorn/app/old_rails.rb +35 -0
  60. data/lib/unicorn/cgi_wrapper.rb +147 -0
  61. data/lib/unicorn/configurator.rb +679 -0
  62. data/lib/unicorn/const.rb +44 -0
  63. data/lib/unicorn/http_request.rb +122 -0
  64. data/lib/unicorn/http_response.rb +75 -0
  65. data/lib/unicorn/http_server.rb +813 -0
  66. data/lib/unicorn/launcher.rb +62 -0
  67. data/lib/unicorn/oob_gc.rb +81 -0
  68. data/lib/unicorn/preread_input.rb +33 -0
  69. data/lib/unicorn/socket_helper.rb +231 -0
  70. data/lib/unicorn/ssl_client.rb +11 -0
  71. data/lib/unicorn/ssl_configurator.rb +104 -0
  72. data/lib/unicorn/ssl_server.rb +42 -0
  73. data/lib/unicorn/stream_input.rb +146 -0
  74. data/lib/unicorn/tee_input.rb +126 -0
  75. data/lib/unicorn/tmpio.rb +29 -0
  76. data/lib/unicorn/util.rb +89 -0
  77. data/lib/unicorn/version.rb +1 -0
  78. data/lib/unicorn/worker.rb +152 -0
  79. data/lib/unicorn.rb +118 -0
  80. data/local.mk.sample +59 -0
  81. data/man/man1/unicorn.1 +210 -0
  82. data/man/man1/unicorn_rails.1 +208 -0
  83. data/script/isolate_for_tests +31 -0
  84. data/setup.rb +1586 -0
  85. data/t/.gitignore +4 -0
  86. data/t/GNUmakefile +78 -0
  87. data/t/README +42 -0
  88. data/t/bin/content-md5-put +36 -0
  89. data/t/bin/sha1sum.rb +17 -0
  90. data/t/bin/unused_listen +40 -0
  91. data/t/broken-app.ru +12 -0
  92. data/t/detach.ru +11 -0
  93. data/t/env.ru +3 -0
  94. data/t/fails-rack-lint.ru +5 -0
  95. data/t/heartbeat-timeout.ru +12 -0
  96. data/t/hijack.ru +42 -0
  97. data/t/listener_names.ru +4 -0
  98. data/t/my-tap-lib.sh +201 -0
  99. data/t/oob_gc.ru +20 -0
  100. data/t/oob_gc_path.ru +20 -0
  101. data/t/pid.ru +3 -0
  102. data/t/preread_input.ru +17 -0
  103. data/t/rack-input-tests.ru +21 -0
  104. data/t/t0000-http-basic.sh +50 -0
  105. data/t/t0001-reload-bad-config.sh +53 -0
  106. data/t/t0002-config-conflict.sh +49 -0
  107. data/t/t0002-parser-error.sh +94 -0
  108. data/t/t0003-working_directory.sh +51 -0
  109. data/t/t0004-heartbeat-timeout.sh +69 -0
  110. data/t/t0004-working_directory_broken.sh +24 -0
  111. data/t/t0005-working_directory_app.rb.sh +40 -0
  112. data/t/t0006-reopen-logs.sh +83 -0
  113. data/t/t0006.ru +13 -0
  114. data/t/t0007-working_directory_no_embed_cli.sh +44 -0
  115. data/t/t0008-back_out_of_upgrade.sh +110 -0
  116. data/t/t0009-broken-app.sh +56 -0
  117. data/t/t0009-winch_ttin.sh +59 -0
  118. data/t/t0010-reap-logging.sh +55 -0
  119. data/t/t0011-active-unix-socket.sh +79 -0
  120. data/t/t0012-reload-empty-config.sh +85 -0
  121. data/t/t0013-rewindable-input-false.sh +24 -0
  122. data/t/t0013.ru +12 -0
  123. data/t/t0014-rewindable-input-true.sh +24 -0
  124. data/t/t0014.ru +12 -0
  125. data/t/t0015-configurator-internals.sh +25 -0
  126. data/t/t0016-trust-x-forwarded-false.sh +30 -0
  127. data/t/t0017-trust-x-forwarded-true.sh +30 -0
  128. data/t/t0018-write-on-close.sh +23 -0
  129. data/t/t0019-max_header_len.sh +49 -0
  130. data/t/t0020-at_exit-handler.sh +49 -0
  131. data/t/t0021-process_detach.sh +29 -0
  132. data/t/t0022-listener_names-preload_app.sh +32 -0
  133. data/t/t0100-rack-input-tests.sh +124 -0
  134. data/t/t0116-client_body_buffer_size.sh +80 -0
  135. data/t/t0116.ru +16 -0
  136. data/t/t0200-rack-hijack.sh +27 -0
  137. data/t/t0300-no-default-middleware.sh +20 -0
  138. data/t/t9000-preread-input.sh +48 -0
  139. data/t/t9001-oob_gc.sh +47 -0
  140. data/t/t9002-oob_gc-path.sh +75 -0
  141. data/t/test-lib.sh +128 -0
  142. data/t/write-on-close.ru +11 -0
  143. data/test/aggregate.rb +15 -0
  144. data/test/benchmark/README +50 -0
  145. data/test/benchmark/dd.ru +18 -0
  146. data/test/benchmark/stack.ru +8 -0
  147. data/test/exec/README +5 -0
  148. data/test/exec/test_exec.rb +1047 -0
  149. data/test/test_helper.rb +297 -0
  150. data/test/unit/test_configurator.rb +175 -0
  151. data/test/unit/test_droplet.rb +28 -0
  152. data/test/unit/test_http_parser.rb +854 -0
  153. data/test/unit/test_http_parser_ng.rb +731 -0
  154. data/test/unit/test_http_parser_xftrust.rb +38 -0
  155. data/test/unit/test_request.rb +182 -0
  156. data/test/unit/test_response.rb +99 -0
  157. data/test/unit/test_server.rb +268 -0
  158. data/test/unit/test_signals.rb +188 -0
  159. data/test/unit/test_sni_hostnames.rb +47 -0
  160. data/test/unit/test_socket_helper.rb +197 -0
  161. data/test/unit/test_stream_input.rb +203 -0
  162. data/test/unit/test_tee_input.rb +294 -0
  163. data/test/unit/test_upload.rb +306 -0
  164. data/test/unit/test_util.rb +105 -0
  165. data/unicorn.gemspec +44 -0
  166. metadata +326 -0
@@ -0,0 +1,813 @@
1
+ # -*- encoding: binary -*-
2
+ require "unicorn/ssl_server"
3
+
4
+ # This is the process manager of Unicorn. This manages worker
5
+ # processes which in turn handle the I/O and application process.
6
+ # Listener sockets are started in the master process and shared with
7
+ # forked worker children.
8
+ #
9
+ # Users do not need to know the internals of this class, but reading the
10
+ # {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb]
11
+ # is education for programmers wishing to learn how \Unicorn works.
12
+ # See Unicorn::Configurator for information on how to configure \Unicorn.
13
+ class Unicorn::HttpServer
14
+ # :stopdoc:
15
+ attr_accessor :app, :request, :timeout, :worker_processes,
16
+ :before_fork, :after_fork, :before_exec,
17
+ :listener_opts, :preload_app,
18
+ :reexec_pid, :orig_app, :init_listeners,
19
+ :master_pid, :config, :ready_pipe, :user
20
+
21
+ attr_reader :pid, :logger
22
+ include Unicorn::SocketHelper
23
+ include Unicorn::HttpResponse
24
+ include Unicorn::SSLServer
25
+
26
+ # backwards compatibility with 1.x
27
+ Worker = Unicorn::Worker
28
+
29
+ # all bound listener sockets
30
+ LISTENERS = []
31
+
32
+ # listeners we have yet to bind
33
+ NEW_LISTENERS = []
34
+
35
+ # This hash maps PIDs to Workers
36
+ WORKERS = {}
37
+
38
+ # We use SELF_PIPE differently in the master and worker processes:
39
+ #
40
+ # * The master process never closes or reinitializes this once
41
+ # initialized. Signal handlers in the master process will write to
42
+ # it to wake up the master from IO.select in exactly the same manner
43
+ # djb describes in http://cr.yp.to/docs/selfpipe.html
44
+ #
45
+ # * The workers immediately close the pipe they inherit. See the
46
+ # Unicorn::Worker class for the pipe workers use.
47
+ SELF_PIPE = []
48
+
49
+ # signal queue used for self-piping
50
+ SIG_QUEUE = []
51
+
52
+ # list of signals we care about and trap in master.
53
+ QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
54
+
55
+ # :startdoc:
56
+ # We populate this at startup so we can figure out how to reexecute
57
+ # and upgrade the currently running instance of Unicorn
58
+ # This Hash is considered a stable interface and changing its contents
59
+ # will allow you to switch between different installations of Unicorn
60
+ # or even different installations of the same applications without
61
+ # downtime. Keys of this constant Hash are described as follows:
62
+ #
63
+ # * 0 - the path to the unicorn/unicorn_rails executable
64
+ # * :argv - a deep copy of the ARGV array the executable originally saw
65
+ # * :cwd - the working directory of the application, this is where
66
+ # you originally started Unicorn.
67
+ #
68
+ # To change your unicorn executable to a different path without downtime,
69
+ # you can set the following in your Unicorn config file, HUP and then
70
+ # continue with the traditional USR2 + QUIT upgrade steps:
71
+ #
72
+ # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
73
+ START_CTX = {
74
+ :argv => ARGV.map { |arg| arg.dup },
75
+ 0 => $0.dup,
76
+ }
77
+ # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
78
+ # and like systems
79
+ START_CTX[:cwd] = begin
80
+ a = File.stat(pwd = ENV['PWD'])
81
+ b = File.stat(Dir.pwd)
82
+ a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
83
+ rescue
84
+ Dir.pwd
85
+ end
86
+ # :stopdoc:
87
+
88
+ # Creates a working server on host:port (strange things happen if
89
+ # port isn't a Number). Use HttpServer::run to start the server and
90
+ # HttpServer.run.join to join the thread that's processing
91
+ # incoming requests on the socket.
92
+ def initialize(app, options = {})
93
+ @app = app
94
+ @request = Unicorn::HttpRequest.new
95
+ self.reexec_pid = 0
96
+ options = options.dup
97
+ @ready_pipe = options.delete(:ready_pipe)
98
+ @init_listeners = options[:listeners] ? options[:listeners].dup : []
99
+ options[:use_defaults] = true
100
+ self.config = Unicorn::Configurator.new(options)
101
+ self.listener_opts = {}
102
+
103
+ # we try inheriting listeners first, so we bind them later.
104
+ # we don't write the pid file until we've bound listeners in case
105
+ # unicorn was started twice by mistake. Even though our #pid= method
106
+ # checks for stale/existing pid files, race conditions are still
107
+ # possible (and difficult/non-portable to avoid) and can be likely
108
+ # to clobber the pid if the second start was in quick succession
109
+ # after the first, so we rely on the listener binding to fail in
110
+ # that case. Some tests (in and outside of this source tree) and
111
+ # monitoring tools may also rely on pid files existing before we
112
+ # attempt to connect to the listener(s)
113
+ config.commit!(self, :skip => [:listeners, :pid])
114
+ self.orig_app = app
115
+ end
116
+
117
+ # Runs the thing. Returns self so you can run join on it
118
+ def start
119
+ inherit_listeners!
120
+ # this pipe is used to wake us up from select(2) in #join when signals
121
+ # are trapped. See trap_deferred.
122
+ SELF_PIPE.replace(Unicorn.pipe)
123
+ @master_pid = $$
124
+
125
+ # setup signal handlers before writing pid file in case people get
126
+ # trigger happy and send signals as soon as the pid file exists.
127
+ # Note that signals don't actually get handled until the #join method
128
+ QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
129
+ trap(:CHLD) { awaken_master }
130
+
131
+ # write pid early for Mongrel compatibility if we're not inheriting sockets
132
+ # This is needed for compatibility some Monit setups at least.
133
+ # This unfortunately has the side effect of clobbering valid PID if
134
+ # we upgrade and the upgrade breaks during preload_app==true && build_app!
135
+ self.pid = config[:pid]
136
+
137
+ build_app! if preload_app
138
+ bind_new_listeners!
139
+
140
+ spawn_missing_workers
141
+ self
142
+ end
143
+
144
+ # replaces current listener set with +listeners+. This will
145
+ # close the socket if it will not exist in the new listener set
146
+ def listeners=(listeners)
147
+ cur_names, dead_names = [], []
148
+ listener_names.each do |name|
149
+ if ?/ == name[0]
150
+ # mark unlinked sockets as dead so we can rebind them
151
+ (File.socket?(name) ? cur_names : dead_names) << name
152
+ else
153
+ cur_names << name
154
+ end
155
+ end
156
+ set_names = listener_names(listeners)
157
+ dead_names.concat(cur_names - set_names).uniq!
158
+
159
+ LISTENERS.delete_if do |io|
160
+ if dead_names.include?(sock_name(io))
161
+ IO_PURGATORY.delete_if do |pio|
162
+ pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
163
+ end
164
+ (io.close rescue nil).nil? # true
165
+ else
166
+ set_server_sockopt(io, listener_opts[sock_name(io)])
167
+ false
168
+ end
169
+ end
170
+
171
+ (set_names - cur_names).each { |addr| listen(addr) }
172
+ end
173
+
174
+ def stdout_path=(path); redirect_io($stdout, path); end
175
+ def stderr_path=(path); redirect_io($stderr, path); end
176
+
177
+ def logger=(obj)
178
+ Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
179
+ end
180
+
181
+ def clobber_pid(path)
182
+ unlink_pid_safe(@pid) if @pid
183
+ if path
184
+ fp = begin
185
+ tmp = "#{File.dirname(path)}/#{rand}.#$$"
186
+ File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
187
+ rescue Errno::EEXIST
188
+ retry
189
+ end
190
+ fp.syswrite("#$$\n")
191
+ File.rename(fp.path, path)
192
+ fp.close
193
+ end
194
+ end
195
+
196
+ # sets the path for the PID file of the master process
197
+ def pid=(path)
198
+ if path
199
+ if x = valid_pid?(path)
200
+ return path if pid && path == pid && x == $$
201
+ if x == reexec_pid && pid =~ /\.oldbin\z/
202
+ logger.warn("will not set pid=#{path} while reexec-ed "\
203
+ "child is running PID:#{x}")
204
+ return
205
+ end
206
+ raise ArgumentError, "Already running on PID:#{x} " \
207
+ "(or pid=#{path} is stale)"
208
+ end
209
+ end
210
+
211
+ # rename the old pid if possible
212
+ if @pid && path
213
+ begin
214
+ File.rename(@pid, path)
215
+ rescue Errno::ENOENT, Errno::EXDEV
216
+ # a user may have accidentally removed the original,
217
+ # obviously cross-FS renames don't work, either.
218
+ clobber_pid(path)
219
+ end
220
+ else
221
+ clobber_pid(path)
222
+ end
223
+ @pid = path
224
+ end
225
+
226
+ # add a given address to the +listeners+ set, idempotently
227
+ # Allows workers to add a private, per-process listener via the
228
+ # after_fork hook. Very useful for debugging and testing.
229
+ # +:tries+ may be specified as an option for the number of times
230
+ # to retry, and +:delay+ may be specified as the time in seconds
231
+ # to delay between retries.
232
+ # A negative value for +:tries+ indicates the listen will be
233
+ # retried indefinitely, this is useful when workers belonging to
234
+ # different masters are spawned during a transparent upgrade.
235
+ def listen(address, opt = {}.merge(listener_opts[address] || {}))
236
+ address = config.expand_addr(address)
237
+ return if String === address && listener_names.include?(address)
238
+
239
+ delay = opt[:delay] || 0.5
240
+ tries = opt[:tries] || 5
241
+ begin
242
+ io = bind_listen(address, opt)
243
+ unless Kgio::TCPServer === io || Kgio::UNIXServer === io
244
+ prevent_autoclose(io)
245
+ io = server_cast(io)
246
+ end
247
+ logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
248
+ LISTENERS << io
249
+ io
250
+ rescue Errno::EADDRINUSE => err
251
+ logger.error "adding listener failed addr=#{address} (in use)"
252
+ raise err if tries == 0
253
+ tries -= 1
254
+ logger.error "retrying in #{delay} seconds " \
255
+ "(#{tries < 0 ? 'infinite' : tries} tries left)"
256
+ sleep(delay)
257
+ retry
258
+ rescue => err
259
+ logger.fatal "error adding listener addr=#{address}"
260
+ raise err
261
+ end
262
+ end
263
+
264
+ # monitors children and receives signals forever
265
+ # (or until a termination signal is sent). This handles signals
266
+ # one-at-a-time time and we'll happily drop signals in case somebody
267
+ # is signalling us too often.
268
+ def join
269
+ respawn = true
270
+ last_check = Time.now
271
+
272
+ proc_name 'master'
273
+ logger.info "master process ready" # test_exec.rb relies on this message
274
+ if @ready_pipe
275
+ @ready_pipe.syswrite($$.to_s)
276
+ @ready_pipe = @ready_pipe.close rescue nil
277
+ end
278
+ begin
279
+ reap_all_workers
280
+ case SIG_QUEUE.shift
281
+ when nil
282
+ # avoid murdering workers after our master process (or the
283
+ # machine) comes out of suspend/hibernation
284
+ if (last_check + @timeout) >= (last_check = Time.now)
285
+ sleep_time = murder_lazy_workers
286
+ else
287
+ sleep_time = @timeout/2.0 + 1
288
+ @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
289
+ end
290
+ maintain_worker_count if respawn
291
+ master_sleep(sleep_time)
292
+ when :QUIT # graceful shutdown
293
+ break
294
+ when :TERM, :INT # immediate shutdown
295
+ stop(false)
296
+ break
297
+ when :USR1 # rotate logs
298
+ logger.info "master reopening logs..."
299
+ Unicorn::Util.reopen_logs
300
+ logger.info "master done reopening logs"
301
+ soft_kill_each_worker(:USR1)
302
+ when :USR2 # exec binary, stay alive in case something went wrong
303
+ reexec
304
+ when :WINCH
305
+ if Unicorn::Configurator::RACKUP[:daemonized]
306
+ respawn = false
307
+ logger.info "gracefully stopping all workers"
308
+ soft_kill_each_worker(:QUIT)
309
+ self.worker_processes = 0
310
+ else
311
+ logger.info "SIGWINCH ignored because we're not daemonized"
312
+ end
313
+ when :TTIN
314
+ respawn = true
315
+ self.worker_processes += 1
316
+ when :TTOU
317
+ self.worker_processes -= 1 if self.worker_processes > 0
318
+ when :HUP
319
+ respawn = true
320
+ if config.config_file
321
+ load_config!
322
+ else # exec binary and exit if there's no config file
323
+ logger.info "config_file not present, reexecuting binary"
324
+ reexec
325
+ end
326
+ end
327
+ rescue => e
328
+ Unicorn.log_error(@logger, "master loop error", e)
329
+ end while true
330
+ stop # gracefully shutdown all workers on our way out
331
+ logger.info "master complete"
332
+ unlink_pid_safe(pid) if pid
333
+ end
334
+
335
+ # Terminates all workers, but does not exit master process
336
+ def stop(graceful = true)
337
+ self.listeners = []
338
+ limit = Time.now + timeout
339
+ until WORKERS.empty? || Time.now > limit
340
+ if graceful
341
+ soft_kill_each_worker(:QUIT)
342
+ else
343
+ kill_each_worker(:TERM)
344
+ end
345
+ sleep(0.1)
346
+ reap_all_workers
347
+ end
348
+ kill_each_worker(:KILL)
349
+ end
350
+
351
+ def rewindable_input
352
+ Unicorn::HttpRequest.input_class.method_defined?(:rewind)
353
+ end
354
+
355
+ def rewindable_input=(bool)
356
+ Unicorn::HttpRequest.input_class = bool ?
357
+ Unicorn::TeeInput : Unicorn::StreamInput
358
+ end
359
+
360
+ def client_body_buffer_size
361
+ Unicorn::TeeInput.client_body_buffer_size
362
+ end
363
+
364
+ def client_body_buffer_size=(bytes)
365
+ Unicorn::TeeInput.client_body_buffer_size = bytes
366
+ end
367
+
368
+ def trust_x_forwarded
369
+ Unicorn::HttpParser.trust_x_forwarded?
370
+ end
371
+
372
+ def trust_x_forwarded=(bool)
373
+ Unicorn::HttpParser.trust_x_forwarded = bool
374
+ end
375
+
376
+ def check_client_connection
377
+ Unicorn::HttpRequest.check_client_connection
378
+ end
379
+
380
+ def check_client_connection=(bool)
381
+ Unicorn::HttpRequest.check_client_connection = bool
382
+ end
383
+
384
+ private
385
+
386
+ # wait for a signal hander to wake us up and then consume the pipe
387
+ def master_sleep(sec)
388
+ IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
389
+ SELF_PIPE[0].kgio_tryread(11)
390
+ end
391
+
392
+ def awaken_master
393
+ return if $$ != @master_pid
394
+ SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
395
+ end
396
+
397
+ # reaps all unreaped workers
398
+ def reap_all_workers
399
+ begin
400
+ wpid, status = Process.waitpid2(-1, Process::WNOHANG)
401
+ wpid or return
402
+ if reexec_pid == wpid
403
+ logger.error "reaped #{status.inspect} exec()-ed"
404
+ self.reexec_pid = 0
405
+ self.pid = pid.chomp('.oldbin') if pid
406
+ proc_name 'master'
407
+ else
408
+ worker = WORKERS.delete(wpid) and worker.close rescue nil
409
+ m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
410
+ status.success? ? logger.info(m) : logger.error(m)
411
+ end
412
+ rescue Errno::ECHILD
413
+ break
414
+ end while true
415
+ end
416
+
417
+ # reexecutes the START_CTX with a new binary
418
+ def reexec
419
+ if reexec_pid > 0
420
+ begin
421
+ Process.kill(0, reexec_pid)
422
+ logger.error "reexec-ed child already running PID:#{reexec_pid}"
423
+ return
424
+ rescue Errno::ESRCH
425
+ self.reexec_pid = 0
426
+ end
427
+ end
428
+
429
+ if pid
430
+ old_pid = "#{pid}.oldbin"
431
+ begin
432
+ self.pid = old_pid # clear the path for a new pid file
433
+ rescue ArgumentError
434
+ logger.error "old PID:#{valid_pid?(old_pid)} running with " \
435
+ "existing pid=#{old_pid}, refusing rexec"
436
+ return
437
+ rescue => e
438
+ logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
439
+ return
440
+ end
441
+ end
442
+
443
+ self.reexec_pid = fork do
444
+ listener_fds = {}
445
+ LISTENERS.each do |sock|
446
+ # IO#close_on_exec= will be available on any future version of
447
+ # Ruby that sets FD_CLOEXEC by default on new file descriptors
448
+ # ref: http://redmine.ruby-lang.org/issues/5041
449
+ sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
450
+ listener_fds[sock.fileno] = sock
451
+ end
452
+ ENV['UNICORN_FD'] = listener_fds.keys.join(',')
453
+ Dir.chdir(START_CTX[:cwd])
454
+ cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
455
+
456
+ # avoid leaking FDs we don't know about, but let before_exec
457
+ # unset FD_CLOEXEC, if anything else in the app eventually
458
+ # relies on FD inheritence.
459
+ (3..1024).each do |io|
460
+ next if listener_fds.include?(io)
461
+ io = IO.for_fd(io) rescue next
462
+ prevent_autoclose(io)
463
+ io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
464
+ end
465
+
466
+ # exec(command, hash) works in at least 1.9.1+, but will only be
467
+ # required in 1.9.4/2.0.0 at earliest.
468
+ cmd << listener_fds if RUBY_VERSION >= "1.9.1"
469
+ logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
470
+ before_exec.call(self)
471
+ exec(*cmd)
472
+ end
473
+ proc_name 'master (old)'
474
+ end
475
+
476
+ # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
477
+ def murder_lazy_workers
478
+ next_sleep = @timeout - 1
479
+ now = Time.now.to_i
480
+ WORKERS.dup.each_pair do |wpid, worker|
481
+ tick = worker.tick
482
+ 0 == tick and next # skip workers that haven't processed any clients
483
+ diff = now - tick
484
+ tmp = @timeout - diff
485
+ if tmp >= 0
486
+ next_sleep > tmp and next_sleep = tmp
487
+ next
488
+ end
489
+ next_sleep = 0
490
+ logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
491
+ "(#{diff}s > #{@timeout}s), killing"
492
+ kill_worker(:TERM, pid)
493
+ fork do
494
+ sleep(0.5)
495
+ kill_worker(:KILL, pid) # take no prisoners for timeout violations
496
+ end
497
+ end
498
+ next_sleep <= 0 ? 1 : next_sleep
499
+ end
500
+
501
+ def after_fork_internal
502
+ SELF_PIPE.each { |io| io.close }.clear # this is master-only, now
503
+ @ready_pipe.close if @ready_pipe
504
+ Unicorn::Configurator::RACKUP.clear
505
+ @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
506
+
507
+ srand # http://redmine.ruby-lang.org/issues/4338
508
+
509
+ # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
510
+ # dying workers can recycle pids
511
+ OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
512
+ end
513
+
514
+ def spawn_missing_workers
515
+ worker_nr = -1
516
+ until (worker_nr += 1) == @worker_processes
517
+ WORKERS.value?(worker_nr) and next
518
+ worker = Worker.new(worker_nr)
519
+ before_fork.call(self, worker)
520
+ if pid = fork
521
+ WORKERS[pid] = worker
522
+ worker.atfork_parent
523
+ else
524
+ after_fork_internal
525
+ worker_loop(worker)
526
+ exit
527
+ end
528
+ end
529
+ rescue => e
530
+ @logger.error(e) rescue nil
531
+ exit!
532
+ end
533
+
534
+ def maintain_worker_count
535
+ (off = WORKERS.size - worker_processes) == 0 and return
536
+ off < 0 and return spawn_missing_workers
537
+ WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
538
+ end
539
+
540
+ # if we get any error, try to write something back to the client
541
+ # assuming we haven't closed the socket, but don't get hung up
542
+ # if the socket is already closed or broken. We'll always ensure
543
+ # the socket is closed at the end of this function
544
+ def handle_error(client, e)
545
+ code = case e
546
+ when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
547
+ # client disconnected on us and there's nothing we can do
548
+ when Unicorn::RequestURITooLongError
549
+ 414
550
+ when Unicorn::RequestEntityTooLargeError
551
+ 413
552
+ when Unicorn::HttpParserError # try to tell the client they're bad
553
+ 400
554
+ else
555
+ Unicorn.log_error(@logger, "app error", e)
556
+ 500
557
+ end
558
+ if code
559
+ client.kgio_trywrite(err_response(code, @request.response_start_sent))
560
+ end
561
+ client.close
562
+ rescue
563
+ end
564
+
565
+ def expect_100_response
566
+ if @request.response_start_sent
567
+ Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED
568
+ else
569
+ Unicorn::Const::EXPECT_100_RESPONSE
570
+ end
571
+ end
572
+
573
+ # once a client is accepted, it is processed in its entirety here
574
+ # in 3 easy steps: read request, call app, write app response
575
+ def process_client(client)
576
+ status, headers, body = @app.call(env = @request.read(client))
577
+ return if @request.hijacked?
578
+
579
+ if 100 == status.to_i
580
+ client.write(expect_100_response)
581
+ env.delete(Unicorn::Const::HTTP_EXPECT)
582
+ status, headers, body = @app.call(env)
583
+ return if @request.hijacked?
584
+ end
585
+ @request.headers? or headers = nil
586
+ http_response_write(client, status, headers, body,
587
+ @request.response_start_sent)
588
+ unless client.closed? # rack.hijack may've close this for us
589
+ client.shutdown # in case of fork() in Rack app
590
+ client.close # flush and uncork socket immediately, no keepalive
591
+ end
592
+ rescue => e
593
+ handle_error(client, e)
594
+ end
595
+
596
+ EXIT_SIGS = [ :QUIT, :TERM, :INT ]
597
+ WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
598
+
599
+ def nuke_listeners!(readers)
600
+ # only called from the worker, ordering is important here
601
+ tmp = readers.dup
602
+ readers.replace([false]) # ensure worker does not continue ASAP
603
+ tmp.each { |io| io.close rescue nil } # break out of IO.select
604
+ end
605
+
606
+ # gets rid of stuff the worker has no business keeping track of
607
+ # to free some resources and drops all sig handlers.
608
+ # traps for USR1, USR2, and HUP may be set in the after_fork Proc
609
+ # by the user.
610
+ def init_worker_process(worker)
611
+ worker.atfork_child
612
+ # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
613
+ EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
614
+ exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
615
+ WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
616
+ trap(:CHLD, 'DEFAULT')
617
+ SIG_QUEUE.clear
618
+ proc_name "worker[#{worker.nr}]"
619
+ START_CTX.clear
620
+ WORKERS.clear
621
+
622
+ after_fork.call(self, worker) # can drop perms and create listeners
623
+ LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
624
+
625
+ worker.user(*user) if user.kind_of?(Array) && ! worker.switched
626
+ self.timeout /= 2.0 # halve it for select()
627
+ @config = nil
628
+ build_app! unless preload_app
629
+ ssl_enable!
630
+ @after_fork = @listener_opts = @orig_app = nil
631
+ readers = LISTENERS.dup
632
+ readers << worker
633
+ trap(:QUIT) { nuke_listeners!(readers) }
634
+ readers
635
+ end
636
+
637
+ def reopen_worker_logs(worker_nr)
638
+ logger.info "worker=#{worker_nr} reopening logs..."
639
+ Unicorn::Util.reopen_logs
640
+ logger.info "worker=#{worker_nr} done reopening logs"
641
+ rescue => e
642
+ logger.error(e) rescue nil
643
+ exit!(77) # EX_NOPERM in sysexits.h
644
+ end
645
+
646
+ # runs inside each forked worker, this sits around and waits
647
+ # for connections and doesn't die until the parent dies (or is
648
+ # given a INT, QUIT, or TERM signal)
649
+ def worker_loop(worker)
650
+ ppid = master_pid
651
+ readers = init_worker_process(worker)
652
+ nr = 0 # this becomes negative if we need to reopen logs
653
+
654
+ # this only works immediately if the master sent us the signal
655
+ # (which is the normal case)
656
+ trap(:USR1) { nr = -65536 }
657
+
658
+ ready = readers.dup
659
+ @logger.info "worker=#{worker.nr} ready"
660
+
661
+ begin
662
+ nr < 0 and reopen_worker_logs(worker.nr)
663
+ nr = 0
664
+ worker.tick = Time.now.to_i
665
+ tmp = ready.dup
666
+ while sock = tmp.shift
667
+ # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
668
+ # but that will return false
669
+ if client = sock.kgio_tryaccept
670
+ process_client(client)
671
+ nr += 1
672
+ worker.tick = Time.now.to_i
673
+ end
674
+ break if nr < 0
675
+ end
676
+
677
+ # make the following bet: if we accepted clients this round,
678
+ # we're probably reasonably busy, so avoid calling select()
679
+ # and do a speculative non-blocking accept() on ready listeners
680
+ # before we sleep again in select().
681
+ unless nr == 0
682
+ tmp = ready.dup
683
+ redo
684
+ end
685
+
686
+ ppid == Process.ppid or return
687
+
688
+ # timeout used so we can detect parent death:
689
+ worker.tick = Time.now.to_i
690
+ ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
691
+ rescue => e
692
+ redo if nr < 0 && readers[0]
693
+ Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
694
+ end while readers[0]
695
+ end
696
+
697
+ # delivers a signal to a worker and fails gracefully if the worker
698
+ # is no longer running.
699
+ def kill_worker(signal, wpid)
700
+ Process.kill(signal, wpid)
701
+ rescue Errno::ESRCH
702
+ worker = WORKERS.delete(wpid) and worker.close rescue nil
703
+ end
704
+
705
+ # delivers a signal to each worker
706
+ def kill_each_worker(signal)
707
+ WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
708
+ end
709
+
710
+ def soft_kill_each_worker(signal)
711
+ WORKERS.each_value { |worker| worker.soft_kill(signal) }
712
+ end
713
+
714
+ # unlinks a PID file at given +path+ if it contains the current PID
715
+ # still potentially racy without locking the directory (which is
716
+ # non-portable and may interact badly with other programs), but the
717
+ # window for hitting the race condition is small
718
+ def unlink_pid_safe(path)
719
+ (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
720
+ end
721
+
722
+ # returns a PID if a given path contains a non-stale PID file,
723
+ # nil otherwise.
724
+ def valid_pid?(path)
725
+ wpid = File.read(path).to_i
726
+ wpid <= 0 and return
727
+ Process.kill(0, wpid)
728
+ wpid
729
+ rescue Errno::EPERM
730
+ logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
731
+ nil
732
+ rescue Errno::ESRCH, Errno::ENOENT
733
+ # don't unlink stale pid files, racy without non-portable locking...
734
+ end
735
+
736
+ def load_config!
737
+ loaded_app = app
738
+ logger.info "reloading config_file=#{config.config_file}"
739
+ config[:listeners].replace(@init_listeners)
740
+ config.reload
741
+ config.commit!(self)
742
+ soft_kill_each_worker(:QUIT)
743
+ Unicorn::Util.reopen_logs
744
+ self.app = orig_app
745
+ build_app! if preload_app
746
+ logger.info "done reloading config_file=#{config.config_file}"
747
+ rescue StandardError, LoadError, SyntaxError => e
748
+ Unicorn.log_error(@logger,
749
+ "error reloading config_file=#{config.config_file}", e)
750
+ self.app = loaded_app
751
+ end
752
+
753
+ # returns an array of string names for the given listener array
754
+ def listener_names(listeners = LISTENERS)
755
+ listeners.map { |io| sock_name(io) }
756
+ end
757
+
758
+ def build_app!
759
+ if app.respond_to?(:arity) && app.arity == 0
760
+ if defined?(Gem) && Gem.respond_to?(:refresh)
761
+ logger.info "Refreshing Gem list"
762
+ Gem.refresh
763
+ end
764
+ self.app = app.call
765
+ end
766
+ end
767
+
768
+ def proc_name(tag)
769
+ $0 = ([ File.basename(START_CTX[0]), tag
770
+ ]).concat(START_CTX[:argv]).join(' ')
771
+ end
772
+
773
+ def redirect_io(io, path)
774
+ File.open(path, 'ab') { |fp| io.reopen(fp) } if path
775
+ io.sync = true
776
+ end
777
+
778
+ def inherit_listeners!
779
+ # inherit sockets from parents, they need to be plain Socket objects
780
+ # before they become Kgio::UNIXServer or Kgio::TCPServer
781
+ inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
782
+ io = Socket.for_fd(fd.to_i)
783
+ set_server_sockopt(io, listener_opts[sock_name(io)])
784
+ prevent_autoclose(io)
785
+ logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
786
+ server_cast(io)
787
+ end
788
+
789
+ config_listeners = config[:listeners].dup
790
+ LISTENERS.replace(inherited)
791
+
792
+ # we start out with generic Socket objects that get cast to either
793
+ # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
794
+ # objects share the same OS-level file descriptor as the higher-level
795
+ # *Server objects; we need to prevent Socket objects from being
796
+ # garbage-collected
797
+ config_listeners -= listener_names
798
+ if config_listeners.empty? && LISTENERS.empty?
799
+ config_listeners << Unicorn::Const::DEFAULT_LISTEN
800
+ @init_listeners << Unicorn::Const::DEFAULT_LISTEN
801
+ START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
802
+ end
803
+ NEW_LISTENERS.replace(config_listeners)
804
+ end
805
+
806
+ # call only after calling inherit_listeners!
807
+ # This binds any listeners we did NOT inherit from the parent
808
+ def bind_new_listeners!
809
+ NEW_LISTENERS.each { |addr| listen(addr) }
810
+ raise ArgumentError, "no listeners" if LISTENERS.empty?
811
+ NEW_LISTENERS.clear
812
+ end
813
+ end