puma 8.0.3-java → 8.1.1-java

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 (66) hide show
  1. checksums.yaml +4 -4
  2. data/History.md +125 -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/lib/puma/binder.rb +29 -0
  21. data/lib/puma/cli.rb +6 -0
  22. data/lib/puma/client.rb +75 -29
  23. data/lib/puma/client_env.rb +32 -18
  24. data/lib/puma/cluster/worker.rb +109 -33
  25. data/lib/puma/cluster/worker_handle.rb +16 -0
  26. data/lib/puma/cluster.rb +173 -45
  27. data/lib/puma/commonlogger.rb +3 -3
  28. data/lib/puma/configuration.rb +22 -3
  29. data/lib/puma/const.rb +11 -9
  30. data/lib/puma/dsl.rb +265 -91
  31. data/lib/puma/launcher.rb +6 -4
  32. data/lib/puma/minissl.rb +2 -5
  33. data/lib/puma/plugin/systemd.rb +1 -1
  34. data/lib/puma/puma_http11.jar +0 -0
  35. data/lib/puma/response.rb +13 -5
  36. data/lib/puma/runner.rb +5 -1
  37. data/lib/puma/sd_notify.rb +4 -1
  38. data/lib/puma/server.rb +45 -20
  39. data/lib/puma/thread_pool.rb +12 -1
  40. data/lib/puma.rb +1 -1
  41. metadata +17 -34
  42. data/docs/fork_worker.md +0 -41
  43. data/docs/grpc.md +0 -62
  44. data/docs/jungle/README.md +0 -9
  45. data/docs/testing_benchmarks_local_files.md +0 -150
  46. data/docs/testing_test_rackup_ci_files.md +0 -36
  47. data/ext/puma_http11/PumaHttp11Service.java +0 -17
  48. data/ext/puma_http11/extconf.rb +0 -65
  49. data/ext/puma_http11/http11_parser.c +0 -1057
  50. data/ext/puma_http11/http11_parser.h +0 -65
  51. data/ext/puma_http11/http11_parser.java.rl +0 -131
  52. data/ext/puma_http11/http11_parser.rl +0 -149
  53. data/ext/puma_http11/http11_parser_common.rl +0 -54
  54. data/ext/puma_http11/mini_ssl.c +0 -859
  55. data/ext/puma_http11/no_ssl/PumaHttp11Service.java +0 -15
  56. data/ext/puma_http11/org/jruby/puma/EnvKey.java +0 -241
  57. data/ext/puma_http11/org/jruby/puma/Http11.java +0 -321
  58. data/ext/puma_http11/org/jruby/puma/Http11Parser.java +0 -441
  59. data/ext/puma_http11/org/jruby/puma/MiniSSL.java +0 -519
  60. data/ext/puma_http11/puma_http11.c +0 -500
  61. data/tools/Dockerfile +0 -26
  62. data/tools/trickletest.rb +0 -44
  63. /data/docs/{nginx.md → deployment/nginx.md} +0 -0
  64. /data/docs/{jungle → deployment}/rc.d/README.md +0 -0
  65. /data/docs/{jungle → deployment}/rc.d/puma +0 -0
  66. /data/docs/{jungle → deployment}/rc.d/puma.conf +0 -0
@@ -12,6 +12,22 @@ module Puma
12
12
 
13
13
  include Puma::Const
14
14
 
15
+ def validate_env
16
+ return unless @env[SERVER_PROTOCOL] == HTTP_11
17
+
18
+ unless @env.key? HTTP_HOST
19
+ @error_status_code = 400
20
+ @env[HTTP_CONNECTION] = CLOSE
21
+ raise HttpParserError, "Missing Host header"
22
+ end
23
+
24
+ if @env[HTTP_HOST].empty?
25
+ @error_status_code = 400
26
+ @env[HTTP_CONNECTION] = CLOSE
27
+ raise HttpParserError, "Invalid Host header"
28
+ end
29
+ end
30
+
15
31
  # Given a Hash +env+ for the request read from +client+, add
