unicorn-heroku-wait 4.8.0.1.g0ed2.dirty

Sign up to get free protection for your applications and to get access to all the features.
Files changed (168) 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 +166 -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 +4861 -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 +267 -0
  21. data/HACKING +134 -0
  22. data/ISSUES +36 -0
  23. data/KNOWN_ISSUES +79 -0
  24. data/LATEST +28 -0
  25. data/LICENSE +67 -0
  26. data/Links +56 -0
  27. data/NEWS +2067 -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 +803 -0
  66. data/lib/unicorn/launcher.rb +62 -0
  67. data/lib/unicorn/oob_gc.rb +71 -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 +211 -0
  82. data/man/man1/unicorn_rails.1 +210 -0
  83. data/script/isolate_for_tests +32 -0
  84. data/setup.rb +1586 -0
  85. data/t/.gitignore +5 -0
  86. data/t/GNUmakefile +82 -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/sslgen.sh +71 -0
  105. data/t/t0000-http-basic.sh +50 -0
  106. data/t/t0001-reload-bad-config.sh +53 -0
  107. data/t/t0002-config-conflict.sh +49 -0
  108. data/t/t0002-parser-error.sh +94 -0
  109. data/t/t0003-working_directory.sh +51 -0
  110. data/t/t0004-heartbeat-timeout.sh +69 -0
  111. data/t/t0004-working_directory_broken.sh +24 -0
  112. data/t/t0005-working_directory_app.rb.sh +40 -0
  113. data/t/t0006-reopen-logs.sh +83 -0
  114. data/t/t0006.ru +13 -0
  115. data/t/t0007-working_directory_no_embed_cli.sh +44 -0
  116. data/t/t0008-back_out_of_upgrade.sh +110 -0
  117. data/t/t0009-broken-app.sh +56 -0
  118. data/t/t0009-winch_ttin.sh +59 -0
  119. data/t/t0010-reap-logging.sh +55 -0
  120. data/t/t0011-active-unix-socket.sh +79 -0
  121. data/t/t0012-reload-empty-config.sh +85 -0
  122. data/t/t0013-rewindable-input-false.sh +24 -0
  123. data/t/t0013.ru +12 -0
  124. data/t/t0014-rewindable-input-true.sh +24 -0
  125. data/t/t0014.ru +12 -0
  126. data/t/t0015-configurator-internals.sh +25 -0
  127. data/t/t0016-trust-x-forwarded-false.sh +30 -0
  128. data/t/t0017-trust-x-forwarded-true.sh +30 -0
  129. data/t/t0018-write-on-close.sh +23 -0
  130. data/t/t0019-max_header_len.sh +49 -0
  131. data/t/t0020-at_exit-handler.sh +49 -0
  132. data/t/t0021-process_detach.sh +29 -0
  133. data/t/t0022-listener_names-preload_app.sh +32 -0
  134. data/t/t0100-rack-input-tests.sh +124 -0
  135. data/t/t0116-client_body_buffer_size.sh +80 -0
  136. data/t/t0116.ru +16 -0
  137. data/t/t0200-rack-hijack.sh +27 -0
  138. data/t/t0300-no-default-middleware.sh +20 -0
  139. data/t/t0600-https-server-basic.sh +48 -0
  140. data/t/t9000-preread-input.sh +48 -0
  141. data/t/t9001-oob_gc.sh +47 -0
  142. data/t/t9002-oob_gc-path.sh +75 -0
  143. data/t/test-lib.sh +128 -0
  144. data/t/write-on-close.ru +11 -0
  145. data/test/aggregate.rb +15 -0
  146. data/test/benchmark/README +50 -0
  147. data/test/benchmark/dd.ru +18 -0
  148. data/test/benchmark/stack.ru +8 -0
  149. data/test/exec/README +5 -0
  150. data/test/exec/test_exec.rb +1047 -0
  151. data/test/test_helper.rb +297 -0
  152. data/test/unit/test_configurator.rb +175 -0
  153. data/test/unit/test_droplet.rb +28 -0
  154. data/test/unit/test_http_parser.rb +854 -0
  155. data/test/unit/test_http_parser_ng.rb +731 -0
  156. data/test/unit/test_http_parser_xftrust.rb +38 -0
  157. data/test/unit/test_request.rb +182 -0
  158. data/test/unit/test_response.rb +99 -0
  159. data/test/unit/test_server.rb +268 -0
  160. data/test/unit/test_signals.rb +188 -0
  161. data/test/unit/test_sni_hostnames.rb +47 -0
  162. data/test/unit/test_socket_helper.rb +197 -0
  163. data/test/unit/test_stream_input.rb +203 -0
  164. data/test/unit/test_tee_input.rb +294 -0
  165. data/test/unit/test_upload.rb +306 -0
  166. data/test/unit/test_util.rb +105 -0
  167. data/unicorn.gemspec +44 -0
  168. metadata +328 -0
