puma 3.12.6 → 6.3.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of puma might be problematic. Click here for more details.

Files changed (100) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +1806 -451
  3. data/LICENSE +23 -20
  4. data/README.md +217 -65
  5. data/bin/puma-wild +3 -9
  6. data/docs/architecture.md +59 -21
  7. data/docs/compile_options.md +55 -0
  8. data/docs/deployment.md +69 -58
  9. data/docs/fork_worker.md +31 -0
  10. data/docs/images/puma-connection-flow-no-reactor.png +0 -0
  11. data/docs/images/puma-connection-flow.png +0 -0
  12. data/docs/images/puma-general-arch.png +0 -0
  13. data/docs/jungle/README.md +9 -0
  14. data/{tools → docs}/jungle/rc.d/README.md +1 -1
  15. data/{tools → docs}/jungle/rc.d/puma +2 -2
  16. data/docs/kubernetes.md +66 -0
  17. data/docs/nginx.md +2 -2
  18. data/docs/plugins.md +22 -12
  19. data/docs/rails_dev_mode.md +28 -0
  20. data/docs/restart.md +47 -22
  21. data/docs/signals.md +13 -11
  22. data/docs/stats.md +142 -0
  23. data/docs/systemd.md +94 -120
  24. data/docs/testing_benchmarks_local_files.md +150 -0
  25. data/docs/testing_test_rackup_ci_files.md +36 -0
  26. data/ext/puma_http11/PumaHttp11Service.java +2 -2
  27. data/ext/puma_http11/ext_help.h +1 -1
  28. data/ext/puma_http11/extconf.rb +61 -3
  29. data/ext/puma_http11/http11_parser.c +103 -117
  30. data/ext/puma_http11/http11_parser.h +2 -2
  31. data/ext/puma_http11/http11_parser.java.rl +22 -38
  32. data/ext/puma_http11/http11_parser.rl +3 -3
  33. data/ext/puma_http11/http11_parser_common.rl +6 -6
  34. data/ext/puma_http11/mini_ssl.c +389 -99
  35. data/ext/puma_http11/no_ssl/PumaHttp11Service.java +15 -0
  36. data/ext/puma_http11/org/jruby/puma/Http11.java +108 -116
  37. data/ext/puma_http11/org/jruby/puma/Http11Parser.java +84 -99
  38. data/ext/puma_http11/org/jruby/puma/MiniSSL.java +248 -92
  39. data/ext/puma_http11/puma_http11.c +49 -57
  40. data/lib/puma/app/status.rb +71 -49
  41. data/lib/puma/binder.rb +244 -150
  42. data/lib/puma/cli.rb +38 -34
  43. data/lib/puma/client.rb +388 -244
  44. data/lib/puma/cluster/worker.rb +180 -0
  45. data/lib/puma/cluster/worker_handle.rb +97 -0
  46. data/lib/puma/cluster.rb +261 -243
  47. data/lib/puma/commonlogger.rb +21 -14
  48. data/lib/puma/configuration.rb +116 -88
  49. data/lib/puma/const.rb +154 -104
  50. data/lib/puma/control_cli.rb +115 -70
  51. data/lib/puma/detect.rb +33 -2
  52. data/lib/puma/dsl.rb +764 -134
  53. data/lib/puma/error_logger.rb +113 -0
  54. data/lib/puma/events.rb +16 -112
  55. data/lib/puma/io_buffer.rb +42 -5
  56. data/lib/puma/jruby_restart.rb +2 -59
  57. data/lib/puma/json_serialization.rb +96 -0
  58. data/lib/puma/launcher/bundle_pruner.rb +104 -0
  59. data/lib/puma/launcher.rb +184 -133
  60. data/lib/puma/log_writer.rb +147 -0
  61. data/lib/puma/minissl/context_builder.rb +93 -0
  62. data/lib/puma/minissl.rb +263 -70
  63. data/lib/puma/null_io.rb +18 -1
  64. data/lib/puma/plugin/systemd.rb +90 -0
  65. data/lib/puma/plugin/tmp_restart.rb +3 -1
  66. data/lib/puma/plugin.rb +7 -13
  67. data/lib/puma/rack/builder.rb +9 -11
  68. data/lib/puma/rack/urlmap.rb +2 -0
  69. data/lib/puma/rack_default.rb +21 -4
  70. data/lib/puma/reactor.rb +93 -315
  71. data/lib/puma/request.rb +671 -0
  72. data/lib/puma/runner.rb +94 -69
  73. data/lib/puma/sd_notify.rb +149 -0
  74. data/lib/puma/server.rb +327 -772
  75. data/lib/puma/single.rb +20 -74
  76. data/lib/puma/state_file.rb +45 -8
  77. data/lib/puma/thread_pool.rb +146 -92
  78. data/lib/puma/util.rb +22 -10
  79. data/lib/puma.rb +60 -5
  80. data/lib/rack/handler/puma.rb +116 -90
  81. data/tools/Dockerfile +16 -0
  82. data/tools/trickletest.rb +0 -1
  83. metadata +54 -32
  84. data/ext/puma_http11/io_buffer.c +0 -155
  85. data/lib/puma/accept_nonblock.rb +0 -23
  86. data/lib/puma/compat.rb +0 -14
  87. data/lib/puma/convenient.rb +0 -25
  88. data/lib/puma/daemon_ext.rb +0 -33
  89. data/lib/puma/delegation.rb +0 -13
  90. data/lib/puma/java_io_buffer.rb +0 -47
  91. data/lib/puma/rack/backports/uri/common_193.rb +0 -33
  92. data/lib/puma/tcp_logger.rb +0 -41
  93. data/tools/jungle/README.md +0 -19
  94. data/tools/jungle/init.d/README.md +0 -61
  95. data/tools/jungle/init.d/puma +0 -421
  96. data/tools/jungle/init.d/run-puma +0 -18
  97. data/tools/jungle/upstart/README.md +0 -61
  98. data/tools/jungle/upstart/puma-manager.conf +0 -31
  99. data/tools/jungle/upstart/puma.conf +0 -69
  100. /data/{tools → docs}/jungle/rc.d/puma.conf +0 -0
data/lib/puma/dsl.rb CHANGED
@@ -1,7 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative 'const'
4
+ require_relative 'util'
5
+
3
6
  module Puma
4
- # The methods that are available for use inside the config file.
7
+ # The methods that are available for use inside the configuration file.
5
8
  # These same methods are used in Puma cli and the rack handler
6
9
  # internally.
7
10
  #
@@ -12,23 +15,110 @@ module Puma
12
15
  # end
13
16
  # config.load
14
17
  #
15
- # puts config.options[:binds]
16
- # "tcp://127.0.0.1:3001"
18
+ # puts config.options[:binds] # => "tcp://127.0.0.1:3001"
17
19
  #
18
20
  # Used to load file:
19
21
  #
20
22
  # $ cat puma_config.rb
