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/lib/puma/client.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require_relative 'detect'
4
4
  require_relative 'io_buffer'
5
5
  require_relative 'client_env'
6
+ require_relative 'null_io'
6
7
  require 'tempfile'
7
8
 
8
9
  if Puma::IS_JRUBY
@@ -18,6 +19,17 @@ module Puma
18
19
 
19
20
  class HttpParserError501 < IOError; end
20
21
 
22
+ # Raised when a +continue_callback+ answers an <tt>Expect: 100-continue</tt>
23
+ # request itself, so the request body is never read.
24
+ class ContinueRejected < StandardError
25
+ attr_reader :response
26
+
27
+ def initialize(response)
28
+ super("Expect: 100-continue answered by continue_callback")
29
+ @response = response
30
+ end
31
+ end
32
+
21
33
  #———————————————————————— DO NOT USE — this class is for internal use only ———
22
34
 
23
35
 
@@ -46,14 +58,16 @@ module Puma
46
58
  ALLOWED_TRANSFER_ENCODING = %w[compress deflate gzip].freeze
47
59
 
48
60
  # chunked body validation
49
- CHUNK_SIZE_INVALID = /[^\h]/.freeze
61
+ CHUNK_SIZE_VALID = /\A\h+\z/.freeze
50
62
  CHUNK_VALID_ENDING = Const::LINE_END
51
63
  CHUNK_VALID_ENDING_SIZE = CHUNK_VALID_ENDING.bytesize
52
64
 
53
65
  # The maximum number of bytes we'll buffer looking for a valid
54
- # chunk header.
66
+ # chunk header, and the maximum size of a trailer section.
55
67
  MAX_CHUNK_HEADER_SIZE = 4096
56
68
 
69
+ SHUTDOWN_READ_GRACE = 1
70
+
57
71
  # The maximum amount of excess data the client sends
58
72
  # using chunk size extensions before we abort the connection.
59
73
  MAX_CHUNK_EXCESS = 16 * 1024
@@ -74,11 +88,13 @@ module Puma
74
88
 
75
89
  attr_reader :env, :to_io, :body, :io, :timeout_at, :ready, :hijacked,
76
90
  :tempfile, :io_buffer, :http_content_length_limit_exceeded,
77
- :requests_served, :error_status_code
91
+ :requests_served, :error_status_code, :bytes_read
78
92
 
79
- attr_writer :peerip, :http_content_length_limit, :supported_http_methods
93
+ attr_writer :peerip, :http_content_length_limit, :supported_http_methods,
94
+ :allow_underscore_headers, :continue_callback
80
95
 
81
- attr_accessor :remote_addr_header, :listener, :env_set_http_version
96
+ attr_accessor :remote_addr_header, :listener, :env_set_http_version,
97
+ :reactor_error
82
98
 
83
99
  def initialize(io, env=nil)
84
100
  @io = io
@@ -105,7 +121,10 @@ module Puma
105
121
 
106
122
  @http_content_length_limit = nil
107
123
  @http_content_length_limit_exceeded = nil
124
+ @allow_underscore_headers = true
125
+ @continue_callback = nil
108
126
  @error_status_code = nil
127
+ @reactor_error = nil
109
128
 
110
129
  @peerip = nil
111
130
  @peer_family = nil
@@ -114,6 +133,8 @@ module Puma
114
133
  @expect_proxy_proto = false
115
134
 
116
135
  @body_remain = 0
136
+ @bytes_read = 0
137
+ @pending_write = nil
117
138
 
118
139
  @in_last_chunk = false
119
140
 
@@ -248,8 +269,9 @@ module Puma
248
269
  true
249
270
  end
250
271
 
251
- def try_to_finish
252
- return read_body if in_data_phase
272
+ def try_to_finish(&deadline)
273
+ return false unless flush_pending_write
274
+ return read_body(&deadline) if in_data_phase
253
275
 
254
276
  data = nil
255
277
  begin
@@ -269,6 +291,7 @@ module Puma
269
291
  raise EOFError