@@ -0,0 +1,803 @@
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
+
124
+ # setup signal handlers before writing pid file in case people get
125
+ # trigger happy and send signals as soon as the pid file exists.
126
+ # Note that signals don't actually get handled until the #join method
127
+ QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
128
+ trap(:CHLD) { awaken_master }
129
+
130
+ # write pid early for Mongrel compatibility if we're not inheriting sockets
131
+ # This is needed for compatibility some Monit setups at least.
132
+ # This unfortunately has the side effect of clobbering valid PID if
133
+ # we upgrade and the upgrade breaks during preload_app==true && build_app!
134
+ self.pid = config[:pid]
135
+
136
+ self.master_pid = $$
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
+ SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
394
+ end
395
+
396
+ # reaps all unreaped workers
397
+ def reap_all_workers
398
+ begin
399
+ wpid, status = Process.waitpid2(-1, Process::WNOHANG)
400
+ wpid or return
401
+ if reexec_pid == wpid
402
+ logger.error "reaped #{status.inspect} exec()-ed"
403
+ self.reexec_pid = 0
404
+ self.pid = pid.chomp('.oldbin') if pid
405
+ proc_name 'master'
406
+ else
407
+ worker = WORKERS.delete(wpid) and worker.close rescue nil
408
+ m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
409
+ status.success? ? logger.info(m) : logger.error(m)
410
+ end
411
+ rescue Errno::ECHILD
412
+ break
413
+ end while true
414
+ end
415
+
416
+ # reexecutes the START_CTX with a new binary
417
+ def reexec
418
+ if reexec_pid > 0
419
+ begin
420
+ Process.kill(0, reexec_pid)
421
+ logger.error "reexec-ed child already running PID:#{reexec_pid}"
422
+ return
423
+ rescue Errno::ESRCH
424
+ self.reexec_pid = 0
425
+ end
426
+ end
427
+
428
+ if pid
429
+ old_pid = "#{pid}.oldbin"
430
+ begin
431
+ self.pid = old_pid # clear the path for a new pid file
432
+ rescue ArgumentError
433
+ logger.error "old PID:#{valid_pid?(old_pid)} running with " \
434
+ "existing pid=#{old_pid}, refusing rexec"
435
+ return
436
+ rescue => e
437
+ logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
438
+ return
439
+ end
440
+ end
441
+
442
+ self.reexec_pid = fork do
443
+ listener_fds = {}
444
+ LISTENERS.each do |sock|
445
+ # IO#close_on_exec= will be available on any future version of
446
+ # Ruby that sets FD_CLOEXEC by default on new file descriptors
447
+ # ref: http://redmine.ruby-lang.org/issues/5041
448
+ sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
449
+ listener_fds[sock.fileno] = sock
450
+ end
451
+ ENV['UNICORN_FD'] = listener_fds.keys.join(',')
452
+ Dir.chdir(START_CTX[:cwd])
453
+ cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
454
+
455
+ # avoid leaking FDs we don't know about, but let before_exec
456
+ # unset FD_CLOEXEC, if anything else in the app eventually
457
+ # relies on FD inheritence.
458
+ (3..1024).each do |io|
459
+ next if listener_fds.include?(io)
460
+ io = IO.for_fd(io) rescue next
461
+ prevent_autoclose(io)
462
+ io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
463
+ end
464
+
465
+ # exec(command, hash) works in at least 1.9.1+, but will only be
466
+ # required in 1.9.4/2.0.0 at earliest.
467
+ cmd << listener_fds if RUBY_VERSION >= "1.9.1"
468
+ logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
469
+ before_exec.call(self)
470
+ exec(*cmd)
471
+ end
472
+ proc_name 'master (old)'
473
+ end
474
+
475
+ # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
476
+ def murder_lazy_workers
477
+ next_sleep = @timeout - 1
478
+ now = Time.now.to_i
479
+ WORKERS.dup.each_pair do |wpid, worker|
480
+ tick = worker.tick
481
+ 0 == tick and next # skip workers that haven't processed any clients
482
+ diff = now - tick
483
+ tmp = @timeout - diff
484
+ if tmp >= 0
485
+ next_sleep > tmp and next_sleep = tmp
486
+ next
487
+ end
488
+ next_sleep = 0
489
+ logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
490
+ "(#{diff}s > #{@timeout}s), killing"
491
+ kill_worker(:KILL, wpid) # take no prisoners for timeout violations
492
+ end
493
+ next_sleep <= 0 ? 1 : next_sleep
494
+ end
495
+
496
+ def after_fork_internal
497
+ SELF_PIPE.each { |io| io.close }.clear # this is master-only, now
498
+ @ready_pipe.close if @ready_pipe
499
+ Unicorn::Configurator::RACKUP.clear
500
+ @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
501
+
502
+ srand # http://redmine.ruby-lang.org/issues/4338
503
+
504
+ # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
505
+ # dying workers can recycle pids
506
+ OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
507
+ end
508
+
509
+ def spawn_missing_workers
510
+ worker_nr = -1
511
+ until (worker_nr += 1) == @worker_processes
512
+ WORKERS.value?(worker_nr) and next
513
+ worker = Worker.new(worker_nr)
514
+ before_fork.call(self, worker)
515
+ if pid = fork
516
+ WORKERS[pid] = worker
517
+ worker.atfork_parent
518
+ else
519
+ after_fork_internal
520
+ worker_loop(worker)
521
+ exit
522
+ end
523
+ end
524
+ rescue => e
525
+ @logger.error(e) rescue nil
526
+ exit!
527
+ end
528
+
529
+ def maintain_worker_count
530
+ (off = WORKERS.size - worker_processes) == 0 and return
531
+ off < 0 and return spawn_missing_workers
532
+ WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
533
+ end
534
+
535
+ # if we get any error, try to write something back to the client
536
+ # assuming we haven't closed the socket, but don't get hung up
537
+ # if the socket is already closed or broken. We'll always ensure
538
+ # the socket is closed at the end of this function
539
+ def handle_error(client, e)
540
+ code = case e
541
+ when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
542
+ # client disconnected on us and there's nothing we can do
543
+ when Unicorn::RequestURITooLongError
544
+ 414
545
+ when Unicorn::RequestEntityTooLargeError
546
+ 413
547
+ when Unicorn::HttpParserError # try to tell the client they're bad
548
+ 400
549
+ else
550
+ Unicorn.log_error(@logger, "app error", e)
551
+ 500
552
+ end
553
+ if code
554
+ client.kgio_trywrite(err_response(code, @request.response_start_sent))
555
+ end
556
+ client.close
557
+ rescue
558
+ end
559
+
560
+ def expect_100_response
561
+ if @request.response_start_sent
562
+ Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED
563
+ else
564
+ Unicorn::Const::EXPECT_100_RESPONSE
565
+ end
566
+ end
567
+
568
+ # once a client is accepted, it is processed in its entirety here
569
+ # in 3 easy steps: read request, call app, write app response
570
+ def process_client(client)
571
+ status, headers, body = @app.call(env = @request.read(client))
572
+ return if @request.hijacked?
573
+
574
+ if 100 == status.to_i
575
+ client.write(expect_100_response)
576
+ env.delete(Unicorn::Const::HTTP_EXPECT)
577
+ status, headers, body = @app.call(env)
578
+ return if @request.hijacked?
579
+ end
580
+ @request.headers? or headers = nil
581
+ http_response_write(client, status, headers, body,
582
+ @request.response_start_sent)
583
+ unless client.closed? # rack.hijack may've close this for us
584
+ client.shutdown # in case of fork() in Rack app
585
+ client.close # flush and uncork socket immediately, no keepalive
586
+ end
587
+ rescue => e
588
+ handle_error(client, e)
589
+ end
590
+
591
+ EXIT_SIGS = [ :QUIT, :TERM, :INT ]
592
+ WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
593
+
594
+ # gets rid of stuff the worker has no business keeping track of
595
+ # to free some resources and drops all sig handlers.
596
+ # traps for USR1, USR2, and HUP may be set in the after_fork Proc
597
+ # by the user.
598
+ def init_worker_process(worker)
599
+ worker.atfork_child
600
+ # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
601
+ EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
602
+ exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
603
+ WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
604
+ trap(:CHLD, 'DEFAULT')
605
+ SIG_QUEUE.clear
606
+ proc_name "worker[#{worker.nr}]"
607
+ START_CTX.clear
608
+ WORKERS.clear
609
+
610
+ after_fork.call(self, worker) # can drop perms and create listeners
611
+ LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
612
+
613
+ worker.user(*user) if user.kind_of?(Array) && ! worker.switched
614
+ self.timeout /= 2.0 # halve it for select()
615
+ @config = nil
616
+ build_app! unless preload_app
617
+ ssl_enable!
618
+ @after_fork = @listener_opts = @orig_app = nil
619
+ readers = LISTENERS.dup
620
+ readers << worker
621
+ trap(:QUIT) { readers.each { |io| io.close }.replace([false]) }
622
+ readers
623
+ end
624
+
625
+ def reopen_worker_logs(worker_nr)
626
+ logger.info "worker=#{worker_nr} reopening logs..."
627
+ Unicorn::Util.reopen_logs
628
+ logger.info "worker=#{worker_nr} done reopening logs"
629
+ rescue => e
630
+ logger.error(e) rescue nil
631
+ exit!(77) # EX_NOPERM in sysexits.h
632
+ end
633
+
634
+ # runs inside each forked worker, this sits around and waits
635
+ # for connections and doesn't die until the parent dies (or is
636
+ # given a INT, QUIT, or TERM signal)
637
+ def worker_loop(worker)
638
+ ppid = master_pid
639
+ readers = init_worker_process(worker)
640
+ nr = 0 # this becomes negative if we need to reopen logs
641
+
642
+ # this only works immediately if the master sent us the signal
643
+ # (which is the normal case)
644
+ trap(:USR1) { nr = -65536 }
645
+
646
+ ready = readers.dup
647
+ @logger.info "worker=#{worker.nr} ready"
648
+
649
+ begin
650
+ nr < 0 and reopen_worker_logs(worker.nr)
651
+ nr = 0
652
+ worker.tick = Time.now.to_i
653
+ tmp = ready.dup
654
+ while sock = tmp.shift
655
+ # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
656
+ # but that will return false
657
+ if client = sock.kgio_tryaccept
658
+ process_client(client)
659
+ nr += 1
660
+ worker.tick = Time.now.to_i
661
+ end
662
+ break if nr < 0
663
+ end
664
+
665
+ # make the following bet: if we accepted clients this round,
666
+ # we're probably reasonably busy, so avoid calling select()
667
+ # and do a speculative non-blocking accept() on ready listeners
668
+ # before we sleep again in select().
669
+ unless nr == 0
670
+ tmp = ready.dup
671
+ redo
672
+ end
673
+
674
+ ppid == Process.ppid or return
675
+
676
+ # timeout used so we can detect parent death:
677
+ worker.tick = Time.now.to_i
678
+ ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
679
+ rescue => e
680
+ redo if nr < 0
681
+ Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
682
+ end while readers[0]
683
+ end
684
+
685
+ # delivers a signal to a worker and fails gracefully if the worker
686
+ # is no longer running.
687
+ def kill_worker(signal, wpid)
688
+ Process.kill(signal, wpid)
689
+ rescue Errno::ESRCH
690
+ worker = WORKERS.delete(wpid) and worker.close rescue nil
691
+ end
692
+
693
+ # delivers a signal to each worker
694
+ def kill_each_worker(signal)
695
+ WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
696
+ end
697
+
698
+ def soft_kill_each_worker(signal)
699
+ WORKERS.each_value { |worker| worker.soft_kill(signal) }
700
+ end
701
+
702
+ # unlinks a PID file at given +path+ if it contains the current PID
703
+ # still potentially racy without locking the directory (which is
704
+ # non-portable and may interact badly with other programs), but the
705
+ # window for hitting the race condition is small
706
+ def unlink_pid_safe(path)
707
+ (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
708
+ end
709
+
710
+ # returns a PID if a given path contains a non-stale PID file,
711
+ # nil otherwise.
712
+ def valid_pid?(path)
713
+ wpid = File.read(path).to_i
714
+ wpid <= 0 and return
715
+ Process.kill(0, wpid)
716
+ wpid
717
+ rescue Errno::EPERM
718
+ logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
719
+ nil
720
+ rescue Errno::ESRCH, Errno::ENOENT
721
+ # don't unlink stale pid files, racy without non-portable locking...
722
+ end
723
+
724
+ def load_config!
725
+ loaded_app = app
726
+ logger.info "reloading config_file=#{config.config_file}"
727
+ config[:listeners].replace(@init_listeners)
728
+ config.reload
729
+ config.commit!(self)
730
+ soft_kill_each_worker(:QUIT)
731
+ Unicorn::Util.reopen_logs
732
+ self.app = orig_app
733
+ build_app! if preload_app
734
+ logger.info "done reloading config_file=#{config.config_file}"
735
+ rescue StandardError, LoadError, SyntaxError => e
736
+ Unicorn.log_error(@logger,
737
+ "error reloading config_file=#{config.config_file}", e)
738
+ self.app = loaded_app
739
+ end
740
+
741
+ # returns an array of string names for the given listener array
742
+ def listener_names(listeners = LISTENERS)
743
+ listeners.map { |io| sock_name(io) }
744
+ end
745
+
746
+ def build_app!
747
+ if app.respond_to?(:arity) && app.arity == 0
748
+ if defined?(Gem) && Gem.respond_to?(:refresh)
749
+ logger.info "Refreshing Gem list"
750
+ Gem.refresh
751
+ end
752
+ self.app = app.call
753
+ logger.info "sleeping #{ENV['UNICORN_SPAWN_SLEEP'] || 25} seconds after spawn for rails init"
754
+ sleep ENV['UNICORN_SPAWN_SLEEP'] || 25
755
+ end
756
+ end
757
+
758
+ def proc_name(tag)
759
+ $0 = ([ File.basename(START_CTX[0]), tag
760
+ ]).concat(START_CTX[:argv]).join(' ')
761
+ end
762
+
763
+ def redirect_io(io, path)
764
+ File.open(path, 'ab') { |fp| io.reopen(fp) } if path
765
+ io.sync = true
766
+ end
767
+
768
+ def inherit_listeners!
769
+ # inherit sockets from parents, they need to be plain Socket objects
770
+ # before they become Kgio::UNIXServer or Kgio::TCPServer
771
+ inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
772
+ io = Socket.for_fd(fd.to_i)
773
+ set_server_sockopt(io, listener_opts[sock_name(io)])
774
+ prevent_autoclose(io)
775
+ logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
776
+ server_cast(io)
777
+ end
778
+
779
+ config_listeners = config[:listeners].dup
780
+ LISTENERS.replace(inherited)
781
+
782
+ # we start out with generic Socket objects that get cast to either
783
+ # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
784
+ # objects share the same OS-level file descriptor as the higher-level
785
+ # *Server objects; we need to prevent Socket objects from being
786
+ # garbage-collected
787
+ config_listeners -= listener_names
788
+ if config_listeners.empty? && LISTENERS.empty?
789
+ config_listeners << Unicorn::Const::DEFAULT_LISTEN
790
+ @init_listeners << Unicorn::Const::DEFAULT_LISTEN
791
+ START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
792
+ end
793
+ NEW_LISTENERS.replace(config_listeners)
794
+ end
795
+
796
+ # call only after calling inherit_listeners!
797
+ # This binds any listeners we did NOT inherit from the parent
798
+ def bind_new_listeners!
799
+ NEW_LISTENERS.each { |addr| listen(addr) }
800
+ raise ArgumentError, "no listeners" if LISTENERS.empty?
801
+ NEW_LISTENERS.clear
802
+ end
803
+ end