21
- # port 3002
23
+ # port 3002
24
+ #
25
+ # Resulting configuration:
22
26
  #
23
27
  # config = Configuration.new(config_file: "puma_config.rb")
24
28
  # config.load
25
29
  #
26
- # puts config.options[:binds]
27
- # # => "tcp://127.0.0.1:3002"
30
+ # puts config.options[:binds] # => "tcp://127.0.0.1:3002"
31
+ #
32
+ # You can also find many examples being used by the test suite in
33
+ # +test/config+.
34
+ #
35
+ # Puma v6 adds the option to specify a key name (String or Symbol) to the
36
+ # hooks that run inside the forked workers. All the hooks run inside the
37
+ # {Puma::Cluster::Worker#run} method.
38
+ #
39
+ # Previously, the worker index and the LogWriter instance were passed to the
40
+ # hook blocks/procs. If a key name is specified, a hash is passed as the last
41
+ # parameter. This allows storage of data, typically objects that are created
42
+ # before the worker that need to be passed to the hook when the worker is shutdown.
43
+ #
44
+ # The following hooks have been updated:
45
+ #
46
+ # | DSL Method | Options Key | Fork Block Location |
47
+ # | on_worker_boot | :before_worker_boot | inside, before |
48
+ # | on_worker_shutdown | :before_worker_shutdown | inside, after |
49
+ # | on_refork | :before_refork | inside |
28
50
  #
29
- # Detailed docs can be found in `examples/config.rb`
30
51
  class DSL
31
- include ConfigDefault
52
+ ON_WORKER_KEY = [String, Symbol].freeze
53
+
54
+ # convenience method so logic can be used in CI
55
+ # @see ssl_bind
56
+ #
57
+ def self.ssl_bind_str(host, port, opts)
58
+ verify = opts.fetch(:verify_mode, 'none').to_s
59
+
60
+ tls_str =
61
+ if opts[:no_tlsv1_1] then '&no_tlsv1_1=true'
62
+ elsif opts[:no_tlsv1] then '&no_tlsv1=true'
63
+ else ''
64
+ end
65
+
66
+ ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify)
67
+
68
+ low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : ''
69
+ backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : ''
70
+
71
+ if defined?(JRUBY_VERSION)
72
+ cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name
73
+ cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites]
74
+ protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil
75
+
76
+ keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}"
77
+ keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type]
78
+ if opts[:truststore]
79
+ truststore_additions = "&truststore=#{opts[:truststore]}"
80
+ truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass]
81
+ truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type]
82
+ end
83
+
84
+ "ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \
85
+ "&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}"
86
+ else
87
+ ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil
88
+ v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil
89
+
90
+ cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil
91
+ key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil
92
+ password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil
93
+
94
+ reuse_flag =
95
+ if (reuse = opts[:reuse])
96
+ if reuse == true
97
+ '&reuse=dflt'
98
+ elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout))
99
+ val = +''
100
+ if (size = reuse[:size]) && Integer === size
101
+ val << size.to_s
102
+ end
103
+ if (timeout = reuse[:timeout]) && Integer === timeout
104
+ val << ",#{timeout}"
105
+ end
106
+ if val.empty?
107
+ nil
108
+ else
109
+ "&reuse=#{val}"
110
+ end
111
+ else
112
+ nil
113
+ end
114
+ else
115
+ nil
116
+ end
117
+
118
+ "ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}" \
119
+ "#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}"
120
+ end
121
+ end
32
122
 
33
123
  def initialize(options, config)
34
124
  @config = config
@@ -62,7 +152,7 @@ module Puma
62
152
  end
63
153
 
64
154
  def default_host
65
- @options[:default_host] || Configuration::DefaultTCPHost
155
+ @options[:default_host] || Configuration::DEFAULTS[:tcp_host]
66
156
  end
67
157
 
68
158
  def inject(&blk)
@@ -79,8 +169,24 @@ module Puma
79
169
  @plugins << @config.load_plugin(name)
80
170
  end
81
171
 
82
- # Use +obj+ or +block+ as the Rack app. This allows a config file to
83
- # be the app itself.
172
+ # Use an object or block as the rack application. This allows the
173
+ # configuration file to be the application itself.
174
+ #
175
+ # @example
176
+ # app do |env|
177
+ # body = 'Hello, World!'
178
+ #
179
+ # [
180
+ # 200,
181
+ # {
182
+ # 'Content-Type' => 'text/plain',
183
+ # 'Content-Length' => body.length.to_s
184
+ # },
185
+ # [body]
186
+ # ]
187
+ # end
188
+ #
189
+ # @see Puma::Configuration#app
84
190
  #
85
191
  def app(obj=nil, &block)
86
192
  obj ||= block
@@ -90,9 +196,20 @@ module Puma
90
196
  @options[:app] = obj
91
197
  end
92
198
 
93
- # Start the Puma control rack app on +url+. This app can be communicated
94
- # with to control the main server.
199
+ # Start the Puma control rack application on +url+. This application can
200
+ # be communicated with to control the main server. Additionally, you can
201
+ # provide an authentication token, so all requests to the control server
202
+ # will need to include that token as a query parameter. This allows for
203
+ # simple authentication.
95
204
  #
205
+ # Check out {Puma::App::Status} to see what the app has available.
206
+ #
207
+ # @example
208
+ # activate_control_app 'unix:///var/run/pumactl.sock'
209
+ # @example
210
+ # activate_control_app 'unix:///var/run/pumactl.sock', { auth_token: '12345' }
211
+ # @example
212
+ # activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true }
96
213
  def activate_control_app(url="auto", opts={})
97
214
  if url == "auto"
98
215
  path = Configuration.temp_path
@@ -103,7 +220,12 @@ module Puma
103
220
  end
104
221
 
105
222
  if opts[:no_token]
106
- auth_token = :none
223
+ # We need to use 'none' rather than :none because this value will be
224
+ # passed on to an instance of OptionParser, which doesn't support
225
+ # symbols as option values.
226
+ #
227
+ # See: https://github.com/puma/puma/issues/1193#issuecomment-305995488
228
+ auth_token = 'none'
107
229
  else
108
230
  auth_token = opts[:auth_token]
109
231
  auth_token ||= Configuration.random_token
@@ -120,22 +242,35 @@ module Puma
120
242
  @options[:config_files] << file
121
243
  end
122
244
 
123
- # Adds a binding for the server to +url+. tcp://, unix://, and ssl:// are the only accepted
124
- # protocols. Use query parameters within the url to specify options.
245
+ # Bind the server to +url+. "tcp://", "unix://" and "ssl://" are the only
246
+ # accepted protocols. Multiple urls can be bound to, calling +bind+ does
247
+ # not overwrite previous bindings.
125
248
  #
126
- # @note multiple urls can be bound to, calling `bind` does not overwrite previous bindings.
249
+ # The default is "tcp://0.0.0.0:9292".
127
250
  #