16
32
  # and fixup keys to comply with Rack's env guidelines.
17
33
  # @param env [Hash] see Puma::Client#env, from request
@@ -105,9 +121,10 @@ module Puma
105
121
  # avoid allocation in the common case (ie there are no headers
106
122
  # with `,` in their names), that's why it has the extra conditionals.
107
123
  #
108
- # @note If a normalized version of a `,` header already exists, we ignore
109
- # the `,` version. This prevents clobbering headers managed by proxies
110
- # but not by clients (Like X-Forwarded-For).
124
+ # @note If underscore headers are disallowed, `,` headers are discarded.
125
+ # Otherwise, if a normalized version of a `,` header already exists, we
126
+ # ignore the `,` version. This prevents clobbering headers managed by
127
+ # proxies but not by clients (Like X-Forwarded-For).
111
128
  #
112
129
  # @param env [Hash] see Puma::Client#env, from request, modifies in place
113
130
  # @version 5.0.3
@@ -115,28 +132,25 @@ module Puma
115
132
  def req_env_post_parse
116
133
  to_delete = nil
117
134
  to_add = nil
135
+ underscore_headers = nil
118
136
 
119
137
  @env.each do |k,v|
120
- if k.start_with?("HTTP_") && k.include?(",") && !UNMASKABLE_HEADERS.key?(k)
121
- if to_delete
122
- to_delete << k
123
- else
124
- to_delete = [k]
125
- end
138
+ next unless k.start_with?("HTTP_") && k.include?(",")
126
139
 
127
- new_k = k.tr(",", "_")
128
- if @env.key?(new_k)
129
- next
130
- end
140
+ (underscore_headers ||= []) << k.delete_prefix("HTTP_").tr("_,", "-_")
141
+ next if @allow_underscore_headers && UNMASKABLE_HEADERS.key?(k)
131
142
 
132
- unless to_add
133
- to_add = {}
134
- end
143
+ (to_delete ||= []) << k
144
+ next unless @allow_underscore_headers
135
145
 
136
- to_add[new_k] = v
137
- end
146
+ new_k = k.tr(",", "_")
147
+ next if @env.key?(new_k)
148
+
149
+ (to_add ||= {})[new_k] = v
138
150
  end
139
151
 
152
+ @env[PUMA_UNDERSCORE_HEADERS] = underscore_headers if underscore_headers
153
+
140
154
  if to_delete # rubocop:disable Style/SafeNavigation
141
155
  to_delete.each { |k| env.delete(k) }
142
156
  end
@@ -26,6 +26,7 @@ module Puma
26
26
  @app = app
27
27
  @server = nil
28
28
  @hook_data = {}
29
+ @worker_pids = []
29
30
  end
30
31
 
31
32
  def run
@@ -72,12 +73,7 @@ module Puma
72
73
 
73
74
  if fork_worker
74
75
  restart_server.clear
75
- worker_pids = []
76
- Signal.trap "SIGCHLD" do
77
- wakeup! if worker_pids.reject! do |p|
78
- Process.wait(p, Process::WNOHANG) rescue true
79
- end
80
- end
76
+ trap_sigchld
81
77
 
82
78
  Thread.new do
83
79
  Puma.set_thread_name "wrkr fork"
@@ -94,13 +90,24 @@ module Puma
94
90
  elsif idx == 0 # restart server
95
91
  restart_server << true << false
96
92
  else # fork worker
97
- worker_pids << pid = spawn_worker(idx)
93
+ pid = spawn_worker(idx)
98
94
  @worker_write << "#{PIPE_FORK}#{pid}:#{idx}\n" rescue nil
99
95
  end
100
96
  end
101
97
  end
102
98
  end
103
99
 
