Class: Puma::Cluster

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

Defined Under Namespace

Classes: Worker

Instance Method Summary collapse

Methods inherited from Runner

#app, #before_restart, #daemon?, #debug, #development?, #error, #load_and_bind, #log, #output_header, #ruby_engine, #start_control, #start_server

Constructor Details

#initialize(cli, events) ⇒ Cluster

Returns a new instance of Cluster.



6
7
8
9
10
11
12
13
14
15
# File 'lib/puma/cluster.rb', line 6

def initialize(cli, events)
  super cli, events

  @phase = 0
  @workers = []
  @next_check = nil

  @phased_state = :idle
  @phased_restart = false
end

Instance Method Details

#all_workers_booted?Boolean

Returns:

  • (Boolean)


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

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

#check_workers(force = false) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
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
192
193
194
195
196
197
# File 'lib/puma/cluster.rb', line 149

def check_workers(force=false)
  return if !force && @next_check && @next_check >= Time.now

  @next_check = Time.now + 5

  any = false

  @workers.each do |w|
    next if !w.booted? && !w.ping_timeout?(@options[:worker_boot_timeout])
    if w.ping_timeout?(@options[:worker_timeout])
      log "! Terminating timed out worker: #{w.pid}"
      w.kill
      any = true
    end
  end

  # If we killed any timed out workers, try to catch them
  # during this loop by giving the kernel time to kill them.
  sleep 1 if any

  while @workers.any?
    pid = Process.waitpid(-1, Process::WNOHANG)
    break unless pid

    @workers.delete_if { |w| w.pid == pid }
  end

  @workers.delete_if(&:dead?)

  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
      if @phased_state == :idle
        @phased_state = :waiting
        log "- Stopping #{w.pid} for phased upgrade..."
      end

      w.term
      log "- #{w.signal} sent to #{w.pid}..."
    end
  end
end

#haltObject



304
305
306
307
# File 'lib/puma/cluster.rb', line 304

def halt
  @status = :halt
  wakeup!
end

#next_worker_indexObject



138
139
140
141
142
143
# File 'lib/puma/cluster.rb', line 138

def next_worker_index
  all_positions =  0...@options[:workers]
  occupied_positions = @workers.map { |w| w.index }
  available_positions = all_positions.to_a - occupied_positions
  available_positions.first
end

#phased_restartObject



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

def phased_restart
  return false if @options[:preload_app]

  @phased_restart = true
  wakeup!

  true
end

#preload?Boolean

Returns:

  • (Boolean)


322
323
324
# File 'lib/puma/cluster.rb', line 322

def preload?
  @options[:preload_app]
end

#redirect_ioObject



39
40
41
42
43
# File 'lib/puma/cluster.rb', line 39

def redirect_io
  super

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

#reload_worker_directoryObject



309
310
311
312
313
# File 'lib/puma/cluster.rb', line 309

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

#restartObject



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

def restart
  @restart = true
  stop
end

#runObject



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
# File 'lib/puma/cluster.rb', line 359

def run
  @status = :run

  output_header "cluster"

  log "* Process workers: #{@options[:workers]}"

  before = Thread.list

  if preload?
    log "* Preloading application"
    load_and_bind

    after = Thread.list

    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 "* Phased restart available"

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

    @launcher.binder.parse @options[:binds], self
  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

  if daemon?
    log "* Daemonizing..."
    Process.daemon(true)
  else
    log "Use Ctrl-C to stop"
  end

  redirect_io

  start_control

  @launcher.write_state

  @master_read, @worker_write = read, @wakeup

  @launcher.config.run_hooks :before_fork, nil

  spawn_workers

  Signal.trap "SIGINT" do
    stop
  end

  @launcher.events.fire_on_booted!

  begin
    force_check = false

    while @status == :run
      begin
        if @phased_restart
          start_phased_restart
          @phased_restart = false
        end

        check_workers force_check

        force_check = false

        res = IO.select([read], nil, nil, 5)

        if res
          req = read.read_nonblock(1)

          next if !req || req == "!"

          result = read.gets
          pid = result.to_i

          if w = @workers.find { |x| x.pid == pid }
            case req
            when "b"
              w.boot!
              log "- Worker #{w.index} (pid: #{pid}) booted, phase: #{w.phase}"
              force_check = true
            when "t"
              w.dead!
              force_check = true
            when "p"
              w.ping!(result.sub(/^\d+/,'').chomp)
            end
          else
            log "! Out-of-sync worker list, no #{pid} worker"
          end
        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 lambad scope of the signals handlers as small as possible.



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/puma/cluster.rb', line 328