128
- # @example Explicitly the socket backlog depth (default is 1024)
129
- # bind('unix:///var/run/puma.sock?backlog=2048')
251
+ # You can use query parameters within the url to specify options:
130
252
  #
131
- # @example Set up ssl cert
132
- # bind('ssl://127.0.0.1:9292?key=key.key&cert=cert.pem')
253
+ # * Set the socket backlog depth with +backlog+, default is 1024.
254
+ # * Set up an SSL certificate with +key+ & +cert+.
255
+ # * Set up an SSL certificate for mTLS with +key+, +cert+, +ca+ and +verify_mode+.
256
+ # * Set whether to optimize for low latency instead of throughput with
257
+ # +low_latency+, default is to not optimize for low latency. This is done
258
+ # via +Socket::TCP_NODELAY+.
259
+ # * Set socket permissions with +umask+.
133
260
  #
134
- # @example Prefer low-latency over higher throughput (via `Socket::TCP_NODELAY`)
135
- # bind('tcp://0.0.0.0:9292?low_latency=true')
261
+ # @example Backlog depth
262
+ # bind 'unix:///var/run/puma.sock?backlog=512'
263
+ # @example SSL cert
264
+ # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem'
265
+ # @example SSL cert for mutual TLS (mTLS)
266
+ # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem&ca=ca.pem&verify_mode=force_peer'
267
+ # @example Disable optimization for low latency
268
+ # bind 'tcp://0.0.0.0:9292?low_latency=false'
269
+ # @example Socket permissions
270
+ # bind 'unix:///var/run/puma.sock?umask=0111'
271
+ # @see Puma::Runner#load_and_bind
272
+ # @see Puma::Cluster#run
136
273
  #
137
- # @example Set socket permissions
138
- # bind('unix:///var/run/puma.sock?umask=0111')
139
274
  def bind(url)
140
275
  @options[:binds] ||= []
141
276
  @options[:binds] << url
@@ -145,48 +280,75 @@ module Puma
145
280
  @options[:binds] = []
146
281
  end
147
282
 
283
+ # Bind to (systemd) activated sockets, regardless of configured binds.
284
+ #
285
+ # Systemd can present sockets as file descriptors that are already opened.
286
+ # By default Puma will use these but only if it was explicitly told to bind
287
+ # to the socket. If not, it will close the activated sockets. This means
288
+ # all configuration is duplicated.
289
+ #
290
+ # Binds can contain additional configuration, but only SSL config is really
291
+ # relevant since the unix and TCP socket options are ignored.
292
+ #
293
+ # This means there is a lot of duplicated configuration for no additional
294
+ # value in most setups. This method tells the launcher to bind to all
295
+ # activated sockets, regardless of existing bind.
296
+ #
297
+ # To clear configured binds, the value only can be passed. This will clear
298
+ # out any binds that may have been configured.
299
+ #
300
+ # @example Use any systemd activated sockets as well as configured binds
301
+ # bind_to_activated_sockets
302
+ #
303
+ # @example Only bind to systemd activated sockets, ignoring other binds
304
+ # bind_to_activated_sockets 'only'
305
+ def bind_to_activated_sockets(bind=true)
306
+ @options[:bind_to_activated_sockets] = bind
307
+ end
308
+
148
309
  # Define the TCP port to bind to. Use +bind+ for more advanced options.
149
310
  #
311
+ # @example
312
+ # port 9292
150
313
  def port(port, host=nil)
151
314
  host ||= default_host
152
- bind "tcp://#{host}:#{port}"
315
+ bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s
153
316
  end
154
317
 
155
- # Define how long persistent connections can be idle before puma closes
156
- # them
157
- #
318
+ # Define how long persistent connections can be idle before Puma closes them.
319
+ # @see Puma::Server.new
158
320
  def persistent_timeout(seconds)
159
321
  @options[:persistent_timeout] = Integer(seconds)
160
322
  end
161
323
 
162
- # Define how long the tcp socket stays open, if no data has been received
163
- #
324
+ # Define how long the tcp socket stays open, if no data has been received.
325
+ # @see Puma::Server.new
164
326
  def first_data_timeout(seconds)
165
327
  @options[:first_data_timeout] = Integer(seconds)
166
328
  end
167
329
 
168
330
  # Work around leaky apps that leave garbage in Thread locals
169
- # across requests
170
- #
331
+ # across requests.
171
332
  def clean_thread_locals(which=true)
172
333
  @options[:clean_thread_locals] = which
173
334
  end
174
335
 
175
- # Daemonize the server into the background. Highly suggest that
176
- # this be combined with +pidfile+ and +stdout_redirect+.
177
- def daemonize(which=true)
178
- @options[:daemon] = which
179
- end
180
-
181
- # When shutting down, drain the accept socket of pending
182
- # connections and process them. This loops over the accept
183
- # socket until there are no more read events and then stops
184
- # looking and waits for the requests to finish.
336
+ # When shutting down, drain the accept socket of pending connections and
337
+ # process them. This loops over the accept socket until there are no more
338
+ # read events and then stops looking and waits for the requests to finish.
339
+ # @see Puma::Server#graceful_shutdown
340
+ #
185
341
  def drain_on_shutdown(which=true)
186
342
  @options[:drain_on_shutdown] = which
187
343
  end
188
344
 
189
- # Set the environment in which the Rack's app will run.
345
+ # Set the environment in which the rack's app will run. The value must be
346
+ # a string.
347
+ #
348
+ # The default is "development".
349
+ #
350
+ # @example
351
+ # environment 'production'
190
352
  def environment(environment)
191
353
  @options[:environment] = environment
192
354
  end
@@ -198,6 +360,7 @@ module Puma
198
360
  #
199
361
  # Puma always waits a few seconds after killing a thread for it to try
200
362
  # to finish up it's work, even in :immediately mode.
363
+ # @see Puma::Server#graceful_shutdown
201
364
  def force_shutdown_after(val=:forever)
202
365
  i = case val
203
366
  when :forever
@@ -205,37 +368,48 @@ module Puma
205
368
  when :immediately
206
369
  0
207
370
  else
208
- Integer(val)
371
+ Float(val)
209
372
  end
210
373
 
211
374
  @options[:force_shutdown_after] = i
212
375
  end
213
376
 
214
377
  # Code to run before doing a restart. This code should
215
- # close logfiles, database connections, etc.
378
+ # close log files, database connections, etc.
216
379
  #
217
380
  # This can be called multiple times to add code each time.
218
381
  #
382
+ # @example
383
+ # on_restart do
384
+ # puts 'On restart...'
385
+ # end
219
386
  def on_restart(&block)
220
387
  @options[:on_restart] ||= []
221
388
  @options[:on_restart] << block
222
389
  end
223
390
 
