preplay_unicorn 4.3.1.2.gc450

Sign up to get free protection for your applications and to get access to all the features.
Files changed (259) 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/.manifest +258 -0
  6. data/.wrongdoc.yml +10 -0
  7. data/Application_Timeouts +77 -0
  8. data/CONTRIBUTORS +35 -0
  9. data/COPYING +674 -0
  10. data/ChangeLog +3839 -0
  11. data/DESIGN +97 -0
  12. data/Documentation/.gitignore +5 -0
  13. data/Documentation/GNUmakefile +30 -0
  14. data/Documentation/unicorn.1.txt +174 -0
  15. data/Documentation/unicorn_rails.1.txt +175 -0
  16. data/FAQ +53 -0
  17. data/GIT-VERSION-FILE +1 -0
  18. data/GIT-VERSION-GEN +40 -0
  19. data/GNUmakefile +294 -0
  20. data/HACKING +134 -0
  21. data/ISSUES +36 -0
  22. data/KNOWN_ISSUES +79 -0
  23. data/LATEST +15 -0
  24. data/LICENSE +64 -0
  25. data/Links +56 -0
  26. data/NEWS +1886 -0
  27. data/PHILOSOPHY +145 -0
  28. data/README +149 -0
  29. data/Rakefile +97 -0
  30. data/SIGNALS +114 -0
  31. data/Sandbox +96 -0
  32. data/TODO +5 -0
  33. data/TUNING +98 -0
  34. data/bin/unicorn +121 -0
  35. data/bin/unicorn_rails +209 -0
  36. data/examples/big_app_gc.rb +2 -0
  37. data/examples/echo.ru +27 -0
  38. data/examples/git.ru +13 -0
  39. data/examples/init.sh +74 -0
  40. data/examples/logger_mp_safe.rb +25 -0
  41. data/examples/logrotate.conf +29 -0
  42. data/examples/nginx.conf +156 -0
  43. data/examples/unicorn.conf.minimal.rb +13 -0
  44. data/examples/unicorn.conf.rb +94 -0
  45. data/ext/unicorn_http/CFLAGS +13 -0
  46. data/ext/unicorn_http/c_util.h +124 -0
  47. data/ext/unicorn_http/common_field_optimization.h +111 -0
  48. data/ext/unicorn_http/ext_help.h +86 -0
  49. data/ext/unicorn_http/extconf.rb +10 -0
  50. data/ext/unicorn_http/global_variables.h +97 -0
  51. data/ext/unicorn_http/httpdate.c +82 -0
  52. data/ext/unicorn_http/unicorn_http.c +4031 -0
  53. data/ext/unicorn_http/unicorn_http.rl +1036 -0
  54. data/ext/unicorn_http/unicorn_http_common.rl +76 -0
  55. data/lib/unicorn/app/exec_cgi.rb +154 -0
  56. data/lib/unicorn/app/inetd.rb +109 -0
  57. data/lib/unicorn/app/old_rails/static.rb +59 -0
  58. data/lib/unicorn/app/old_rails.rb +35 -0
  59. data/lib/unicorn/cgi_wrapper.rb +147 -0
  60. data/lib/unicorn/configurator.rb +641 -0
  61. data/lib/unicorn/const.rb +40 -0
  62. data/lib/unicorn/http_request.rb +77 -0
  63. data/lib/unicorn/http_response.rb +45 -0
  64. data/lib/unicorn/http_server.rb +748 -0
  65. data/lib/unicorn/launcher.rb +62 -0
  66. data/lib/unicorn/oob_gc.rb +71 -0
  67. data/lib/unicorn/preread_input.rb +33 -0
  68. data/lib/unicorn/socket_helper.rb +208 -0
  69. data/lib/unicorn/ssl_client.rb +11 -0
  70. data/lib/unicorn/ssl_configurator.rb +104 -0
  71. data/lib/unicorn/ssl_server.rb +42 -0
  72. data/lib/unicorn/stream_input.rb +149 -0
  73. data/lib/unicorn/tee_input.rb +126 -0
  74. data/lib/unicorn/tmpio.rb +29 -0
  75. data/lib/unicorn/util.rb +68 -0
  76. data/lib/unicorn/worker.rb +88 -0
  77. data/lib/unicorn.rb +107 -0
  78. data/local.mk.sample +59 -0
  79. data/man/man1/unicorn.1 +201 -0
  80. data/man/man1/unicorn_rails.1 +208 -0
  81. data/preplay_unicorn.gemspec +44 -0
  82. data/script/isolate_for_tests +50 -0
  83. data/setup.rb +1586 -0
  84. data/t/.gitignore +5 -0
  85. data/t/GNUmakefile +82 -0
  86. data/t/README +42 -0
  87. data/t/bin/content-md5-put +36 -0
  88. data/t/bin/sha1sum.rb +17 -0
  89. data/t/bin/unused_listen +40 -0
  90. data/t/bin/utee +12 -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/heartbeat-timeout.ru +12 -0
  95. data/t/my-tap-lib.sh +201 -0
  96. data/t/oob_gc.ru +21 -0
  97. data/t/oob_gc_path.ru +21 -0
  98. data/t/pid.ru +3 -0
  99. data/t/preread_input.ru +17 -0
  100. data/t/rack-input-tests.ru +21 -0
  101. data/t/rails3-app/.gitignore +4 -0
  102. data/t/rails3-app/Gemfile +26 -0
  103. data/t/rails3-app/Rakefile +10 -0
  104. data/t/rails3-app/app/controllers/application_controller.rb +4 -0
  105. data/t/rails3-app/app/helpers/application_helper.rb +2 -0
  106. data/t/rails3-app/app/views/layouts/application.html.erb +14 -0
  107. data/t/rails3-app/config/application.rb +46 -0
  108. data/t/rails3-app/config/boot.rb +6 -0
  109. data/t/rails3-app/config/database.yml +22 -0
  110. data/t/rails3-app/config/environment.rb +5 -0
  111. data/t/rails3-app/config/environments/development.rb +19 -0
  112. data/t/rails3-app/config/environments/production.rb +42 -0
  113. data/t/rails3-app/config/environments/test.rb +32 -0
  114. data/t/rails3-app/config/initializers/backtrace_silencers.rb +7 -0
  115. data/t/rails3-app/config/initializers/inflections.rb +10 -0
  116. data/t/rails3-app/config/initializers/mime_types.rb +5 -0
  117. data/t/rails3-app/config/initializers/secret_token.rb +7 -0
  118. data/t/rails3-app/config/initializers/session_store.rb +8 -0
  119. data/t/rails3-app/config/locales/en.yml +5 -0
  120. data/t/rails3-app/config/routes.rb +58 -0
  121. data/t/rails3-app/config.ru +4 -0
  122. data/t/rails3-app/db/seeds.rb +7 -0
  123. data/t/rails3-app/doc/README_FOR_APP +2 -0
  124. data/t/rails3-app/lib/tasks/.gitkeep +0 -0
  125. data/t/rails3-app/public/404.html +1 -0
  126. data/t/rails3-app/public/500.html +1 -0
  127. data/t/rails3-app/public/x.txt +1 -0
  128. data/t/rails3-app/script/rails +9 -0
  129. data/t/rails3-app/test/performance/browsing_test.rb +9 -0
  130. data/t/rails3-app/test/test_helper.rb +13 -0
  131. data/t/rails3-app/vendor/plugins/.gitkeep +0 -0
  132. data/t/sslgen.sh +71 -0
  133. data/t/t0000-http-basic.sh +50 -0
  134. data/t/t0001-reload-bad-config.sh +53 -0
  135. data/t/t0002-config-conflict.sh +49 -0
  136. data/t/t0002-parser-error.sh +94 -0
  137. data/t/t0003-working_directory.sh +51 -0
  138. data/t/t0004-heartbeat-timeout.sh +69 -0
  139. data/t/t0004-working_directory_broken.sh +24 -0
  140. data/t/t0005-working_directory_app.rb.sh +37 -0
  141. data/t/t0006-reopen-logs.sh +83 -0
  142. data/t/t0006.ru +13 -0
  143. data/t/t0007-working_directory_no_embed_cli.sh +44 -0
  144. data/t/t0008-back_out_of_upgrade.sh +110 -0
  145. data/t/t0009-broken-app.sh +56 -0
  146. data/t/t0009-winch_ttin.sh +59 -0
  147. data/t/t0010-reap-logging.sh +55 -0
  148. data/t/t0011-active-unix-socket.sh +79 -0
  149. data/t/t0012-reload-empty-config.sh +85 -0
  150. data/t/t0013-rewindable-input-false.sh +24 -0
  151. data/t/t0013.ru +12 -0
  152. data/t/t0014-rewindable-input-true.sh +24 -0
  153. data/t/t0014.ru +12 -0
  154. data/t/t0015-configurator-internals.sh +25 -0
  155. data/t/t0016-trust-x-forwarded-false.sh +30 -0
  156. data/t/t0017-trust-x-forwarded-true.sh +30 -0
  157. data/t/t0018-write-on-close.sh +23 -0
  158. data/t/t0019-max_header_len.sh +49 -0
  159. data/t/t0020-at_exit-handler.sh +49 -0
  160. data/t/t0021-process_detach.sh +29 -0
  161. data/t/t0100-rack-input-tests.sh +124 -0
  162. data/t/t0116-client_body_buffer_size.sh +80 -0
  163. data/t/t0116.ru +16 -0
  164. data/t/t0300-rails3-basic.sh +28 -0
  165. data/t/t0301-rails3-missing-config-ru.sh +33 -0
  166. data/t/t0302-rails3-alt-working_directory.sh +32 -0
  167. data/t/t0303-rails3-alt-working_directory_config.ru.sh +56 -0
  168. data/t/t0304-rails3-alt-working_directory_no_embed_cli.sh +52 -0
  169. data/t/t0600-https-server-basic.sh +48 -0
  170. data/t/t9000-preread-input.sh +48 -0
  171. data/t/t9001-oob_gc.sh +47 -0
  172. data/t/t9002-oob_gc-path.sh +75 -0
  173. data/t/test-lib.sh +113 -0
  174. data/t/test-rails3.sh +27 -0
  175. data/t/write-on-close.ru +11 -0
  176. data/test/aggregate.rb +15 -0
  177. data/test/benchmark/README +50 -0
  178. data/test/benchmark/dd.ru +18 -0
  179. data/test/benchmark/stack.ru +8 -0
  180. data/test/exec/README +5 -0
  181. data/test/exec/test_exec.rb +1055 -0
  182. data/test/rails/app-1.2.3/.gitignore +2 -0
  183. data/test/rails/app-1.2.3/Rakefile +7 -0
  184. data/test/rails/app-1.2.3/app/controllers/application.rb +6 -0
  185. data/test/rails/app-1.2.3/app/controllers/foo_controller.rb +36 -0
  186. data/test/rails/app-1.2.3/app/helpers/application_helper.rb +4 -0
  187. data/test/rails/app-1.2.3/config/boot.rb +11 -0
  188. data/test/rails/app-1.2.3/config/database.yml +12 -0
  189. data/test/rails/app-1.2.3/config/environment.rb +13 -0
  190. data/test/rails/app-1.2.3/config/environments/development.rb +9 -0
  191. data/test/rails/app-1.2.3/config/environments/production.rb +5 -0
  192. data/test/rails/app-1.2.3/config/routes.rb +6 -0
  193. data/test/rails/app-1.2.3/db/.gitignore +0 -0
  194. data/test/rails/app-1.2.3/log/.gitignore +1 -0
  195. data/test/rails/app-1.2.3/public/404.html +1 -0
  196. data/test/rails/app-1.2.3/public/500.html +1 -0
  197. data/test/rails/app-2.0.2/.gitignore +2 -0
  198. data/test/rails/app-2.0.2/Rakefile +7 -0
  199. data/test/rails/app-2.0.2/app/controllers/application.rb +4 -0
  200. data/test/rails/app-2.0.2/app/controllers/foo_controller.rb +36 -0
  201. data/test/rails/app-2.0.2/app/helpers/application_helper.rb +4 -0
  202. data/test/rails/app-2.0.2/config/boot.rb +11 -0
  203. data/test/rails/app-2.0.2/config/database.yml +12 -0
  204. data/test/rails/app-2.0.2/config/environment.rb +17 -0
  205. data/test/rails/app-2.0.2/config/environments/development.rb +8 -0
  206. data/test/rails/app-2.0.2/config/environments/production.rb +5 -0
  207. data/test/rails/app-2.0.2/config/routes.rb +6 -0
  208. data/test/rails/app-2.0.2/db/.gitignore +0 -0
  209. data/test/rails/app-2.0.2/log/.gitignore +1 -0
  210. data/test/rails/app-2.0.2/public/404.html +1 -0
  211. data/test/rails/app-2.0.2/public/500.html +1 -0
  212. data/test/rails/app-2.1.2/.gitignore +2 -0
  213. data/test/rails/app-2.1.2/Rakefile +7 -0
  214. data/test/rails/app-2.1.2/app/controllers/application.rb +4 -0
  215. data/test/rails/app-2.1.2/app/controllers/foo_controller.rb +36 -0
  216. data/test/rails/app-2.1.2/app/helpers/application_helper.rb +4 -0
  217. data/test/rails/app-2.1.2/config/boot.rb +111 -0
  218. data/test/rails/app-2.1.2/config/database.yml +12 -0
  219. data/test/rails/app-2.1.2/config/environment.rb +17 -0
  220. data/test/rails/app-2.1.2/config/environments/development.rb +7 -0
  221. data/test/rails/app-2.1.2/config/environments/production.rb +5 -0
  222. data/test/rails/app-2.1.2/config/routes.rb +6 -0
  223. data/test/rails/app-2.1.2/db/.gitignore +0 -0
  224. data/test/rails/app-2.1.2/log/.gitignore +1 -0
  225. data/test/rails/app-2.1.2/public/404.html +1 -0
  226. data/test/rails/app-2.1.2/public/500.html +1 -0
  227. data/test/rails/app-2.2.2/.gitignore +2 -0
  228. data/test/rails/app-2.2.2/Rakefile +7 -0
  229. data/test/rails/app-2.2.2/app/controllers/application.rb +4 -0
  230. data/test/rails/app-2.2.2/app/controllers/foo_controller.rb +36 -0
  231. data/test/rails/app-2.2.2/app/helpers/application_helper.rb +4 -0
  232. data/test/rails/app-2.2.2/config/boot.rb +111 -0
  233. data/test/rails/app-2.2.2/config/database.yml +12 -0
  234. data/test/rails/app-2.2.2/config/environment.rb +17 -0
  235. data/test/rails/app-2.2.2/config/environments/development.rb +7 -0
  236. data/test/rails/app-2.2.2/config/environments/production.rb +5 -0
  237. data/test/rails/app-2.2.2/config/routes.rb +6 -0
  238. data/test/rails/app-2.2.2/db/.gitignore +0 -0
  239. data/test/rails/app-2.2.2/log/.gitignore +1 -0
  240. data/test/rails/app-2.2.2/public/404.html +1 -0
  241. data/test/rails/app-2.2.2/public/500.html +1 -0
  242. data/test/rails/test_rails.rb +287 -0
  243. data/test/test_helper.rb +300 -0
  244. data/test/unit/test_configurator.rb +158 -0
  245. data/test/unit/test_droplet.rb +28 -0
  246. data/test/unit/test_http_parser.rb +860 -0
  247. data/test/unit/test_http_parser_ng.rb +716 -0
  248. data/test/unit/test_http_parser_xftrust.rb +38 -0
  249. data/test/unit/test_request.rb +197 -0
  250. data/test/unit/test_response.rb +99 -0
  251. data/test/unit/test_server.rb +289 -0
  252. data/test/unit/test_signals.rb +207 -0
  253. data/test/unit/test_sni_hostnames.rb +47 -0
  254. data/test/unit/test_socket_helper.rb +192 -0
  255. data/test/unit/test_stream_input.rb +204 -0
  256. data/test/unit/test_tee_input.rb +296 -0
  257. data/test/unit/test_upload.rb +306 -0
  258. data/test/unit/test_util.rb +100 -0
  259. metadata +428 -0
