yahns Ruby server user/dev discussion
 help / color / mirror / code / Atom feed
blob c61d583347a9fa30a8f8bf84bb310aaa758c7309 7239 bytes (raw)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
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
137
138
139
140
141
142
143
144
145
146
147
148
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
198
199
200
201
202
203
204
205
206
207
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
 
# -*- encoding: binary -*-
# Copyright (C) 2013-2016 all contributors <yahns-public@yhbt.net>
# License: GPL-3.0+ (https://www.gnu.org/licenses/gpl-3.0.txt)
# frozen_string_literal: true

module Yahns::ServerMP # :nodoc:
  EXIT_SIGS = [ :QUIT, :TERM, :INT ]

  def maintain_worker_count
    (off = @workers.size - @worker_processes) == 0 and return
    off < 0 and return spawn_missing_workers
    @workers.each_value do |worker|
      worker.nr >= @worker_processes and worker.soft_kill(Signal.list["QUIT"])
    end
  end

  # fakes delivery of a signal to each worker
  def soft_kill_each_worker(sig)
    sig = Signal.list[sig]
    @workers.each_value { |worker| worker.soft_kill(sig) }
  end

  # this is the first thing that runs after forking in a child
  # gets rid of stuff the worker has no business keeping track of
  # to free some resources and drops all sig handlers.
  # traps for USR1, USR2, and HUP may be set in the after_fork Proc
  # by the user.
  def worker_atfork_internal(worker)
    worker.atfork_child

    # daemon_pipe may be true for non-initial workers
    @daemon_pipe = @daemon_pipe.close if @daemon_pipe.respond_to?(:close)

    srand # in case this pops up again: https://bugs.ruby-lang.org/issues/4338

    # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
    # dying workers can recycle pids
    OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
    # we'll re-trap EXIT_SIGS later for graceful shutdown iff we accept clients
    EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
    exit!(0) if (@sig_queue & EXIT_SIGS)[0] # did we inherit sigs from parent?
    @sig_queue = []

    # ignore WINCH, TTIN, TTOU, HUP in the workers
    (Yahns::Server::QUEUE_SIGS - EXIT_SIGS).each { |sig| trap(sig, nil) }
    trap(:CHLD, 'DEFAULT')
    @logger.info("worker=#{worker.nr} spawned pid=#$$")
    proc_name "worker[#{worker.nr}]"
    Yahns::START.clear
    @sev.close
    @sev = Yahns::Sigevent.new
    switch_user(*@user) if @user
    @user = @workers = nil
    __call_hooks(@atfork_child, worker.nr)
    @atfork_child = @atfork_parent = @atfork_prepare = @submasters = nil
  end

  def __call_hooks(ary, worker_nr)
    ary.each { |x| x.call(worker_nr) } if ary
  end

  def spawn_missing_submasters
    @submasters.each do |sm|
      next if sm.pid # we don't expect dozens of submasters
      pid = sm.pid = fork
      if pid
        @logger.info("submaster=#{sm.key.inspect} pid=#{pid}")
      else
        # expand env variables like LISTEN_PID in the child
        env = sm.cmd[0]
        env.each { |k,v| env[k] = v.call if v.respond_to?(:call) }
        exec(*(sm.cmd))
      end
    end
  rescue => e
    Yahns::Log.exception(@logger, 'spawning submaster', e)
    exit!
  end

  def spawn_missing_workers
    worker_nr = -1
    until (worker_nr += 1) == @worker_processes
      @workers.value?(worker_nr) and next
      worker = Yahns::Worker.new(worker_nr)
      @logger.info("worker=#{worker_nr} spawning...")
      __call_hooks(@atfork_prepare, worker_nr)
      if pid = fork
        @workers[pid] = worker.atfork_parent
        # XXX is this useful?
        __call_hooks(@atfork_parent, worker_nr)
      else
        worker_atfork_internal(worker)
        run_mp_worker(worker)
      end
    end
  rescue => e
    Yahns::Log.exception(@logger, "spawning worker", e)
    exit!
  end

  # monitors children and receives signals forever
  # (or until a termination signal is sent).  This handles signals
  # one-at-a-time time and we'll happily drop signals in case somebody
  # is signalling us too often.
  def join
    spawn_missing_submasters
    spawn_missing_workers
    state = :respawn # :QUIT, :WINCH
    proc_name 'master'
    @logger.info "master process ready"
    daemon_ready
    begin
      @sev.kgio_wait_readable
      @sev.yahns_step
      reap_all
      case sig = @sig_queue.shift
      when *EXIT_SIGS # graceful shutdown (twice for non graceful)
        @listeners.each(&:close).clear
        soft_kill_each_worker("QUIT")
        kill_each_submaster(sig)
        state = :QUIT
      when :USR1 # rotate logs
        usr1_reopen("master ")
        soft_kill_each_worker("USR1")
        kill_each_submaster(sig)
      when :USR2 # exec binary, stay alive in case something went wrong
        reexec
      when :WINCH
        if $stdin.tty?
          @logger.info "SIGWINCH ignored because we're not daemonized"
        else
          state = :WINCH
          @logger.info "gracefully stopping all workers"
          soft_kill_each_worker("QUIT")
          @worker_processes = 0
        end
      when :TTIN
        state = :respawn unless state == :QUIT
        @worker_processes += 1
      when :TTOU
        @worker_processes -= 1 if @worker_processes > 0
      when :HUP
        state = :respawn unless state == :QUIT
        if @config.config_file
          load_config!
        else # exec binary and exit if there's no config file
          @logger.info "config_file not present, reexecuting binary"
          reexec
        end
      end while @sig_queue[0]
      if state == :respawn
        spawn_missing_submasters
        maintain_worker_count
      end
    rescue => e
      Yahns::Log.exception(@logger, "master loop error", e)
    end while state != :QUIT || @workers.size > 0
    @logger.info "master complete"
    unlink_pid_safe(@pid) if @pid
  end

  def fdmap_init_mp
    fdmap = fdmap_init # builds apps (if not preloading)
    [:USR1, *EXIT_SIGS].each { |sig| trap(sig) { sqwakeup(sig) } }
    @config.postfork_cleanup # reduce live objects
    fdmap
  end

  def run_mp_worker(worker)
    fdmap = fdmap_init_mp
    alive = true
    watch = [ worker, @sev ]
    begin
      alive = mp_sig_handle(watch, alive)
    rescue => e
      Yahns::Log.exception(@logger, "main worker loop", e)
    end while alive || dropping(fdmap)
    exit
  ensure
    quit_finish
  end

  def mp_sig_handle(watch, alive)
    # not performance critical
    watch.delete_if { |io| io.to_io.closed? }
    if r = IO.select(watch, nil, nil, alive ? nil : 0.1)
      r[0].each(&:yahns_step)
    end
    case @sig_queue.shift
    when *EXIT_SIGS
      return quit_enter(alive)
    when :USR1
      usr1_reopen("worker ")
    end
    alive
  end

  # reaps all unreaped workers/reexec processes
  def reap_all
    begin
      wpid, status = Process.waitpid2(-1, Process::WNOHANG)
      wpid or return
      if @reexec_pid == wpid
        @logger.error "reaped #{status.inspect} exec()-ed"
        @reexec_pid = 0
        self.pid = @pid.chomp('.oldbin') if @pid
        proc_name('master')
        next
      end
      if worker = @workers.delete(wpid)
        desc = "worker=#{worker.nr}"
      elsif sm = @submasters.find { |s| s.pid == wpid }
        sm.pid = nil
        desc = "submaster=#{sm.key.inspect}"
      end
      m = "reaped #{status.inspect} #{desc || '(unknown)'}"
      status.success? ? @logger.info(m) : @logger.error(m)
    rescue Errno::ECHILD
      return
    end while true
  end

  def kill_each_submaster(sig)
    @submasters.each do |sm|
      pid = sm.pid or next
      begin
        Process.kill(sig, pid)
      rescue => e
        @logger.error("#{e.message} killing submaster=#{sm.key.inspect}")
      end
    end
  end
end

debug log:

solving c61d583 ...
found c61d583 in https://yhbt.net/yahns-public/20170407034215.25377-1-yahns-public@yhbt.net/
found c9cd207 in https://yhbt.net/yahns.git
preparing index
index prepared:
100644 c9cd2079fe32245e939e97940f8cc14a206e2b25	lib/yahns/server_mp.rb

applying [1/1] https://yhbt.net/yahns-public/20170407034215.25377-1-yahns-public@yhbt.net/
diff --git a/lib/yahns/server_mp.rb b/lib/yahns/server_mp.rb
index c9cd207..c61d583 100644

Checking patch lib/yahns/server_mp.rb...
Applied patch lib/yahns/server_mp.rb cleanly.

index at:
100644 c61d583347a9fa30a8f8bf84bb310aaa758c7309	lib/yahns/server_mp.rb

Code repositories for project(s) associated with this public inbox

	https://yhbt.net/yahns.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).