224
- # Command to use to restart puma. This should be just how to
225
- # load puma itself (ie. 'ruby -Ilib bin/puma'), not the arguments
226
- # to puma, as those are the same as the original process.
391
+ # Command to use to restart Puma. This should be just how to
392
+ # load Puma itself (ie. 'ruby -Ilib bin/puma'), not the arguments
393
+ # to Puma, as those are the same as the original process.
227
394
  #
395
+ # @example
396
+ # restart_command '/u/app/lolcat/bin/restart_puma'
228
397
  def restart_command(cmd)
229
398
  @options[:restart_cmd] = cmd.to_s
230
399
  end
231
400
 
232
- # Store the pid of the server in the file at +path+.
401
+ # Store the pid of the server in the file at "path".
402
+ #
403
+ # @example
404
+ # pidfile '/u/apps/lolcat/tmp/pids/puma.pid'
233
405
  def pidfile(path)
234
406
  @options[:pidfile] = path.to_s
235
407
  end
236
408
 
237
- # Disable request logging.
409
+ # Disable request logging, if this isn't used it'll be enabled by default.
238
410
  #
411
+ # @example
412
+ # quiet
239
413
  def quiet(which=true)
240
414
  @options[:log_requests] = !which
241
415
  end
@@ -246,6 +420,11 @@ module Puma
246
420
  @options[:log_requests] = which
247
421
  end
248
422
 
423
+ # Pass in a custom logging class instance
424
+ def custom_logger(custom_logger)
425
+ @options[:custom_logger] = custom_logger
426
+ end
427
+
249
428
  # Show debugging info
250
429
  #
251
430
  def debug
@@ -254,30 +433,54 @@ module Puma
254
433
 
255
434
  # Load +path+ as a rackup file.
256
435
  #
436
+ # The default is "config.ru".
437
+ #
438
+ # @example
439
+ # rackup '/u/apps/lolcat/config.ru'
257
440
  def rackup(path)
258
- @options[:rackup] = path.to_s
441
+ @options[:rackup] ||= path.to_s
259
442
  end
260
443
 
261
- # Run Puma in TCP mode
262
- #
263
- def tcp_mode!
264
- @options[:mode] = :tcp
444
+ # Allows setting `env['rack.url_scheme']`.
445
+ # Only necessary if X-Forwarded-Proto is not being set by your proxy
446
+ # Normal values are 'http' or 'https'.
447
+ def rack_url_scheme(scheme=nil)
448
+ @options[:rack_url_scheme] = scheme
265
449
  end
266
450
 
267
451
  def early_hints(answer=true)
268
452
  @options[:early_hints] = answer
269
453
  end
270
454
 
271
- # Redirect STDOUT and STDERR to files specified.
455
+ # Redirect +STDOUT+ and +STDERR+ to files specified. The +append+ parameter
456
+ # specifies whether the output is appended, the default is +false+.
457
+ #
458
+ # @example
459
+ # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr'
460
+ # @example
461
+ # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr', true
272
462
  def stdout_redirect(stdout=nil, stderr=nil, append=false)
273
463
  @options[:redirect_stdout] = stdout
274
464
  @options[:redirect_stderr] = stderr
275
465
  @options[:redirect_append] = append
276
466
  end
277
467
 
468
+ def log_formatter(&block)
469
+ @options[:log_formatter] = block
470
+ end
471
+
278
472
  # Configure +min+ to be the minimum number of threads to use to answer
279
473
  # requests and +max+ the maximum.
280
474
  #
475
+ # The default is the environment variables +PUMA_MIN_THREADS+ / +PUMA_MAX_THREADS+
476
+ # (or +MIN_THREADS+ / +MAX_THREADS+ if the +PUMA_+ variables aren't set).
477
+ #
478
+ # If these environment variables aren't set, the default is "0, 5" in MRI or "0, 16" for other interpreters.
479
+ #
480
+ # @example
481
+ # threads 0, 16
482
+ # @example
483
+ # threads 5, 5
281
484
  def threads(min, max)
282
485
  min = Integer(min)
283
486
  max = Integer(max)
@@ -293,115 +496,267 @@ module Puma
293
496
  @options[:max_threads] = max
294
497
  end
295
498
 
296
- def ssl_bind(host, port, opts)
297
- verify = opts.fetch(:verify_mode, 'none')
298
-
299
- if defined?(JRUBY_VERSION)
300
- keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}"
301
- bind "ssl://#{host}:#{port}?cert=#{opts[:cert]}&key=#{opts[:key]}&#{keystore_additions}&verify_mode=#{verify}"
302
- else
303
- bind "ssl://#{host}:#{port}?cert=#{opts[:cert]}&key=#{opts[:key]}&verify_mode=#{verify}"
304
- end
499
+ # Instead of using +bind+ and manually constructing a URI like:
500
+ #
501
+ # bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path'
502
+ #
503
+ # you can use the this method.
504
+ #
505
+ # When binding on localhost you don't need to specify +cert+ and +key+,
506
+ # Puma will assume you are using the +localhost+ gem and try to load the
507
+ # appropriate files.
508
+ #
509
+ # When using the options hash parameter, the `reuse:` value is either
510
+ # `true`, which sets reuse 'on' with default values, or a hash, with `:size`
511
+ # and/or `:timeout` keys, each with integer values.
512
+ #
513
+ # @example
514
+ # ssl_bind '127.0.0.1', '9292', {
515
+ # cert: path_to_cert,
516
+ # key: path_to_key,
517
+ # ssl_cipher_filter: cipher_filter, # optional
518
+ # verify_mode: verify_mode, # default 'none'
519
+ # verification_flags: flags, # optional, not supported by JRuby
520
+ # reuse: true # optional
521
+ # }
522
+ #
523
+ # @example Using self-signed certificate with the +localhost+ gem:
524
+ # ssl_bind '127.0.0.1', '9292'
525
+ #
526
+ # @example Alternatively, you can provide +cert_pem+ and +key_pem+:
527
+ # ssl_bind '127.0.0.1', '9292', {
528
+ # cert_pem: File.read(path_to_cert),
529
+ # key_pem: File.read(path_to_key),
530
+ # reuse: {size: 2_000, timeout: 20} # optional
531
+ # }
532
+ #
533
+ # @example For JRuby, two keys are required: +keystore+ & +keystore_pass+
534
+ # ssl_bind '127.0.0.1', '9292', {
535
+ # keystore: path_to_keystore,
536
+ # keystore_pass: password,
537
+ # ssl_cipher_list: cipher_list, # optional
538
+ # verify_mode: verify_mode # default 'none'
539
+ # }
540
+ def ssl_bind(host, port, opts = {})
541
+ add_pem_values_to_options_store(opts)
542
+ bind self.class.ssl_bind_str(host, port, opts)
305
543
  end
306
544
 
307
545
  # Use +path+ as the file to store the server info state. This is
308
- # used by pumactl to query and control the server.
546
+ # used by +pumactl+ to query and control the server.
309
547
  #
548
+ # @example
549
+ # state_path '/u/apps/lolcat/tmp/pids/puma.state'
310
550
  def state_path(path)