270
292
  end
271
293
 
294
+ @bytes_read += data.bytesize
272
295
  if @buffer
273
296
  @buffer << data
274
297
  else
@@ -282,18 +305,54 @@ module Puma
282
305
  @parser.finished? ? process_env_body : false
283
306
  end
284
307
 
285
- def eagerly_finish
308
+ def eagerly_finish(&deadline)
286
309
  return true if @ready
287
- while @to_io.wait_readable(0) # rubocop: disable Style/WhileUntilModifier
288
- return true if try_to_finish
310
+ while !write_pending? && @to_io.wait_readable(0)
311
+ read = @bytes_read
312
+ return true if try_to_finish(&deadline)
313
+ check_deadline(&deadline) if deadline
314
+ return false if @bytes_read == read
289
315
  end
290
316
  false
291
317
  end
292
318
 
293
- def finish(timeout)
319
+ def finish(timeout, &deadline)
294
320
  return if @ready
295
- @to_io.wait_readable(timeout) || timeout! until try_to_finish
321
+ set_timeout timeout
322
+ read = @bytes_read
323
+ until try_to_finish(&deadline)
324
+ if @bytes_read > read
325
+ set_timeout timeout
326
+ read = @bytes_read
327
+ elsif self.timeout == 0
328
+ timeout!
329
+ end
330
+ if deadline
331
+ check_deadline(&deadline)
332
+ limit = yield
333
+ wait = [self.timeout, limit ? limit - Process.clock_gettime(Process::CLOCK_MONOTONIC) : 0.1].min
334
+ wait_io(wait) if wait > 0
335
+ else
336
+ wait_io(self.timeout) || timeout!
337
+ end
338
+ end
339
+ end
340
+
341
+ def write_pending?
342
+ !@pending_write.nil? || (@io.respond_to?(:write_pending?) && @io.write_pending?)
343
+ end
344
+
345
+ def take_pending_write
346
+ str = @pending_write
347
+ @pending_write = nil
348
+ str
349
+ end
350
+
351
+ def wait_io(timeout)
352
+ return @to_io.wait_readable(timeout) unless write_pending?
353
+ @to_io.wait_writable(timeout)
296
354
  end
355
+ private :wait_io
297
356
 
298
357
  # Wraps `@parser.execute` and adds meaningful error messages
299
358
  # @return [Integer] bytes of buffer read by parser
@@ -310,6 +369,8 @@ module Puma
310
369
  raise e unless HttpParserError === e && e.message.include?('non-SSL')
311
370
 
312
371
  req, _ = @buffer.split "\r\n\r\n"
372
+ raise e if req.nil? || req.empty?
373
+
313
374
  request_line, headers = req.split "\r\n", 2
314
375
 
315
376
  # below checks for request issues and changes error message accordingly
@@ -340,6 +401,7 @@ module Puma
340
401
 
341
402
  # processes the `env` and the request body
342
403
  def process_env_body
404
+ validate_env
343
405
  temp = setup_body
344
406
  normalize_env
345
407
  req_env_post_parse
@@ -354,11 +416,41 @@ module Puma
354
416
 
355
417
  def write_error(status_code)
356
418
  begin
357
- @io << ERROR_RESPONSE[status_code]
419
+ write_interim ERROR_RESPONSE[status_code]
358
420
  rescue StandardError
359
421
  end
360
422
  end
361
423
 
424
+ def write_interim(str)
425
+ if @pending_write
426
+ @pending_write << str
427
+ return flush_pending_write
428
+ end
429
+
430
+ n = @io.write_nonblock(str, exception: false)
431
+ if n == :wait_writable
432
+ @pending_write = +str unless @io.respond_to?(:write_pending?) && @io.write_pending?
433
+ elsif n < str.bytesize
434
+ @pending_write = str.byteslice(n..-1)
435
+ end
436
+ rescue SystemCallError, IOError
437
+ raise ConnectionError, "Connection error detected during write"
438
+ end
439
+ private :write_interim
440
+
441
+ def flush_pending_write
442
+ return true unless @pending_write
443
+
444
+ n = @io.write_nonblock(@pending_write, exception: false)
445
+ return false if n == :wait_writable
446
+
447
+ @pending_write = n == @pending_write.bytesize ? nil : @pending_write.byteslice(n..-1)
448
+ @pending_write.nil?
449
+ rescue SystemCallError, IOError
450
+ raise ConnectionError, "Connection error detected during write"
451
+ end
452
+ private :flush_pending_write
453
+
362
454
  def peerip
