puma 2.1.1 → 7.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. checksums.yaml +7 -0
  2. data/History.md +3273 -0
  3. data/LICENSE +23 -20
  4. data/README.md +388 -100
  5. data/bin/puma-wild +25 -0
  6. data/bin/pumactl +1 -1
  7. data/docs/architecture.md +74 -0
  8. data/docs/compile_options.md +55 -0
  9. data/docs/deployment.md +137 -0
  10. data/docs/fork_worker.md +41 -0
  11. data/docs/images/puma-connection-flow-no-reactor.png +0 -0
  12. data/docs/images/puma-connection-flow.png +0 -0
  13. data/docs/images/puma-general-arch.png +0 -0
  14. data/docs/java_options.md +54 -0
  15. data/docs/jungle/README.md +9 -0
  16. data/docs/jungle/rc.d/README.md +74 -0
  17. data/docs/jungle/rc.d/puma +61 -0
  18. data/docs/jungle/rc.d/puma.conf +10 -0
  19. data/docs/kubernetes.md +73 -0
  20. data/docs/nginx.md +5 -5
  21. data/docs/plugins.md +42 -0
  22. data/docs/rails_dev_mode.md +28 -0
  23. data/docs/restart.md +65 -0
  24. data/docs/signals.md +98 -0
  25. data/docs/stats.md +148 -0
  26. data/docs/systemd.md +253 -0
  27. data/docs/testing_benchmarks_local_files.md +150 -0
  28. data/docs/testing_test_rackup_ci_files.md +36 -0
  29. data/ext/puma_http11/PumaHttp11Service.java +2 -2
  30. data/ext/puma_http11/extconf.rb +59 -2
  31. data/ext/puma_http11/http11_parser.c +319 -487
  32. data/ext/puma_http11/http11_parser.h +15 -13
  33. data/ext/puma_http11/http11_parser.java.rl +27 -43
  34. data/ext/puma_http11/http11_parser.rl +27 -24
  35. data/ext/puma_http11/http11_parser_common.rl +8 -8
  36. data/ext/puma_http11/mini_ssl.c +696 -38
  37. data/ext/puma_http11/no_ssl/PumaHttp11Service.java +15 -0
  38. data/ext/puma_http11/org/jruby/puma/Http11.java +145 -113
  39. data/ext/puma_http11/org/jruby/puma/Http11Parser.java +139 -172
  40. data/ext/puma_http11/org/jruby/puma/MiniSSL.java +413 -193
  41. data/ext/puma_http11/puma_http11.c +183 -175
  42. data/lib/puma/app/status.rb +77 -29
  43. data/lib/puma/binder.rb +349 -119
  44. data/lib/puma/cli.rb +164 -769
  45. data/lib/puma/client.rb +591 -132
  46. data/lib/puma/cluster/worker.rb +183 -0
  47. data/lib/puma/cluster/worker_handle.rb +127 -0
  48. data/lib/puma/cluster.rb +634 -0
  49. data/lib/puma/cluster_accept_loop_delay.rb +91 -0
  50. data/lib/puma/commonlogger.rb +115 -0
  51. data/lib/puma/configuration.rb +370 -202
  52. data/lib/puma/const.rb +266 -115
  53. data/lib/puma/control_cli.rb +219 -120
  54. data/lib/puma/detect.rb +45 -2
  55. data/lib/puma/dsl.rb +1496 -0
  56. data/lib/puma/error_logger.rb +115 -0
  57. data/lib/puma/events.rb +44 -60
  58. data/lib/puma/io_buffer.rb +48 -5
  59. data/lib/puma/jruby_restart.rb +2 -51
  60. data/lib/puma/json_serialization.rb +96 -0
  61. data/lib/puma/launcher/bundle_pruner.rb +104 -0
  62. data/lib/puma/launcher.rb +502 -0
  63. data/lib/puma/log_writer.rb +147 -0
  64. data/lib/puma/minissl/context_builder.rb +96 -0
  65. data/lib/puma/minissl.rb +355 -37
  66. data/lib/puma/null_io.rb +79 -12
  67. data/lib/puma/plugin/systemd.rb +90 -0
  68. data/lib/puma/plugin/tmp_restart.rb +36 -0
  69. data/lib/puma/plugin.rb +111 -0
  70. data/lib/puma/rack/builder.rb +297 -0
  71. data/lib/puma/rack/urlmap.rb +93 -0
  72. data/lib/puma/rack_default.rb +21 -4
  73. data/lib/puma/reactor.rb +102 -133
  74. data/lib/puma/request.rb +703 -0
  75. data/lib/puma/runner.rb +211 -0
  76. data/lib/puma/sd_notify.rb +146 -0
  77. data/lib/puma/server.rb +544 -436
  78. data/lib/puma/single.rb +72 -0
  79. data/lib/puma/state_file.rb +69 -0
  80. data/lib/puma/thread_pool.rb +282 -56
  81. data/lib/puma/util.rb +125 -0
  82. data/lib/puma.rb +80 -6
  83. data/lib/rack/handler/puma.rb +125 -47
  84. data/tools/Dockerfile +26 -0
  85. data/tools/trickletest.rb +44 -0
  86. metadata +77 -148
  87. data/COPYING +0 -55
  88. data/Gemfile +0 -10
  89. data/History.txt +0 -291
  90. data/Manifest.txt +0 -60
  91. data/Rakefile +0 -121
  92. data/TODO +0 -5
  93. data/docs/config.md +0 -0
  94. data/ext/puma_http11/ext_help.h +0 -15
  95. data/ext/puma_http11/io_buffer.c +0 -154
  96. data/lib/puma/accept_nonblock.rb +0 -23
  97. data/lib/puma/capistrano.rb +0 -34
  98. data/lib/puma/compat.rb +0 -11
  99. data/lib/puma/daemon_ext.rb +0 -20
  100. data/lib/puma/delegation.rb +0 -11
  101. data/lib/puma/java_io_buffer.rb +0 -45
  102. data/lib/puma/rack_patch.rb +0 -25
  103. data/puma.gemspec +0 -45
  104. data/test/test_app_status.rb +0 -88
  105. data/test/test_cli.rb +0 -171
  106. data/test/test_config.rb +0 -16
  107. data/test/test_http10.rb +0 -27
  108. data/test/test_http11.rb +0 -126
  109. data/test/test_integration.rb +0 -154
  110. data/test/test_iobuffer.rb +0 -38
  111. data/test/test_minissl.rb +0 -25
  112. data/test/test_null_io.rb +0 -31
  113. data/test/test_persistent.rb +0 -238
  114. data/test/test_puma_server.rb +0 -207
  115. data/test/test_rack_handler.rb +0 -10
  116. data/test/test_rack_server.rb +0 -141
  117. data/test/test_thread_pool.rb +0 -146
  118. data/test/test_unix_socket.rb +0 -39
  119. data/test/test_ws.rb +0 -89
  120. data/tools/jungle/init.d/README.md +0 -54
  121. data/tools/jungle/init.d/puma +0 -332
  122. data/tools/jungle/init.d/run-puma +0 -3
  123. data/tools/jungle/upstart/README.md +0 -61
  124. data/tools/jungle/upstart/puma-manager.conf +0 -31
  125. data/tools/jungle/upstart/puma.conf +0 -52