@@ -0,0 +1,748 @@
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
+ :after_worker_ready, :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, :URG ]
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 + QUIT 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 :QUIT # graceful shutdown
275
+ break
276
+ when :TERM, :INT # 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(:QUIT)
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
+ when :URG
309
+ after_worker_ready.call(self)
310
+ end
311
+
312
+ rescue => e
313
+ Unicorn.log_error(@logger, "master loop error", e)
314
+ end while true
315
+ stop # gracefully shutdown all workers on our way out
316
+ logger.info "master complete"
317
+ unlink_pid_safe(pid) if pid
318
+ end
319
+
320
+ # Terminates all workers, but does not exit master process
321
+ def stop(graceful = true)
322
+ self.listeners = []
323
+ limit = Time.now + timeout
324
+ until WORKERS.empty? || Time.now > limit
325
+ kill_each_worker(graceful ? :QUIT : :TERM)
326
+ sleep(0.1)
327
+ reap_all_workers
328
+ end
329
+ kill_each_worker(:KILL)
330
+ end
331
+
332
+ def rewindable_input
333
+ Unicorn::HttpRequest.input_class.method_defined?(:rewind)
334
+ end
335
+
336
+ def rewindable_input=(bool)
337
+ Unicorn::HttpRequest.input_class = bool ?
338
+ Unicorn::TeeInput : Unicorn::StreamInput
339
+ end
340
+
341
+ def client_body_buffer_size
342
+ Unicorn::TeeInput.client_body_buffer_size
343
+ end
344
+
345
+ def client_body_buffer_size=(bytes)
346
+ Unicorn::TeeInput.client_body_buffer_size = bytes
347
+ end
348
+
349
+ def trust_x_forwarded
350
+ Unicorn::HttpParser.trust_x_forwarded?
351
+ end
352
+
353
+ def trust_x_forwarded=(bool)
354
+ Unicorn::HttpParser.trust_x_forwarded = bool
355
+ end
356
+
357
+ private
358
+
359
+ # wait for a signal hander to wake us up and then consume the pipe
360
+ def master_sleep(sec)
361
+ IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
362
+ SELF_PIPE[0].kgio_tryread(11)
363
+ end
364
+
365
+ def awaken_master
366
+ SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
367
+ end
368
+
369
+ # reaps all unreaped workers
370
+ def reap_all_workers
371
+ begin
372
+ wpid, status = Process.waitpid2(-1, Process::WNOHANG)
373
+ wpid or return
374
+ if reexec_pid == wpid
375
+ logger.error "reaped #{status.inspect} exec()-ed"
376
+ self.reexec_pid = 0
377
+ self.pid = pid.chomp('.oldbin') if pid
378
+ proc_name 'master'
379
+ else
380
+ worker = WORKERS.delete(wpid) and worker.close rescue nil
381
+ m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
382
+ status.success? ? logger.info(m) : logger.error(m)
383
+ end
384
+ rescue Errno::ECHILD
385
+ break
386
+ end while true
387
+ end
388
+
389
+ # reexecutes the START_CTX with a new binary
390
+ def reexec
391
+ if reexec_pid > 0
392
+ begin
393
+ Process.kill(0, reexec_pid)
394
+ logger.error "reexec-ed child already running PID:#{reexec_pid}"
395
+ return
396
+ rescue Errno::ESRCH
397
+ self.reexec_pid = 0
398
+ end
399
+ end
400
+
401
+ if pid
402
+ old_pid = "#{pid}.oldbin"
403
+ begin
404
+ self.pid = old_pid # clear the path for a new pid file
405
+ rescue ArgumentError
406
+ logger.error "old PID:#{valid_pid?(old_pid)} running with " \
407
+ "existing pid=#{old_pid}, refusing rexec"
408
+ return
409
+ rescue => e
410
+ logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
411
+ return
412
+ end
413
+ end
414
+
415
+ self.reexec_pid = fork do
416
+ listener_fds = Hash[LISTENERS.map do |sock|
417
+ # IO#close_on_exec= will be available on any future version of
418
+ # Ruby that sets FD_CLOEXEC by default on new file descriptors
419
+ # ref: http://redmine.ruby-lang.org/issues/5041
420
+ sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
421
+ [ sock.fileno, sock ]
422
+ end]
423
+ ENV['UNICORN_FD'] = listener_fds.keys.join(',')
424
+ Dir.chdir(START_CTX[:cwd])
425
+ cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
426
+
427
+ # avoid leaking FDs we don't know about, but let before_exec
428
+ # unset FD_CLOEXEC, if anything else in the app eventually
429
+ # relies on FD inheritence.
430
+ (3..1024).each do |io|
431
+ next if listener_fds.include?(io)
432
+ io = IO.for_fd(io) rescue next
433
+ IO_PURGATORY << io
434
+ io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
435
+ end
436
+
437
+ # exec(command, hash) works in at least 1.9.1+, but will only be
438
+ # required in 1.9.4/2.0.0 at earliest.
439
+ cmd << listener_fds if RUBY_VERSION >= "1.9.1"
440
+ logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
441
+ before_exec.call(self)
442
+ exec(*cmd)
443
+ end
444
+ proc_name 'master (old)'
445
+ end
446
+
447
+ # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
448
+ def murder_lazy_workers
449
+ next_sleep = @timeout - 1
450
+ now = Time.now.to_i
451
+ WORKERS.dup.each_pair do |wpid, worker|
452
+ tick = worker.tick
453
+ 0 == tick and next # skip workers that haven't processed any clients
454
+ diff = now - tick
455
+ tmp = @timeout - diff
456
+ if tmp >= 0
457
+ next_sleep > tmp and next_sleep = tmp
458
+ next
459
+ end
460
+ next_sleep = 0
461
+ logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
462
+ "(#{diff}s > #{@timeout}s), killing"
463
+ kill_worker(:KILL, wpid) # take no prisoners for timeout violations
464
+ end
465
+ next_sleep <= 0 ? 1 : next_sleep
466
+ end
467
+
468
+ def after_fork_internal
469
+ @ready_pipe.close if @ready_pipe
470
+ Unicorn::Configurator::RACKUP.clear
471
+ @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
472
+
473
+ srand # http://redmine.ruby-lang.org/issues/4338
474
+
475
+ # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
476
+ # dying workers can recycle pids
477
+ OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
478
+ end
479
+
480
+ def spawn_missing_workers
481
+ worker_nr = -1
482
+ until (worker_nr += 1) == @worker_processes
483
+ WORKERS.value?(worker_nr) and next
484
+ worker = Worker.new(worker_nr)
485
+ before_fork.call(self, worker)
486
+ if pid = fork
487
+ WORKERS[pid] = worker
488
+ else
489
+ after_fork_internal
490
+ worker_loop(worker)
491
+ exit
492
+ end
493
+ end
494
+ rescue => e
495
+ @logger.error(e) rescue nil
496
+ exit!
497
+ end
498
+
499
+ def maintain_worker_count
500
+ (off = WORKERS.size - worker_processes) == 0 and return
501
+ off < 0 and return spawn_missing_workers
502
+ WORKERS.dup.each_pair { |wpid,w|
503
+ w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
504
+ }
505
+ end
506
+
507
+ # if we get any error, try to write something back to the client
508
+ # assuming we haven't closed the socket, but don't get hung up
509
+ # if the socket is already closed or broken. We'll always ensure
510
+ # the socket is closed at the end of this function
511
+ def handle_error(client, e)
512
+ msg = case e
513
+ when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF,
514
+ Errno::ENOTCONN
515
+ Unicorn::Const::ERROR_500_RESPONSE
516
+ when Unicorn::RequestURITooLongError
517
+ Unicorn::Const::ERROR_414_RESPONSE
518
+ when Unicorn::RequestEntityTooLargeError
519
+ Unicorn::Const::ERROR_413_RESPONSE
520
+ when Unicorn::HttpParserError # try to tell the client they're bad
521
+ Unicorn::Const::ERROR_400_RESPONSE
522
+ else
523
+ Unicorn.log_error(@logger, "app error", e)
524
+ Unicorn::Const::ERROR_500_RESPONSE
525
+ end
526
+ client.kgio_trywrite(msg)
527
+ client.close
528
+ rescue
529
+ end
530
+
531
+ # once a client is accepted, it is processed in its entirety here
532
+ # in 3 easy steps: read request, call app, write app response
533
+ def process_client(client)
534
+ status, headers, body = @app.call(env = @request.read(client))
535
+
536
+ if 100 == status.to_i
537
+ client.write(Unicorn::Const::EXPECT_100_RESPONSE)
538
+ env.delete(Unicorn::Const::HTTP_EXPECT)
539
+ status, headers, body = @app.call(env)
540
+ end
541
+ @request.headers? or headers = nil
542
+ http_response_write(client, status, headers, body)
543
+ client.shutdown # in case of fork() in Rack app
544
+ client.close # flush and uncork socket immediately, no keepalive
545
+ rescue => e
546
+ handle_error(client, e)
547
+ end
548
+
549
+ EXIT_SIGS = [ :QUIT, :TERM, :INT ]
550
+ WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
551
+
552
+ # gets rid of stuff the worker has no business keeping track of
553
+ # to free some resources and drops all sig handlers.
554
+ # traps for USR1, USR2, and HUP may be set in the after_fork Proc
555
+ # by the user.
556
+ def init_worker_process(worker)
557
+ # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
558
+ EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
559
+ exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
560
+ WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
561
+ trap(:CHLD, 'DEFAULT')
562
+ SIG_QUEUE.clear
563
+ proc_name "worker[#{worker.nr}]"
564
+ START_CTX.clear
565
+ init_self_pipe!
566
+ WORKERS.clear
567
+ LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
568
+ after_fork.call(self, worker) # can drop perms
569
+ worker.user(*user) if user.kind_of?(Array) && ! worker.switched
570
+ self.timeout /= 2.0 # halve it for select()
571
+ @config = nil
572
+ build_app! unless preload_app
573
+ ssl_enable!
574
+ @after_fork = @listener_opts = @orig_app = nil
575
+ end
576
+
577
+ def reopen_worker_logs(worker_nr)
578
+ logger.info "worker=#{worker_nr} reopening logs..."
579
+ Unicorn::Util.reopen_logs
580
+ logger.info "worker=#{worker_nr} done reopening logs"
581
+ init_self_pipe!
582
+ rescue => e
583
+ logger.error(e) rescue nil
584
+ exit!(77) # EX_NOPERM in sysexits.h
585
+ end
586
+
587
+ # runs inside each forked worker, this sits around and waits
588
+ # for connections and doesn't die until the parent dies (or is
589
+ # given a INT, QUIT, or TERM signal)
590
+ def worker_loop(worker)
591
+ ppid = master_pid
592
+ init_worker_process(worker)
593
+ nr = 0 # this becomes negative if we need to reopen logs
594
+ l = LISTENERS.dup
595
+ ready = l.dup
596
+
597
+ # closing anything we IO.select on will raise EBADF
598
+ trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
599
+ trap(:QUIT) { worker = nil; LISTENERS.each { |s| s.close rescue nil }.clear }
600
+ logger.info "worker=#{worker.nr} ready"
601
+ Process.kill(:URG, ppid)
602
+
603
+ begin
604
+ nr < 0 and reopen_worker_logs(worker.nr)
605
+ nr = 0
606
+
607
+ worker.tick = Time.now.to_i
608
+ while sock = ready.shift
609
+ if client = sock.kgio_tryaccept
610
+ process_client(client)
611
+ nr += 1
612
+ worker.tick = Time.now.to_i
613
+ end
614
+ break if nr < 0
615
+ end
616
+
617
+ # make the following bet: if we accepted clients this round,
618
+ # we're probably reasonably busy, so avoid calling select()
619
+ # and do a speculative non-blocking accept() on ready listeners
620
+ # before we sleep again in select().
621
+ unless nr == 0 # (nr < 0) => reopen logs (unlikely)
622
+ ready = l.dup
623
+ redo
624
+ end
625
+
626
+ ppid == Process.ppid or return
627
+
628
+ # timeout used so we can detect parent death:
629
+ worker.tick = Time.now.to_i
630
+ ret = IO.select(l, nil, SELF_PIPE, @timeout) and ready = ret[0]
631
+ rescue => e
632
+ redo if nr < 0 && (Errno::EBADF === e || IOError === e) # reopen logs
633
+ Unicorn.log_error(@logger, "listen loop error", e) if worker
634
+ end while worker
635
+ end
636
+
637
+ # delivers a signal to a worker and fails gracefully if the worker
638
+ # is no longer running.
639
+ def kill_worker(signal, wpid)
640
+ Process.kill(signal, wpid)
641
+ rescue Errno::ESRCH
642
+ worker = WORKERS.delete(wpid) and worker.close rescue nil
643
+ end
644
+
645
+ # delivers a signal to each worker
646
+ def kill_each_worker(signal)
647
+ WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
648
+ end
649
+
650
+ # unlinks a PID file at given +path+ if it contains the current PID
651
+ # still potentially racy without locking the directory (which is
652
+ # non-portable and may interact badly with other programs), but the
653
+ # window for hitting the race condition is small
654
+ def unlink_pid_safe(path)
655
+ (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
656
+ end
657
+
658
+ # returns a PID if a given path contains a non-stale PID file,
659
+ # nil otherwise.
660
+ def valid_pid?(path)
661
+ wpid = File.read(path).to_i
662
+ wpid <= 0 and return
663
+ Process.kill(0, wpid)
664
+ wpid
665
+ rescue Errno::EPERM
666
+ logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
667
+ nil
668
+ rescue Errno::ESRCH, Errno::ENOENT
669
+ # don't unlink stale pid files, racy without non-portable locking...
670
+ end
671
+
672
+ def load_config!
673
+ loaded_app = app
674
+ logger.info "reloading config_file=#{config.config_file}"
675
+ config[:listeners].replace(@init_listeners)
676
+ config.reload
677
+ config.commit!(self)
678
+ kill_each_worker(:QUIT)
679
+ Unicorn::Util.reopen_logs
680
+ self.app = orig_app
681
+ build_app! if preload_app
682
+ logger.info "done reloading config_file=#{config.config_file}"
683
+ rescue StandardError, LoadError, SyntaxError => e
684
+ Unicorn.log_error(@logger,
685
+ "error reloading config_file=#{config.config_file}", e)
686
+ self.app = loaded_app
687
+ end
688
+
689
+ # returns an array of string names for the given listener array
690
+ def listener_names(listeners = LISTENERS)
691
+ listeners.map { |io| sock_name(io) }
692
+ end
693
+
694
+ def build_app!
695
+ if app.respond_to?(:arity) && app.arity == 0
696
+ if defined?(Gem) && Gem.respond_to?(:refresh)
697
+ logger.info "Refreshing Gem list"
698
+ Gem.refresh
699
+ end
700
+ self.app = app.call
701
+ end
702
+ end
703
+
704
+ def proc_name(tag)
705
+ $0 = ([ File.basename(START_CTX[0]), tag
706
+ ]).concat(START_CTX[:argv]).join(' ')
707
+ end
708
+
709
+ def redirect_io(io, path)
710
+ File.open(path, 'ab') { |fp| io.reopen(fp) } if path
711
+ io.sync = true
712
+ end
713
+
714
+ def init_self_pipe!
715
+ SELF_PIPE.each { |io| io.close rescue nil }
716
+ SELF_PIPE.replace(Kgio::Pipe.new)
717
+ SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
718
+ end
719
+
720
+ def inherit_listeners!
721
+ # inherit sockets from parents, they need to be plain Socket objects
722
+ # before they become Kgio::UNIXServer or Kgio::TCPServer
723
+ inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
724
+ io = Socket.for_fd(fd.to_i)
725
+ set_server_sockopt(io, listener_opts[sock_name(io)])
726
+ IO_PURGATORY << io
727
+ logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
728
+ server_cast(io)
729
+ end
730
+
731
+ config_listeners = config[:listeners].dup
732
+ LISTENERS.replace(inherited)
733
+
734
+ # we start out with generic Socket objects that get cast to either
735
+ # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
736
+ # objects share the same OS-level file descriptor as the higher-level
737
+ # *Server objects; we need to prevent Socket objects from being
738
+ # garbage-collected
739
+ config_listeners -= listener_names
740
+ if config_listeners.empty? && LISTENERS.empty?
741
+ config_listeners << Unicorn::Const::DEFAULT_LISTEN
742
+ @init_listeners << Unicorn::Const::DEFAULT_LISTEN
743
+ START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
744
+ end
745
+ config_listeners.each { |addr| listen(addr) }
746
+ raise ArgumentError, "no listeners" if LISTENERS.empty?
747
+ end
748
+ end