100
+ mold = false
101
+
102
+ if @options[:mold_worker]
103
+ Signal.trap "SIGURG" do
104
+ mold = true
105
+ restart_server.clear
106
+ @server.begin_restart
107
+ restart_server << false
108
+ end
109
+ end
110
+
104
111
  Signal.trap "SIGTERM" do
105
112
  @worker_write << "#{PIPE_EXTERNAL_TERM}#{Process.pid}\n" rescue nil
106
113
  restart_server.clear
@@ -117,38 +124,24 @@ module Puma
117
124
 
118
125
  while restart_server.pop
119
126
  server_thread = @server.run
127
+ # A promotion received before the server was running had no effect.
128
+ @server.begin_restart if mold
120
129
 
121
130
  if @log_writer.debug? && index == 0
122
131
  debug_loaded_extensions "Loaded Extensions - worker 0:"
123
132
  end
124
133
 
125
- stat_thread ||= Thread.new(@worker_write) do |io|
126
- Puma.set_thread_name "stat pld"
127
- base_payload = "#{PIPE_PING}#{Process.pid}"
128
-
129
- while true
130
- begin
131
- payload = base_payload.dup
132
-
133
- hsh = @server.stats
134
- hsh.each do |k, v|
135
- payload << %Q! "#{k}":#{v || 0},!
136
- end
137
- # sub call properly adds 'closing' string
138
- io << payload.sub(/,\z/, " }\n")
139
- @server.reset_max
140
- rescue IOError
141
- break
142
- end
143
- sleep @options[:worker_check_interval]
144
- end
145
- end
134
+ start_stat_thread
146
135
  server_thread.join
147
136
  end
148
137
 
149
- # Invoke any worker shutdown hooks so they can prevent the worker
150
- # exiting until any background operations are completed
151
- @config.run_hooks(:before_worker_shutdown, index, @log_writer, @hook_data)
138
+ if mold
139
+ run_mold
140
+ else
141
+ # Invoke any worker shutdown hooks so they can prevent the worker
142
+ # exiting until any background operations are completed
143
+ @config.run_hooks(:before_worker_shutdown, index, @log_writer, @hook_data)
144
+ end
152
145
  ensure
153
146
  @worker_write << "#{PIPE_TERM}#{Process.pid}\n" rescue nil
154
147
  @worker_write.close
@@ -156,15 +149,97 @@ module Puma
156
149
 
157
150
  private
158
151
 
152
+ def start_stat_thread
153
+ @stat_thread ||= Thread.new(@worker_write) do |io|
154
+ Puma.set_thread_name "stat pld"
155
+ base_payload = "#{PIPE_PING}#{Process.pid}"
156
+
157
+ while true
158
+ begin
159
+ payload = base_payload.dup
160
+
161
+ hsh = @server.stats
162
+ hsh.each do |k, v|
163
+ payload << %Q! "#{k}":#{v || 0},!
164
+ end
165
+ # sub call properly adds 'closing' string
166
+ io << payload.sub(/,\z/, " }\n")
167
+ @server.reset_max
168
+ rescue SystemCallError, IOError
169
+ break
170
+ end
171
+ sleep @options[:worker_check_interval]
172
+ end
173
+ end
174
+ end
175
+
176
+ def run_mold
177
+ $0 = $0.sub("cluster worker", "mold")
178
+
179
+ retired = false
180
+ stopping = false
181
+ stop_read, stop_write = @mold_stop_pipe = Puma::Util.pipe
182
+ Signal.trap "SIGURG" do
183
+ retired = true
184
+ stop_write.write_nonblock(".", exception: false)
185
+ end
186
+ Signal.trap "SIGTERM" do
187
+ @worker_write << "#{PIPE_EXTERNAL_TERM}#{Process.pid}\n" rescue nil
188
+ stopping = true
189
+ stop_write.write_nonblock(".", exception: false)
190
+ end
191
+
192
+ trap_sigchld
193
+
194
+ @config.run_hooks(:after_mold_promotion, index, @log_writer, @hook_data)
195
+ start_stat_thread
196
+ @worker_write << "#{PIPE_MOLD}#{Process.pid}\n"
197
+
198
+ loop do
199
+ IO.select([@fork_pipe, stop_read])
200
+ # A retired mold must not read indices meant for its replacement.
201
+ break if retired || stopping
202
+
203
+ idx = @fork_pipe.sysread(MOLD_FORK_BYTES).unpack1(MOLD_FORK_FORMAT)
204
+ pid = spawn_worker(idx)
205
+ @worker_write << "#{PIPE_FORK}#{pid}:#{idx}\n"
206
+ rescue EOFError
207
+ break
208
+ end
209
+
210
+ if retired
211
+ # Stay alive until stopped, so the workers this mold forked are
212
+ # reaped and the master is woken as they exit.
213
+ stop_read.read(1) until stopping
214
+ end
215
+
216
+ @config.run_hooks(:before_mold_shutdown, index, @log_writer, @hook_data)
217
+ end
218
+
219
+ def trap_sigchld
220
+ Signal.trap "SIGCHLD" do
221
+ wakeup! if @worker_pids.reject! do |p|
222
+ Process.wait(p, Process::WNOHANG) rescue true
223
+ end
224
+ end
225
+ end
226
+
159
227
  def spawn_worker(idx)