data/lib/puma/dsl.rb ADDED
@@ -0,0 +1,1496 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'const'
4
+ require_relative 'util'
5
+
6
+ module Puma
7
+ # The methods that are available for use inside the configuration file.
8
+ # These same methods are used in Puma cli and the rack handler
9
+ # internally.
10
+ #
11
+ # Used manually (via CLI class):
12
+ #
13
+ # config = Configuration.new({}) do |user_config|
14
+ # user_config.port 3001
15
+ # end
16
+ # config.clamp
17
+ #
18
+ # puts config.options[:binds] # => "tcp://127.0.0.1:3001"
19
+ #
20
+ # Used to load file:
21
+ #
22
+ # $ cat puma_config.rb
23
+ # port 3002
24
+ #
25
+ # Resulting configuration:
26
+ #
27
+ # config = Configuration.new(config_file: "puma_config.rb")
28
+ # config.clamp
29
+ #
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
+ # | before_worker_boot | :before_worker_boot | inside, before |
48
+ # | before_worker_shutdown | :before_worker_shutdown | inside, after |
49
+ # | before_refork | :before_refork | inside |
50
+ # | after_refork | :after_refork | inside |
51
+ #
52
+ class DSL
53
+ ON_WORKER_KEY = [String, Symbol].freeze
54
+
55
+ # Convenience method so logic can be used in CI.
56
+ #
57
+ # @see ssl_bind
58
+ #
59
+ def self.ssl_bind_str(host, port, opts)
60
+ verify = opts.fetch(:verify_mode, 'none').to_s
61
+
62
+ tls_str =
63
+ if opts[:no_tlsv1_1] then '&no_tlsv1_1=true'
64
+ elsif opts[:no_tlsv1] then '&no_tlsv1=true'
65
+ else ''
66
+ end
67
+
68
+ ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify)
69
+
70
+ low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : ''
71
+ backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : ''
72
+
73
+ if defined?(JRUBY_VERSION)
74
+ cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name
75
+ cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites]
76
+ protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil
77
+
78
+ keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}"
79
+ keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type]
80
+ if opts[:truststore]
81
+ truststore_additions = "&truststore=#{opts[:truststore]}"
82
+ truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass]
83
+ truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type]
84
+ end
85
+
86
+ "ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \
87
+ "&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}"
88
+ else
89
+ ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil
90
+ ssl_ciphersuites = opts[:ssl_ciphersuites] ? "&ssl_ciphersuites=#{opts[:ssl_ciphersuites]}" : nil
91
+ v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil
92
+
93
+ cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil
94
+ key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil
95
+ password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil
96
+
97
+ reuse_flag =
98
+ if (reuse = opts[:reuse])
99
+ if reuse == true
100
+ '&reuse=dflt'
101
+ elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout))
102
+ val = +''
103
+ if (size = reuse[:size]) && Integer === size
104
+ val << size.to_s
105
+ end
106
+ if (timeout = reuse[:timeout]) && Integer === timeout
107
+ val << ",#{timeout}"
108
+ end
109
+ if val.empty?
110
+ nil
111
+ else
112
+ "&reuse=#{val}"
113
+ end
114
+ else
115
+ nil
116
+ end
117
+ else
118
+ nil
119
+ end
120
+
121
+ "ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}#{ssl_ciphersuites}" \
122
+ "#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}"
123
+ end
124
+ end
125
+
126
+ def initialize(options, config)
127
+ @config = config
128
+ @options = options
129
+
130
+ @plugins = []
131
+ end
132
+
133
+ def _load_from(path)
134
+ if path
135
+ @path = path
136
+ instance_eval(File.read(path), path, 1)
137
+ end
138
+ ensure
139
+ _offer_plugins
140
+ end
141
+
142
+ def _offer_plugins
143
+ @plugins.each do |o|
144
+ if o.respond_to? :config
145
+ @options.shift
146
+ o.config self
147
+ end
148
+ end
149
+
150
+ @plugins.clear
151
+ end
152
+
153
+ def set_default_host(host)
154
+ @options[:default_host] = host
155
+ end
156
+
157
+ def default_host
158
+ @options[:default_host] || Configuration::DEFAULTS[:tcp_host]
159
+ end
160
+
161
+ def inject(&blk)
162
+ instance_eval(&blk)
163
+ end
164
+
165
+ def get(key,default=nil)
166
+ @options[key.to_sym] || default
167
+ end
168
+
169
+ # Load the named plugin for use by this configuration.
170
+ #
171
+ # @example
172
+ # plugin :tmp_restart
173
+ #
174
+ def plugin(name)
175
+ @plugins << @config.load_plugin(name)
176
+ end
177
+
178
+ # Use an object or block as the rack application. This allows the
179
+ # configuration file to be the application itself.
180
+ #
181
+ # @example
182
+ # app do |env|
183
+ # body = 'Hello, World!'
184
+ #
185
+ # [
186
+ # 200,
187
+ # {
188
+ # 'Content-Type' => 'text/plain',
189
+ # 'Content-Length' => body.length.to_s
190
+ # },
191
+ # [body]
192
+ # ]
193
+ # end
194
+ #
195
+ # @see Puma::Configuration#app
196
+ #
197
+ def app(obj=nil, &block)
198
+ obj ||= block
199
+
200
+ raise "Provide either a #call'able or a block" unless obj
201
+
202
+ @options[:app] = obj
203
+ end
204
+
205
+ # Start the Puma control rack application on +url+. This application can
206
+ # be communicated with to control the main server. Additionally, you can
207
+ # provide an authentication token, so all requests to the control server
208
+ # will need to include that token as a query parameter. This allows for
209
+ # simple authentication.
210
+ #
211
+ # Check out {Puma::App::Status} to see what the app has available.
212
+ #
213
+ # @example
214
+ # activate_control_app 'unix:///var/run/pumactl.sock'
215
+ # @example
216
+ # activate_control_app 'unix:///var/run/pumactl.sock', { auth_token: '12345' }
217
+ # @example
218
+ # activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true }
219
+ # @example
220
+ # activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true, data_only: true}
221
+ #
222
+ def activate_control_app(url="auto", opts={})
223
+ if url == "auto"
224
+ path = Configuration.temp_path
225
+ @options[:control_url] = "unix://#{path}"
226
+ @options[:control_url_temp] = path
227
+ else
228
+ @options[:control_url] = url
229
+ end
230
+
231
+ if opts[:no_token]
232
+ # We need to use 'none' rather than :none because this value will be
233
+ # passed on to an instance of OptionParser, which doesn't support
234
+ # symbols as option values.
235
+ #
236
+ # See: https://github.com/puma/puma/issues/1193#issuecomment-305995488
237
+ auth_token = 'none'
238
+ else
239
+ auth_token = opts[:auth_token]
240
+ auth_token ||= Configuration.random_token
241
+ end
242
+
243
+ @options[:control_auth_token] = auth_token
244
+ @options[:control_url_umask] = opts[:umask] if opts[:umask]
245
+ @options[:control_data_only] = opts[:data_only] if opts[:data_only]
246
+ end
247
+
248
+ # Load additional configuration from a file.
249
+ # Files get loaded later via Configuration#load.
250
+ #
251
+ # @example
252
+ # load 'config/puma/production.rb'
253
+ #
254
+ def load(file)
255
+ @options[:config_files] ||= []
256
+ @options[:config_files] << file
257
+ end
258
+
259
+ # Bind the server to +url+. "tcp://", "unix://" and "ssl://" are the only
260
+ # accepted protocols. Multiple urls can be bound to, calling +bind+ does
261
+ # not overwrite previous bindings.
262
+ #
263
+ # The default is "tcp://0.0.0.0:9292".
264
+ #
265
+ # You can use query parameters within the url to specify options:
266
+ #
267
+ # * Set the socket backlog depth with +backlog+, default is 1024.
268
+ # * Set up an SSL certificate with +key+ & +cert+.
269
+ # * Set up an SSL certificate for mTLS with +key+, +cert+, +ca+ and +verify_mode+.
270
+ # * Set whether to optimize for low latency instead of throughput with
271
+ # +low_latency+, default is to not optimize for low latency. This is done
272
+ # via +Socket::TCP_NODELAY+.
273
+ # * Set socket permissions with +umask+.
274
+ #
275
+ # @example Backlog depth
276
+ # bind 'unix:///var/run/puma.sock?backlog=512'
277
+ # @example SSL cert
278
+ # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem'
279
+ # @example SSL cert for mutual TLS (mTLS)
280
+ # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem&ca=ca.pem&verify_mode=force_peer'
281
+ # @example Disable optimization for low latency
282
+ # bind 'tcp://0.0.0.0:9292?low_latency=false'
283
+ # @example Socket permissions
284
+ # bind 'unix:///var/run/puma.sock?umask=0111'
285
+ #
286
+ # @see Puma::Runner#load_and_bind
287
+ # @see Puma::Cluster#run
288
+ #
289
+ def bind(url)
290
+ @options[:binds] ||= []
291
+ @options[:binds] << url
292
+ end
293
+
294
+ def clear_binds!
295
+ @options[:binds] = []
296
+ end
297
+
298
+ # Bind to (systemd) activated sockets, regardless of configured binds.
299
+ #
300
+ # Systemd can present sockets as file descriptors that are already opened.
301
+ # By default Puma will use these but only if it was explicitly told to bind
302
+ # to the socket. If not, it will close the activated sockets. This means
303
+ # all configuration is duplicated.
304
+ #
305
+ # Binds can contain additional configuration, but only SSL config is really
306
+ # relevant since the unix and TCP socket options are ignored.
307
+ #
308
+ # This means there is a lot of duplicated configuration for no additional
309
+ # value in most setups. This method tells the launcher to bind to all
310
+ # activated sockets, regardless of existing bind.
311
+ #
312
+ # To clear configured binds, the value only can be passed. This will clear
313
+ # out any binds that may have been configured.
314
+ #
315
+ # @example Use any systemd activated sockets as well as configured binds
316
+ # bind_to_activated_sockets
317
+ #
318
+ # @example Only bind to systemd activated sockets, ignoring other binds
319
+ # bind_to_activated_sockets 'only'
320
+ #
321
+ def bind_to_activated_sockets(bind=true)
322
+ @options[:bind_to_activated_sockets] = bind
323
+ end
324
+
325
+ # Define the TCP port to bind to. Use `bind` for more advanced options.
326
+ #
327
+ # The default is +9292+.
328
+ #
329
+ # @example
330
+ # port 3000
331
+ #
332
+ def port(port, host=nil)
333
+ host ||= default_host
334
+ bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s
335
+ end
336
+
337
+ # Define how long the tcp socket stays open, if no data has been received.
338
+ #
339
+ # The default is 30 seconds.
340
+ #
341
+ # @example
342
+ # first_data_timeout 40
343
+ #
344
+ # @see Puma::Server.new
345
+ #
346
+ def first_data_timeout(seconds)
347
+ @options[:first_data_timeout] = Integer(seconds)
348
+ end
349
+
350
+ # Define how long persistent connections can be idle before Puma closes them.
351
+ #
352
+ # The default is 20 seconds.
353
+ #
354
+ # @example
355
+ # persistent_timeout 30
356
+ #
357
+ # @see Puma::Server.new
358
+ #
359
+ def persistent_timeout(seconds)
360
+ @options[:persistent_timeout] = Integer(seconds)
361
+ end
362
+
363
+ # If a new request is not received within this number of seconds, begin shutting down.
364
+ #
365
+ # The default is +nil+.
366
+ #
367
+ # @example
368
+ # idle_timeout 60
369
+ #
370
+ # @see Puma::Server.new
371
+ #
372
+ def idle_timeout(seconds)
373
+ @options[:idle_timeout] = Integer(seconds)
374
+ end
375
+
376
+ # Use a clean fiber per request which ensures a clean slate for fiber
377
+ # locals and fiber storage. Also provides a cleaner backtrace with less
378
+ # Puma internal stack frames.
379
+ #
380
+ # The default is +false+.
381
+ #
382
+ # @example
383
+ # fiber_per_request
384
+ #
385
+ def fiber_per_request(which=true)
386
+ @options[:fiber_per_request] = which
387
+ end
388
+
389
+ alias clean_thread_locals fiber_per_request
390
+
391
+ # When shutting down, drain the accept socket of pending connections and
392
+ # process them. This loops over the accept socket until there are no more
393
+ # read events and then stops looking and waits for the requests to finish.
394
+ #
395
+ # @see Puma::Server#graceful_shutdown
396
+ #
397
+ def drain_on_shutdown(which=true)
398
+ @options[:drain_on_shutdown] = which
399
+ end
400
+
401
+ # Set the environment in which the rack's app will run. The value must be
402
+ # a string.
403
+ #
404
+ # The default is "development".
405
+ #
406
+ # @example
407
+ # environment 'production'
408
+ #
409
+ def environment(environment)
410
+ @options[:environment] = environment
411
+ end
412
+
413
+ # How long to wait for threads to stop when shutting them down.
414
+ # Specifying :immediately will cause Puma to kill the threads immediately.
415
+ # Otherwise the value is the number of seconds to wait.
416
+ #
417
+ # Puma always waits a few seconds after killing a thread for it to try
418
+ # to finish up it's work, even in :immediately mode.
419
+ #
420
+ # The default is +:forever+.
421
+ #
422
+ # @see Puma::Server#graceful_shutdown
423
+ #
424
+ def force_shutdown_after(val=:forever)
425
+ i = case val
426
+ when :forever
427
+ -1
428
+ when :immediately
429
+ 0
430
+ else
431
+ Float(val)
432
+ end
433
+
434
+ @options[:force_shutdown_after] = i
435
+ end
436
+
437
+ # Code to run before doing a restart. This code should
438
+ # close log files, database connections, etc.
439
+ #
440
+ # This can be called multiple times to add code each time.
441
+ #
442
+ # @example
443
+ # before_restart do
444
+ # puts 'On restart...'
445
+ # end
446
+ #
447
+ def before_restart(&block)
448
+ Puma.deprecate_method_change :on_restart, __callee__, __method__
449
+
450
+ process_hook :before_restart, nil, block
451
+ end
452
+
453
+ alias_method :on_restart, :before_restart
454
+
455
+ # Command to use to restart Puma. This should be just how to
456
+ # load Puma itself (ie. 'ruby -Ilib bin/puma'), not the arguments
457
+ # to Puma, as those are the same as the original process.
458
+ #
459
+ # @example
460
+ # restart_command '/u/app/lolcat/bin/restart_puma'
461
+ #
462
+ def restart_command(cmd)
463
+ @options[:restart_cmd] = cmd.to_s
464
+ end
465
+
466
+ # Store the pid of the server in the file at "path".
467
+ #
468
+ # @example
469
+ # pidfile '/u/apps/lolcat/tmp/pids/puma.pid'
470
+ #
471
+ def pidfile(path)
472
+ @options[:pidfile] = path.to_s
473
+ end
474
+
475
+ # Disable request logging, the inverse of `log_requests`.
476
+ #
477
+ # The default is +true+.
478
+ #
479
+ # @example
480
+ # quiet
481
+ #
482
+ def quiet(which=true)
483
+ @options[:log_requests] = !which
484
+ end
485
+
486
+ # Enable request logging, the inverse of `quiet`.
487
+ #
488
+ # The default is +false+.
489
+ #
490
+ # @example
491
+ # log_requests
492
+ #
493
+ def log_requests(which=true)
494
+ @options[:log_requests] = which
495
+ end
496
+
497
+ # Pass in a custom logging class instance
498
+ #
499
+ # @example
500
+ # custom_logger Logger.new('t.log')
501
+ #
502
+ def custom_logger(custom_logger)
503
+ @options[:custom_logger] = custom_logger
504
+ end
505
+
506
+ # Show debugging info
507
+ #
508
+ # The default is +false+.
509
+ #
510
+ # @example
511
+ # debug
512
+ #
513
+ def debug
514
+ @options[:debug] = true
515
+ end
516
+
517
+ # Load +path+ as a rackup file.
518
+ #
519
+ # The default is "config.ru".
520
+ #
521
+ # @example
522
+ # rackup '/u/apps/lolcat/config.ru'
523
+ #
524
+ def rackup(path)
525
+ @options[:rackup] ||= path.to_s
526
+ end
527
+
528
+ # Allows setting `env['rack.url_scheme']`.
529
+ # Only necessary if X-Forwarded-Proto is not being set by your proxy
530
+ # Normal values are 'http' or 'https'.
531
+ #
532
+ def rack_url_scheme(scheme=nil)
533
+ @options[:rack_url_scheme] = scheme
534
+ end
535
+
536
+ # Enable HTTP 103 Early Hints responses.
537
+ #
538
+ # The default is +nil+.
539
+ #
540
+ # @example
541
+ # early_hints
542
+ #
543
+ def early_hints(answer=true)
544
+ @options[:early_hints] = answer
545
+ end
546
+
547
+ # Redirect +STDOUT+ and +STDERR+ to files specified. The +append+ parameter
548
+ # specifies whether the output is appended.
549
+ #
550
+ # The default is +false+.
551
+ #
552
+ # @example
553
+ # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr'
554
+ # @example
555
+ # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr', true
556
+ #
557
+ def stdout_redirect(stdout=nil, stderr=nil, append=false)
558
+ @options[:redirect_stdout] = stdout
559
+ @options[:redirect_stderr] = stderr
560
+ @options[:redirect_append] = append
561
+ end
562
+
563
+ def log_formatter(&block)
564
+ @options[:log_formatter] = block
565
+ end
566
+
567
+ # Configure the number of threads to use to answer requests.
568
+ #
569
+ # It can be a single fixed number, or a +min+ and a +max+.
570
+ #
571
+ # The default is the environment variables +PUMA_MIN_THREADS+ / +PUMA_MAX_THREADS+
572
+ # (or +MIN_THREADS+ / +MAX_THREADS+ if the +PUMA_+ variables aren't set).
573
+ #
574
+ # If these environment variables aren't set, the default is "0, 5" in MRI or "0, 16" for other interpreters.
575
+ #
576
+ # @example
577
+ # threads 5
578
+ # @example
579
+ # threads 0, 16
580
+ # @example
581
+ # threads 5, 5
582
+ #
583
+ def threads(min, max = min)
584
+ min = Integer(min)
585
+ max = Integer(max)
586
+ if min > max
587
+ raise "The minimum (#{min}) number of threads must be less than or equal to the max (#{max})"
588
+ end
589
+
590
+ if max < 1
591
+ raise "The maximum number of threads (#{max}) must be greater than 0"
592
+ end
593
+
594
+ @options[:min_threads] = min
595
+ @options[:max_threads] = max
596
+ end
597
+
598
+ # Instead of using +bind+ and manually constructing a URI like:
599
+ #
600
+ # bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path'
601
+ #
602
+ # you can use the this method.
603
+ #
604
+ # When binding on localhost you don't need to specify +cert+ and +key+,
605
+ # Puma will assume you are using the +localhost+ gem and try to load the
606
+ # appropriate files.
607
+ #
608
+ # When using the options hash parameter, the `reuse:` value is either
609
+ # `true`, which sets reuse 'on' with default values, or a hash, with `:size`
610
+ # and/or `:timeout` keys, each with integer values.
611
+ #
612
+ # The `cert:` options hash parameter can be the path to a certificate
613
+ # file including all intermediate certificates in PEM format.
614
+ #
615
+ # The `cert_pem:` options hash parameter can be String containing the
616
+ # cerificate and all intermediate certificates in PEM format.
617
+ #
618
+ # @example
619
+ # ssl_bind '127.0.0.1', '9292', {
620
+ # cert: path_to_cert,
621
+ # key: path_to_key,
622
+ # ssl_cipher_filter: cipher_filter, # optional
623
+ # ssl_ciphersuites: ciphersuites, # optional
624
+ # verify_mode: verify_mode, # default 'none'
625
+ # verification_flags: flags, # optional, not supported by JRuby
626
+ # reuse: true # optional
627
+ # }
628
+ #
629
+ # @example Using self-signed certificate with the +localhost+ gem:
630
+ # ssl_bind '127.0.0.1', '9292'
631
+ #
632
+ # @example Alternatively, you can provide +cert_pem+ and +key_pem+:
633
+ # ssl_bind '127.0.0.1', '9292', {
634
+ # cert_pem: File.read(path_to_cert),
635
+ # key_pem: File.read(path_to_key),
636
+ # reuse: {size: 2_000, timeout: 20} # optional
637
+ # }
638
+ #
639
+ # @example For JRuby, two keys are required: +keystore+ & +keystore_pass+
640
+ # ssl_bind '127.0.0.1', '9292', {
641
+ # keystore: path_to_keystore,
642
+ # keystore_pass: password,
643
+ # ssl_cipher_list: cipher_list, # optional
644
+ # verify_mode: verify_mode # default 'none'
645
+ # }
646
+ #
647
+ def ssl_bind(host, port, opts = {})
648
+ add_pem_values_to_options_store(opts)
649
+ bind self.class.ssl_bind_str(host, port, opts)
650
+ end
651
+
652
+ # Use +path+ as the file to store the server info state. This is
653
+ # used by +pumactl+ to query and control the server.
654
+ #
655
+ # @example
656
+ # state_path '/u/apps/lolcat/tmp/pids/puma.state'
657
+ #
658
+ def state_path(path)
659
+ @options[:state] = path.to_s
660
+ end
661
+
662
+ # Use +permission+ to restrict permissions for the state file. By convention,
663
+ # +permission+ is an octal number (e.g. `0640` or `0o640`).
664
+ #
665
+ # @example
666
+ # state_permission 0600
667
+ #
668
+ def state_permission(permission)
669
+ @options[:state_permission] = permission
670
+ end
671
+
672
+ # How many worker processes to run. Typically this is set to the number of
673
+ # available cores.
674
+ #
675
+ # The default is the value of the environment variable +WEB_CONCURRENCY+ if
676
+ # set, otherwise 0. Passing +:auto+ will set the value to
677
+ # +Concurrent.available_processor_count+ (requires the concurrent-ruby gem).
678
+ # On some platforms (e.g. under CPU quotas) this may be fractional, and Puma
679
+ # will round down. If it rounds down to 0, Puma will run in single mode and
680
+ # cluster-only hooks like +before_worker_boot+ will not execute.
681
+ # If you rely on cluster-only hooks, set an explicit worker count.
682
+ #
683
+ # A value of 0 or nil means run in single mode.
684
+ #
685
+ # @example
686
+ # workers 2
687
+ # workers :auto
688
+ #
689
+ # @see Puma::Cluster
690
+ #
691
+ def workers(count)
692
+ @options[:workers] = count.nil? ? 0 : @config.send(:parse_workers, count)
693
+ end
694
+
695
+ # Disable warning message when running in cluster mode with a single worker.
696
+ #
697
+ # Cluster mode has some overhead of running an additional 'control' process
698
+ # in order to manage the cluster. If only running a single worker it is
699
+ # likely not worth paying that overhead vs running in single mode with
700
+ # additional threads instead.
701
+ #
702
+ # There are some scenarios where running cluster mode with a single worker
703
+ # may still be warranted and valid under certain deployment scenarios, see
704
+ # https://github.com/puma/puma/issues/2534
705
+ #
706
+ # Moving from workers = 1 to workers = 0 will save 10-30% of memory use.
707
+ #
708
+ # The default is +false+.
709
+ #
710
+ # @note Cluster mode only.
711
+ #
712
+ # @example
713
+ # silence_single_worker_warning
714
+ #
715
+ def silence_single_worker_warning
716
+ @options[:silence_single_worker_warning] = true
717
+ end
718
+
719
+ # Disable warning message when running single mode with callback hook defined.
720
+ #
721
+ # The default is +false+.
722
+ #
723
+ # @example
724
+ # silence_fork_callback_warning
725
+ #
726
+ def silence_fork_callback_warning
727
+ @options[:silence_fork_callback_warning] = true
728
+ end
729
+
730
+ # Code to run immediately before master process
731
+ # forks workers (once on boot). These hooks can block if necessary
732
+ # to wait for background operations unknown to Puma to finish before
733
+ # the process terminates.
734
+ # This can be used to close any connections to remote servers (database,
735
+ # Redis, ...) that were opened when preloading the code.
736
+ #
737
+ # This can be called multiple times to add several hooks.
738
+ #
739
+ # @note Cluster mode only.
740
+ #
741
+ # @example
742
+ # before_fork do
743
+ # puts "Starting workers..."
744
+ # end
745
+ #
746
+ def before_fork(&block)
747
+ process_hook :before_fork, nil, block, cluster_only: true
748
+ end
749
+
750
+ # Code to run in a worker when it boots to setup
751
+ # the process before booting the app.
752
+ #
753
+ # This can be called multiple times to add several hooks.
754
+ #
755
+ # @note Cluster mode only.
756
+ #
757
+ # @example
758
+ # before_worker_boot do
759
+ # puts 'Before worker boot...'
760
+ # end
761
+ #
762
+ def before_worker_boot(key = nil, &block)
763
+ Puma.deprecate_method_change :on_worker_boot, __callee__, __method__
764
+
765
+ process_hook :before_worker_boot, key, block, cluster_only: true
766
+ end
767
+
768
+ alias_method :on_worker_boot, :before_worker_boot
769
+
770
+ # Code to run immediately before a worker shuts
771
+ # down (after it has finished processing HTTP requests). The worker's
772
+ # index is passed as an argument. These hooks
773
+ # can block if necessary to wait for background operations unknown
774
+ # to Puma to finish before the process terminates.
775
+ #
776
+ # This can be called multiple times to add several hooks.
777
+ #
778
+ # @note Cluster mode only.
779
+ #
780
+ # @example
781
+ # before_worker_shutdown do
782
+ # puts 'On worker shutdown...'
783
+ # end
784
+ #
785
+ def before_worker_shutdown(key = nil, &block)
786
+ Puma.deprecate_method_change :on_worker_shutdown, __callee__, __method__
787
+
788
+ process_hook :before_worker_shutdown, key, block, cluster_only: true
789
+ end
790
+
791
+ alias_method :on_worker_shutdown, :before_worker_shutdown
792
+
793
+ # Code to run in the master right before a worker is started. The worker's
794
+ # index is passed as an argument.
795
+ #
796
+ # This can be called multiple times to add several hooks.
797
+ #
798
+ # @note Cluster mode only.
799
+ #
800
+ # @example
801
+ # before_worker_fork do
802
+ # puts 'Before worker fork...'
803
+ # end
804
+ #
805
+ def before_worker_fork(&block)
806
+ Puma.deprecate_method_change :on_worker_fork, __callee__, __method__
807
+
808
+ process_hook :before_worker_fork, nil, block, cluster_only: true
809
+ end
810
+
811
+ alias_method :on_worker_fork, :before_worker_fork
812
+
813
+ # Code to run in the master after a worker has been started. The worker's
814
+ # index is passed as an argument.
815
+ #
816
+ # This is called everytime a worker is to be started.
817
+ #
818
+ # @note Cluster mode only.
819
+ #
820
+ # @example
821
+ # after_worker_fork do
822
+ # puts 'After worker fork...'
823
+ # end
824
+ #
825
+ def after_worker_fork(&block)
826
+ process_hook :after_worker_fork, nil, block, cluster_only: true
827
+ end
828
+
829
+ alias_method :after_worker_boot, :after_worker_fork
830
+
831
+ # Code to run in the master right after a worker has stopped. The worker's
832
+ # index and Process::Status are passed as arguments.
833
+ #
834
+ # @note Cluster mode only.
835
+ #
836
+ # @example
837
+ # after_worker_shutdown do |worker_handle|
838
+ # puts 'Worker crashed' unless worker_handle.process_status.success?
839
+ # end
840
+ #
841
+ def after_worker_shutdown(&block)
842
+ process_hook :after_worker_shutdown, nil, block, cluster_only: true
843
+ end
844
+
845
+ # Code to run after puma is booted (works for both single and cluster modes).
846
+ #
847
+ # @example
848
+ # after_booted do
849
+ # puts 'After booting...'
850
+ # end
851
+ #
852
+ def after_booted(&block)
853
+ Puma.deprecate_method_change :on_booted, __callee__, __method__
854
+
855
+ @config.events.after_booted(&block)
856
+ end
857
+
858
+ alias_method :on_booted, :after_booted
859
+
860
+ # Code to run after puma is stopped (works for both: single and clustered)
861
+ #
862
+ # @example
863
+ # after_stopped do
864
+ # puts 'After stopping...'
865
+ # end
866
+ #
867
+ def after_stopped(&block)
868
+ Puma.deprecate_method_change :on_stopped, __callee__, __method__
869
+
870
+ @config.events.after_stopped(&block)
871
+ end
872
+ alias_method :on_stopped, :after_stopped
873
+
874
+ # When `fork_worker` is enabled, code to run in Worker 0
875
+ # before all other workers are re-forked from this process,
876
+ # after the server has temporarily stopped serving requests
877
+ # (once per complete refork cycle).
878
+ #
879
+ # This can be used to trigger extra garbage-collection to maximize
880
+ # copy-on-write efficiency, or close any connections to remote servers
881
+ # (database, Redis, ...) that were opened while the server was running.
882
+ #
883
+ # This can be called multiple times to add several hooks.
884
+ #
885
+ # @note Cluster mode with `fork_worker` enabled only.
886
+ #
887
+ # @example
888
+ # before_refork do
889
+ # 3.times {GC.start}
890
+ # end
891
+ #
892
+ # @version 5.0.0
893
+ #
894
+ def before_refork(key = nil, &block)
895
+ Puma.deprecate_method_change :on_refork, __callee__, __method__
896
+
897
+ process_hook :before_refork, key, block, cluster_only: true
898
+ end
899
+
900
+ alias_method :on_refork, :before_refork
901
+
902
+ # When `fork_worker` is enabled, code to run in Worker 0
903
+ # after all other workers are re-forked from this process,
904
+ # after the server has temporarily stopped serving requests
905
+ # (once per complete refork cycle).
906
+ #
907
+ # This can be used to re-open any connections to remote servers
908
+ # (database, Redis, ...) that were closed via before_refork.
909
+ #
910
+ # This can be called multiple times to add several hooks.
911
+ #
912
+ # @note Cluster mode with `fork_worker` enabled only.
913
+ #
914
+ # @example
915
+ # after_refork do
916
+ # puts 'After refork...'
917
+ # end
918
+ #
919
+ def after_refork(key = nil, &block)
920
+ process_hook :after_refork, key, block
921
+ end
922
+
923
+ # Provide a block to be executed just before a thread is added to the thread
924
+ # pool. Be careful: while the block executes, thread creation is delayed, and
925
+ # probably a request will have to wait too! The new thread will not be added to
926
+ # the threadpool until the provided block returns.
927
+ #
928
+ # Return values are ignored.
929
+ # Raising an exception will log a warning.
930
+ #
931
+ # This hook is useful for doing something when the thread pool grows.
932
+ #
933
+ # This can be called multiple times to add several hooks.
934
+ #
935
+ # @example
936
+ # before_thread_start do
937
+ # puts 'On thread start...'
938
+ # end
939
+ #
940
+ def before_thread_start(&block)
941
+ Puma.deprecate_method_change :on_thread_start, __callee__, __method__
942
+
943
+ process_hook :before_thread_start, nil, block
944
+ end
945
+
946
+ alias_method :on_thread_start, :before_thread_start
947
+
948
+ # Provide a block to be executed after a thread is trimmed from the thread
949
+ # pool. Be careful: while this block executes, Puma's main loop is
950
+ # blocked, so no new requests will be picked up.
951
+ #
952
+ # This hook only runs when a thread in the threadpool is trimmed by Puma.
953
+ # It does not run when a thread dies due to exceptions or any other cause.
954
+ #
955
+ # Return values are ignored.
956
+ # Raising an exception will log a warning.
957
+ #
958
+ # This hook is useful for cleaning up thread local resources when a thread
959
+ # is trimmed.
960
+ #
961
+ # This can be called multiple times to add several hooks.
962
+ #
963
+ # @example
964
+ # before_thread_exit do
965
+ # puts 'On thread exit...'
966
+ # end
967
+ #
968
+ def before_thread_exit(&block)
969
+ Puma.deprecate_method_change :on_thread_exit, __callee__, __method__
970
+
971
+ process_hook :before_thread_exit, nil, block
972
+ end
973
+
974
+ alias_method :on_thread_exit, :before_thread_exit
975
+
976
+ # Code to run out-of-band when the worker is idle.
977
+ # These hooks run immediately after a request has finished
978
+ # processing and there are no busy threads on the worker.
979
+ # The worker doesn't accept new requests until this code finishes.
980
+ #
981
+ # This hook is useful for running out-of-band garbage collection
982
+ # or scheduling asynchronous tasks to execute after a response.
983
+ #
984
+ # This can be called multiple times to add several hooks.
985
+ #
986
+ def out_of_band(&block)
987
+ process_hook :out_of_band, nil, block
988
+ end
989
+
990
+ # The directory to operate out of.
991
+ #
992
+ # The default is the current directory.
993
+ #
994
+ # @example
995
+ # directory '/u/apps/lolcat'
996
+ #
997
+ def directory(dir)
998
+ @options[:directory] = dir.to_s
999
+ end
1000
+
1001
+ # Preload the application before forking the workers; this conflicts with
1002
+ # the phased restart feature.
1003
+ #
1004
+ # The default is +true+ if your app uses more than 1 worker.
1005
+ #
1006
+ # @note Cluster mode only.
1007
+ # @note When using `fork_worker`, this only applies to worker 0.
1008
+ #
1009
+ # @example
1010
+ # preload_app!
1011
+ #
1012
+ def preload_app!(answer=true)
1013
+ @options[:preload_app] = answer
1014
+ end
1015
+
1016
+ # Use +obj+ or +block+ as the low level error handler. This allows the
1017
+ # configuration file to change the default error on the server.
1018
+ #
1019
+ # @example
1020
+ # lowlevel_error_handler do |err|
1021
+ # [200, {}, ["error page"]]
1022
+ # end
1023
+ #
1024
+ def lowlevel_error_handler(obj=nil, &block)
1025
+ obj ||= block
1026
+ raise "Provide either a #call'able or a block" unless obj
1027
+ @options[:lowlevel_error_handler] = obj
1028
+ end
1029
+
1030
+ # This option is used to allow your app and its gems to be
1031
+ # properly reloaded when not using preload.
1032
+ #
1033
+ # When set, if Puma detects that it's been invoked in the
1034
+ # context of Bundler, it will cleanup the environment and
1035
+ # re-run itself outside the Bundler environment, but directly
1036
+ # using the files that Bundler has setup.
1037
+ #
1038
+ # This means that Puma is now decoupled from your Bundler
1039
+ # context and when each worker loads, it will be loading a
1040
+ # new Bundler context and thus can float around as the release
1041
+ # dictates.
1042
+ #
1043
+ # @note This is incompatible with +preload_app!+.
1044
+ # @note This is only supported for RubyGems 2.2+
1045
+ #
1046
+ # @see extra_runtime_dependencies
1047
+ #
1048
+ def prune_bundler(answer=true)
1049
+ @options[:prune_bundler] = answer
1050
+ end
1051
+
1052
+ # Raises a SignalException when SIGTERM is received. In environments where
1053
+ # SIGTERM is something expected, you can suppress these with this option.
1054
+ #
1055
+ # This can be useful for example in Kubernetes, where rolling restart is
1056
+ # guaranteed usually on the infrastructure level.
1057
+ #
1058
+ # The default is +true+.
1059
+ #
1060
+ # @example
1061
+ # raise_exception_on_sigterm false
1062
+ #
1063
+ # @see Puma::Launcher#setup_signals
1064
+ # @see Puma::Cluster#setup_signals
1065
+ #
1066
+ def raise_exception_on_sigterm(answer=true)
1067
+ @options[:raise_exception_on_sigterm] = answer
1068
+ end
1069
+
1070
+ # When using prune_bundler, if extra runtime dependencies need to be loaded to
1071
+ # initialize your app, then this setting can be used. This includes any Puma plugins.
1072
+ #
1073
+ # Before bundler is pruned, the gem names supplied will be looked up in the bundler
1074
+ # context and then loaded again after bundler is pruned.
1075
+ # Only applies if prune_bundler is used.
1076
+ #
1077
+ # @example
1078
+ # extra_runtime_dependencies ['gem_name_1', 'gem_name_2']
1079
+ # @example
1080
+ # extra_runtime_dependencies ['puma_worker_killer', 'puma-heroku']
1081
+ #
1082
+ # @see Puma::Launcher#extra_runtime_deps_directories
1083
+ #
1084
+ def extra_runtime_dependencies(answer = [])
1085
+ @options[:extra_runtime_dependencies] = Array(answer)
1086
+ end
1087
+
1088
+ # Additional text to display in process listing.
1089
+ #
1090
+ # If you do not specify a tag, Puma will infer it. If you do not want Puma
1091
+ # to add a tag, use an empty string.
1092
+ #
1093
+ # The default is the current file or directory base name.
1094
+ #
1095
+ # @example
1096
+ # tag 'app name'
1097
+ # @example
1098
+ # tag ''
1099
+ #
1100
+ def tag(string)
1101
+ @options[:tag] = string.to_s
1102
+ end
1103
+
1104
+ # Change the default interval for checking workers.
1105
+ #
1106
+ # The default is 5 seconds.
1107
+ #
1108
+ # @note Cluster mode only.
1109
+ #
1110
+ # @example
1111
+ # worker_check_interval 10
1112
+ #
1113
+ # @see Puma::Cluster#check_workers
1114
+ #
1115
+ def worker_check_interval(interval)
1116
+ @options[:worker_check_interval] = Integer(interval)
1117
+ end
1118
+
1119
+ # Verifies that all workers have checked in to the master process within
1120
+ # the given timeout. If not the worker process will be restarted. This is
1121
+ # not a request timeout, it is to protect against a hung or dead process.
1122
+ # Setting this value will not protect against slow requests.
1123
+ #
1124
+ # This value must be greater than worker_check_interval.
1125
+ #
1126
+ # The default is 60 seconds.
1127
+ #
1128
+ # @note Cluster mode only.
1129
+ #
1130
+ # @example
1131
+ # worker_timeout 60
1132
+ #
1133
+ # @see Puma::Cluster::Worker#ping_timeout
1134
+ #
1135
+ def worker_timeout(timeout)
1136
+ timeout = Integer(timeout)
1137
+ min = @options.fetch(:worker_check_interval, Configuration::DEFAULTS[:worker_check_interval])
1138
+
1139
+ if timeout <= min
1140
+ raise "The minimum worker_timeout must be greater than the worker reporting interval (#{min})"
1141
+ end
1142
+
1143
+ @options[:worker_timeout] = timeout
1144
+ end
1145
+
1146
+ # Change the default worker timeout for booting.
1147
+ #
1148
+ # The default is the value of `worker_timeout`.
1149
+ #
1150
+ # @note Cluster mode only.
1151
+ #
1152
+ # @example
1153
+ # worker_boot_timeout 60
1154
+ #
1155
+ # @see Puma::Cluster::Worker#ping_timeout
1156
+ #
1157
+ def worker_boot_timeout(timeout)
1158
+ @options[:worker_boot_timeout] = Integer(timeout)
1159
+ end
1160
+
1161
+ # Set the timeout for worker shutdown.
1162
+ #
1163
+ # The default is 30 seconds.
1164
+ #
1165
+ # @note Cluster mode only.
1166
+ #
1167
+ # @example
1168
+ # worker_shutdown_timeout 90
1169
+ #
1170
+ # @see Puma::Cluster::Worker#term
1171
+ #
1172
+ def worker_shutdown_timeout(timeout)
1173
+ @options[:worker_shutdown_timeout] = Integer(timeout)
1174
+ end
1175
+
1176
+ # Set the strategy for worker culling.
1177
+ #
1178
+ # There are two possible values:
1179
+ #
1180
+ # 1. **:youngest** - the youngest workers (i.e. the workers that were
1181
+ # the most recently started) will be culled.
1182
+ # 2. **:oldest** - the oldest workers (i.e. the workers that were started
1183
+ # the longest time ago) will be culled.
1184
+ #
1185
+ # The default is +:youngest+.
1186
+ #
1187
+ # @note Cluster mode only.
1188
+ #
1189
+ # @example
1190
+ # worker_culling_strategy :oldest
1191
+ #
1192
+ # @see Puma::Cluster#cull_workers
1193
+ #
1194
+ def worker_culling_strategy(strategy)
1195
+ strategy = strategy.to_sym
1196
+
1197
+ if ![:youngest, :oldest].include?(strategy)
1198
+ raise "Invalid value for worker_culling_strategy - #{strategy}"
1199
+ end
1200
+
1201
+ @options[:worker_culling_strategy] = strategy
1202
+ end
1203
+
1204
+ # When set to true, workers accept all requests
1205
+ # and queue them before passing them to the handlers.
1206
+ # When set to false, each worker process accepts exactly as
1207
+ # many requests as it is configured to simultaneously handle.
1208
+ #
1209
+ # Queueing requests generally improves performance. In some
1210
+ # cases, such as a single threaded application, it may be
1211
+ # better to ensure requests get balanced across workers.
1212
+ #
1213
+ # Note that setting this to false disables HTTP keepalive and
1214
+ # slow clients will occupy a handler thread while the request
1215
+ # is being sent. A reverse proxy, such as nginx, can handle
1216
+ # slow clients and queue requests before they reach Puma.
1217
+ #
1218
+ # The default is +true+.
1219
+ #
1220
+ # @see Puma::Server
1221
+ #
1222
+ def queue_requests(answer=true)
1223
+ @options[:queue_requests] = answer
1224
+ end
1225
+
1226
+ # When a shutdown is requested, the backtraces of all the
1227
+ # threads will be written to $stdout. This can help figure
1228
+ # out why shutdown is hanging.
1229
+ #
1230
+ def shutdown_debug(val=true)
1231
+ @options[:shutdown_debug] = val
1232
+ end
1233
+
1234
+
1235
+ # Maximum delay of worker accept loop.
1236
+ #
1237
+ # Attempts to route traffic to less-busy workers by causing a busy worker to delay
1238
+ # listening on the socket, allowing workers which are not processing as many
1239
+ # requests to pick up new requests first.
1240
+ #
1241
+ # The default is 0.005 seconds.
1242
+ #
1243
+ # To turn off this feature, set the value to 0.
1244
+ #
1245
+ # @note Cluster mode with >= 2 workers only.
1246
+ #
1247
+ # @note Interpreters with forking support only.
1248
+ #
1249
+ # @see Puma::Server#handle_servers
1250
+ # @see Puma::ThreadPool#wait_for_less_busy_worker
1251
+ #
1252
+ def wait_for_less_busy_worker(val=0.005)
1253
+ @options[:wait_for_less_busy_worker] = val.to_f
1254
+ end
1255
+
1256
+ # Control how the remote address of the connection is set. This
1257
+ # is configurable because to calculate the true socket peer address
1258
+ # a kernel syscall is required which for very fast rack handlers
1259
+ # slows down the handling significantly.
1260
+ #
1261
+ # There are 5 possible values:
1262
+ #
1263
+ # 1. **:socket** - read the peername from the socket using the
1264
+ # syscall. This is the normal behavior. If this fails for any reason (e.g.,
1265
+ # if the peer disconnects between the connection being accepted and the getpeername
1266
+ # system call), Puma will return "0.0.0.0"
1267
+ # 2. **:localhost** - set the remote address to "127.0.0.1"
1268
+ # 3. **header: <http_header>**- set the remote address to the value of the
1269
+ # provided http header. For instance:
1270
+ # `set_remote_address header: "X-Real-IP"`.
1271
+ # Only the first word (as separated by spaces or comma) is used, allowing
1272
+ # headers such as X-Forwarded-For to be used as well. If this header is absent,
1273
+ # Puma will fall back to the behavior of :socket
1274
+ # 4. **proxy_protocol: :v1**- set the remote address to the value read from the
1275
+ # HAproxy PROXY protocol, version 1. If the request does not have the PROXY
1276
+ # protocol attached to it, will fall back to :socket
1277
+ # 5. **\<Any string\>** - this allows you to hardcode remote address to any value
1278
+ # you wish. Because Puma never uses this field anyway, it's format is
1279
+ # entirely in your hands.
1280
+ #
1281
+ # The default is +:socket+.
1282
+ #
1283
+ # @example
1284
+ # set_remote_address :localhost
1285
+ #
1286
+ def set_remote_address(val=:socket)
1287
+ case val
1288
+ when :socket
1289
+ @options[:remote_address] = val
1290
+ when :localhost
1291
+ @options[:remote_address] = :value
1292
+ @options[:remote_address_value] = "127.0.0.1".freeze
1293
+ when String
1294
+ @options[:remote_address] = :value
1295
+ @options[:remote_address_value] = val
1296
+ when Hash
1297
+ if hdr = val[:header]
1298
+ @options[:remote_address] = :header
1299
+ @options[:remote_address_header] = "HTTP_" + hdr.upcase.tr("-", "_")
1300
+ elsif protocol_version = val[:proxy_protocol]
1301
+ @options[:remote_address] = :proxy_protocol
1302
+ protocol_version = protocol_version.downcase.to_sym
1303
+ unless [:v1].include?(protocol_version)
1304
+ raise "Invalid value for proxy_protocol - #{protocol_version.inspect}"
1305
+ end
1306
+ @options[:remote_address_proxy_protocol] = protocol_version
1307
+ else
1308
+ raise "Invalid value for set_remote_address - #{val.inspect}"
1309
+ end
1310
+ else
1311
+ raise "Invalid value for set_remote_address - #{val}"
1312
+ end
1313
+ end
1314
+
1315
+ # When enabled, workers will be forked from worker 0 instead of from the master process.
1316
+ # This option is similar to `preload_app` because the app is preloaded before forking,
1317
+ # but it is compatible with phased restart.
1318
+ #
1319
+ # This option also enables the `refork` command (SIGURG), which optimizes copy-on-write performance
1320
+ # in a running app.
1321
+ #
1322
+ # A refork will automatically trigger once after the specified number of requests
1323
+ # (default 1000), or pass 0 to disable auto refork.
1324
+ #
1325
+ # @note This is experimental.
1326
+ # @note Cluster mode only.
1327
+ #
1328
+ def fork_worker(after_requests=1000)
1329
+ @options[:fork_worker] = Integer(after_requests)
1330
+ end
1331
+
1332
+ # @deprecated Use {#max_keep_alive} instead.
1333
+ #
1334
+ def max_fast_inline(num_of_requests)
1335
+ Puma.deprecate_method_change :max_fast_inline, __method__, :max_keep_alive
1336
+ @options[:max_keep_alive] ||= Float(num_of_requests) unless num_of_requests.nil?
1337
+ end
1338
+
1339
+ # The number of requests a keep-alive client can submit before being closed.
1340
+ # Note that some applications (server to server) may benefit from a very high
1341
+ # number or Float::INFINITY.
1342
+ #
1343
+ # The default is 999.
1344
+ #
1345
+ # @example
1346
+ # max_keep_alive 20
1347
+ #
1348
+ def max_keep_alive(num_of_requests)
1349
+ @options[:max_keep_alive] = Float(num_of_requests) unless num_of_requests.nil?
1350
+ end
1351
+
1352
+ # When `true`, keep-alive connections are maintained on inbound requests.
1353
+ # Enabling this setting reduces the number of TCP operations, reducing response
1354
+ # times for connections that can send multiple requests in a single connection.
1355
+ #
1356
+ # When Puma receives more incoming connections than available Puma threads,
1357
+ # enabling the keep-alive behavior may result in processing requests out-of-order,
1358
+ # increasing overall response time variance. Increased response time variance
1359
+ # means that the overall average of response times might not change, but more
1360
+ # outliers will exist. Those long-tail outliers may significantly affect response
1361
+ # times for some processed requests.
1362
+ #
1363
+ # When `false`, Puma closes the connection after each request, requiring the
1364
+ # client to open a new request. Disabling this setting guarantees that requests
1365
+ # will be processed in the order they are fully received, decreasing response
1366
+ # variance and eliminating long-tail outliers caused by keep-alive behavior.
1367
+ # The trade-off is that the number of TCP operations required will increase.
1368
+ #
1369
+ # The default is +true+.
1370
+ #
1371
+ # @example
1372
+ # enable_keep_alives false
1373
+ #
1374
+ def enable_keep_alives(enabled=true)
1375
+ @options[:enable_keep_alives] = enabled
1376
+ end
1377
+
1378
+ # Specify the backend for the IO selector.
1379
+ #
1380
+ # Provided values will be passed directly to +NIO::Selector.new+, with the
1381
+ # exception of +:auto+ which will let nio4r choose the backend.
1382
+ #
1383
+ # Check the documentation of +NIO::Selector.backends+ for the list of valid
1384
+ # options. Note that the available options on your system will depend on the
1385
+ # operating system. If you want to use the pure Ruby backend (not
1386
+ # recommended due to its comparatively low performance), set environment
1387
+ # variable +NIO4R_PURE+ to +true+.
1388
+ #
1389
+ # The default is +:auto+.
1390
+ #
1391
+ # @see https://github.com/socketry/nio4r/blob/main/lib/nio/selector.rb
1392
+ #
1393
+ def io_selector_backend(backend)
1394
+ @options[:io_selector_backend] = backend.to_sym
1395
+ end
1396
+
1397
+ # Ensures +STDOUT+ and +STDERR+ is immediately flushed to the underlying
1398
+ # operating system and is not buffered internally
1399
+ #
1400
+ # The default is +true+.
1401
+ #
1402
+ # @example
1403
+ # mutate_stdout_and_stderr_to_sync_on_write false
1404
+ #
1405
+ def mutate_stdout_and_stderr_to_sync_on_write(enabled=true)
1406
+ @options[:mutate_stdout_and_stderr_to_sync_on_write] = enabled
1407
+ end
1408
+
1409
+ # Specify how big the request payload should be, in bytes.
1410
+ # This limit is compared against Content-Length HTTP header.
1411
+ # If the payload size (CONTENT_LENGTH) is larger than http_content_length_limit,
1412
+ # HTTP 413 status code is returned.
1413
+ #
1414
+ # When no Content-Length http header is present, it is compared against the
1415
+ # size of the body of the request.
1416
+ #
1417
+ # The default is +nil+.
1418
+ #
1419
+ # @example
1420
+ # http_content_length_limit 2_000_000_000
1421
+ #
1422
+ def http_content_length_limit(limit)
1423
+ @options[:http_content_length_limit] = limit
1424
+ end
1425
+
1426
+ # Supported http methods, which will replace `Puma::Const::SUPPORTED_HTTP_METHODS`.
1427
+ # The value of `:any` will allows all methods, otherwise, the value must be
1428
+ # an array of strings. Note that methods are all uppercase.
1429
+ #
1430
+ # `Puma::Const::SUPPORTED_HTTP_METHODS` is conservative, if you want a
1431
+ # complete set of methods, the methods defined by the
1432
+ # [IANA Method Registry](https://www.iana.org/assignments/http-methods/http-methods.xhtml)
1433
+ # are pre-defined as the constant `Puma::Const::IANA_HTTP_METHODS`.
1434
+ #
1435
+ # @note If the `methods` value is `:any`, no method check with be performed,
1436
+ # similar to Puma v5 and earlier.
1437
+ #
1438
+ # @example Adds 'PROPFIND' to existing supported methods
1439
+ # supported_http_methods(Puma::Const::SUPPORTED_HTTP_METHODS + ['PROPFIND'])
1440
+ # @example Restricts methods to the array elements
1441
+ # supported_http_methods %w[HEAD GET POST PUT DELETE OPTIONS PROPFIND]
1442
+ # @example Restricts methods to the methods in the IANA Registry
1443
+ # supported_http_methods Puma::Const::IANA_HTTP_METHODS
1444
+ # @example Allows any method
1445
+ # supported_http_methods :any
1446
+ #
1447
+ def supported_http_methods(methods)
1448
+ if methods == :any
1449
+ @options[:supported_http_methods] = :any
1450
+ elsif Array === methods && methods == (ary = methods.grep(String).uniq) &&
1451
+ !ary.empty?
1452
+ @options[:supported_http_methods] = ary
1453
+ else
1454
+ raise "supported_http_methods must be ':any' or a unique array of strings"
1455
+ end
1456
+ end
1457
+
1458
+ private
1459
+
1460
+ # To avoid adding cert_pem and key_pem as URI params, we store them on the
1461
+ # options[:store] from where Puma binder knows how to find and extract them.
1462
+ #
1463
+ def add_pem_values_to_options_store(opts)
1464
+ return if defined?(JRUBY_VERSION)
1465
+
1466
+ @options[:store] ||= []
1467
+
1468
+ # Store cert_pem and key_pem to options[:store] if present
1469
+ [:cert, :key].each do |v|
1470
+ opt_key = :"#{v}_pem"
1471
+ if opts[opt_key]
1472
+ index = @options[:store].length
1473
+ @options[:store] << opts[opt_key]
1474
+ opts[v] = "store:#{index}"
1475
+ end
1476
+ end
1477
+ end
1478
+
1479
+ def process_hook(options_key, key, block, cluster_only: false)
1480
+ raise ArgumentError, "expected #{options_key} to be given a block" unless block
1481
+
1482
+ @config.hooks[options_key] = true
1483
+
1484
+ @options[options_key] ||= []
1485
+ hook_options = { block: block, cluster_only: cluster_only }
1486
+ hook_options[:id] = if ON_WORKER_KEY.include?(key.class)
1487
+ key.to_sym
1488
+ elsif key.nil?
1489
+ nil
1490
+ else
1491
+ raise "'#{options_key}' key must be String or Symbol"
1492
+ end
1493
+ @options[options_key] << hook_options
1494
+ end
1495
+ end
1496
+ end