311
551
  @options[:state] = path.to_s
312
552
  end
313
553
 
314
- # *Cluster mode only* How many worker processes to run.
554
+ # Use +permission+ to restrict permissions for the state file.
555
+ #
556
+ # @example
557
+ # state_permission 0600
558
+ # @version 5.0.0
559
+ #
560
+ def state_permission(permission)
561
+ @options[:state_permission] = permission
562
+ end
563
+
564
+ # How many worker processes to run. Typically this is set to
565
+ # the number of available cores.
566
+ #
567
+ # The default is the value of the environment variable +WEB_CONCURRENCY+ if
568
+ # set, otherwise 0.
315
569
  #
570
+ # @note Cluster mode only.
571
+ # @see Puma::Cluster
316
572
  def workers(count)
317
573
  @options[:workers] = count.to_i
318
574
  end
319
575
 
320
- # *Cluster mode only* Code to run immediately before master process
576
+ # Disable warning message when running in cluster mode with a single worker.
577
+ #
578
+ # Cluster mode has some overhead of running an additional 'control' process
579
+ # in order to manage the cluster. If only running a single worker it is
580
+ # likely not worth paying that overhead vs running in single mode with
581
+ # additional threads instead.
582
+ #
583
+ # There are some scenarios where running cluster mode with a single worker
584
+ # may still be warranted and valid under certain deployment scenarios, see
585
+ # https://github.com/puma/puma/issues/2534
586
+ #
587
+ # Moving from workers = 1 to workers = 0 will save 10-30% of memory use.
588
+ #
589
+ # @note Cluster mode only.
590
+ def silence_single_worker_warning
591
+ @options[:silence_single_worker_warning] = true
592
+ end
593
+
594
+ # Disable warning message when running single mode with callback hook defined.
595
+ def silence_fork_callback_warning
596
+ @options[:silence_fork_callback_warning] = true
597
+ end
598
+
599
+ # Code to run immediately before master process
321
600
  # forks workers (once on boot). These hooks can block if necessary
322
- # to wait for background operations unknown to puma to finish before
601
+ # to wait for background operations unknown to Puma to finish before
323
602
  # the process terminates.
324
- # This can be used to close any connections to remote servers (database, redis, ...)
325
- # that were opened when preloading the code
603
+ # This can be used to close any connections to remote servers (database,
604
+ # Redis, ...) that were opened when preloading the code.
326
605
  #
327
- # This can be called multiple times to add hooks.
606
+ # This can be called multiple times to add several hooks.
328
607
  #
608
+ # @note Cluster mode only.
609
+ # @example
610
+ # before_fork do
611
+ # puts "Starting workers..."
612
+ # end
329
613
  def before_fork(&block)
614
+ warn_if_in_single_mode('before_fork')
615
+
330
616
  @options[:before_fork] ||= []
331
617
  @options[:before_fork] << block
332
618
  end
333
619
 
334
- # *Cluster mode only* Code to run in a worker when it boots to setup
620
+ # Code to run in a worker when it boots to setup
335
621
  # the process before booting the app.
336
622
  #
337
- # This can be called multiple times to add hooks.
623
+ # This can be called multiple times to add several hooks.
338
624
  #
339
- def on_worker_boot(&block)
340
- @options[:before_worker_boot] ||= []
341
- @options[:before_worker_boot] << block
625
+ # @note Cluster mode only.
626
+ # @example
627
+ # on_worker_boot do
628
+ # puts 'Before worker boot...'
629
+ # end
630
+ def on_worker_boot(key = nil, &block)
631
+ warn_if_in_single_mode('on_worker_boot')
632
+
633
+ process_hook :before_worker_boot, key, block, 'on_worker_boot'
342
634
  end
343
635
 
344
- # *Cluster mode only* Code to run immediately before a worker shuts
636
+ # Code to run immediately before a worker shuts
345
637
  # down (after it has finished processing HTTP requests). These hooks
346
638
  # can block if necessary to wait for background operations unknown
347
- # to puma to finish before the process terminates.
639
+ # to Puma to finish before the process terminates.
348
640
  #
349
- # This can be called multiple times to add hooks.
641
+ # This can be called multiple times to add several hooks.
350
642
  #
351
- def on_worker_shutdown(&block)
352
- @options[:before_worker_shutdown] ||= []
353
- @options[:before_worker_shutdown] << block
643
+ # @note Cluster mode only.
644
+ # @example
645
+ # on_worker_shutdown do
646
+ # puts 'On worker shutdown...'
647
+ # end
648
+ def on_worker_shutdown(key = nil, &block)
649
+ warn_if_in_single_mode('on_worker_shutdown')
650
+
651
+ process_hook :before_worker_shutdown, key, block, 'on_worker_shutdown'
354
652
  end
355
653
 
356
- # *Cluster mode only* Code to run in the master when it is
357
- # about to create the worker by forking itself.
654
+ # Code to run in the master right before a worker is started. The worker's
655
+ # index is passed as an argument.
358
656
  #
359
- # This can be called multiple times to add hooks.
657
+ # This can be called multiple times to add several hooks.
360
658
  #
659
+ # @note Cluster mode only.
660
+ # @example
661
+ # on_worker_fork do
662
+ # puts 'Before worker fork...'
663
+ # end
361
664
  def on_worker_fork(&block)
362
- @options[:before_worker_fork] ||= []
363
- @options[:before_worker_fork] << block
665
+ warn_if_in_single_mode('on_worker_fork')
666
+
667
+ process_hook :before_worker_fork, nil, block, 'on_worker_fork'
364
668
  end
365
669
 
366
- # *Cluster mode only* Code to run in the master after it starts
367
- # a worker.
670
+ # Code to run in the master after a worker has been started. The worker's
671
+ # index is passed as an argument.
368
672
  #
369
- # This can be called multiple times to add hooks.
673
+ # This is called everytime a worker is to be started.
370
674
  #
675
+ # @note Cluster mode only.
676
+ # @example
677
+ # after_worker_fork do
678
+ # puts 'After worker fork...'
679
+ # end
371
680
  def after_worker_fork(&block)
372
- @options[:after_worker_fork] ||= []
373
- @options[:after_worker_fork] = block
681
+ warn_if_in_single_mode('after_worker_fork')
682
+
683
+ process_hook :after_worker_fork, nil, block, 'after_worker_fork'
374
684
  end
375
685
 
376
686
  alias_method :after_worker_boot, :after_worker_fork
377
687
 