def setup_signals
  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
    @workers.last.term
    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
      stop
    end
  end
end

#spawn_workersObject



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/puma/cluster.rb', line 111

def spawn_workers
  diff = @options[:workers] - @workers.size

  master = Process.pid

  diff.times do
    idx = next_worker_index
    @launcher.config.run_hooks :before_worker_fork, idx

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

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

    @launcher.config.run_hooks :after_worker_fork, idx
  end

  if diff > 0
    @phased_state = :idle
  end
end

#start_phased_restartObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/puma/cluster.rb', line 28

def start_phased_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

#statsObject



315
316
317
318
319
320
# File 'lib/puma/cluster.rb', line 315

def stats
  old_worker_count = @workers.count { |w| w.phase != @phase }
  booted_worker_count = @workers.count { |w| w.booted? }
  worker_status = '[' + @workers.map{ |w| %Q!{ "pid": #{w.pid}, "index": #{w.index}, "phase": #{w.phase}, "booted": #{w.booted?}, "last_checkin": "#{w.last_checkin.utc.iso8601}", "last_status": #{w.last_status} }!}.join(",") + ']'
  %Q!{ "workers": #{@workers.size}, "phase": #{@phase}, "booted_workers": #{booted_worker_count}, "old_workers": #{old_worker_count}, "worker_status": #{worker_status} }!
end

#stopObject



292
293
294
295
# File 'lib/puma/cluster.rb', line 292

def stop
  @status = :stop
  wakeup!
end

#stop_blockedObject



297
298
299
300
301
302
# File 'lib/puma/cluster.rb', line 297

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

#stop_workersObject



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

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

  begin
    Process.waitall
  rescue Interrupt
    log "! Cancelled waiting for workers"
  end
end

#wakeup!Object



199
200
201
202
203
204
205
206
# File 'lib/puma/cluster.rb', line 199

def wakeup!
  return unless @wakeup

  begin
    @wakeup.write "!" unless @wakeup.closed?
  rescue SystemCallError, IOError
  end
end

#worker(index, master) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/puma/cluster.rb', line 208

def worker(index, master)
  title = "puma: cluster worker #{index}: #{master}"
  title << " [#{@options[:tag]}]" if @options[:tag] && !@options[:tag].empty?
  $0 = title

  Signal.trap "SIGINT", "IGNORE"

  @workers = []
  @master_read.close
  @suicide_pipe.close

  Thread.new do
    IO.select [@check_pipe]
    log "! Detected parent died, dying"
    exit! 1
  end

  # If we're not running under a Bundler context, then
  # report the info about the context we will be using
  if !ENV['BUNDLE_GEMFILE']
    if File.exist?("Gemfile")
      log "+ Gemfile in context: #{File.expand_path("Gemfile")}"
    elsif File.exist?("gems.rb")
      log "+ Gemfile in context: #{File.expand_path("gems.rb")}"
    end
  end

  # Invoke any worker boot hooks so they can get
  # things in shape before booting the app.
  @launcher.config.run_hooks :before_worker_boot, index

  server = start_server

  Signal.trap "SIGTERM" do
    server.stop
  end

  begin
    @worker_write << "b#{Process.pid}\n"
  rescue SystemCallError, IOError
    STDERR.puts "Master seems to have exited, exiting."
    return
  end

  Thread.new(@worker_write) do |io|
    base_payload = "p#{Process.pid}"

    while true
      sleep 5
      begin
        b = server.backlog
        r = server.running
        payload = %Q!#{base_payload}{ "backlog":#{b}, "running":#{r} }\n!
        io << payload
      rescue IOError
        break
      end
    end
  end

  server.run.join

  # Invoke any worker shutdown hooks so they can prevent the worker
  # exiting until any background operations are completed
  @launcher.config.run_hooks :before_worker_shutdown, index
ensure
  @worker_write << "t#{Process.pid}\n" rescue nil
  @worker_write.close
end