puma 8.0.2 → 8.1.2

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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +154 -0
  3. data/README.md +28 -378
  4. data/docs/binding.md +135 -0
  5. data/docs/cluster_mode.md +241 -0
  6. data/docs/configuration.md +78 -0
  7. data/docs/{stats.md → control_server.md} +28 -8
  8. data/docs/{deployment.md → deployment/README.md} +23 -7
  9. data/docs/{kubernetes.md → deployment/kubernetes.md} +4 -4
  10. data/docs/{systemd.md → deployment/systemd.md} +4 -2
  11. data/docs/plugins.md +62 -3
  12. data/docs/puma_support.md +92 -0
  13. data/docs/rails_dev_mode.md +2 -2
  14. data/docs/restart.md +8 -3
  15. data/docs/signals.md +4 -2
  16. data/docs/{5.0-Upgrade.md → upgrading/5.0-Upgrade.md} +3 -3
  17. data/docs/{6.0-Upgrade.md → upgrading/6.0-Upgrade.md} +3 -3
  18. data/docs/{7.0-Upgrade.md → upgrading/7.0-Upgrade.md} +2 -2
  19. data/docs/{8.0-Upgrade.md → upgrading/8.0-Upgrade.md} +4 -4
  20. data/ext/puma_http11/extconf.rb +2 -0
  21. data/ext/puma_http11/http11_parser.c +6 -2
  22. data/ext/puma_http11/mini_ssl.c +18 -7
  23. data/ext/puma_http11/puma_http11.c +28 -3
  24. data/lib/puma/binder.rb +29 -0
  25. data/lib/puma/cli.rb +6 -0
  26. data/lib/puma/client.rb +178 -44
  27. data/lib/puma/client_env.rb +32 -18
  28. data/lib/puma/cluster/worker.rb +109 -33
  29. data/lib/puma/cluster/worker_handle.rb +16 -0
  30. data/lib/puma/cluster.rb +173 -45
  31. data/lib/puma/commonlogger.rb +3 -3
  32. data/lib/puma/configuration.rb +23 -3
  33. data/lib/puma/const.rb +14 -9
  34. data/lib/puma/control_cli.rb +14 -3
  35. data/lib/puma/dsl.rb +279 -92
  36. data/lib/puma/launcher.rb +6 -4
  37. data/lib/puma/minissl.rb +98 -56
  38. data/lib/puma/plugin/systemd.rb +1 -1
  39. data/lib/puma/reactor.rb +35 -3
  40. data/lib/puma/response.rb +28 -6
  41. data/lib/puma/runner.rb +5 -1
  42. data/lib/puma/sd_notify.rb +4 -1
  43. data/lib/puma/server.rb +131 -35
  44. data/lib/puma/thread_pool.rb +12 -1
  45. data/lib/puma/util.rb +8 -4
  46. data/lib/puma.rb +1 -1
  47. metadata +19 -31
  48. data/docs/fork_worker.md +0 -41
  49. data/docs/grpc.md +0 -62
  50. data/docs/jungle/README.md +0 -9
  51. data/docs/testing_benchmarks_local_files.md +0 -150
  52. data/docs/testing_test_rackup_ci_files.md +0 -36
  53. data/ext/puma_http11/PumaHttp11Service.java +0 -17
  54. data/ext/puma_http11/http11_parser.java.rl +0 -131
  55. data/ext/puma_http11/http11_parser.rl +0 -149
  56. data/ext/puma_http11/http11_parser_common.rl +0 -54
  57. data/ext/puma_http11/no_ssl/PumaHttp11Service.java +0 -15
  58. data/ext/puma_http11/org/jruby/puma/EnvKey.java +0 -241
  59. data/ext/puma_http11/org/jruby/puma/Http11.java +0 -321
  60. data/ext/puma_http11/org/jruby/puma/Http11Parser.java +0 -441
  61. data/ext/puma_http11/org/jruby/puma/MiniSSL.java +0 -509
  62. data/tools/Dockerfile +0 -26
  63. data/tools/trickletest.rb +0 -44
  64. /data/docs/{nginx.md → deployment/nginx.md} +0 -0
  65. /data/docs/{jungle → deployment}/rc.d/README.md +0 -0
  66. /data/docs/{jungle → deployment}/rc.d/puma +0 -0
  67. /data/docs/{jungle → deployment}/rc.d/puma.conf +0 -0