160
228
  @config.run_hooks(:before_worker_fork, idx, @log_writer, @hook_data)
161
229
 
230
+ pipes = { check_pipe: @check_pipe, worker_write: @worker_write }
231
+ if @options[:mold_worker]
232
+ pipes[:fork_pipe] = @fork_pipe
233
+ pipes[:wakeup] = @wakeup
234
+ end
235
+
162
236
  pid = fork do
237
+ @mold_stop_pipe&.each(&:close)
238
+
163
239
  new_worker = Worker.new index: idx,
164
240
  master: master,
165
241
  launcher: @launcher,
166
- pipes: { check_pipe: @check_pipe,
167
- worker_write: @worker_write },
242
+ pipes: pipes,
168
243
  app: @app
169
244
  new_worker.run
170
245
  end
@@ -175,6 +250,7 @@ module Puma
175
250
  exit! 1
176
251
  end
177
252
 
253
+ @worker_pids << pid
178
254
  @config.run_hooks(:after_worker_fork, idx, @log_writer, @hook_data)
179
255
  pid
180
256
  end
@@ -25,6 +25,7 @@ module Puma
25
25
  @last_checkin = Time.now
26
26
  @last_status = {}
27
27
  @term = false
28
+ @mold = false
28
29
  @worker_max = Array.new WORKER_MAX_KEYS.length, 0
29
30
  end
30
31
 
@@ -54,6 +55,21 @@ module Puma
54
55
  @term
55
56
  end
56
57
 
58
+ def mold?
59
+ @mold
60
+ end
61
+
62
+ def mold!
63
+ @mold = true
64
+ Process.kill "URG", @pid
65
+ rescue Errno::ESRCH
66
+ end
67
+
68
+ def retire!
69
+ Process.kill "URG", @pid
70
+ rescue Errno::ESRCH
71
+ end
72
+
57
73
  def ping!(status)
58
74
  hsh = {}
59
75
  k, v = nil, nil
data/lib/puma/cluster.rb CHANGED
@@ -15,6 +15,9 @@ module Puma
15
15
  # via the `spawn_workers` method call. Each worker will have it's own
16
16
  # instance of a `Puma::Server`.
17
17
  class Cluster < Runner
18
+ MOLD_FORK_FORMAT = "L"
19
+ MOLD_FORK_BYTES = 4
20
+
18
21
  def initialize(launcher)
19
22
  super(launcher)
20
23
 
@@ -24,6 +27,11 @@ module Puma
24
27
 
25
28
  @worker_max = [] # keeps track of 'max' stat values