378
- # The directory to operate out of.
379
- def directory(dir)
380
- @options[:directory] = dir.to_s
688
+ # Code to run after puma is booted (works for both: single and clustered)
689
+ #
690
+ # @example
691
+ # on_booted do
692
+ # puts 'After booting...'
693
+ # end
694
+ def on_booted(&block)
695
+ @config.options[:events].on_booted(&block)
696
+ end
697
+
698
+ # When `fork_worker` is enabled, code to run in Worker 0
699
+ # before all other workers are re-forked from this process,
700
+ # after the server has temporarily stopped serving requests
701
+ # (once per complete refork cycle).
702
+ #
703
+ # This can be used to trigger extra garbage-collection to maximize
704
+ # copy-on-write efficiency, or close any connections to remote servers
705
+ # (database, Redis, ...) that were opened while the server was running.
706
+ #
707
+ # This can be called multiple times to add several hooks.
708
+ #
709
+ # @note Cluster mode with `fork_worker` enabled only.
710
+ # @example
711
+ # on_refork do
712
+ # 3.times {GC.start}
713
+ # end
714
+ # @version 5.0.0
715
+ #
716
+ def on_refork(key = nil, &block)
717
+ process_hook :before_refork, key, block, 'on_refork'
381
718
  end
382
719
 
383
- # DEPRECATED: The directory to operate out of.
384
- def worker_directory(dir)
385
- $stderr.puts "worker_directory is deprecated. Please use `directory`"
386
- directory dir
720
+ # Code to run out-of-band when the worker is idle.
721
+ # These hooks run immediately after a request has finished
722
+ # processing and there are no busy threads on the worker.
723
+ # The worker doesn't accept new requests until this code finishes.
724
+ #
725
+ # This hook is useful for running out-of-band garbage collection
726
+ # or scheduling asynchronous tasks to execute after a response.
727
+ #
728
+ # This can be called multiple times to add several hooks.
729
+ def out_of_band(&block)
730
+ process_hook :out_of_band, nil, block, 'out_of_band'
387
731
  end
388
732
 
389
- # Run the app as a raw TCP app instead of an HTTP rack app
390
- def tcp_mode
391
- @options[:mode] = :tcp
733
+ # The directory to operate out of.
734
+ #
735
+ # The default is the current directory.
736
+ #
737
+ # @example
738
+ # directory '/u/apps/lolcat'
739
+ def directory(dir)
740
+ @options[:directory] = dir.to_s
392
741
  end
393
742
 
394
- # *Cluster mode only* Preload the application before starting
395
- # the workers and setting up the listen ports. This conflicts
396
- # with using the phased restart feature, you can't use both.
743
+ # Preload the application before starting the workers; this conflicts with
744
+ # phased restart feature. On by default if your app uses more than 1 worker.
397
745
  #
746
+ # @note Cluster mode only.
747
+ # @example
748
+ # preload_app!
398
749
  def preload_app!(answer=true)
399
750
  @options[:preload_app] = answer
400
751
  end
401
752
 
402
- # Use +obj+ or +block+ as the low level error handler. This allows a config file to
403
- # change the default error on the server.
753
+ # Use +obj+ or +block+ as the low level error handler. This allows the
754
+ # configuration file to change the default error on the server.
404
755
  #
756
+ # @example
757
+ # lowlevel_error_handler do |err|
758
+ # [200, {}, ["error page"]]
759
+ # end
405
760
  def lowlevel_error_handler(obj=nil, &block)
406
761
  obj ||= block
407
762
  raise "Provide either a #call'able or a block" unless obj
@@ -411,42 +766,153 @@ module Puma
411
766
  # This option is used to allow your app and its gems to be
412
767
  # properly reloaded when not using preload.
413
768
  #
414
- # When set, if puma detects that it's been invoked in the
769
+ # When set, if Puma detects that it's been invoked in the
415
770
  # context of Bundler, it will cleanup the environment and
416
771
  # re-run itself outside the Bundler environment, but directly
417
772
  # using the files that Bundler has setup.
418
773
  #
419
- # This means that puma is now decoupled from your Bundler
774
+ # This means that Puma is now decoupled from your Bundler
420
775
  # context and when each worker loads, it will be loading a
421
776
  # new Bundler context and thus can float around as the release
422
777
  # dictates.
778
+ #
779
+ # @see extra_runtime_dependencies
780
+ #
781
+ # @note This is incompatible with +preload_app!+.
782
+ # @note This is only supported for RubyGems 2.2+
423
783
  def prune_bundler(answer=true)
424
784
  @options[:prune_bundler] = answer
425
785
  end
426
786
 
427
- # Additional text to display in process listing
787
+ # By default, Puma will raise SignalException when SIGTERM is received. In
788
+ # environments where SIGTERM is something expected, you can suppress these
789
+ # with this option.
790
+ #
791
+ # This can be useful for example in Kubernetes, where rolling restart is
792
+ # guaranteed usually on infrastructure level.
793
+ #
794
+ # @example
795
+ # raise_exception_on_sigterm false
796
+ # @see Puma::Launcher#setup_signals
797
+ # @see Puma::Cluster#setup_signals
798
+ #
799
+ def raise_exception_on_sigterm(answer=true)
800
+ @options[:raise_exception_on_sigterm] = answer
801
+ end
802
+
803
+ # When using prune_bundler, if extra runtime dependencies need to be loaded to
804
+ # initialize your app, then this setting can be used. This includes any Puma plugins.
805
+ #
806
+ # Before bundler is pruned, the gem names supplied will be looked up in the bundler
807
+ # context and then loaded again after bundler is pruned.
808
+ # Only applies if prune_bundler is used.
809
+ #
810
+ # @example
811
+ # extra_runtime_dependencies ['gem_name_1', 'gem_name_2']
812
+ # @example
813
+ # extra_runtime_dependencies ['puma_worker_killer', 'puma-heroku']
814
+ # @see Puma::Launcher#extra_runtime_deps_directories
815
+ #
816
+ def extra_runtime_dependencies(answer = [])
817
+ @options[:extra_runtime_dependencies] = Array(answer)
818
+ end
819
+
820
+ # Additional text to display in process listing.
821
+ #
822
+ # If you do not specify a tag, Puma will infer it. If you do not want Puma
823
+ # to add a tag, use an empty string.
824
+ #
825
+ # @example
826
+ # tag 'app name'
827
+ # @example
828
+ # tag ''
428
829
  def tag(string)
429
830
  @options[:tag] = string.to_s
430
831
  end
431
832
 
432
- # *Cluster mode only* Set the timeout for workers in seconds
433
- # When set the master process will terminate any workers
434
- # that have not checked in within the given +timeout+.
435
- # This mitigates hung processes. Default value is 60 seconds.
833
+ # Change the default interval for checking workers.
834
+ #
835
+ # The default value is 5 seconds.
836
+ #
837
+ # @note Cluster mode only.
838
+ # @example
839
+ # worker_check_interval 5
840
+ # @see Puma::Cluster#check_workers
841
+ #
842
+ def worker_check_interval(interval)
843
+ @options[:worker_check_interval] = Integer(interval)
844
+ end
845
+
846
+ # Verifies that all workers have checked in to the master process within
847
+ # the given timeout. If not the worker process will be restarted. This is
848
+ # not a request timeout, it is to protect against a hung or dead process.
849
+ # Setting this value will not protect against slow requests.
850
+ #
851
+ # The minimum value is 6 seconds, the default value is 60 seconds.
852
+ #
853
+ # @note Cluster mode only.
854
+ # @example
855
+ # worker_timeout 60
856
+ # @see Puma::Cluster::Worker#ping_timeout
857
+ #
436
858
  def worker_timeout(timeout)