data/docs/binding.md ADDED
@@ -0,0 +1,135 @@
1
+ # Binding TCP / Sockets
2
+
3
+ Bind Puma to a socket with the `-b` (or `--bind`) flag:
4
+
5
+ ```
6
+ $ puma -b tcp://127.0.0.1:9292
7
+ ```
8
+
9
+ When using a TCP socket on Linux, Puma will automatically skip requests whose connection has closed by the time it's taken from the queue. If you'd like to avoid wasting time on connections that are closing after your app starts handling them, you can call `env["puma.connection_closed?"]` at any time during the lifecycle of a request. A `false` result does not guarantee that the connection will remain open. Puma cannot check this for you during a request: it is waiting for your app to return a response.
10
+
11
+ To use a UNIX Socket instead of TCP:
12
+
13
+ ```
14
+ $ puma -b unix:///var/run/puma.sock
15
+ ```
16
+
17
+ If you need to change the permissions of the UNIX socket, just add a umask parameter:
18
+
19
+ ```
20
+ $ puma -b 'unix:///var/run/puma.sock?umask=0111'
21
+ ```
22
+
23
+ Need a bit of security? Use SSL sockets:
24
+
25
+ ```
26
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert'
27
+ ```
28
+ ## Self-signed SSL certificates (via the [`localhost`] gem, for development use):
29
+
30
+ Puma supports the [`localhost`] gem for self-signed certificates. This is particularly useful if you want to use Puma with SSL locally, and self-signed certificates will work for your use-case. Currently, the integration can only be used in MRI.
31
+
32
+ Puma automatically configures SSL when the [`localhost`] gem is loaded in a `development` environment:
33
+
34
+ Add the gem to your Gemfile:
35
+ ```ruby
36
+ group(:development) do
37
+ gem 'localhost'
38
+ end
39
+ ```
40
+
41
+ And require it implicitly using bundler:
42
+ ```ruby
43
+ require "bundler"
44
+ Bundler.require(:default, ENV["RACK_ENV"].to_sym)
45
+ ```
46
+
47
+ Alternatively, you can require the gem in your configuration file, either `config/puma/development.rb`, `config/puma.rb`, or set via the `-C` cli option:
48
+ ```ruby
49
+ require 'localhost'
50
+ # configuration methods (from Puma::DSL) as needed
51
+ ```
52
+
53
+ Additionally, Puma must be listening to an SSL socket:
54
+
55
+ ```shell
56
+ $ puma -b 'ssl://localhost:9292' -C config/use_local_host.rb
57
+
58
+ # The following options allow you to reach Puma over HTTP as well:
59
+ $ puma -b ssl://localhost:9292 -b tcp://localhost:9393 -C config/use_local_host.rb
60
+ ```
61
+
62
+ [`localhost`]: https://github.com/socketry/localhost
63
+
64
+ ## Controlling SSL Cipher Suites
65
+
66
+ To use or avoid specific SSL ciphers for TLSv1.2 and below, use `ssl_cipher_filter` or `ssl_cipher_list` options.
67
+
68
+ ### Ruby:
69
+
70
+ ```
71
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert&ssl_cipher_filter=!aNULL:AES+SHA'
72
+ ```
73
+
74
+ ### JRuby:
75
+
76
+ ```
77
+ $ puma -b 'ssl://127.0.0.1:9292?keystore=path_to_keystore&keystore-pass=keystore_password&ssl_cipher_list=TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA'
78
+ ```
79
+
80
+ To configure the available TLSv1.3 ciphersuites, use `ssl_ciphersuites` option (not available for JRuby).
81
+
82
+ ### Ruby:
83
+
84
+ ```
85
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert&ssl_ciphersuites=TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256'
86
+ ```
87
+
88
+ See https://www.openssl.org/docs/man1.1.1/man1/ciphers.html for cipher filter format and full list of cipher suites.
89
+
90
+ Disable TLS v1 with the `no_tlsv1` option:
91
+
92
+ ```
93
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert&no_tlsv1=true'
94
+ ```
95
+
96
+ ## Controlling OpenSSL Verification Flags
97
+
98
+ To enable verification flags offered by OpenSSL, use `verification_flags` (not available for JRuby):
99
+
100
+ ```
101
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert&verification_flags=PARTIAL_CHAIN'
102
+ ```
103
+
104
+ You can also set multiple verification flags (by separating them with a comma):
105
+
106
+ ```
107
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert&verification_flags=PARTIAL_CHAIN,CRL_CHECK'
108
+ ```
109
+
110
+ List of available flags: `USE_CHECK_TIME`, `CRL_CHECK`, `CRL_CHECK_ALL`, `IGNORE_CRITICAL`, `X509_STRICT`, `ALLOW_PROXY_CERTS`, `POLICY_CHECK`, `EXPLICIT_POLICY`, `INHIBIT_ANY`, `INHIBIT_MAP`, `NOTIFY_POLICY`, `EXTENDED_CRL_SUPPORT`, `USE_DELTAS`, `CHECK_SS_SIGNATURE`, `TRUSTED_FIRST`, `SUITEB_128_LOS_ONLY`, `SUITEB_192_LOS`, `SUITEB_128_LOS`, `PARTIAL_CHAIN`, `NO_ALT_CHAINS`, `NO_CHECK_TIME`
111
+ (see https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_hostflags.html#VERIFICATION-FLAGS).
112
+
113
+ ## Controlling OpenSSL Password Decryption
114
+
115
+ To enable runtime decryption of an encrypted SSL key (not available for JRuby), use `key_password_command`:
116
+
117
+ ```
118
+ $ puma -b 'ssl://127.0.0.1:9292?key=path_to_key&cert=path_to_cert&key_password_command=/path/to/command.sh'
119
+ ```
120
+
121
+ `key_password_command` must:
122
+
123
+ 1. Be executable by Puma.
124
+ 2. Print the decryption password to stdout.
125
+
126
+ For example:
127
+
128
+ ```shell
129
+ #!/bin/sh
130
+
131
+ echo "this is my password"
132
+ ```
133
+
134
+ `key_password_command` can be used with `key` or `key_pem`. If the key
135
+ is not encrypted, the executable will not be called.
@@ -0,0 +1,241 @@
1
+ # Cluster mode
2
+
3
+ Puma also offers "cluster mode". Cluster mode `fork`s workers from a master process. Each child process still has its own thread pool. You can tune the number of workers with the `-w` (or `--workers`) flag:
4
+
5
+ ```
6
+ $ puma -t 8:32 -w 3
7
+ ```
8
+
9
+ Or with the `WEB_CONCURRENCY` environment variable:
10
+
11
+ ```
12
+ $ WEB_CONCURRENCY=3 puma -t 8:32
13
+ ```
14
+
15
+ When using a config file, most applications can simply set `workers :auto` (requires the `concurrent-ruby` gem) to match the number of worker processes to the available processors:
16
+
17
+ ```ruby
18
+ # config/puma.rb
19
+ workers :auto
20
+ ```
21
+
22
+ See [`workers :auto` gotchas](../lib/puma/dsl.rb).
23
+
24
+ Note that threads are still used in cluster mode, and the `-t` thread flag setting is per worker, so `-w 2 -t 16:16` will spawn 32 threads in total, with 16 in each worker process.
25
+
26
+ If `workers` is set to `:auto`, or the `WEB_CONCURRENCY` environment variable is set to `"auto"`, and the `concurrent-ruby` gem is available in your application, Puma will set the worker process count to the result of [available processors](https://msp-greg.github.io/concurrent-ruby/Concurrent.html#available_processor_count-class_method).
27
+
28
+ For an in-depth discussion of the tradeoffs of thread and process count settings, [see our docs](deployment/README.md).
29
+
30
+ In cluster mode, Puma can "preload" your application. This loads all the application code *prior* to forking. Preloading reduces total memory usage of your application via an operating system feature called [copy-on-write](https://en.wikipedia.org/wiki/Copy-on-write).
31
+
32
+ If the number of workers is greater than 1 (and `--prune-bundler` has not been specified), preloading will be enabled by default. Otherwise, you can use the `--preload` flag from the command line:
33
+
34
+ ```
35
+ $ puma -w 3 --preload
36
+ ```
37
+
38
+ Or, if you're using a configuration file, you can use the `preload_app!` method:
39
+
40
+ ```ruby
41
+ # config/puma.rb
42
+ workers 3
43
+ preload_app!
44
+ ```
45
+
46
+ Preloading can’t be used with phased restart, since phased restart kills and restarts workers one-by-one, and preloading copies the code of master into the workers.
47
+
48
+ ## Cluster mode hooks
49
+
50
+ When using clustered mode, Puma's configuration DSL provides `before_fork`, `before_worker_boot`, and `after_worker_shutdown`
51
+ hooks to run code when the master process forks, the child workers are booted, and after each child worker exits respectively.
52
+
53
+ It is recommended to use these hooks with `preload_app!`, otherwise constants loaded by your
54
+ application (such as `Rails`) will not be available inside the hooks.
55
+
56
+ ```ruby
57
+ # config/puma.rb
58
+ before_fork do
59
+ # Add code to run inside the Puma master process before it forks a worker child.
60
+ end
61
+
62
+ before_worker_boot do
63
+ # Add code to run inside the Puma worker process after forking.
64
+ end
65
+
66
+ after_worker_shutdown do |worker_handle|
67
+ # Add code to run inside the Puma master process after a worker exits. `worker.process_status` can be used to get the
68
+ # `Process::Status` of the exited worker.
69
+ end
70
+ ```
71
+
72
+ In addition, there are `before_refork` and `after_refork` hooks which are used only in [`fork_worker` mode](#fork-worker-cluster-mode-experimental),
73
+ when the worker 0 child process forks a grandchild worker:
74
+
75
+ ```ruby
76
+ before_refork do
77
+ # Used only when fork_worker mode is enabled. Add code to run inside the Puma worker 0
78
+ # child process before it forks a grandchild worker.
79
+ end
80
+ ```
81
+
82
+ ```ruby
83
+ after_refork do
84
+ # Used only when fork_worker mode is enabled. Add code to run inside the Puma worker 0
85
+ # child process after it forks a grandchild worker.
86
+ end
87
+ ```
88
+
89
+ Importantly, note the following considerations when Ruby forks a child process:
90
+
91
+ 1. File descriptors such as network sockets **are** copied from the parent to the forked
92
+ child process. Dual-use of the same sockets by parent and child will result in I/O conflicts
93
+ such as `SocketError`, `Errno::EPIPE`, and `EOFError`.
94
+ 2. Background Ruby threads, including threads used by various third-party gems for connection
95
+ monitoring, etc., are **not** copied to the child process. Often this does not cause
96
+ immediate problems until a third-party connection goes down, at which point there will
97
+ be no supervisor to reconnect it.
98
+
99
+ Therefore, we recommend the following:
100
+
101
+ 1. If possible, do not establish any socket connections (HTTP, database connections, etc.)
102
+ inside Puma's master process when booting.
103
+ 2. If (1) is not possible, use `before_fork` and `before_refork` to disconnect the parent's socket
104
+ connections when forking, so that they are not accidentally copied to the child process.
105
+ 3. Use `before_worker_boot` to restart any background threads on the forked child.
106
+ 4. Use `after_refork` to restart any background threads on the parent.
107
+
108
+ ## Fork-Worker Cluster Mode [Experimental]
109
+
110
+ `fork_worker` (`--fork-worker` from the CLI) is an experimental cluster-mode configuration option. This mode causes Puma to fork additional workers from worker 0, instead of directly from the master process.
111
+
112
+ ```
113
+ 10000 \_ puma 8.0.2 (tcp://0.0.0.0:9292) [puma]
114
+ 10001 \_ puma: cluster worker 0: 10000 [puma]
115
+ 10002 \_ puma: cluster worker 1: 10000 [puma]
116
+ 10003 \_ puma: cluster worker 2: 10000 [puma]
117
+ 10004 \_ puma: cluster worker 3: 10000 [puma]
118
+ ```
119
+
120
+ The `fork_worker` option allows your application to be initialized only once for copy-on-write memory savings, and it has two additional advantages:
121
+
122
+ 1. **Compatible with phased restart.** With `preload_app!` disabled, the master process doesn't load the application, so this mode works with phased restart (`SIGUSR1` or `pumactl phased-restart`). When worker 0 reloads as part of a phased restart, it initializes a new copy of your application first, then the other workers reload by forking from this new worker already containing the new preloaded application.
123
+
124
+ This allows a phased restart to complete as quickly as a hot restart (`SIGUSR2` or `pumactl restart`), while still minimizing downtime by staggering the restart across cluster workers.
125
+
126
+ 2. **'Refork' for additional copy-on-write improvements in running applications.** Fork-worker mode introduces a new `refork` command that re-loads all nonzero workers by re-forking them from worker 0.
127
+
128
+ This command can potentially improve memory utilization in large or complex applications that don't fully pre-initialize on startup, because the re-forked workers can share copy-on-write memory with a worker that has been running for a while and serving requests.
129
+
130
+ You can trigger a refork by sending the cluster the `SIGURG` signal or running the `pumactl refork` command at any time. A refork will also automatically trigger once, after a certain number of requests have been processed by worker 0 (default 1000). To configure the number of requests before the auto-refork, pass a positive integer argument to `fork_worker` (e.g., `fork_worker 1000`), or `0` to disable.
131
+
132
+ ### Usage Considerations
133
+
134
+ - `fork_worker` introduces new `before_refork` and `after_refork` configuration hooks. Note the following:
135
+ - When initially forking the parent process to the worker 0 child, `before_fork` will trigger on the parent process and `before_worker_boot` will trigger on the worker 0 child as normal.
136
+ - When forking the worker 0 child to grandchild workers, `before_refork` and `after_refork` will trigger on the worker 0 child, and `before_worker_boot` will trigger on each grandchild worker.
137
+ - For clarity, `before_fork` does not trigger on worker 0, and `after_refork` does not trigger on the grandchild.
138
+ - As a general migration guide:
139
+ - Copy any logic within your existing `before_fork` hook to the `before_refork` hook.
140
+ - Consider copying logic from your `before_worker_boot` hook to the `after_refork` hook, if it is needed to reset the state of worker 0 after it forks.
141
+
142
+ ### Limitations
143
+
144
+ - This mode is still very experimental so there may be bugs or edge-cases, particularly around expected behavior of existing hooks. Please open a [bug report](https://github.com/puma/puma/issues/new?template=bug_report.md) if you encounter any issues.
145
+
146
+ - In order to fork new workers cleanly, worker 0 shuts down its server and stops serving requests so there are no open file descriptors or other kinds of shared global state between processes, and to maximize copy-on-write efficiency across the newly-forked workers. This may temporarily reduce total capacity of the cluster during a phased restart / refork.
147
+
148
+ - In a cluster with `n` workers, a normal phased restart stops and restarts workers one by one while the application is loaded in each process, so `n-1` workers are available serving requests during the restart. In a phased restart in fork-worker mode, the application is first loaded in worker 0 while `n-1` workers are available, then worker 0 remains stopped while the rest of the workers are reloaded one by one, leaving only `n-2` workers to be available for a brief period of time. Reloading the rest of the workers should be quick because the application is preloaded at that point, but there may be situations where it can take longer (slow clients, long-running application code, slow worker-fork hooks, etc).
149
+
150
+ ## Mold-Worker Cluster Mode [Experimental]
151
+
152
+ `mold_worker` (`--mold-worker` from the CLI) is an alternative to `fork_worker`. Instead of forking from a worker that also serves requests, Puma promotes a worker to a "mold", which stops serving requests and only forks new workers. Because the mold never serves traffic, a slow request, timeout or memory limit can't take it down mid-refork.
153
+
154
+ ```
155
+ 10000 \_ puma 8.0.2 (tcp://0.0.0.0:9292) [puma]
156
+ 10005 \_ puma: mold 2: 10000 [puma]
157
+ 10011 \_ puma: cluster worker 0: 10000 [puma]
158
+ 10012 \_ puma: cluster worker 1: 10000 [puma]
159
+ 10013 \_ puma: cluster worker 2: 10000 [puma]
160
+ ```
161
+
162
+ Workers are forked from the master at boot. Each request threshold (default `1000`) promotes the busiest worker to a new mold, retires the previous one, and reforks every worker from the new mold.
163
+
164
+ ```ruby
165
+ mold_worker 1000, 2000, 4000
166
+ ```
167
+
168
+ ### Usage Considerations
169
+
170
+ - Thresholds are per worker, counted from when that worker booted. Workers forked from a mold start again at zero, so with the config above a worker is promoted after 1000 requests, and a worker from that generation is promoted after another 2000.
171
+ - After the last threshold, molds are only replaced by `SIGURG` or `pumactl refork`, which promote the busiest worker at any time.
172
+ - A phased restart (`SIGUSR1` or `pumactl phased-restart`) retires the mold and forks workers from the master, so new code is loaded, then starts the thresholds again. As with any phased restart, this requires `preload_app!` to be disabled.
173
+ - `mold_worker` cannot be combined with `fork_worker`.
174
+ - On Linux 3.4+, workers are reparented to the master rather than orphaned if their mold exits.
175
+ - `mold_worker` introduces new `after_mold_promotion` and `before_mold_shutdown` configuration hooks.
176
+ - `after_mold_promotion` runs in the mold after it stops serving requests, before it forks any workers. Use it for what you would do in `before_refork`, such as closing connections or running garbage collection.
177
+ - `before_mold_shutdown` runs in the mold before it exits.
178
+ - `before_worker_boot` runs in each forked worker, as usual. Use it for what you would do in `after_refork`.
179
+
180
+ ## Using gRPC with Puma in Clustered Mode
181
+
182
+ This guide shows how to set up gRPC with Puma in a clustered environment using Puma's hooks to manage gRPC's lifecycle methods during forking.
183
+
184
+ ### The Problem
185
+
186
+ In a clustered Puma setup, you might encounter the following error when using gRPC:
187
+
188
+ ```
189
+ grpc cannot be used between calls to GRPC.prefork and GRPC.postfork_child or GRPC.postfork_parent
190
+ ```
191
+
192
+ To work correctly, gRPC needs these methods called at specific points in the process lifecycle:
193
+ - `GRPC.prefork`: Called before forking.
194
+ - `GRPC.postfork_child`: Called in the child process after forking.
195
+ - `GRPC.postfork_parent`: Called in the parent process after forking.
196
+
197
+ Puma provides hooks such as `before_worker_fork`, `after_worker_fork`, and `before_worker_boot` to execute code during these lifecycle events. Understanding the behavior of these hooks is key to ensuring gRPC operates correctly in a clustered setup.
198
+
199
+ ### The Solution
200
+
201
+ #### Example Configuration
202
+
203
+ This configuration integrates gRPC's lifecycle methods in a clustered Puma setup and works whether preloading is enabled or not.
204
+
205
+ ```ruby
206
+ # config/puma.rb
207
+
208
+ is_mac = RUBY_PLATFORM.include?("darwin")
209
+
210
+ before_worker_fork do |index|
211
+ GRPC.prefork unless is_mac
212
+ end
213
+
214
+ after_worker_fork do |index|
215
+ GRPC.postfork_parent unless is_mac
216
+ end
217
+
218
+ before_worker_boot do
219
+ GRPC.postfork_child unless is_mac
220
+ end
221
+ ```
222
+
223
+ #### Understanding the Lifecycle and Hooks
224
+
225
+ Puma's hooks determine when to call gRPC's lifecycle methods. Each hook plays a specific role in managing the lifecycle during forking:
226
+
227
+ - **`before_worker_fork`**:
228
+ - This hook runs before forking workers and is where you call `GRPC.prefork`.
229
+ - In preloading setups (default in Puma v7), it runs in the **master process** before workers are forked, as the application is preloaded in the master process.
230
+ - Without preloading, it still runs in the **master process** before forking workers, but the application is not preloaded.
231
+ - `GRPC.prefork` is called here to prepare GRPC for the forking process.
232
+
233
+ - **`after_worker_fork`**:
234
+ - This hook always runs in the **master process** after a worker is forked, regardless of whether preloading is enabled.
235
+ - Call `GRPC.postfork_parent` here to finalize the master process's state after forking.
236
+
237
+ - **`before_worker_boot`**:
238
+ - This hook always runs in the **worker process** after it is forked, regardless of whether preloading is enabled.
239
+ - Call `GRPC.postfork_child` here to finalize the worker's state.
240
+
241
+ **Note**: On macOS, these methods are skipped because gRPC does not require them due to differences in how forking works.
@@ -0,0 +1,78 @@
1
+ # Configuration
2
+
3
+ ## Configuration File
4
+
5
+ You can also provide a configuration file with the `-C` (or `--config`) flag:
6
+
7
+ ```
8
+ $ puma -C /path/to/config
9
+ ```
10
+
11
+ If no configuration file is specified, Puma will look for a configuration file at `config/puma.rb`. If an environment is specified (via the `--environment` flag or through the `APP_ENV`, `RACK_ENV`, or `RAILS_ENV` environment variables) Puma looks for a configuration file at `config/puma/<environment_name>.rb` and then falls back to `config/puma.rb`.
12
+
13
+ If you want to prevent Puma from looking for a configuration file in those locations, include the `--no-config` flag:
14
+
15
+ ```
16
+ $ puma --no-config
17
+
18
+ # or
19
+
20
+ $ puma -C "-"
21
+ ```
22
+
23
+ The other side-effects of setting the environment are whether to show stack traces (in `development` or `test`), and setting RACK_ENV may potentially affect middleware looking for this value to change their behavior. The default puma RACK_ENV value is `development`. You can see all config default values in `Puma::Configuration#puma_default_options` or [configuration.rb](https://github.com/puma/puma/blob/61c6213fbab/lib/puma/configuration.rb#L182-L204).
24
+
25
+ ## Thread Pool
26
+
27
+ Puma uses a thread pool. You can set the minimum and maximum number of threads that are available in the pool with the `-t` (or `--threads`) flag:
28
+
29
+ ```
30
+ $ puma -t 8:32
31
+ ```
32
+
33
+ Puma will automatically scale the number of threads, from the minimum until it caps out at the maximum, based on how much traffic is present. The current default is `0:16` and on MRI is `0:5`. Feel free to experiment, but be careful not to set the number of maximum threads to a large number, as you may exhaust resources on the system (or cause contention for the Global VM Lock, when using MRI).
34
+
35
+ Be aware that additionally Puma creates threads on its own for internal purposes (e.g. handling slow clients). So, even if you specify -t 1:1, expect around 7 threads created in your application.
36
+
37
+ ## Master process lifecycle hooks
38
+
39
+ Puma's configuration DSL provides master process lifecycle hooks `after_booted`, `before_restart`, and `after_stopped`
40
+ which may be used to specify code blocks to run on each event:
41
+
42
+ ```ruby
43
+ # config/puma.rb
44
+ after_booted do
45
+ # Add code to run in the Puma master process after it boots,
46
+ # and also after a phased restart completes.
47
+ end
48
+
49
+ before_restart do
50
+ # Add code to run in the Puma master process when it receives
51
+ # a restart command but before it restarts.
52
+ end
53
+
54
+ after_stopped do
55
+ # Add code to run in the Puma master process after outstanding
56
+ # requests have finished and Puma has stopped.
57
+ end
58
+ ```
59
+
60
+ ## Error handling
61
+
62
+ If Puma encounters an error outside of the context of your application, it will respond with a 400/500 and a simple
63
+ textual error message (see `Puma::Server#lowlevel_error` or [server.rb](https://github.com/puma/puma/blob/main/lib/puma/server.rb)).
64
+ You can specify custom behavior for this scenario. For example, you can report the error to your third-party
65
+ error-tracking service (in this example, [rollbar](https://rollbar.com)):
66
+
67
+ ```ruby
68
+ lowlevel_error_handler do |e, env, status|
69
+ if status == 400
70
+ message = "The server could not process the request due to an error, such as an incorrectly typed URL, malformed syntax, or a URL that contains illegal characters.\n"
71
+ else
72
+ message = "An error has occurred, and engineers have been informed. Please reload the page. If you continue to have problems, contact support@example.com\n"
73
+ Rollbar.critical(e)
74
+ end
75
+
76
+ [status, {}, [message]]
77
+ end
78
+ ```
@@ -1,3 +1,21 @@
1
+ # Control/Status Server
2
+
3
+ Puma has a built-in status and control app that can be used to query and control Puma.
4
+
5
+ ```
6
+ $ puma --control-url tcp://127.0.0.1:9293 --control-token foo
7
+ ```
8
+
9
+ Puma will start the control server on localhost port 9293. All requests to the control server will need to include a control token (in this case, `token=foo`) as a query parameter. This allows for simple authentication. Check out `Puma::App::Status` or [status.rb](https://github.com/puma/puma/blob/main/lib/puma/app/status.rb) to see what the status app has available.
10
+
11
+ You can also interact with the control server via `pumactl`. This command will restart Puma:
12
+
13
+ ```
14
+ $ pumactl --control-url 'tcp://127.0.0.1:9293' --control-token foo restart
15
+ ```
16
+
17
+ To see a list of `pumactl` options, use `pumactl --help`.
18
+
1
19
  ## Accessing stats
2
20
 
3
21
  Stats can be accessed in two ways:
@@ -6,8 +24,6 @@ Stats can be accessed in two ways:
6
24
 
7
25
  `$ pumactl stats` or `GET /stats`
8
26
 
9
- [Read more about `pumactl` and the control server in the README.](https://github.com/puma/puma#controlstatus-server).
10
-
11
27
  ### Puma.stats
12
28
 
13
29
  `Puma.stats` produces a JSON string. `Puma.stats_hash` produces a ruby hash.
@@ -55,24 +71,24 @@ end
55
71
 
56
72
  When Puma runs in single mode, these stats are available at the top level. When Puma runs in cluster mode, these stats are available within the `worker_status` array in a hash labeled `last_status`, in an array of hashes where one hash represents each worker.
57
73
 
58
- * backlog: requests that are waiting for an available thread to be available. if this is frequently above 0, you need more capacity.
74
+ * backlog: requests that are waiting for an available thread to be available. If this is frequently above 0, you need more capacity.
59
75
  * running: how many threads are spawned. A spawned thread may be busy processing a request or waiting for a new request. If `min_threads` and `max_threads` are set to the same number,
60
76
  this will be a never-changing number (other than rare cases when a thread dies, etc).
61
77
  * busy_threads: `running` - `how many threads are waiting to receive work` + `how many requests are waiting for a thread to pick them up`.
62
- this is a "wholistic" stat reflecting the overall current state of work to be done and the capacity to do it.
78
+ This is a "wholistic" stat reflecting the overall current state of work to be done and the capacity to do it.
63
79
  * pool_capacity: `how many threads are waiting to receive work` + `max_threads` - `running`. In a typical configuration where `min_threads`
64
80
  and `max_threads` are configured to the same number, this is simply `how many threads are waiting to receive work`. This number exists only as a stat
65
81
  and is not used for any internal decisions, unlike `busy_threads`, which is usually a more useful stat.
66
82
  * max_threads: the maximum number of threads Puma is configured to spool per worker
67
83
  * requests_count: the number of requests this worker has served since starting
68
- * reactor_max: the maximum observed number of requests held in Puma's "reactor" which is used for asyncronously buffering request bodies. This stat is reset on every call, so it's the maximum value observed since the last stat call.
84
+ * reactor_max: the maximum observed number of requests held in Puma's "reactor" which is used for asynchronously buffering request bodies. This stat is reset on every call, so it's the maximum value observed since the last stat call.
69
85
  * backlog_max: the maximum number of requests that have been fully buffered by the reactor and placed in a ready queue, but have not yet been picked up by a server thread. This stat is reset on every call, so it's the maximum value observed since the last stat call.
70
86
 
71
87
  ### cluster mode
72
88
 
73
- * phase: which phase of restart the process is in, during [phased restart](https://github.com/puma/puma/blob/main/docs/restart.md)
89
+ * phase: which phase of restart the process is in, during [phased restart](restart.md)
74
90
  * workers: ??
75
- * booted_workers: how many workers currently running?
91
+ * booted_workers: how many workers are currently running?
76
92
  * old_workers: ??
77
93
  * worker_status: array of hashes of info for each worker (see below)
78
94
 
@@ -80,7 +96,7 @@ When Puma runs in single mode, these stats are available at the top level. When
80
96
 
81
97
  * started_at: when the worker started
82
98
  * pid: the process id of the worker process
83
- * index: each worker gets a number. if Puma is configured to have 3 workers, then this will be 0, 1, or 2
99
+ * index: each worker gets a number. If Puma is configured to have 3 workers, then this will be 0, 1, or 2
84
100
  * booted: if it's done booting [?]
85
101
  * last_checkin: Last time the worker responded to the master process' heartbeat check.
86
102
  * last_status: a hash of info about the worker's state handling requests. See the explanation for this in "single mode and individual workers in cluster mode" section above.
@@ -146,3 +162,7 @@ Here are two example stats hashes produced by `Puma.stats`:
146
162
  ]
147
163
  }
148
164
  ```
165
+
166
+ ## Monitoring
167
+
168
+ * [puma-status](https://github.com/ylecuyer/puma-status) — Monitor CPU/Mem/Load of running puma instances from the CLI
@@ -41,7 +41,7 @@ Set your config with the following process:
41
41
 
42
42
  For most deployments, adding `concurrent-ruby` and using `workers :auto` is the right starting point.
43
43
 
44
- See [`workers :auto` gotchas](../lib/puma/dsl.rb).
44
+ See [`workers :auto` gotchas](../../lib/puma/dsl.rb).
45
45
 
46
46
  ## Worker utilization
47
47
 
@@ -66,7 +66,7 @@ If latency is important to you, you will have to accept lower utilization, and v
66
66
 
67
67
  You will have to make a decision about how "big" to make each pod/VPS/server/dyno.
68
68
 
69
- **TL:DR;**: 80% of Puma apps will end up deploying "pods" of 4 workers, 5 threads each, 4 vCPU and 8GB of RAM.
69
+ **TL;DR**: 80% of Puma apps will end up deploying "pods" of 4 workers, 5 threads each, 4 vCPU and 8GB of RAM.
70
70
 
71
71
  For the rest of this discussion, we'll adopt the Kubernetes term of "pods".
72
72
 
@@ -109,19 +109,21 @@ to monitor them as child processes. This gives them fast response to crashes and
109
109
  makes it easy to figure out what is going on. Additionally, unlike `unicorn`,
110
110
  Puma does not require daemonization to do zero-downtime restarts.
111
111
 
112
- I see people using daemonization because they start puma directly via Capistrano
112
+ I see people using daemonization because they start puma directly via a Capistrano
113
113
  task and thus want it to live on past the `cap deploy`. To these people, I say:
114
114
  You need to be using a process monitor. Nothing is making sure Puma stays up in
115
115
  this scenario! You're just waiting for something weird to happen, Puma to die,
116
- and to get paged at 3 AM. Do yourself a favor, at least the process monitoring
116
+ and to get paged at 3 AM. Do yourself a favor, at least use the process monitoring
117
117
  your OS comes with, be it `sysvinit` or `systemd`. Or branch out and use `runit`
118
118
  or hell, even `monit`.
119
119
 
120
+ Additionally, Puma has support for built-in daemonization via the [puma-daemon](https://github.com/kigster/puma-daemon) ruby gem. The gem restores the `daemonize` option that was removed from Puma starting version 5, but only for MRI Ruby.
121
+
120
122
  ## Restarting
121
123
 
122
124
  You probably will want to deploy some new code at some point, and you'd like
123
125
  Puma to start running that new code. There are a few options for restarting
124
- Puma, described separately in our [restart documentation](restart.md).
126
+ Puma, described separately in our [restart documentation](../restart.md).
125
127
 
126
128
  ## Migrating from Unicorn
127
129
 
@@ -132,6 +134,20 @@ Puma, described separately in our [restart documentation](restart.md).
132
134
  * As you grow more confident in the thread-safety of your app, you can tune the
133
135
  workers down and the threads up.
134
136
 
135
- ## Ubuntu / Systemd (Systemctl) Installation
137
+ ## Process monitors and guides
138
+
139
+ It is common to use process monitors with Puma. Modern process monitors like systemd or rc.d
140
+ provide continuous monitoring and restarts for increased reliability in production environments:
141
+
142
+ * [rc.d](rc.d/README.md)
143
+ * [systemd](systemd.md)
144
+ * [Kubernetes](kubernetes.md)
145
+ * [nginx](nginx.md)
146
+
147
+ Community guides:
148
+
149
+ * [Deploying Puma on OpenBSD using relayd and httpd](https://gist.github.com/anon987654321/4532cf8d6c59c1f43ec8973faa031103)
150
+
151
+ ## Capistrano
136
152
 
137
- See [systemd.md](systemd.md)
153
+ Puma has support for Capistrano with an [external gem](https://github.com/seuros/capistrano-puma).
@@ -57,17 +57,17 @@ For some high-throughput systems, it is possible that some HTTP requests will re
57
57
 
58
58
  1. The replication controller determines a pod should be shut down.
59
59
  2. The Pod is set to the “Terminating” State and removed from the endpoints list of all Services, so that it receives no more requests.
60
- 3. The pods pre-stop hook get called. The default for this is to send `SIGTERM` to the process inside the pod.
60
+ 3. The pod's pre-stop hook gets called. The default for this is to send `SIGTERM` to the process inside the pod.
61
61
  4. The pod has up to `terminationGracePeriodSeconds` (default: 30 seconds) to gracefully shut down. Puma will do this (after it receives SIGTERM) by closing down the socket that accepts new requests and finishing any requests already running before exiting the Puma process.
62
62
  5. If the pod is still running after `terminationGracePeriodSeconds` has elapsed, the pod receives `SIGKILL` to make sure the process inside it stops. After that, the container exits and all other Kubernetes objects associated with it are cleaned up.
63
63
 
64
- There is a subtle race condition between step 2 and 3: The replication controller does not synchronously remove the pod from the Services AND THEN call the pre-stop hook of the pod, but rather it asynchronously sends "remove this pod from your endpoints" requests to the Services and then immediately proceeds to invoke the pods' pre-stop hook. If the Service controller (typically something like nginx or haproxy) receives and handles this request "too" late (due to internal lag or network latency between the replication and Service controllers) then it is possible that the Service controller will send one or more requests to a Puma process which has already shut down its listening socket. These requests will then fail with 5XX error codes.
64
+ There is a subtle race condition between steps 2 and 3: The replication controller does not synchronously remove the pod from the Services AND THEN call the pre-stop hook of the pod, but rather it asynchronously sends "remove this pod from your endpoints" requests to the Services and then immediately proceeds to invoke the pod's pre-stop hook. If the Service controller (typically something like nginx or haproxy) receives and handles this request "too" late (due to internal lag or network latency between the replication and Service controllers) then it is possible that the Service controller will send one or more requests to a Puma process which has already shut down its listening socket. These requests will then fail with 5XX error codes.
65
65
 
66
- The way Kubernetes works this way, rather than handling step 2 synchronously, is due to the CAP theorem: in a distributed system there is no way to guarantee that any message will arrive promptly. In particular, waiting for all Service controllers to report back might get stuck for an indefinite time if one of them has already been terminated or if there has been a net split. A way to work around this is to add a sleep to the pre-stop hook of the same time as the `terminationGracePeriodSeconds` time. This will allow the Puma process to keep serving new requests during the entire grace period, although it will no longer receive new requests after all Service controllers have propagated the removal of the pod from their endpoint lists. Then, after `terminationGracePeriodSeconds`, the pod receives `SIGKILL` and closes down. If your process can't handle SIGKILL properly, for example because it needs to release locks in different services, you can also sleep for a shorter period (and/or increase `terminationGracePeriodSeconds`) as long as the time slept is longer than the time that your Service controllers take to propagate the pod removal. The downside of this workaround is that all pods will take at minimum the amount of time slept to shut down and this will increase the time required for your rolling deploy.
66
+ The reason Kubernetes works this way, rather than handling step 2 synchronously, is due to the CAP theorem: in a distributed system there is no way to guarantee that any message will arrive promptly. In particular, waiting for all Service controllers to report back might get stuck for an indefinite time if one of them has already been terminated or if there has been a net split. A way to work around this is to add a sleep to the pre-stop hook of the same time as the `terminationGracePeriodSeconds` time. This will allow the Puma process to keep serving new requests during the entire grace period, although it will no longer receive new requests after all Service controllers have propagated the removal of the pod from their endpoint lists. Then, after `terminationGracePeriodSeconds`, the pod receives `SIGKILL` and closes down. If your process can't handle SIGKILL properly, for example because it needs to release locks in different services, you can also sleep for a shorter period (and/or increase `terminationGracePeriodSeconds`) as long as the time slept is longer than the time that your Service controllers take to propagate the pod removal. The downside of this workaround is that all pods will take at minimum the amount of time slept to shut down and this will increase the time required for your rolling deploy.
67
67
 
68
68
  More discussions and links to relevant articles can be found in https://github.com/puma/puma/issues/2343.
69
69
 
70
70
  ## Workers Per Pod, and Other Config Issues
71
71
 
72
- See our [deployment docs](./deployment.md) for more information about how to correctly size your pods and choose the right number of workers and threads.
72
+ See our [deployment docs](README.md) for more information about how to correctly size your pods and choose the right number of workers and threads.
73
73
 
@@ -30,6 +30,8 @@ After=network.target
30
30
  Type=notify
31
31
 
32
32
  # If your Puma process locks up, systemd's watchdog will restart it within seconds.
33
+ # Puma pings the watchdog as soon as it reports readiness, and every
34
+ # WatchdogSec/2 after that.
33
35
  WatchdogSec=10
34
36
 
35
37
  # Preferably configure a non-privileged user
@@ -71,7 +73,7 @@ for additional details.
71
73
  systemd and Puma also support socket activation, where systemd opens the
72
74
  listening socket(s) in advance and provides them to the Puma master process on
73
75
  startup. Among other advantages, this keeps listening sockets open across puma
74
- restarts and achieves graceful restarts, including when upgraded Puma, and is
76
+ restarts and achieves graceful restarts, including when upgrading Puma, and is
75
77
  compatible with both cluster mode and application preload.
76
78
 
77
79
  **Note:** Any wrapper scripts which `exec`, or other indirections in `ExecStart`
@@ -244,7 +246,7 @@ cap $stage puma:stop --dry-run
244
246
  ### Disabling Puma Systemd Integration
245
247
 
246
248
  If you would like to disable Puma's systemd integration, for example if you handle it elsewhere
247
- in your code yourself, simply set the the environment variable `PUMA_SKIP_SYSTEMD` to any value.
249
+ in your code yourself, simply set the environment variable `PUMA_SKIP_SYSTEMD` to any value.
248
250
 
249
251
 
250
252