363
455
  return @peerip if @peerip
364
456
 
@@ -422,12 +514,22 @@ module Puma
422
514
  # @return [Boolean] true if the body can be completely read, false otherwise
423
515
  #
424
516
  def setup_body
517
+ # The parsers preserve underscores as commas to distinguish these aliases
518
+ # from real framing headers. Reject them before 100 Continue or body reads,
519
+ # regardless of allow_underscore_headers, to avoid proxy disagreements.
520
+ if @env.key?('HTTP_CONTENT,LENGTH') || @env.key?('HTTP_TRANSFER,ENCODING')
521
+ @error_status_code = 400
522
+ @env[HTTP_CONNECTION] = CLOSE
523
+ raise HttpParserError, 'Underscores are not allowed in HTTP framing headers'
524
+ end
525
+
425
526
  @body_read_start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
426
527
 
427
528
  if @env[HTTP_EXPECT] == CONTINUE
428
- # TODO allow a hook here to check the headers before going forward
429
- @io << HTTP_11_100
430
- @io.flush
529
+ if @continue_callback && (response = @continue_callback.call(@env))
530
+ reject_continue response
531
+ end
532
+ write_interim HTTP_11_100
431
533
  end
432
534
 
433
535
  @read_header = false
@@ -522,9 +624,9 @@ module Puma
522
624
  false
523
625
  end
524
626
 
525
- def read_body
627
+ def read_body(&deadline)
526
628
  if @chunked_body
527
- return read_chunked_body
629
+ return read_chunked_body(&deadline)
528
630
  end
529
631
 
530
632
  # Read an odd sized chunk so we can read even sized ones
@@ -549,6 +651,7 @@ module Puma
549
651
  raise EOFError
550
652
  end
551
653
 
654
+ @bytes_read += chunk.bytesize
552
655
  remain -= @body.write(chunk)
553
656
  end
554
657
 
@@ -563,7 +666,7 @@ module Puma
563
666
  end
564
667
  end
565
668
 
566
- def read_chunked_body
669
+ def read_chunked_body(&deadline)
567
670
  while true
568
671
  begin
569
672
  chunk = @io.read_nonblock(CHUNK_SIZE, @read_buffer)
@@ -581,13 +684,27 @@ module Puma
581
684
  raise EOFError
582
685
  end
583
686
 
687
+ @bytes_read += chunk.bytesize
584
688
  if decode_chunk(chunk)
585
689
  @env[CONTENT_LENGTH] = @chunked_content_length.to_s
586
690
  return true
587
691
  end
692
+
693
+ check_deadline(&deadline) if deadline
588
694
  end
589
695
  end
590
696
 
697
+ def check_deadline
698
+ limit = yield
699
+ return unless limit
700
+
701
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
702
+ return if now < limit
703
+ return if now < limit + SHUTDOWN_READ_GRACE && @to_io.wait_readable(0)
704
+
705
+ timeout!
706
+ end
707
+
591
708
  def setup_chunked_body(body)
592
709
  @chunked_body = true
593
710
  @partial_part_left = 0
@@ -616,6 +733,8 @@ module Puma
616
733
  end
617
734
 
618
735
  def decode_chunk(chunk)
736
+ return finish_last_chunk(@prev_chunk + chunk) if @in_last_chunk
737
+
619
738
  if @partial_part_left > 0
620
739
  if @partial_part_left <= chunk.size
621
740
  if @partial_part_left > 2