437
- @options[:worker_timeout] = Integer(timeout)
859
+ timeout = Integer(timeout)
860
+ min = @options.fetch(:worker_check_interval, Configuration::DEFAULTS[:worker_check_interval])
861
+
862
+ if timeout <= min
863
+ raise "The minimum worker_timeout must be greater than the worker reporting interval (#{min})"
864
+ end
865
+
866
+ @options[:worker_timeout] = timeout
438
867
  end
439
868
 
440
- # *Cluster mode only* Set the timeout for workers to boot
869
+ # Change the default worker timeout for booting.
870
+ #
871
+ # If unspecified, this defaults to the value of worker_timeout.
872
+ #
873
+ # @note Cluster mode only.
874
+ #
875
+ # @example
876
+ # worker_boot_timeout 60
877
+ # @see Puma::Cluster::Worker#ping_timeout
878
+ #
441
879
  def worker_boot_timeout(timeout)
442
880
  @options[:worker_boot_timeout] = Integer(timeout)
443
881
  end
444
882
 
445
- # *Cluster mode only* Set the timeout for worker shutdown
883
+ # Set the timeout for worker shutdown.
884
+ #
885
+ # @note Cluster mode only.
886
+ # @see Puma::Cluster::Worker#term
887
+ #
446
888
  def worker_shutdown_timeout(timeout)
447
889
  @options[:worker_shutdown_timeout] = Integer(timeout)
448
890
  end
449
891
 
892
+ # Set the strategy for worker culling.
893
+ #
894
+ # There are two possible values:
895
+ #
896
+ # 1. **:youngest** - the youngest workers (i.e. the workers that were
897
+ # the most recently started) will be culled.
898
+ # 2. **:oldest** - the oldest workers (i.e. the workers that were started
899
+ # the longest time ago) will be culled.
900
+ #
901
+ # @note Cluster mode only.
902
+ # @example
903
+ # worker_culling_strategy :oldest
904
+ # @see Puma::Cluster#cull_workers
905
+ #
906
+ def worker_culling_strategy(strategy)
907
+ stategy = strategy.to_sym
908
+
909
+ if ![:youngest, :oldest].include?(strategy)
910
+ raise "Invalid value for worker_culling_strategy - #{stategy}"
911
+ end
912
+
913
+ @options[:worker_culling_strategy] = strategy
914
+ end
915
+
450
916
  # When set to true (the default), workers accept all requests
451
917
  # and queue them before passing them to the handlers.
452
918
  # When set to false, each worker process accepts exactly as
@@ -459,7 +925,8 @@ module Puma
459
925
  # Note that setting this to false disables HTTP keepalive and
460
926
  # slow clients will occupy a handler thread while the request
461
927
  # is being sent. A reverse proxy, such as nginx, can handle
462
- # slow clients and queue requests before they reach puma.
928
+ # slow clients and queue requests before they reach Puma.
929
+ # @see Puma::Server
463
930
  def queue_requests(answer=true)
464
931
  @options[:queue_requests] = answer
465
932
  end
@@ -467,29 +934,50 @@ module Puma
467
934
  # When a shutdown is requested, the backtraces of all the
468
935
  # threads will be written to $stdout. This can help figure
469
936
  # out why shutdown is hanging.
937
+ #
470
938
  def shutdown_debug(val=true)
471
939
  @options[:shutdown_debug] = val
472
940
  end
473
941
 
942
+
943
+ # Attempts to route traffic to less-busy workers by causing them to delay
944
+ # listening on the socket, allowing workers which are not processing any
945
+ # requests to pick up new requests first.
946
+ #
947
+ # Only works on MRI. For all other interpreters, this setting does nothing.
948
+ # @see Puma::Server#handle_servers
949
+ # @see Puma::ThreadPool#wait_for_less_busy_worker
950
+ # @version 5.0.0
951
+ #
952
+ def wait_for_less_busy_worker(val=0.005)
953
+ @options[:wait_for_less_busy_worker] = val.to_f
954
+ end
955
+
474
956
  # Control how the remote address of the connection is set. This
475
957
  # is configurable because to calculate the true socket peer address
476
958
  # a kernel syscall is required which for very fast rack handlers
477
959
  # slows down the handling significantly.
478
960
  #
479
- # There are 4 possible values:
480
- #
481
- # * :socket (the default) - read the peername from the socket using the
482
- # syscall. This is the normal behavior.
483
- # * :localhost - set the remote address to "127.0.0.1"
484
- # * header: http_header - set the remote address to the value of the
485
- # provided http header. For instance:
486
- # `set_remote_address header: "X-Real-IP"`.
487
- # Only the first word (as separated by spaces or comma)
488
- # is used, allowing headers such as X-Forwarded-For
489
- # to be used as well.
490
- # * Any string - this allows you to hardcode remote address to any value
491
- # you wish. Because puma never uses this field anyway, it's
492
- # format is entirely in your hands.
961
+ # There are 5 possible values:
962
+ #
963
+ # 1. **:socket** (the default) - read the peername from the socket using the
964
+ # syscall. This is the normal behavior. If this fails for any reason (e.g.,
965
+ # if the peer disconnects between the connection being accepted and the getpeername
966
+ # system call), Puma will return "0.0.0.0"
967
+ # 2. **:localhost** - set the remote address to "127.0.0.1"
968
+ # 3. **header: <http_header>**- set the remote address to the value of the
969
+ # provided http header. For instance:
970
+ # `set_remote_address header: "X-Real-IP"`.
971
+ # Only the first word (as separated by spaces or comma) is used, allowing
972
+ # headers such as X-Forwarded-For to be used as well. If this header is absent,
973
+ # Puma will fall back to the behavior of :socket
974
+ # 4. **proxy_protocol: :v1**- set the remote address to the value read from the
975
+ # HAproxy PROXY protocol, version 1. If the request does not have the PROXY
976
+ # protocol attached to it, will fall back to :socket
977
+ # 5. **\<Any string\>** - this allows you to hardcode remote address to any value
978
+ # you wish. Because Puma never uses this field anyway, it's format is
979
+ # entirely in your hands.
980
+ #
493
981
  def set_remote_address(val=:socket)
494
982
  case val
495
983
  when :socket
@@ -504,6 +992,13 @@ module Puma
504
992
  if hdr = val[:header]
505
993
  @options[:remote_address] = :header
506
994
  @options[:remote_address_header] = "HTTP_" + hdr.upcase.tr("-", "_")
