Class: Puma::DSL
- Inherits:
-
Object
- Object
- Puma::DSL
- Defined in:
- lib/puma/dsl.rb
Overview
The methods that are available for use inside the configuration file. These same methods are used in Puma cli and the rack handler internally.
Used manually (via CLI class):
config = Configuration.new({}) do |user_config|
user_config.port 3001
end
config.clamp
puts config.[:binds] # => "tcp://127.0.0.1:3001"
Used to load file:
$ cat puma_config.rb
port 3002
Resulting configuration:
config = Configuration.new(config_file: "puma_config.rb")
config.clamp
puts config.[:binds] # => "tcp://127.0.0.1:3002"
You can also find many examples being used by the test suite in test/config.
Puma v6 adds the option to specify a key name (String or Symbol) to the hooks that run inside the forked workers. All the hooks run inside the Cluster::Worker#run method.
Previously, the worker index and the LogWriter instance were passed to the hook blocks/procs. If a key name is specified, a hash is passed as the last parameter. This allows storage of data, typically objects that are created before the worker that need to be passed to the hook when the worker is shutdown.
The following hooks have been updated:
| DSL Method | Options Key | Fork Block Location |
| before_worker_boot | :before_worker_boot | inside, before |
| before_worker_shutdown | :before_worker_shutdown | inside, after |
| before_refork | :before_refork | inside |
| after_refork | :after_refork | inside |
Constant Summary collapse
- ON_WORKER_KEY =
[String, Symbol].freeze
Class Method Summary collapse
-
.ssl_bind_str(host, port, opts) ⇒ Object
Convenience method so logic can be used in CI.
Instance Method Summary collapse
- #_load_from(path) ⇒ Object
- #_offer_plugins ⇒ Object
-
#activate_control_app(url = "auto", opts = {}) ⇒ Object
Start the Puma control rack application on
url. -
#after_booted(&block) ⇒ Object
(also: #on_booted)
Code to run after puma is booted (works for both single and cluster modes).
-
#after_refork(key = nil, &block) ⇒ Object
When ‘fork_worker` is enabled, code to run in Worker 0 after all other workers are re-forked from this process, after the server has temporarily stopped serving requests (once per complete refork cycle).
-
#after_stopped(&block) ⇒ Object
(also: #on_stopped)
Code to run after puma is stopped (works for both: single and clustered).
-
#after_worker_fork(&block) ⇒ Object
(also: #after_worker_boot)
Code to run in the master after a worker has been started.
-
#after_worker_shutdown(&block) ⇒ Object
Code to run in the master right after a worker has stopped.
-
#app(obj = nil, &block) ⇒ Object
Use an object or block as the rack application.
-
#before_fork(&block) ⇒ Object
Code to run immediately before master process forks workers (once on boot).
-
#before_refork(key = nil, &block) ⇒ Object
(also: #on_refork)
When ‘fork_worker` is enabled, code to run in Worker 0 before all other workers are re-forked from this process, after the server has temporarily stopped serving requests (once per complete refork cycle).
-
#before_restart(&block) ⇒ Object
(also: #on_restart)
Code to run before doing a restart.
-
#before_thread_exit(&block) ⇒ Object
(also: #on_thread_exit)
Provide a block to be executed after a thread is trimmed from the thread pool.
-
#before_thread_start(&block) ⇒ Object
(also: #on_thread_start)
Provide a block to be executed just before a thread is added to the thread pool.
-
#before_worker_boot(key = nil, &block) ⇒ Object
(also: #on_worker_boot)
Code to run in a worker when it boots to setup the process before booting the app.
-
#before_worker_fork(&block) ⇒ Object
(also: #on_worker_fork)
Code to run in the master right before a worker is started.
-
#before_worker_shutdown(key = nil, &block) ⇒ Object
(also: #on_worker_shutdown)
Code to run immediately before a worker shuts down (after it has finished processing HTTP requests).
-
#bind(url) ⇒ Object
Bind the server to
url. -
#bind_to_activated_sockets(bind = true) ⇒ Object
Bind to (systemd) activated sockets, regardless of configured binds.
- #clear_binds! ⇒ Object
-
#custom_logger(custom_logger) ⇒ Object
Pass in a custom logging class instance.
-
#debug ⇒ Object
Show debugging info.
- #default_host ⇒ Object
-
#directory(dir) ⇒ Object
The directory to operate out of.
-
#drain_on_shutdown(which = true) ⇒ Object
When shutting down, drain the accept socket of pending connections and process them.
-
#early_hints(answer = true) ⇒ Object
Enable HTTP 103 Early Hints responses.
-
#enable_keep_alives(enabled = true) ⇒ Object
When ‘true`, keep-alive connections are maintained on inbound requests.
-
#environment(environment) ⇒ Object
Set the environment in which the rack’s app will run.
-
#extra_runtime_dependencies(answer = []) ⇒ Object
When using prune_bundler, if extra runtime dependencies need to be loaded to initialize your app, then this setting can be used.
-
#fiber_per_request(which = true) ⇒ Object
(also: #clean_thread_locals)
Use a clean fiber per request which ensures a clean slate for fiber locals and fiber storage.
-
#first_data_timeout(seconds) ⇒ Object
Define how long the tcp socket stays open, if no data has been received.
-
#force_shutdown_after(val = :forever) ⇒ Object
How long to wait for threads to stop when shutting them down.
-
#fork_worker(after_requests = 1000) ⇒ Object
When enabled, workers will be forked from worker 0 instead of from the master process.
- #get(key, default = nil) ⇒ Object
-
#http_content_length_limit(limit) ⇒ Object
Specify how big the request payload should be, in bytes.
-
#idle_timeout(seconds) ⇒ Object
If a new request is not received within this number of seconds, begin shutting down.
-
#initialize(options, config) ⇒ DSL
constructor
A new instance of DSL.
- #inject(&blk) ⇒ Object
-
#io_selector_backend(backend) ⇒ Object
Specify the backend for the IO selector.
-
#load(file) ⇒ Object
Load additional configuration from a file.
- #log_formatter(&block) ⇒ Object
-
#log_requests(which = true) ⇒ Object
Enable request logging, the inverse of ‘quiet`.
-
#lowlevel_error_handler(obj = nil, &block) ⇒ Object
Use
objorblockas the low level error handler. -
#max_fast_inline(num_of_requests) ⇒ Object
deprecated
Deprecated.
Use #max_keep_alive instead.
-
#max_keep_alive(num_of_requests) ⇒ Object
The number of requests a keep-alive client can submit before being closed.
-
#mutate_stdout_and_stderr_to_sync_on_write(enabled = true) ⇒ Object
Ensures
STDOUTandSTDERRis immediately flushed to the underlying operating system and is not buffered internally. -
#out_of_band(&block) ⇒ Object
Code to run out-of-band when the worker is idle.
-
#persistent_timeout(seconds) ⇒ Object
Define how long persistent connections can be idle before Puma closes them.
-
#pidfile(path) ⇒ Object
Store the pid of the server in the file at “path”.
-
#plugin(name) ⇒ Object
Load the named plugin for use by this configuration.
-
#port(port, host = nil) ⇒ Object
Define the TCP port to bind to.
-
#preload_app!(answer = true) ⇒ Object
Preload the application before forking the workers; this conflicts with the phased restart feature.
-
#prune_bundler(answer = true) ⇒ Object
This option is used to allow your app and its gems to be properly reloaded when not using preload.
-
#queue_requests(answer = true) ⇒ Object
When set to true, workers accept all requests and queue them before passing them to the handlers.
-
#quiet(which = true) ⇒ Object
Disable request logging, the inverse of ‘log_requests`.
-
#rack_url_scheme(scheme = nil) ⇒ Object
Allows setting ‘env`.
-
#rackup(path) ⇒ Object
Load
pathas a rackup file. -
#raise_exception_on_sigterm(answer = true) ⇒ Object
Raises a SignalException when SIGTERM is received.
-
#restart_command(cmd) ⇒ Object
Command to use to restart Puma.
- #set_default_host(host) ⇒ Object
-
#set_remote_address(val = :socket) ⇒ Object
Control how the remote address of the connection is set.
-
#shutdown_debug(val = true) ⇒ Object
When a shutdown is requested, the backtraces of all the threads will be written to $stdout.
-
#silence_fork_callback_warning ⇒ Object
Disable warning message when running single mode with callback hook defined.
-
#silence_single_worker_warning ⇒ Object
Disable warning message when running in cluster mode with a single worker.
-
#ssl_bind(host, port, opts = {}) ⇒ Object
Instead of using
bindand manually constructing a URI like:. -
#state_path(path) ⇒ Object
Use
pathas the file to store the server info state. -
#state_permission(permission) ⇒ Object
Use
permissionto restrict permissions for the state file. -
#stdout_redirect(stdout = nil, stderr = nil, append = false) ⇒ Object
Redirect
STDOUTandSTDERRto files specified. -
#supported_http_methods(methods) ⇒ Object
Supported http methods, which will replace ‘Puma::Const::SUPPORTED_HTTP_METHODS`.
-
#tag(string) ⇒ Object
Additional text to display in process listing.
-
#threads(min, max = min) ⇒ Object
Configure the number of threads to use to answer requests.
-
#wait_for_less_busy_worker(val = 0.005) ⇒ Object
Maximum delay of worker accept loop.
-
#worker_boot_timeout(timeout) ⇒ Object
Change the default worker timeout for booting.
-
#worker_check_interval(interval) ⇒ Object
Change the default interval for checking workers.
-
#worker_culling_strategy(strategy) ⇒ Object
Set the strategy for worker culling.
-
#worker_shutdown_timeout(timeout) ⇒ Object
Set the timeout for worker shutdown.
-
#worker_timeout(timeout) ⇒ Object
Verifies that all workers have checked in to the master process within the given timeout.
-
#workers(count) ⇒ Object
How many worker processes to run.
Constructor Details
#initialize(options, config) ⇒ DSL
Returns a new instance of DSL.
126 127 128 129 130 131 |
# File 'lib/puma/dsl.rb', line 126 def initialize(, config) @config = config = @plugins = [] end |
Class Method Details
.ssl_bind_str(host, port, opts) ⇒ Object
Convenience method so logic can be used in CI.
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/puma/dsl.rb', line 59 def self.ssl_bind_str(host, port, opts) verify = opts.fetch(:verify_mode, 'none').to_s tls_str = if opts[:no_tlsv1_1] then '&no_tlsv1_1=true' elsif opts[:no_tlsv1] then '&no_tlsv1=true' else '' end ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify) low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : '' backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : '' if defined?(JRUBY_VERSION) cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites] protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}" keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type] if opts[:truststore] truststore_additions = "&truststore=#{opts[:truststore]}" truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass] truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type] end "ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \ "&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}" else ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil ssl_ciphersuites = opts[:ssl_ciphersuites] ? "&ssl_ciphersuites=#{opts[:ssl_ciphersuites]}" : nil v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil reuse_flag = if (reuse = opts[:reuse]) if reuse == true '&reuse=dflt' elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout)) val = +'' if (size = reuse[:size]) && Integer === size val << size.to_s end if (timeout = reuse[:timeout]) && Integer === timeout val << ",#{timeout}" end if val.empty? nil else "&reuse=#{val}" end else nil end else nil end "ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}#{ssl_ciphersuites}" \ "#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}" end end |
Instance Method Details
#_load_from(path) ⇒ Object
133 134 135 136 137 138 139 140 |
# File 'lib/puma/dsl.rb', line 133 def _load_from(path) if path @path = path instance_eval(File.read(path), path, 1) end ensure _offer_plugins end |
#_offer_plugins ⇒ Object
142 143 144 145 146 147 148 149 150 151 |
# File 'lib/puma/dsl.rb', line 142 def _offer_plugins @plugins.each do |o| if o.respond_to? :config .shift o.config self end end @plugins.clear end |
#activate_control_app(url = "auto", opts = {}) ⇒ Object
Start the Puma control rack application on url. This application can be communicated with to control the main server. Additionally, you can provide an authentication token, so all requests to the control server will need to include that token as a query parameter. This allows for simple authentication.
Check out App::Status to see what the app has available.
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# File 'lib/puma/dsl.rb', line 220 def activate_control_app(url="auto", opts={}) if url == "auto" path = Configuration.temp_path [:control_url] = "unix://#{path}" [:control_url_temp] = path else [:control_url] = url end if opts[:no_token] # We need to use 'none' rather than :none because this value will be # passed on to an instance of OptionParser, which doesn't support # symbols as option values. # # See: https://github.com/puma/puma/issues/1193#issuecomment-305995488 auth_token = 'none' else auth_token = opts[:auth_token] auth_token ||= Configuration.random_token end [:control_auth_token] = auth_token [:control_url_umask] = opts[:umask] if opts[:umask] end |
#after_booted(&block) ⇒ Object Also known as: on_booted
Code to run after puma is booted (works for both single and cluster modes).
843 844 845 846 847 |
# File 'lib/puma/dsl.rb', line 843 def after_booted(&block) Puma.deprecate_method_change :on_booted, __callee__, __method__ @config.events.after_booted(&block) end |
#after_refork(key = nil, &block) ⇒ Object
Cluster mode with ‘fork_worker` enabled only.
When ‘fork_worker` is enabled, code to run in Worker 0 after all other workers are re-forked from this process, after the server has temporarily stopped serving requests (once per complete refork cycle).
This can be used to re-open any connections to remote servers (database, Redis, …) that were closed via before_refork.
This can be called multiple times to add several hooks.
910 911 912 |
# File 'lib/puma/dsl.rb', line 910 def after_refork(key = nil, &block) process_hook :after_refork, key, block end |
#after_stopped(&block) ⇒ Object Also known as: on_stopped
Code to run after puma is stopped (works for both: single and clustered)
858 859 860 861 862 |
# File 'lib/puma/dsl.rb', line 858 def after_stopped(&block) Puma.deprecate_method_change :on_stopped, __callee__, __method__ @config.events.after_stopped(&block) end |
#after_worker_fork(&block) ⇒ Object Also known as: after_worker_boot
Cluster mode only.
Code to run in the master after a worker has been started. The worker’s index is passed as an argument.
This is called everytime a worker is to be started.
816 817 818 |
# File 'lib/puma/dsl.rb', line 816 def after_worker_fork(&block) process_hook :after_worker_fork, nil, block, cluster_only: true end |
#after_worker_shutdown(&block) ⇒ Object
Cluster mode only.
Code to run in the master right after a worker has stopped. The worker’s index and Process::Status are passed as arguments.
832 833 834 |
# File 'lib/puma/dsl.rb', line 832 def after_worker_shutdown(&block) process_hook :after_worker_shutdown, nil, block, cluster_only: true end |
#app(obj = nil, &block) ⇒ Object
Use an object or block as the rack application. This allows the configuration file to be the application itself.
197 198 199 200 201 202 203 |
# File 'lib/puma/dsl.rb', line 197 def app(obj=nil, &block) obj ||= block raise "Provide either a #call'able or a block" unless obj [:app] = obj end |
#before_fork(&block) ⇒ Object
Cluster mode only.
Code to run immediately before master process forks workers (once on boot). These hooks can block if necessary to wait for background operations unknown to Puma to finish before the process terminates. This can be used to close any connections to remote servers (database, Redis, …) that were opened when preloading the code.
This can be called multiple times to add several hooks.
737 738 739 |
# File 'lib/puma/dsl.rb', line 737 def before_fork(&block) process_hook :before_fork, nil, block, cluster_only: true end |
#before_refork(key = nil, &block) ⇒ Object Also known as: on_refork
Cluster mode with ‘fork_worker` enabled only.
When ‘fork_worker` is enabled, code to run in Worker 0 before all other workers are re-forked from this process, after the server has temporarily stopped serving requests (once per complete refork cycle).
This can be used to trigger extra garbage-collection to maximize copy-on-write efficiency, or close any connections to remote servers (database, Redis, …) that were opened while the server was running.
This can be called multiple times to add several hooks.
885 886 887 888 889 |
# File 'lib/puma/dsl.rb', line 885 def before_refork(key = nil, &block) Puma.deprecate_method_change :on_refork, __callee__, __method__ process_hook :before_refork, key, block, cluster_only: true end |
#before_restart(&block) ⇒ Object Also known as: on_restart
Code to run before doing a restart. This code should close log files, database connections, etc.
This can be called multiple times to add code each time.
444 445 446 447 448 |
# File 'lib/puma/dsl.rb', line 444 def before_restart(&block) Puma.deprecate_method_change :on_restart, __callee__, __method__ process_hook :before_restart, nil, block end |
#before_thread_exit(&block) ⇒ Object Also known as: on_thread_exit
Provide a block to be executed after a thread is trimmed from the thread pool. Be careful: while this block executes, Puma’s main loop is blocked, so no new requests will be picked up.
This hook only runs when a thread in the threadpool is trimmed by Puma. It does not run when a thread dies due to exceptions or any other cause.
Return values are ignored. Raising an exception will log a warning.
This hook is useful for cleaning up thread local resources when a thread is trimmed.
This can be called multiple times to add several hooks.
959 960 961 962 963 |
# File 'lib/puma/dsl.rb', line 959 def before_thread_exit(&block) Puma.deprecate_method_change :on_thread_exit, __callee__, __method__ process_hook :before_thread_exit, nil, block end |
#before_thread_start(&block) ⇒ Object Also known as: on_thread_start
Provide a block to be executed just before a thread is added to the thread pool. Be careful: while the block executes, thread creation is delayed, and probably a request will have to wait too! The new thread will not be added to the threadpool until the provided block returns.
Return values are ignored. Raising an exception will log a warning.
This hook is useful for doing something when the thread pool grows.
This can be called multiple times to add several hooks.
931 932 933 934 935 |
# File 'lib/puma/dsl.rb', line 931 def before_thread_start(&block) Puma.deprecate_method_change :on_thread_start, __callee__, __method__ process_hook :before_thread_start, nil, block end |
#before_worker_boot(key = nil, &block) ⇒ Object Also known as: on_worker_boot
Cluster mode only.
Code to run in a worker when it boots to setup the process before booting the app.
This can be called multiple times to add several hooks.
753 754 755 756 757 |
# File 'lib/puma/dsl.rb', line 753 def before_worker_boot(key = nil, &block) Puma.deprecate_method_change :on_worker_boot, __callee__, __method__ process_hook :before_worker_boot, key, block, cluster_only: true end |
#before_worker_fork(&block) ⇒ Object Also known as: on_worker_fork
Cluster mode only.
Code to run in the master right before a worker is started. The worker’s index is passed as an argument.
This can be called multiple times to add several hooks.
796 797 798 799 800 |
# File 'lib/puma/dsl.rb', line 796 def before_worker_fork(&block) Puma.deprecate_method_change :on_worker_fork, __callee__, __method__ process_hook :before_worker_fork, nil, block, cluster_only: true end |
#before_worker_shutdown(key = nil, &block) ⇒ Object Also known as: on_worker_shutdown
Cluster mode only.
Code to run immediately before a worker shuts down (after it has finished processing HTTP requests). The worker’s index is passed as an argument. These hooks can block if necessary to wait for background operations unknown to Puma to finish before the process terminates.
This can be called multiple times to add several hooks.
776 777 778 779 780 |
# File 'lib/puma/dsl.rb', line 776 def before_worker_shutdown(key = nil, &block) Puma.deprecate_method_change :on_worker_shutdown, __callee__, __method__ process_hook :before_worker_shutdown, key, block, cluster_only: true end |
#bind(url) ⇒ Object
Bind the server to url. “tcp://”, “unix://” and “ssl://” are the only accepted protocols. Multiple urls can be bound to, calling bind does not overwrite previous bindings.
The default is “tcp://0.0.0.0:9292”.
You can use query parameters within the url to specify options:
-
Set the socket backlog depth with
backlog, default is 1024. -
Set up an SSL certificate with
key&cert. -
Set up an SSL certificate for mTLS with
key,cert,caandverify_mode. -
Set whether to optimize for low latency instead of throughput with
low_latency, default is to not optimize for low latency. This is done viaSocket::TCP_NODELAY. -
Set socket permissions with
umask.
286 287 288 289 |
# File 'lib/puma/dsl.rb', line 286 def bind(url) [:binds] ||= [] [:binds] << url end |
#bind_to_activated_sockets(bind = true) ⇒ Object
Bind to (systemd) activated sockets, regardless of configured binds.
Systemd can present sockets as file descriptors that are already opened. By default Puma will use these but only if it was explicitly told to bind to the socket. If not, it will close the activated sockets. This means all configuration is duplicated.
Binds can contain additional configuration, but only SSL config is really relevant since the unix and TCP socket options are ignored.
This means there is a lot of duplicated configuration for no additional value in most setups. This method tells the launcher to bind to all activated sockets, regardless of existing bind.
To clear configured binds, the value only can be passed. This will clear out any binds that may have been configured.
318 319 320 |
# File 'lib/puma/dsl.rb', line 318 def bind_to_activated_sockets(bind=true) [:bind_to_activated_sockets] = bind end |
#clear_binds! ⇒ Object
291 292 293 |
# File 'lib/puma/dsl.rb', line 291 def clear_binds! [:binds] = [] end |
#custom_logger(custom_logger) ⇒ Object
Pass in a custom logging class instance
499 500 501 |
# File 'lib/puma/dsl.rb', line 499 def custom_logger(custom_logger) [:custom_logger] = custom_logger end |
#debug ⇒ Object
Show debugging info
The default is false.
510 511 512 |
# File 'lib/puma/dsl.rb', line 510 def debug [:debug] = true end |
#default_host ⇒ Object
157 158 159 |
# File 'lib/puma/dsl.rb', line 157 def default_host [:default_host] || Configuration::DEFAULTS[:tcp_host] end |
#directory(dir) ⇒ Object
The directory to operate out of.
The default is the current directory.
988 989 990 |
# File 'lib/puma/dsl.rb', line 988 def directory(dir) [:directory] = dir.to_s end |
#drain_on_shutdown(which = true) ⇒ Object
When shutting down, drain the accept socket of pending connections and process them. This loops over the accept socket until there are no more read events and then stops looking and waits for the requests to finish.
394 395 396 |
# File 'lib/puma/dsl.rb', line 394 def drain_on_shutdown(which=true) [:drain_on_shutdown] = which end |
#early_hints(answer = true) ⇒ Object
Enable HTTP 103 Early Hints responses.
The default is nil.
540 541 542 |
# File 'lib/puma/dsl.rb', line 540 def early_hints(answer=true) [:early_hints] = answer end |
#enable_keep_alives(enabled = true) ⇒ Object
When ‘true`, keep-alive connections are maintained on inbound requests. Enabling this setting reduces the number of TCP operations, reducing response times for connections that can send multiple requests in a single connection.
When Puma receives more incoming connections than available Puma threads, enabling the keep-alive behavior may result in processing requests out-of-order, increasing overall response time variance. Increased response time variance means that the overall average of response times might not change, but more outliers will exist. Those long-tail outliers may significantly affect response times for some processed requests.
When ‘false`, Puma closes the connection after each request, requiring the client to open a new request. Disabling this setting guarantees that requests will be processed in the order they are fully received, decreasing response variance and eliminating long-tail outliers caused by keep-alive behavior. The trade-off is that the number of TCP operations required will increase.
The default is true.
1364 1365 1366 |
# File 'lib/puma/dsl.rb', line 1364 def enable_keep_alives(enabled=true) [:enable_keep_alives] = enabled end |
#environment(environment) ⇒ Object
Set the environment in which the rack’s app will run. The value must be a string.
The default is “development”.
406 407 408 |
# File 'lib/puma/dsl.rb', line 406 def environment(environment) [:environment] = environment end |
#extra_runtime_dependencies(answer = []) ⇒ Object
When using prune_bundler, if extra runtime dependencies need to be loaded to initialize your app, then this setting can be used. This includes any Puma plugins.
Before bundler is pruned, the gem names supplied will be looked up in the bundler context and then loaded again after bundler is pruned. Only applies if prune_bundler is used.
1074 1075 1076 |
# File 'lib/puma/dsl.rb', line 1074 def extra_runtime_dependencies(answer = []) [:extra_runtime_dependencies] = Array(answer) end |
#fiber_per_request(which = true) ⇒ Object Also known as: clean_thread_locals
Use a clean fiber per request which ensures a clean slate for fiber locals and fiber storage. Also provides a cleaner backtrace with less Puma internal stack frames.
The default is false.
382 383 384 |
# File 'lib/puma/dsl.rb', line 382 def fiber_per_request(which=true) [:fiber_per_request] = which end |
#first_data_timeout(seconds) ⇒ Object
Define how long the tcp socket stays open, if no data has been received.
The default is 30 seconds.
343 344 345 |
# File 'lib/puma/dsl.rb', line 343 def first_data_timeout(seconds) [:first_data_timeout] = Integer(seconds) end |
#force_shutdown_after(val = :forever) ⇒ Object
How long to wait for threads to stop when shutting them down. Specifying :immediately will cause Puma to kill the threads immediately. Otherwise the value is the number of seconds to wait.
Puma always waits a few seconds after killing a thread for it to try to finish up it’s work, even in :immediately mode.
The default is :forever.
421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/puma/dsl.rb', line 421 def force_shutdown_after(val=:forever) i = case val when :forever -1 when :immediately 0 else Float(val) end [:force_shutdown_after] = i end |
#fork_worker(after_requests = 1000) ⇒ Object
This is experimental.
Cluster mode only.
When enabled, workers will be forked from worker 0 instead of from the master process. This option is similar to ‘preload_app` because the app is preloaded before forking, but it is compatible with phased restart.
This option also enables the ‘refork` command (SIGURG), which optimizes copy-on-write performance in a running app.
A refork will automatically trigger once after the specified number of requests (default 1000), or pass 0 to disable auto refork.
1318 1319 1320 |
# File 'lib/puma/dsl.rb', line 1318 def fork_worker(after_requests=1000) [:fork_worker] = Integer(after_requests) end |
#get(key, default = nil) ⇒ Object
165 166 167 |
# File 'lib/puma/dsl.rb', line 165 def get(key,default=nil) [key.to_sym] || default end |
#http_content_length_limit(limit) ⇒ Object
Specify how big the request payload should be, in bytes. This limit is compared against Content-Length HTTP header. If the payload size (CONTENT_LENGTH) is larger than http_content_length_limit, HTTP 413 status code is returned.
When no Content-Length http header is present, it is compared against the size of the body of the request.
The default is nil.
1412 1413 1414 |
# File 'lib/puma/dsl.rb', line 1412 def http_content_length_limit(limit) [:http_content_length_limit] = limit end |
#idle_timeout(seconds) ⇒ Object
If a new request is not received within this number of seconds, begin shutting down.
The default is nil.
369 370 371 |
# File 'lib/puma/dsl.rb', line 369 def idle_timeout(seconds) [:idle_timeout] = Integer(seconds) end |
#inject(&blk) ⇒ Object
161 162 163 |
# File 'lib/puma/dsl.rb', line 161 def inject(&blk) instance_eval(&blk) end |
#io_selector_backend(backend) ⇒ Object
Specify the backend for the IO selector.
Provided values will be passed directly to NIO::Selector.new, with the exception of :auto which will let nio4r choose the backend.
Check the documentation of NIO::Selector.backends for the list of valid options. Note that the available options on your system will depend on the operating system. If you want to use the pure Ruby backend (not recommended due to its comparatively low performance), set environment variable NIO4R_PURE to true.
The default is :auto.
1383 1384 1385 |
# File 'lib/puma/dsl.rb', line 1383 def io_selector_backend(backend) [:io_selector_backend] = backend.to_sym end |
#load(file) ⇒ Object
Load additional configuration from a file. Files get loaded later via Configuration#load.
251 252 253 254 |
# File 'lib/puma/dsl.rb', line 251 def load(file) [:config_files] ||= [] [:config_files] << file end |
#log_formatter(&block) ⇒ Object
560 561 562 |
# File 'lib/puma/dsl.rb', line 560 def log_formatter(&block) [:log_formatter] = block end |
#log_requests(which = true) ⇒ Object
Enable request logging, the inverse of ‘quiet`.
The default is false.
490 491 492 |
# File 'lib/puma/dsl.rb', line 490 def log_requests(which=true) [:log_requests] = which end |
#lowlevel_error_handler(obj = nil, &block) ⇒ Object
Use obj or block as the low level error handler. This allows the configuration file to change the default error on the server.
1014 1015 1016 1017 1018 |
# File 'lib/puma/dsl.rb', line 1014 def lowlevel_error_handler(obj=nil, &block) obj ||= block raise "Provide either a #call'able or a block" unless obj [:lowlevel_error_handler] = obj end |
#max_fast_inline(num_of_requests) ⇒ Object
Use #max_keep_alive instead.
1324 1325 1326 1327 |
# File 'lib/puma/dsl.rb', line 1324 def max_fast_inline(num_of_requests) Puma.deprecate_method_change :max_fast_inline, __method__, :max_keep_alive [:max_keep_alive] ||= Float(num_of_requests) unless num_of_requests.nil? end |
#max_keep_alive(num_of_requests) ⇒ Object
The number of requests a keep-alive client can submit before being closed. Note that some applications (server to server) may benefit from a very high number or Float::INFINITY.
The default is 999.
1338 1339 1340 |
# File 'lib/puma/dsl.rb', line 1338 def max_keep_alive(num_of_requests) [:max_keep_alive] = Float(num_of_requests) unless num_of_requests.nil? end |
#mutate_stdout_and_stderr_to_sync_on_write(enabled = true) ⇒ Object
Ensures STDOUT and STDERR is immediately flushed to the underlying operating system and is not buffered internally
The default is true.
1395 1396 1397 |
# File 'lib/puma/dsl.rb', line 1395 def mutate_stdout_and_stderr_to_sync_on_write(enabled=true) [:mutate_stdout_and_stderr_to_sync_on_write] = enabled end |
#out_of_band(&block) ⇒ Object
Code to run out-of-band when the worker is idle. These hooks run immediately after a request has finished processing and there are no busy threads on the worker. The worker doesn’t accept new requests until this code finishes.
This hook is useful for running out-of-band garbage collection or scheduling asynchronous tasks to execute after a response.
This can be called multiple times to add several hooks.
977 978 979 |
# File 'lib/puma/dsl.rb', line 977 def out_of_band(&block) process_hook :out_of_band, nil, block end |
#persistent_timeout(seconds) ⇒ Object
Define how long persistent connections can be idle before Puma closes them.
The default is 20 seconds.
356 357 358 |
# File 'lib/puma/dsl.rb', line 356 def persistent_timeout(seconds) [:persistent_timeout] = Integer(seconds) end |
#pidfile(path) ⇒ Object
Store the pid of the server in the file at “path”.
468 469 470 |
# File 'lib/puma/dsl.rb', line 468 def pidfile(path) [:pidfile] = path.to_s end |
#plugin(name) ⇒ Object
Load the named plugin for use by this configuration.
174 175 176 |
# File 'lib/puma/dsl.rb', line 174 def plugin(name) @plugins << @config.load_plugin(name) end |
#port(port, host = nil) ⇒ Object
Define the TCP port to bind to. Use ‘bind` for more advanced options.
The default is 9292.
329 330 331 332 |
# File 'lib/puma/dsl.rb', line 329 def port(port, host=nil) host ||= default_host bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s end |
#preload_app!(answer = true) ⇒ Object
Cluster mode only.
Preload the application before forking the workers; this conflicts with the phased restart feature.
The default is true if your app uses more than 1 worker.
1002 1003 1004 |
# File 'lib/puma/dsl.rb', line 1002 def preload_app!(answer=true) [:preload_app] = answer end |
#prune_bundler(answer = true) ⇒ Object
This is incompatible with preload_app!.
This is only supported for RubyGems 2.2+
This option is used to allow your app and its gems to be properly reloaded when not using preload.
When set, if Puma detects that it’s been invoked in the context of Bundler, it will cleanup the environment and re-run itself outside the Bundler environment, but directly using the files that Bundler has setup.
This means that Puma is now decoupled from your Bundler context and when each worker loads, it will be loading a new Bundler context and thus can float around as the release dictates.
1038 1039 1040 |
# File 'lib/puma/dsl.rb', line 1038 def prune_bundler(answer=true) [:prune_bundler] = answer end |
#queue_requests(answer = true) ⇒ Object
When set to true, workers accept all requests and queue them before passing them to the handlers. When set to false, each worker process accepts exactly as many requests as it is configured to simultaneously handle.
Queueing requests generally improves performance. In some cases, such as a single threaded application, it may be better to ensure requests get balanced across workers.
Note that setting this to false disables HTTP keepalive and slow clients will occupy a handler thread while the request is being sent. A reverse proxy, such as nginx, can handle slow clients and queue requests before they reach Puma.
The default is true.
1212 1213 1214 |
# File 'lib/puma/dsl.rb', line 1212 def queue_requests(answer=true) [:queue_requests] = answer end |
#quiet(which = true) ⇒ Object
Disable request logging, the inverse of ‘log_requests`.
The default is true.
479 480 481 |
# File 'lib/puma/dsl.rb', line 479 def quiet(which=true) [:log_requests] = !which end |
#rack_url_scheme(scheme = nil) ⇒ Object
Allows setting ‘env`. Only necessary if X-Forwarded-Proto is not being set by your proxy Normal values are ’http’ or ‘https’.
529 530 531 |
# File 'lib/puma/dsl.rb', line 529 def rack_url_scheme(scheme=nil) [:rack_url_scheme] = scheme end |
#rackup(path) ⇒ Object
Load path as a rackup file.
The default is “config.ru”.
521 522 523 |
# File 'lib/puma/dsl.rb', line 521 def rackup(path) [:rackup] ||= path.to_s end |
#raise_exception_on_sigterm(answer = true) ⇒ Object
Raises a SignalException when SIGTERM is received. In environments where SIGTERM is something expected, you can suppress these with this option.
This can be useful for example in Kubernetes, where rolling restart is guaranteed usually on the infrastructure level.
The default is true.
1056 1057 1058 |
# File 'lib/puma/dsl.rb', line 1056 def raise_exception_on_sigterm(answer=true) [:raise_exception_on_sigterm] = answer end |
#restart_command(cmd) ⇒ Object
Command to use to restart Puma. This should be just how to load Puma itself (ie. ‘ruby -Ilib bin/puma’), not the arguments to Puma, as those are the same as the original process.
459 460 461 |
# File 'lib/puma/dsl.rb', line 459 def restart_command(cmd) [:restart_cmd] = cmd.to_s end |
#set_default_host(host) ⇒ Object
153 154 155 |
# File 'lib/puma/dsl.rb', line 153 def set_default_host(host) [:default_host] = host end |
#set_remote_address(val = :socket) ⇒ Object
Control how the remote address of the connection is set. This is configurable because to calculate the true socket peer address a kernel syscall is required which for very fast rack handlers slows down the handling significantly.
There are 5 possible values:
-
:socket - read the peername from the socket using the syscall. This is the normal behavior. If this fails for any reason (e.g., if the peer disconnects between the connection being accepted and the getpeername system call), Puma will return “0.0.0.0”
-
:localhost - set the remote address to “127.0.0.1”
-
**header: <http_header>**- set the remote address to the value of the provided http header. For instance: ‘set_remote_address header: “X-Real-IP”`. Only the first word (as separated by spaces or comma) is used, allowing headers such as X-Forwarded-For to be used as well. If this header is absent, Puma will fall back to the behavior of :socket
-
**proxy_protocol: :v1**- set the remote address to the value read from the HAproxy PROXY protocol, version 1. If the request does not have the PROXY protocol attached to it, will fall back to :socket
-
**<Any string>** - this allows you to hardcode remote address to any value you wish. Because Puma never uses this field anyway, it’s format is entirely in your hands.
The default is :socket.
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 |
# File 'lib/puma/dsl.rb', line 1276 def set_remote_address(val=:socket) case val when :socket [:remote_address] = val when :localhost [:remote_address] = :value [:remote_address_value] = "127.0.0.1".freeze when String [:remote_address] = :value [:remote_address_value] = val when Hash if hdr = val[:header] [:remote_address] = :header [:remote_address_header] = "HTTP_" + hdr.upcase.tr("-", "_") elsif protocol_version = val[:proxy_protocol] [:remote_address] = :proxy_protocol protocol_version = protocol_version.downcase.to_sym unless [:v1].include?(protocol_version) raise "Invalid value for proxy_protocol - #{protocol_version.inspect}" end [:remote_address_proxy_protocol] = protocol_version else raise "Invalid value for set_remote_address - #{val.inspect}" end else raise "Invalid value for set_remote_address - #{val}" end end |
#shutdown_debug(val = true) ⇒ Object
When a shutdown is requested, the backtraces of all the threads will be written to $stdout. This can help figure out why shutdown is hanging.
1220 1221 1222 |
# File 'lib/puma/dsl.rb', line 1220 def shutdown_debug(val=true) [:shutdown_debug] = val end |
#silence_fork_callback_warning ⇒ Object
Disable warning message when running single mode with callback hook defined.
The default is false.
717 718 719 |
# File 'lib/puma/dsl.rb', line 717 def silence_fork_callback_warning [:silence_fork_callback_warning] = true end |
#silence_single_worker_warning ⇒ Object
Cluster mode only.
Disable warning message when running in cluster mode with a single worker.
Cluster mode has some overhead of running an additional ‘control’ process in order to manage the cluster. If only running a single worker it is likely not worth paying that overhead vs running in single mode with additional threads instead.
There are some scenarios where running cluster mode with a single worker may still be warranted and valid under certain deployment scenarios, see github.com/puma/puma/issues/2534
Moving from workers = 1 to workers = 0 will save 10-30% of memory use.
The default is false.
706 707 708 |
# File 'lib/puma/dsl.rb', line 706 def silence_single_worker_warning [:silence_single_worker_warning] = true end |
#ssl_bind(host, port, opts = {}) ⇒ Object
Instead of using bind and manually constructing a URI like:
bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path'
you can use the this method.
When binding on localhost you don’t need to specify cert and key, Puma will assume you are using the localhost gem and try to load the appropriate files.
When using the options hash parameter, the ‘reuse:` value is either `true`, which sets reuse ’on’ with default values, or a hash, with ‘:size` and/or `:timeout` keys, each with integer values.
The ‘cert:` options hash parameter can be the path to a certificate file including all intermediate certificates in PEM format.
The ‘cert_pem:` options hash parameter can be String containing the cerificate and all intermediate certificates in PEM format.
644 645 646 647 |
# File 'lib/puma/dsl.rb', line 644 def ssl_bind(host, port, opts = {}) (opts) bind self.class.ssl_bind_str(host, port, opts) end |
#state_path(path) ⇒ Object
Use path as the file to store the server info state. This is used by pumactl to query and control the server.
655 656 657 |
# File 'lib/puma/dsl.rb', line 655 def state_path(path) [:state] = path.to_s end |
#state_permission(permission) ⇒ Object
Use permission to restrict permissions for the state file. By convention, permission is an octal number (e.g. ‘0640` or `0o640`).
665 666 667 |
# File 'lib/puma/dsl.rb', line 665 def () [:state_permission] = end |
#stdout_redirect(stdout = nil, stderr = nil, append = false) ⇒ Object
Redirect STDOUT and STDERR to files specified. The append parameter specifies whether the output is appended.
The default is false.
554 555 556 557 558 |
# File 'lib/puma/dsl.rb', line 554 def stdout_redirect(stdout=nil, stderr=nil, append=false) [:redirect_stdout] = stdout [:redirect_stderr] = stderr [:redirect_append] = append end |
#supported_http_methods(methods) ⇒ Object
If the ‘methods` value is `:any`, no method check with be performed, similar to Puma v5 and earlier.
Supported http methods, which will replace ‘Puma::Const::SUPPORTED_HTTP_METHODS`. The value of `:any` will allows all methods, otherwise, the value must be an array of strings. Note that methods are all uppercase.
‘Puma::Const::SUPPORTED_HTTP_METHODS` is conservative, if you want a complete set of methods, the methods defined by the [IANA Method Registry](www.iana.org/assignments/http-methods/http-methods.xhtml) are pre-defined as the constant `Puma::Const::IANA_HTTP_METHODS`.
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 |
# File 'lib/puma/dsl.rb', line 1437 def supported_http_methods(methods) if methods == :any [:supported_http_methods] = :any elsif Array === methods && methods == (ary = methods.grep(String).uniq) && !ary.empty? [:supported_http_methods] = ary else raise "supported_http_methods must be ':any' or a unique array of strings" end end |
#tag(string) ⇒ Object
Additional text to display in process listing.
If you do not specify a tag, Puma will infer it. If you do not want Puma to add a tag, use an empty string.
The default is the current file or directory base name.
1090 1091 1092 |
# File 'lib/puma/dsl.rb', line 1090 def tag(string) [:tag] = string.to_s end |
#threads(min, max = min) ⇒ Object
Configure the number of threads to use to answer requests.
It can be a single fixed number, or a min and a max.
The default is the environment variables PUMA_MIN_THREADS / PUMA_MAX_THREADS (or MIN_THREADS / MAX_THREADS if the PUMA_ variables aren’t set).
If these environment variables aren’t set, the default is “0, 5” in MRI or “0, 16” for other interpreters.
580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
# File 'lib/puma/dsl.rb', line 580 def threads(min, max = min) min = Integer(min) max = Integer(max) if min > max raise "The minimum (#{min}) number of threads must be less than or equal to the max (#{max})" end if max < 1 raise "The maximum number of threads (#{max}) must be greater than 0" end [:min_threads] = min [:max_threads] = max end |
#wait_for_less_busy_worker(val = 0.005) ⇒ Object
Cluster mode with >= 2 workers only.
Interpreters with forking support only.
Maximum delay of worker accept loop.
Attempts to route traffic to less-busy workers by causing a busy worker to delay listening on the socket, allowing workers which are not processing as many requests to pick up new requests first.
The default is 0.005 seconds.
To turn off this feature, set the value to 0.
1242 1243 1244 |
# File 'lib/puma/dsl.rb', line 1242 def wait_for_less_busy_worker(val=0.005) [:wait_for_less_busy_worker] = val.to_f end |
#worker_boot_timeout(timeout) ⇒ Object
Cluster mode only.
Change the default worker timeout for booting.
The default is the value of ‘worker_timeout`.
1147 1148 1149 |
# File 'lib/puma/dsl.rb', line 1147 def worker_boot_timeout(timeout) [:worker_boot_timeout] = Integer(timeout) end |
#worker_check_interval(interval) ⇒ Object
Cluster mode only.
Change the default interval for checking workers.
The default is 5 seconds.
1105 1106 1107 |
# File 'lib/puma/dsl.rb', line 1105 def worker_check_interval(interval) [:worker_check_interval] = Integer(interval) end |
#worker_culling_strategy(strategy) ⇒ Object
Cluster mode only.
Set the strategy for worker culling.
There are two possible values:
-
:youngest - the youngest workers (i.e. the workers that were the most recently started) will be culled.
-
:oldest - the oldest workers (i.e. the workers that were started the longest time ago) will be culled.
The default is :youngest.
1184 1185 1186 1187 1188 1189 1190 1191 1192 |
# File 'lib/puma/dsl.rb', line 1184 def worker_culling_strategy(strategy) strategy = strategy.to_sym if ![:youngest, :oldest].include?(strategy) raise "Invalid value for worker_culling_strategy - #{strategy}" end [:worker_culling_strategy] = strategy end |
#worker_shutdown_timeout(timeout) ⇒ Object
Cluster mode only.
Set the timeout for worker shutdown.
The default is 30 seconds.
1162 1163 1164 |
# File 'lib/puma/dsl.rb', line 1162 def worker_shutdown_timeout(timeout) [:worker_shutdown_timeout] = Integer(timeout) end |
#worker_timeout(timeout) ⇒ Object
Cluster mode only.
Verifies that all workers have checked in to the master process within the given timeout. If not the worker process will be restarted. This is not a request timeout, it is to protect against a hung or dead process. Setting this value will not protect against slow requests.
This value must be greater than worker_check_interval.
The default is 60 seconds.
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 |
# File 'lib/puma/dsl.rb', line 1125 def worker_timeout(timeout) timeout = Integer(timeout) min = .fetch(:worker_check_interval, Configuration::DEFAULTS[:worker_check_interval]) if timeout <= min raise "The minimum worker_timeout must be greater than the worker reporting interval (#{min})" end [:worker_timeout] = timeout end |
#workers(count) ⇒ Object
Cluster mode only.
How many worker processes to run. Typically this is set to the number of available cores.
The default is the value of the environment variable WEB_CONCURRENCY if set, otherwise 0.
682 683 684 |
# File 'lib/puma/dsl.rb', line 682 def workers(count) [:workers] = count.to_i end |