26
29
  @pending_phased_restart = false
30
+ @promoted_mold = nil
31
+ @mold = nil
32
+ @retired_molds = []
33
+ @mold_ready = false
34
+ @mold_threshold_index = 0
27
35
  end
28
36
 
29
37
  # Returns the list of cluster worker handles.
@@ -32,12 +40,12 @@ module Puma
32
40
 
33
41
  def stop_workers
34
42
  log "- Gracefully shutting down workers..."
35
- @workers.each { |x| x.term }
43
+ (@workers + molds).each { |x| x.term }
36
44
 
37
45
  begin
38
46
  loop do
39
47
  wait_workers
40
- break if @workers.reject {|w| w.pid.nil?}.empty?
48
+ break if @workers.reject {|w| w.pid.nil?}.empty? && molds.empty?
41
49
  sleep 0.2
42
50
  end
43
51
  rescue Interrupt
@@ -69,7 +77,7 @@ module Puma
69
77
 
70
78
  def spawn_workers
71
79
  diff = @options[:workers] - @workers.size
72
- return if diff < 1
80
+ return if diff < 1 || @promoted_mold
73
81
 
74
82
  master = Process.pid
75
83
  if @options[:fork_worker]
@@ -82,6 +90,9 @@ module Puma
82
90
  if @options[:fork_worker] && idx != 0
83
91
  @fork_writer << "#{idx}\n"
84
92
  pid = nil
93
+ elsif @mold
94
+ @fork_writer << [idx].pack(MOLD_FORK_FORMAT)
95
+ pid = nil
85
96
  else
86
97
  pid = spawn_worker(idx, master)
87
98
  end
@@ -168,6 +179,8 @@ module Puma
168
179
  end
169
180
 
170
181
  def all_workers_idle_timed_out?
182
+ return false if @pending_phased_restart || @workers.empty?
183
+
171
184
  (@workers.map(&:pid) - idle_timed_out_worker_pids).empty?
172
185
  end
173
186
 
@@ -206,6 +219,10 @@ module Puma
206
219
  t.map!(&:ping_timeout)
207
220
 
208
221
  @next_check = [t.min, @next_check].compact.min
222
+ if @options[:fork_worker] && @workers.any?(&:term?)
223
+ # Orphaned workers cannot wake the master through worker 0 as they exit.
224
+ @next_check = [@next_check, Time.now + 0.1].min
225
+ end
209
226
  end
210
227
 
211
228
  def worker(index, master)
@@ -216,7 +233,7 @@ module Puma
216
233
  @fork_writer.close
217
234
 
218
235
  pipes = { check_pipe: @check_pipe, worker_write: @worker_write }
219
- if @options[:fork_worker]
236
+ if refork?
220
237
  pipes[:fork_pipe] = @fork_pipe
221
238
  pipes[:wakeup] = @wakeup
222
239
  end
@@ -252,7 +269,6 @@ module Puma
252
269
  @status = :stop if @status == :run
253
270
  wakeup!
254
271
  @control&.stop true
255
- Process.waitall
256
272
  end
257
273
 
258
274
  def halt
@@ -299,14 +315,22 @@ module Puma
299
315
  @options[:preload_app]
300
316
  end
301
317
 
318
+ def refork?
319
+ @options[:fork_worker] || @options[:mold_worker]
320
+ end
321
+
302
322
  # @version 5.0.0
303
323
  def fork_worker!
304
324
  if (worker = worker_at 0)
305
- worker.phase += 1
325
+ worker.phase = @phase + 1
306
326
  end
307
327
  phased_restart(true)
308
328
  end
309
329
 
330
+ def mold_worker!
331
+ phased_restart(true)
332
+ end
333
+
310
334
  # We do this in a separate method to keep the lambda scope
311
335
  # of the signals handlers as small as possible.
312
336
  def setup_signals
@@ -325,6 +349,24 @@ module Puma
325
349
  end