995
+ elsif protocol_version = val[:proxy_protocol]
996
+ @options[:remote_address] = :proxy_protocol
997
+ protocol_version = protocol_version.downcase.to_sym
998
+ unless [:v1].include?(protocol_version)
999
+ raise "Invalid value for proxy_protocol - #{protocol_version.inspect}"
1000
+ end
1001
+ @options[:remote_address_proxy_protocol] = protocol_version
507
1002
  else
508
1003
  raise "Invalid value for set_remote_address - #{val.inspect}"
509
1004
  end
@@ -512,5 +1007,140 @@ module Puma
512
1007
  end
513
1008
  end
514
1009
 
1010
+ # When enabled, workers will be forked from worker 0 instead of from the master process.
1011
+ # This option is similar to `preload_app` because the app is preloaded before forking,
1012
+ # but it is compatible with phased restart.
1013
+ #
1014
+ # This option also enables the `refork` command (SIGURG), which optimizes copy-on-write performance
1015
+ # in a running app.
1016
+ #
1017
+ # A refork will automatically trigger once after the specified number of requests
1018
+ # (default 1000), or pass 0 to disable auto refork.
1019
+ #
1020
+ # @note Cluster mode only.
1021
+ # @version 5.0.0
1022
+ #
1023
+ def fork_worker(after_requests=1000)
1024
+ @options[:fork_worker] = Integer(after_requests)
1025
+ end
1026
+
1027
+ # The number of requests to attempt inline before sending a client back to
1028
+ # the reactor to be subject to normal ordering.
1029
+ #
1030
+ def max_fast_inline(num_of_requests)
1031
+ @options[:max_fast_inline] = Float(num_of_requests)
1032
+ end
1033
+
1034
+ # Specify the backend for the IO selector.
1035
+ #
1036
+ # Provided values will be passed directly to +NIO::Selector.new+, with the
1037
+ # exception of +:auto+ which will let nio4r choose the backend.
1038
+ #
1039
+ # Check the documentation of +NIO::Selector.backends+ for the list of valid
1040
+ # options. Note that the available options on your system will depend on the
1041
+ # operating system. If you want to use the pure Ruby backend (not
1042
+ # recommended due to its comparatively low performance), set environment
1043
+ # variable +NIO4R_PURE+ to +true+.
1044
+ #
1045
+ # The default is +:auto+.
1046
+ #
1047
+ # @see https://github.com/socketry/nio4r/blob/master/lib/nio/selector.rb
1048
+ #
1049
+ def io_selector_backend(backend)
1050
+ @options[:io_selector_backend] = backend.to_sym
1051
+ end
1052
+
1053
+ def mutate_stdout_and_stderr_to_sync_on_write(enabled=true)
1054
+ @options[:mutate_stdout_and_stderr_to_sync_on_write] = enabled
1055
+ end
1056
+
1057
+ # Specify how big the request payload should be, in bytes.
1058
+ # This limit is compared against Content-Length HTTP header.
1059
+ # If the payload size (CONTENT_LENGTH) is larger than http_content_length_limit,
1060
+ # HTTP 413 status code is returned.
1061
+ #
1062
+ # When no Content-Length http header is present, it is compared against the
1063
+ # size of the body of the request.
1064
+ #
1065
+ # The default value for http_content_length_limit is nil.
1066
+ def http_content_length_limit(limit)
1067
+ @options[:http_content_length_limit] = limit
1068
+ end
1069
+
1070
+ # Supported http methods, which will replace `Puma::Const::SUPPORTED_HTTP_METHODS`.
1071
+ # The value of `:any` will allows all methods, otherwise, the value must be
1072
+ # an array of strings. Note that methods are all uppercase.
1073
+ #
1074
+ # `Puma::Const::SUPPORTED_HTTP_METHODS` is conservative, if you want a
1075
+ # complete set of methods, the methods defined by the
1076
+ # [IANA Method Registry](https://www.iana.org/assignments/http-methods/http-methods.xhtml)
1077
+ # are pre-defined as the constant `Puma::Const::IANA_HTTP_METHODS`.
1078
+ #
1079
+ # @note If the `methods` value is `:any`, no method check with be performed,
1080
+ # similar to Puma v5 and earlier.
1081
+ #
1082
+ # @example Adds 'PROPFIND' to existing supported methods
1083
+ # supported_http_methods(Puma::Const::SUPPORTED_HTTP_METHODS + ['PROPFIND'])
1084
+ # @example Restricts methods to the array elements
1085
+ # supported_http_methods %w[HEAD GET POST PUT DELETE OPTIONS PROPFIND]
1086
+ # @example Restricts methods to the methods in the IANA Registry
1087
+ # supported_http_methods Puma::Const::IANA_HTTP_METHODS
1088
+ # @example Allows any method
1089
+ # supported_http_methods :any
1090
+ #
1091
+ def supported_http_methods(methods)
1092
+ if methods == :any
1093
+ @options[:supported_http_methods] = :any
1094
+ elsif Array === methods && methods == (ary = methods.grep(String).uniq) &&
1095
+ !ary.empty?
1096
+ @options[:supported_http_methods] = ary
1097
+ else
1098
+ raise "supported_http_methods must be ':any' or a unique array of strings"
1099
+ end
1100
+ end
1101
+
1102
+ private
1103
+
1104
+ # To avoid adding cert_pem and key_pem as URI params, we store them on the
1105
+ # options[:store] from where Puma binder knows how to find and extract them.
1106
+ def add_pem_values_to_options_store(opts)
1107
+ return if defined?(JRUBY_VERSION)
1108
+
1109
+ @options[:store] ||= []
1110
+
1111
+ # Store cert_pem and key_pem to options[:store] if present
1112
+ [:cert, :key].each do |v|
1113
+ opt_key = :"#{v}_pem"
1114
+ if opts[opt_key]
1115
+ index = @options[:store].length
1116
+ @options[:store] << opts[opt_key]
1117
+ opts[v] = "store:#{index}"
1118
+ end
1119
+ end
1120
+ end
1121
+
1122
+ def process_hook(options_key, key, block, meth)
1123
+ @options[options_key] ||= []
1124
+ if ON_WORKER_KEY.include? key.class
1125
+ @options[options_key] << [block, key.to_sym]
1126
+ elsif key.nil?
1127
+ @options[options_key] << block
1128
+ else
1129
+ raise "'#{meth}' key must be String or Symbol"
1130
+ end
1131
+ end
1132
+
1133
+ def warn_if_in_single_mode(hook_name)
1134
+ return if @options[:silence_fork_callback_warning]
1135
+
1136
+ if (@options[:workers] || 0) == 0
1137
+ log_string =
1138
+ "Warning: You specified code to run in a `#{hook_name}` block, " \
1139
+ "but Puma is not configured to run in cluster mode (worker count > 0 ), " \
1140
+ "so your `#{hook_name}` block did not run"
1141
+
1142
+ LogWriter.stdio.log(log_string)
1143
+ end
1144
+ end
515
1145
  end
516
1146
  end