@@ -651,31 +770,18 @@ module Puma
651
770
  # Puma doesn't process chunk extensions, but should parse if they're
652
771
  # present, which is the reason for the semicolon regex
653
772
  chunk_hex = line.strip[/\A[^;]+/]
654
- if CHUNK_SIZE_INVALID.match? chunk_hex
655
- raise HttpParserError, "Invalid chunk size: '#{chunk_hex}'"
773
+ unless CHUNK_SIZE_VALID.match? chunk_hex
774
+ err_msg = chunk_hex && !chunk_hex.empty? ?
775
+ "Invalid chunk size: '#{chunk_hex}'" :
776
+ "Chunk size cannot be empty or nil"
777
+ raise HttpParserError, err_msg
656
778
  end
779
+
657
780
  len = chunk_hex.to_i(16)
658
781
  if len == 0
659
782
  @in_last_chunk = true
660
783
  @body.rewind
661
- rest = io.read
662
- if rest.bytesize < CHUNK_VALID_ENDING_SIZE
663
- @buffer = nil
664
- @partial_part_left = CHUNK_VALID_ENDING_SIZE - rest.bytesize
665
- return false
666
- else
667
- # if the next character is a CRLF, set buffer to everything after that CRLF
668
- start_of_rest = if rest.start_with?(CHUNK_VALID_ENDING)
669
- CHUNK_VALID_ENDING_SIZE
670
- else # we have started a trailer section, which we do not support. skip it!
671
- rest.index(CHUNK_VALID_ENDING*2) + CHUNK_VALID_ENDING_SIZE*2
672
- end
673
-
674
- @buffer = rest[start_of_rest..-1]
675
- @buffer = nil if @buffer.empty?
676
- set_ready
677
- return true
678
- end
784
+ return finish_last_chunk(io.read)
679
785
  end
680
786
 
681
787
  # Track the excess as a function of the size of the
@@ -728,12 +834,33 @@ module Puma
728
834
  end
729
835
  end
730
836
 
731
- if @in_last_chunk
732
- set_ready
733
- true
734
- else
735
- false
837
+ false
838
+ end
839
+
840
+ # Consume the terminator that ends a chunked body. Per RFC 9112 §7.1.2
841
+ # this is either a bare CRLF or an optional trailer section ending in
842
+ # CRLF*2. Puma does not surface trailers, so we skip past them. Bytes
843
+ # past the terminator belong to the next pipelined request.
844
+ def finish_last_chunk(rest)
845
+ if rest.start_with?(CHUNK_VALID_ENDING)
846
+ trailer_end = CHUNK_VALID_ENDING_SIZE
847
+ elsif idx = rest.index(CHUNK_VALID_ENDING * 2)
848
+ trailer_end = idx + CHUNK_VALID_ENDING_SIZE * 2
849
+ elsif rest.bytesize < MAX_CHUNK_HEADER_SIZE
850
+ @prev_chunk = rest
851
+ return false
736
852
  end
853
+
854
+ if trailer_end.nil? || trailer_end > MAX_CHUNK_HEADER_SIZE
855
+ @env[HTTP_CONNECTION] = CLOSE
856
+ raise HttpParserError, "maximum size of chunk trailer exceeded"
857
+ end
858
+
859
+ @prev_chunk = ""
860
+ @buffer = rest[trailer_end..-1]
861
+ @buffer = nil if @buffer.empty?
862
+ set_ready
863
+ true
737
864
  end
738
865
 
739
866
  def set_ready
@@ -744,6 +871,13 @@ module Puma
744
871
  @ready = true
745
872
  end
746
873
 
874
+ def reject_continue(response)
875
+ @buffer = nil
876
+ @body = EmptyBody
877
+ @env[HTTP_CONNECTION] = 'close'
878
+ raise ContinueRejected, response
879
+ end
880
+
747
881
  def raise_above_http_content_limit
748
882
  @http_content_length_limit_exceeded = true
749
883
  @buffer = nil
@@ -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