unicorn-heroku 4.3.1.1.gc608.dirty

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