326
350
  end
327
351
 
352
+ if @options[:mold_worker]
353
+ Signal.trap "SIGURG" do
354
+ mold_worker!
355
+ end
356
+
357
+ @events.register(:ping!) do |w|
358
+ threshold = @options[:mold_worker][@mold_threshold_index]
359
+ next unless threshold &&
360
+ !w.mold? &&
361
+ !@pending_phased_restart &&
362
+ w.last_status[:requests_count] >= threshold &&
363
+ all_workers_in_phase?
364
+
365
+ @mold_threshold_index += 1
366
+ mold_worker!
367
+ end
368
+ end
369
+
328
370
  Signal.trap "SIGCHLD" do
329
371
  wakeup!
330
372
  end
@@ -375,7 +417,7 @@ module Puma
375
417
 
376
418
  before = Thread.list.reject(&fork_safe)
377
419
 
378
- log "* Restarts: (\u2714) hot (\u2716) phased (#{@options[:fork_worker] ? "\u2714" : "\u2716"}) refork"
420
+ log "* Restarts: (\u2714) hot (\u2716) phased (#{refork? ? "\u2714" : "\u2716"}) refork"
379
421
  log "* Preloading application"
380
422
  load_and_bind
381
423
 
@@ -393,7 +435,7 @@ module Puma
393
435
  end
394
436
  end
395
437
  else
396
- log "* Restarts: (\u2714) hot (\u2714) phased (#{@options[:fork_worker] ? "\u2714" : "\u2716"}) refork"
438
+ log "* Restarts: (\u2714) hot (\u2714) phased (#{refork? ? "\u2714" : "\u2716"}) refork"
397
439
 
398
440
  unless @config.app_configured?
399
441
  error "No application configured, nothing to run"
@@ -437,6 +479,9 @@ module Puma
437
479
 
438
480
  @config.run_hooks(:before_fork, nil, @log_writer)
439
481
 
482
+ # Reparent workers to the master if their mold exits.
483
+ Puma.enable_child_subreaper if @options[:mold_worker]
484
+
440
485
  spawn_workers
441
486
 
442
487
  Signal.trap "SIGINT" do
@@ -446,7 +491,6 @@ module Puma
446
491
  begin
447
492
  booted = false
448
493
  in_phased_restart = false
449
- workers_not_booted = @options[:workers]
450
494
 
451
495
  while @status == :run
452
496
  begin
@@ -455,15 +499,11 @@ module Puma
455
499
  break
456
500
  end
457
501
 
458
- if @pending_phased_restart
502
+ if @pending_phased_restart && prepare_phased_restart
459
503
  start_phased_restart(@pending_phased_restart == :refork)
460
504
 
461
505
  in_phased_restart = @pending_phased_restart
462
506
  @pending_phased_restart = false
463
-
464
- workers_not_booted = @options[:workers]
465
- # worker 0 is not restarted on refork
466
- workers_not_booted -= 1 if in_phased_restart == :refork
467
507
  end
468
508
 
469
509
  check_workers(in_phased_restart == :refork)
@@ -479,20 +519,28 @@ module Puma
479
519
 
480
520
  result = read.gets
481
521
  pid = result.to_i
522
+ w = (@workers + molds).find { |x| x.pid == pid }
482
523
 
483
- if req == PIPE_BOOT || req == PIPE_FORK
524
+ if !w && (req == PIPE_BOOT || req == PIPE_FORK)
484
525
  pid, idx = result.split(':').map(&:to_i)
485
526
  w = worker_at idx
486
- w.pid = pid if w.pid.nil?
527
+ if w && w.pid.nil?
528
+ w.pid = pid
529
+ else
530
+ w = nil
531
+ begin
532
+ Process.kill "KILL", pid
533
+ rescue Errno::ESRCH
534
+ end
535
+ end
487
536
  end
488
537
 
