Module: Ferrum::Browser::Process::Killer

Defined in:
lib/ferrum/browser/process/killer.rb,
sig/ferrum/browser/process/killer.rbs

Overview

OS-level process termination and user-data-directory removal, kept separate from the rest of Ferrum::Browser::Process (spawning, CDP handshake, ...). Both the GC finalizer and the explicit #stop path need to run the exact same kill/cleanup logic on plain pid/path values -- never on self. A finalizer proc that closes over the object it's attached to creates a reference cycle GC can never collect, so the finalizer would never run; keeping this logic as free functions taking plain arguments sidesteps that entirely.

Constant Summary collapse

KILL_TIMEOUT =

Returns:

  • (::Integer)
2
WAIT_KILLED =

Returns:

  • (::Float)
0.05
REAP_TIMEOUT =

Returns:

  • (::Float)
0.5
REMOVE_DIR_RETRIES =

Returns:

  • (::Integer)
5
REMOVE_DIR_RETRY_DELAY =

Returns:

  • (::Float)
0.1

Class Method Summary collapse

Class Method Details

.finalizer(pids, path) ⇒ Proc

Builds the proc registered as a browser's ObjectSpace finalizer, cleaning up after a browser nobody quit.

Kills every pid first and removes the directory afterwards. That order is the whole point of this being one finalizer instead of two: Ruby runs an object's finalizers in registration order, and removing the user data directory while the browser is still alive means Chrome recreates it on the way out, leaking it for good.

Parameters:

  • pids (Array<Integer>, Integer, nil) —

    Process ids to kill, e.g. the browser and Xvfb.

  • path (String, nil) —

    User data directory to remove once they are dead.

Returns:

  • (Proc)


136
137
138
139
140
141
142
# File 'lib/ferrum/browser/process/killer.rb', line 136

def finalizer(pids, path)
  pids = Array(pids).compact
  proc do
    pids.each { |pid| kill(pid) }
    remove_directory(path) if path
  end
end

.kill(pid, grace: 0) ⇒ void

This method returns an undefined value.

Kills the process at the given pid (and its process group, if any), escalating from TERM to KILL if it doesn't exit within KILL_TIMEOUT seconds.

Parameters:

  • pid (Integer)
  • grace (Numeric) (defaults to: 0) —

    Seconds to wait for the process to exit on its own before it's signaled, e.g. after asking the browser to close.

  • grace: (::Numeric) (defaults to: 0)


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
# File 'lib/ferrum/browser/process/killer.rb', line 42

def kill(pid, grace: 0)
  return taskkill(pid, grace) if Utils::Platform.windows?

  leader_exited = false
  start = Utils::ElapsedTime.monotonic_time
  while grace.positive? && !Utils::ElapsedTime.timeout?(start, grace)
    leader_exited ||= !::Process.wait(pid, ::Process::WNOHANG).nil?
    return if leader_exited && !process_group_alive?(pid)

    sleep(WAIT_KILLED)
  end

  send_signal(pid, "TERM")
  start = Utils::ElapsedTime.monotonic_time
  loop do
    # The leader (the pid we actually spawned and can #wait on) may
    # exit well before the rest of its process group does -- e.g. a
    # renderer/zygote that ignores TERM. Reaping the leader must not
    # by itself end the loop, or that child is orphaned forever
    # since KILL is only ever sent from the timeout branch below.
    leader_exited ||= !::Process.wait(pid, ::Process::WNOHANG).nil?
    break if leader_exited && !process_group_alive?(pid)

    sleep(WAIT_KILLED)
    next unless Utils::ElapsedTime.timeout?(start, KILL_TIMEOUT)

    send_signal(pid, "KILL")
    wait_reaped(pid) unless leader_exited
    break
  end
rescue Errno::ESRCH, Errno::ECHILD
  # nop
end

.process_group_alive?(pid) ⇒ Boolean

Checks whether any process in pid's process group is still alive.

Parameters:

  • pid (Integer)

Returns:

  • (Boolean)


170
171
172
173
174
175
176
177
# File 'lib/ferrum/browser/process/killer.rb', line 170

