Class: Puma::Cluster

Inherits:
Runner show all
Defined in:
lib/puma/cluster.rb,
lib/puma/cluster/worker.rb,
lib/puma/cluster/worker_handle.rb

Overview

This class is instantiated by the ‘Puma::Launcher` and used to boot and serve a Ruby application when puma “workers” are needed i.e. when using multi-processes. For example `$ puma -w 5`

An instance of this class will spawn the number of processes passed in via the ‘spawn_workers` method call. Each worker will have it’s own instance of a ‘Puma::Server`.

Defined Under Namespace

Classes: Worker, WorkerHandle

Instance Attribute Summary collapse

Attributes inherited from Runner

#app, #options, #ruby_engine

Instance Method Summary collapse

Methods inherited from Runner

#close_control_listeners, #debug, #development?, #error, #load_and_bind, #log, #output_header, #redirected_io?, #start_control, #start_server, #stop_control, #test?, #wakeup!

Constructor Details

#initialize(launcher) ⇒ Cluster

Returns a new instance of Cluster.



18
19
20
21
22
23
24
25
26
# File 'lib/puma/cluster.rb', line 18

def initialize(launcher)
  super(launcher)

  @phase = 0
  @workers = []
  @next_check = Time.now

  @phased_restart = false
end

Instance Attribute Details

#next_worker_indexObject (readonly)



142
143
144
145
146
147
# File 'lib/puma/cluster.rb', line 142

def next_worker_index
  occupied_positions = @workers.map(&:index)
  idx = 0
  idx += 1 until !occupied_positions.include?(idx)
  idx
end

#statsObject (readonly)

Inside of a child process, this will return all zeroes, as @workers is only populated in the master process.



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/puma/cluster.rb', line 255

def stats
  old_worker_count = @workers.count { |w| w.phase != @phase }
  worker_status = @workers.map do |w|
    {
      started_at: utc_iso8601(w.started_at),
      pid: w.pid,
      index: w.index,
      phase: w.phase,
      booted: w.booted?,
      last_checkin: utc_iso8601(w.last_checkin),
      last_status: w.last_status,
    }
  end

  {
    started_at: utc_iso8601(@started_at),
    workers: @workers.size,
    phase: @phase,
    booted_workers: worker_status.count { |w| w[:booted] },
    old_workers: old_worker_count,
    worker_status: worker_status,
  }.merge(super)
end

#workersArray<Puma::Cluster::WorkerHandle> (readonly)

Returns the list of cluster worker handles.

Returns:



30
31
32
# File 'lib/puma/cluster.rb', line 30

def workers
  @workers
end

Instance Method Details

#all_workers_booted?Boolean

Returns:

  • (Boolean)


153
154
155
# File 'lib/puma/cluster.rb', line 153

def all_workers_booted?
  @workers.count { |w| !w.booted? } == 0
end

#all_workers_in_phase?Boolean

Returns:

  • (Boolean)


157
158
159
# File 'lib/puma/cluster.rb', line 157

def all_workers_in_phase?
  @workers.all? { |w| w.phase == @phase }
end

#check_workersObject



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/puma/cluster.rb', line 161

def check_workers
  return if @next_check >= Time.now

  @next_check = Time.now + @options[:worker_check_interval]

  timeout_workers
  wait_workers
  cull_workers
  spawn_workers

  if all_workers_booted?
    # If we're running at proper capacity, check to see if
    # we need to phase any workers out (which will restart
    # in the right phase).
    #
    w = @workers.find { |x| x.phase != @phase }

    if w
      log "- Stopping #{w.pid} for phased upgrade..."
      unless w.term?
        w.term
        log "- #{w.signal} sent to #{w.pid}..."
      end
    end
  end

  t = @workers.reject(&:term?)
  t.map!(&:ping_timeout)

  @next_check = [t.min, @next_check].compact.min
end

#cull_start_index(diff) ⇒ Object



132
133
134
135
136
137
138
139
# File 'lib/puma/cluster.rb', line 132

def cull_start_index(diff)
  case @options[:worker_culling_strategy]
  when :oldest
    0
  else # :youngest
    -diff
  end
end

#cull_workersObject



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/puma/cluster.rb', line 108

def cull_workers
  diff = @workers.size - @options[:workers]
  return if diff < 1
  debug "Culling #{diff} workers"

  workers = workers_to_cull(diff)
  debug "Workers to cull: #{workers.inspect}"

  workers.each do |worker|
    log "- Worker #{worker.index} (PID: #{worker.pid}) terminating"
    worker.term
  end
end

#fork_worker!Object

Version:

  • 5.0.0



284
285
286
287
288
289
# File 'lib/puma/cluster.rb', line 284

def fork_worker!
  if (worker = worker_at 0)
    worker.phase += 1
  end
  phased_restart(true)
end

#haltObject



241
242
243
244
# File 'lib/puma/cluster.rb', line 241

def halt
  @status = :halt
  wakeup!
end

#phased_restart(refork = false) ⇒ Object



220
221
222
223
224
225
226
227
# File 'lib/puma/cluster.rb', line 220

def phased_restart(refork = false)
  return false if @options[:preload_app] && !refork

  @phased_restart = true
  wakeup!

  true
end

#preload?Boolean

Returns:

  • (Boolean)


279
280
281
# File 'lib/puma/cluster.rb', line 279

def preload?
  @options[:preload_app]
end

#redirect_ioObject



59
60
61
62
63
# File 'lib/puma/cluster.rb', line 59

def redirect_io
  super

  @workers.each { |x| x.hup }
end

#reload_worker_directoryObject



246
247
248
249
250
# File 'lib/puma/cluster.rb', line 246

def reload_worker_directory
  dir = @launcher.restart_dir
  log "+ Changing to #{dir}"
  Dir.chdir dir
end

#restartObject



215
216
217
218
# File 'lib/puma/cluster.rb', line 215

def restart
  @restart = true
  stop
end

#runObject



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/puma/cluster.rb', line 344

def run
  @status = :run

  output_header "cluster"

  # This is aligned with the output from Runner, see Runner#output_header
  log "*      Workers: #{@options[:workers]}"

  if preload?
    # Threads explicitly marked as fork safe will be ignored. Used in Rails,
    # but may be used by anyone. Note that we need to explicit
    # Process::Waiter check here because there's a bug in Ruby 2.6 and below
    # where calling thread_variable_get on a Process::Waiter will segfault.
    # We can drop that clause once those versions of Ruby are no longer
    # supported.
    fork_safe = ->(t) { !t.is_a?(Process::Waiter) && t.thread_variable_get(:fork_safe) }

    before = Thread.list.reject(&fork_safe)

    log "*     Restarts: (\u2714) hot (\u2716) phased"
    log "* Preloading application"
    load_and_bind

    after = Thread.list.reject(&fork_safe)

    if after.size > before.size
      threads = (after - before)
      if threads.first.respond_to? :backtrace
        log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot:"
        threads.each do |t|
          log "! #{t.inspect} - #{t.backtrace ? t.backtrace.first : ''}"
        end
      else
        log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot"
      end
    end
  else
    log "*     Restarts: (\u2714) hot (\u2714) phased"

    unless @config.app_configured?
      error "No application configured, nothing to run"
      exit 1
    end

    @launcher.binder.parse @options[:binds]
  end

  read, @wakeup = Puma::Util.pipe

  setup_signals

  # Used by the workers to detect if the master process dies.
  # If select says that @check_pipe is ready, it's because the
  # master has exited and @suicide_pipe has been automatically
  # closed.
  #
  @check_pipe, @suicide_pipe = Puma::Util.pipe

  # Separate pipe used by worker 0 to receive commands to
  # fork new worker processes.
  @fork_pipe, @fork_writer = Puma::Util.pipe

  log "Use Ctrl-C to stop"

  single_worker_warning

  redirect_io

  Plugins.fire_background

  @launcher.write_state

  start_control

  @master_read, @worker_write = read, @wakeup

  @config.run_hooks(:before_fork, nil, @log_writer)

  spawn_workers

  Signal.trap "SIGINT" do
    stop
  end

  begin
    booted = false
    in_phased_restart = false
    workers_not_booted = @options[:workers]

    while @status == :run
      begin
        if @phased_restart
          start_phased_restart
          @phased_restart = false
          in_phased_restart = true
          workers_not_booted = @options[:workers]
        end

        check_workers

        if read.wait_readable([0, @next_check - Time.now].max)
          req = read.read_nonblock(1)

          @next_check = Time.now if req == "!"
          next if !req || req == "!"

          result = read.gets
          pid = result.to_i

          if req == "b" || req == "f"
            pid, idx = result.split(':').map(&:to_i)
            w = worker_at idx
            w.pid = pid if w.pid.nil?
          end

          if w = @workers.find { |x| x.pid == pid }
            case req
            when "b"
              w.boot!
              log "- Worker #{w.index} (PID: #{pid}) booted in #{w.uptime.round(2)}s, phase: #{w.phase}"
              @next_check = Time.now
              workers_not_booted -= 1
            when "e"
              # external term, see worker method, Signal.trap "SIGTERM"
              w.term!
            when "t"
              w.term unless w.term?
            when "p"
              status = result.sub(/^\d+/,'').chomp
              w.ping!(status)
              @events.fire(:ping!, w)

              if in_phased_restart && workers_not_booted.positive? && w0 = worker_at(0)
                w0.ping!(status)
                @events.fire(:ping!, w0)
              end

              if !booted && @workers.none? {|worker| worker.last_status.empty?}
                @events.fire_on_booted!
                debug_loaded_extensions("Loaded Extensions - master:") if @log_writer.debug?
                booted = true
              end
            end
          else
            log "! Out-of-sync worker list, no #{pid} worker"
          end
        end
        if in_phased_restart && workers_not_booted.zero?
          @events.fire_on_booted!
          debug_loaded_extensions("Loaded Extensions - master:") if @log_writer.debug?
          in_phased_restart = false
        end

      rescue Interrupt
        @status = :stop
      end
    end

    stop_workers unless @status == :halt
  ensure
    @check_pipe.close
    @suicide_pipe.close
    read.close
    @wakeup.close
  end
end

#setup_signalsObject

We do this in a separate method to keep the lambda scope of the signals handlers as small as possible.



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/puma/cluster.rb', line 293

def setup_signals
  if @options[:fork_worker]
    Signal.trap "SIGURG" do
      fork_worker!
    end

    # Auto-fork after the specified number of requests.
    if (fork_requests = @options[:fork_worker].to_i) > 0
      @events.register(:ping!) do |w|
        fork_worker! if w.index == 0 &&
          w.phase == 0 &&
          w.last_status[:requests_count] >= fork_requests
      end
    end
  end

  Signal.trap "SIGCHLD" do
    wakeup!
  end

  Signal.trap "TTIN" do
    @options[:workers] += 1
    wakeup!
  end

  Signal.trap "TTOU" do
    @options[:workers] -= 1 if @options[:workers] >= 2
    wakeup!
  end

  master_pid = Process.pid

  Signal.trap "SIGTERM" do
    # The worker installs their own SIGTERM when booted.
    # Until then, this is run by the worker and the worker
    # should just exit if they get it.
    if Process.pid != master_pid
      log "Early termination of worker"
      exit! 0
    else
      @launcher.close_binder_listeners

      stop_workers
      stop
      @events.fire_on_stopped!
      raise(SignalException, "SIGTERM") if @options[:raise_exception_on_sigterm]
      exit 0 # Clean exit, workers were stopped
    end
  end
end

#spawn_worker(idx, master) ⇒ Object

Version:

  • 5.0.0



94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/puma/cluster.rb', line 94

def spawn_worker(idx, master)
  @config.run_hooks(:before_worker_fork, idx, @log_writer)

  pid = fork { worker(idx, master) }
  if !pid
    log "! Complete inability to spawn new workers detected"
    log "! Seppuku is the only choice."
    exit! 1
  end

  @config.run_hooks(:after_worker_fork, idx, @log_writer)
  pid
end

#spawn_workersObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/puma/cluster.rb', line 65

def spawn_workers
  diff = @options[:workers] - @workers.size
  return if diff < 1

  master = Process.pid
  if @options[:fork_worker]
    @fork_writer << "-1\n"
  end

  diff.times do
    idx = next_worker_index

    if @options[:fork_worker] && idx != 0
      @fork_writer << "#{idx}\n"
      pid = nil
    else
      pid = spawn_worker(idx, master)
    end

    debug "Spawned worker: #{pid}"
    @workers << WorkerHandle.new(idx, pid, @phase, @options)
  end

  if @options[:fork_worker] && all_workers_in_phase?
    @fork_writer << "0\n"
  end
end

#start_phased_restartObject



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/puma/cluster.rb', line 47

def start_phased_restart
  @events.fire_on_restart!
  @phase += 1
  log "- Starting phased worker restart, phase: #{@phase}"

  # Be sure to change the directory again before loading
  # the app. This way we can pick up new code.
  dir = @launcher.restart_dir
  log "+ Changing to #{dir}"
  Dir.chdir dir
end

#stopObject



229
230
231
232
# File 'lib/puma/cluster.rb', line 229

def stop
  @status = :stop
  wakeup!
end

#stop_blockedObject



234
235
236
237
238
239
# File 'lib/puma/cluster.rb', line 234

def stop_blocked
  @status = :stop if @status == :run
  wakeup!
  @control&.stop true
  Process.waitall
end

#stop_workersObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/puma/cluster.rb', line 32

def stop_workers
  log "- Gracefully shutting down workers..."
  @workers.each { |x| x.term }

  begin
    loop do
      wait_workers
      break if @workers.reject {|w| w.pid.nil?}.empty?
      sleep 0.2
    end
  rescue Interrupt
    log "! Cancelled waiting for workers"
  end
end

#worker(index, master) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/puma/cluster.rb', line 193

def worker(index, master)
  @workers = []

  @master_read.close
  @suicide_pipe.close
  @fork_writer.close

  pipes = { check_pipe: @check_pipe, worker_write: @worker_write }
  if @options[:fork_worker]
    pipes[:fork_pipe] = @fork_pipe
    pipes[:wakeup] = @wakeup
  end

  server = start_server if preload?
  new_worker = Worker.new index: index,
                          master: master,
                          launcher: @launcher,
                          pipes: pipes,
                          server: server
  new_worker.run
end

#worker_at(idx) ⇒ Object



149
150
151
# File 'lib/puma/cluster.rb', line 149

def worker_at(idx)
  @workers.find { |w| w.index == idx }
end

#workers_to_cull(diff) ⇒ Object



122
123
124
125
126
127
128
129
130
# File 'lib/puma/cluster.rb', line 122

def workers_to_cull(diff)
  workers = @workers.sort_by(&:started_at)

  # In fork_worker mode, worker 0 acts as our master process.
  # We should avoid culling it to preserve copy-on-write memory gains.
  workers.reject! { |w| w.index == 0 } if @options[:fork_worker]

  workers[cull_start_index(diff), diff]
end