489
- if w = @workers.find { |x| x.pid == pid }
538
+ if w
490
539
  case req
491
540
  when PIPE_BOOT
492
541
  w.boot!
493
542
  log "- Worker #{w.index} (PID: #{pid}) booted in #{w.uptime.round(2)}s, phase: #{w.phase}"
494
543
  @next_check = Time.now
495
- workers_not_booted -= 1
496
544
  when PIPE_EXTERNAL_TERM
497
545
  # external term, see worker method, Signal.trap "SIGTERM"
498
546
  w.term!
@@ -503,7 +551,7 @@ module Puma
503
551
  w.ping!(status)
504
552
  @events.fire(:ping!, w)
505
553
 
506
- if in_phased_restart && @options[:fork_worker] && workers_not_booted.positive? && w0 = worker_at(0)
554
+ if in_phased_restart && @options[:fork_worker] && w0 = worker_at(0)
507
555
  w0.ping!(status)
508
556
  @events.fire(:ping!, w0)
509
557
  end
@@ -519,13 +567,17 @@ module Puma
519
567
  else
520
568
  idle_workers[pid] = true
521
569
  end
570
+ when PIPE_MOLD
571
+ activate_mold(w)
572
+ @next_check = Time.now
522
573
  end
523
574
  else
524
575
  log "! Out-of-sync worker list, no #{pid} worker"
525
576
  end
526
577
  end
527
578
 
528
- if in_phased_restart && workers_not_booted.zero?
579
+ if in_phased_restart && @workers.size == @options[:workers] && all_workers_booted? && all_workers_in_phase?
580
+ @retired_molds.each(&:term)
529
581
  @events.fire_after_booted!
530
582
  debug_loaded_extensions("Loaded Extensions - master:") if @log_writer.debug?
531
583
  in_phased_restart = false
@@ -574,43 +626,119 @@ module Puma
574
626
  end
575
627
  end
576
628
 
629
+ fork_worker_exited = false
577
630
  @workers.reject! do |w|
578
- next false if w.pid.nil?
579
- begin
580
- # We may need to check the PID individually because:
581
- # 1. From Ruby versions 2.6 to 3.2, `Process.detach` can prevent or delay
582
- # `Process.wait2(-1)` from detecting a terminated process: https://bugs.ruby-lang.org/issues/19837.
583
- # 2. When `fork_worker` is enabled, some worker may not be direct children,
584
- # but grand children. Because of this they won't be reaped by `Process.wait2(-1)`.
585
- if (status = reaped_children.delete(w.pid) || Process.wait2(w.pid, Process::WNOHANG)&.last)
586
- w.process_status = status
587
- @config.run_hooks(:after_worker_shutdown, w, @log_writer)
588
- true
589
- else
590
- w.term if w.term?
591
- nil
592
- end
593
- rescue Errno::ECHILD
594
- begin
595
- Process.kill(0, w.pid)
596
- # child still alive but has another parent (e.g., using fork_worker)
597
- w.term if w.term?
598
- false
599
- rescue Errno::ESRCH, Errno::EPERM
600
- true # child is already terminated
601
- end
631
+ next w.term? if w.pid.nil?
632
+
633
+ status = reap(w, reaped_children)
634
+ fork_worker_exited = true if status && @options[:fork_worker] && w.index == 0
635
+ if status.is_a?(Process::Status)
636
+ w.process_status = status
637
+ @config.run_hooks(:after_worker_shutdown, w, @log_writer)
602
638
  end
639
+ status
603
640
  end
604
641
 
642
+ clear_pending_workers if fork_worker_exited
643
+ @promoted_mold = nil if @promoted_mold && reap(@promoted_mold, reaped_children)
644
+ if @mold && reap(@mold, reaped_children)
645
+ @mold = nil
646
+ clear_pending_workers
647
+ end
648
+ @retired_molds.reject! { |m| reap(m, reaped_children) }
649
+
605
650
  # Log unknown children