def process_group_alive?(pid)
  ::Process.kill(0, -pid)
  true
rescue Errno::ESRCH
  false
rescue Errno::EPERM
  true
end

.remove_directory(path, retries: REMOVE_DIR_RETRIES, delay: REMOVE_DIR_RETRY_DELAY) ⇒ void

This method returns an undefined value.

Removes the given directory, retrying with exponential backoff on transient errors. Chrome can briefly hold file locks right after being killed, so the directory may not be removable on the first try; retrying avoids leaking temp directories in that case.

Parameters:

  • path (String) —

    Directory to remove.

  • retries (Integer) (defaults to: REMOVE_DIR_RETRIES) —

    Maximum number of removal attempts.

  • delay (Float) (defaults to: REMOVE_DIR_RETRY_DELAY) —

    Base delay, in seconds, before the first retry; doubles on each subsequent attempt.

  • retries: (::Integer) (defaults to: REMOVE_DIR_RETRIES)
  • delay: (::Float) (defaults to: REMOVE_DIR_RETRY_DELAY)


195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/ferrum/browser/process/killer.rb', line 195

def remove_directory(path, retries: REMOVE_DIR_RETRIES, delay: REMOVE_DIR_RETRY_DELAY)
  retries.times do |attempt|
    FileUtils.remove_entry(path)
    break
  rescue Errno::ENOENT
    break
  rescue Errno::ENOTEMPTY, Errno::EBUSY, Errno::EACCES, Errno::EPERM => e
    raise e if attempt == retries - 1

    sleep(delay * (2**attempt))
  end
rescue StandardError => e
  warn("[Ferrum] Failed to remove user data dir #{path}: #{e.class}: #{e.message}")
end

.send_signal(pid, name) ⇒ void

This method returns an undefined value.

Signals the whole process group Chrome was spawned into (it's spawned with pgroup: true), so its child processes (renderer, GPU, zygote, ...) are cleaned up too instead of being left orphaned. Falls back to signaling just the pid directly if there's no such process group to signal (e.g. Xvfb, which isn't spawned with pgroup: true) or the group can't be signaled.

Parameters:

  • pid (Integer)
  • name (String)


157
158
159
160
161
# File 'lib/ferrum/browser/process/killer.rb', line 157

def send_signal(pid, name)
  ::Process.kill(name, -pid)
rescue Errno::EPERM, Errno::ESRCH
  ::Process.kill(name, pid)
end

.taskkill(pid, grace) ⇒ void

This method returns an undefined value.

Kills the process tree at the given pid on Windows, where Process.kill is unreliable, after waiting grace seconds for it to exit on its own.

Parameters:

  • pid (Integer)
  • grace (Numeric)


86
87
88
89
90
# File 'lib/ferrum/browser/process/killer.rb', line 86

def taskkill(pid, grace)
  return if grace.positive? && wait_reaped(pid, timeout: grace)

  ::Process.kill("KILL", pid) unless system("taskkill /f /t /pid #{pid} >NUL 2>NUL")
end

.wait_reaped(pid, timeout: REAP_TIMEOUT) ⇒ Integer?

Waits for pid to become reapable, giving up after timeout.

Deliberately a bounded poll rather than a blocking Process.wait. #finalizer installs #kill as an ObjectSpace finalizer, so it can run while the interpreter is shutting down, and a blocking wait there never returns.

Parameters:

  • pid (Integer)
  • timeout (Float) (defaults to: REAP_TIMEOUT)
  • timeout: (::Float) (defaults to: REAP_TIMEOUT)

Returns:

  • (Integer, nil) —

    The reaped pid, or nil if it didn't exit in time or wasn't ours.



106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/ferrum/browser/process/killer.rb', line 106

def wait_reaped(pid, timeout: REAP_TIMEOUT)
  start = Utils::ElapsedTime.monotonic_time
  loop do
    reaped = ::Process.wait(pid, ::Process::WNOHANG)
    return reaped if reaped
    return nil if Utils::ElapsedTime.timeout?(start, timeout)

    sleep(WAIT_KILLED)
  end
rescue Errno::ECHILD, Errno::ESRCH
  nil
end