puma 3.12.6 → 6.2.2

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