606
651
  reaped_children.each do |pid, status|
607
652
  log "! reaped unknown child process pid=#{pid} status=#{status}"
608
653
  end
609
654
  end
610
655
 
656
+ def clear_pending_workers
657
+ @workers.reject! { |w| w.pid.nil? }
658
+ while @fork_pipe.read_nonblock(4096, exception: false).is_a?(String)
659
+ end
660
+ end
661
+
662
+ # Returns the process status once the process has exited, true if it has
663
+ # exited but its status cannot be collected, or nil if it is still running.
664
+ def reap(handle, reaped_children)
665
+ # We may need to check the PID individually because:
666
+ # 1. From Ruby versions 2.6 to 3.2, `Process.detach` can prevent or delay
667
+ # `Process.wait2(-1)` from detecting a terminated process: https://bugs.ruby-lang.org/issues/19837.
668
+ # 2. When `fork_worker` or `mold_worker` is enabled, some workers may not be direct children,
669
+ # but grandchildren. Because of this they won't be reaped by `Process.wait2(-1)`.
670
+ status = reaped_children.delete(handle.pid) || Process.wait2(handle.pid, Process::WNOHANG)&.last
671
+ handle.term if !status && handle.term?
672
+ status
673
+ rescue Errno::ECHILD
674
+ begin
675
+ Process.kill(0, handle.pid)
676
+ # child still alive but has another parent (e.g., using fork_worker)
677
+ handle.term if handle.term?
678
+ nil
679
+ rescue Errno::ESRCH, Errno::EPERM
680
+ true # child is already terminated
681
+ end
682
+ end
683
+
684
+ def molds
685
+ [@promoted_mold, @mold, *@retired_molds].compact
686
+ end
687
+
688
+ # Returns true once workers can be restarted. With `mold_worker`, a refork
689
+ # first promotes a new mold and waits for it, while a phased restart
690
+ # retires all molds so workers are forked from the master.
691
+ def prepare_phased_restart
692
+ return true unless @options[:mold_worker]
693
+
694
+ if @pending_phased_restart != :refork
695
+ retire_molds
696
+ @mold_ready = false
697
+ @mold_threshold_index = 0
698
+ true
699
+ elsif @mold_ready
700
+ @mold_ready = false
701
+ true
702
+ else
703
+ promote_mold unless @promoted_mold
704
+ false
705
+ end
706
+ end
707
+
708
+ def promote_mold
709
+ candidate = @workers.select { |w| w.booted? && !w.term? }
710
+ .max_by { |w| w.last_status[:requests_count].to_i }
711
+ return unless candidate
712
+
713
+ log "- Promoting worker #{candidate.index} (PID: #{candidate.pid}) to mold"
714
+ @workers.delete candidate
715
+ @promoted_mold = candidate
716
+ candidate.mold!
717
+ end
718
+
719
+ def activate_mold(mold)
720
+ return unless mold == @promoted_mold
721
+
722
+ log "- Mold (PID: #{mold.pid}) ready"
723
+ @promoted_mold = nil
724
+ retire_molds
725
+ @mold = mold
726
+ @mold_ready = true
727
+ end
728
+
729
+ # A promoted mold has forked no workers, so it is stopped now. An active
730
+ # mold stops forking, and is stopped once the restart completes.
731
+ def retire_molds
732
+ @promoted_mold&.term
733
+ @mold&.retire!
734
+ @retired_molds.concat [@promoted_mold, @mold].compact
735
+ @promoted_mold = nil
736
+ @mold = nil
737
+ end
738
+
611
739
  # @version 5.0.0
612
740
  def timeout_workers
613
- @workers.each do |w|
741
+ (@workers + molds).each do |w|
614
742
  if !w.term? && w.ping_timeout <= Time.now
615
743
  details = if w.booted?
616
744
  "(Worker #{w.index} failed to check in within #{@options[:worker_timeout]} seconds)"