Class: Ferrum::Browser::Process

Inherits:
Object
  • Object
show all
Defined in:
lib/ferrum/browser/process.rb

Constant Summary collapse

KILL_TIMEOUT =
2
PROCESS_TIMEOUT =
1
BROWSER_PATH =
ENV["BROWSER_PATH"]
BROWSER_HOST =
"127.0.0.1"
BROWSER_PORT =
"0"
DEFAULT_OPTIONS =
{
  "headless" => nil,
  "disable-gpu" => nil,
  "hide-scrollbars" => nil,
  "mute-audio" => nil,
  "enable-automation" => nil,
  "disable-web-security" => nil,
  "disable-session-crashed-bubble" => nil,
  "disable-breakpad" => nil,
  "disable-sync" => nil,
  "no-first-run" => nil,
  "use-mock-keychain" => nil,
  "keep-alive-for-test" => nil,
  "disable-popup-blocking" => nil,
  "disable-extensions" => nil,
  "disable-hang-monitor" => nil,
  "disable-features" => "site-per-process,TranslateUI",
  "disable-translate" => nil,
  "disable-background-networking" => nil,
  "enable-features" => "NetworkService,NetworkServiceInProcess",
  "disable-background-timer-throttling" => nil,
  "disable-backgrounding-occluded-windows" => nil,
  "disable-client-side-phishing-detection" => nil,
  "disable-default-apps" => nil,
  "disable-dev-shm-usage" => nil,
  "disable-ipc-flooding-protection" => nil,
  "disable-prompt-on-repost" => nil,
  "disable-renderer-backgrounding" => nil,
  "force-color-profile" => "srgb",
  "metrics-recording-only" => nil,
  "safebrowsing-disable-auto-update" => nil,
  "password-store" => "basic",
  # Note: --no-sandbox is not needed if you properly setup a user in the container.
  # https://github.com/ebidel/lighthouse-ci/blob/master/builder/Dockerfile#L35-L40
  # "no-sandbox" => nil,
}.freeze
NOT_FOUND =
"Could not find an executable for chrome. Try to make it " \
"available on the PATH or set environment varible for " \
"example BROWSER_PATH=\"/Applications/Chromium.app/Contents/MacOS/Chromium\""

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Process

Returns a new instance of Process.



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

def initialize(options)
  @options = {}

  @path = options[:browser_path] || BROWSER_PATH || self.class.detect_browser_path

  if options[:url]
    url = URI.join(options[:url].to_s, "/json/version")
    response = JSON.parse(::Net::HTTP.get(url))
    set_ws_url(response["webSocketDebuggerUrl"])
    return
  end

  # Doesn't work on MacOS, so we need to set it by CDP as well
  @options.merge!("window-size" => options[:window_size].join(","))

  port = options.fetch(:port, BROWSER_PORT)
  @options.merge!("remote-debugging-port" => port)

  host = options.fetch(:host, BROWSER_HOST)
  @options.merge!("remote-debugging-address" => host)

  @options.merge!("user-data-dir" => Dir.mktmpdir)

  @options = DEFAULT_OPTIONS.merge(@options)

  unless options.fetch(:headless, true)
    @options.delete("headless")
    @options.delete("disable-gpu")
  end

  @process_timeout = options.fetch(:process_timeout, PROCESS_TIMEOUT)

  @options.merge!(options.fetch(:browser_options, {}))

  @logger = options[:logger]
end

Instance Attribute Details

#cmdObject (readonly)

Returns the value of attribute cmd.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def cmd
  @cmd
end

#hostObject (readonly)

Returns the value of attribute host.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def host
  @host
end

#optionsObject (readonly)

Returns the value of attribute options.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def options
  @options
end

#pathObject (readonly)

Returns the value of attribute path.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def path
  @path
end

#pidObject (readonly)

Returns the value of attribute pid.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def pid
  @pid
end

#portObject (readonly)

Returns the value of attribute port.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def port
  @port
end

#ws_urlObject (readonly)

Returns the value of attribute ws_url.



59
60
61
# File 'lib/ferrum/browser/process.rb', line 59

def ws_url
  @ws_url
end

Class Method Details

.detect_browser_pathObject



86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/ferrum/browser/process.rb', line 86

def self.detect_browser_path
  if RUBY_PLATFORM.include?("darwin")
    [
      "/Applications/Chromium.app/Contents/MacOS/Chromium",
      "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    ].find { |path| File.exist?(path) }
  else
    %w[chromium google-chrome-unstable google-chrome-beta google-chrome chrome chromium-browser google-chrome-stable].reduce(nil) do |path, exe|
      path = Cliver.detect(exe)
      break path if path
    end
  end
end

.process_killer(pid) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/ferrum/browser/process.rb', line 65

def self.process_killer(pid)
  proc do
    begin
      if Ferrum.windows?
        ::Process.kill("KILL", pid)
      else
        ::Process.kill("USR1", pid)
        start = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
        while ::Process.wait(pid, ::Process::WNOHANG).nil?
          sleep 0.05
          next unless (::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start) > KILL_TIMEOUT
          ::Process.kill("KILL", pid)
          ::Process.wait(pid)
          break
        end
      end
    rescue Errno::ESRCH, Errno::ECHILD
    end
  end
end

.start(*args) ⇒ Object



61
62
63
# File 'lib/ferrum/browser/process.rb', line 61

def self.start(*args)
  new(*args).tap(&:start)
end

Instance Method Details

#restartObject



169
170
171
172
# File 'lib/ferrum/browser/process.rb', line 169

def restart
  stop
  start
end

#startObject



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

def start
  # Don't do anything as browser is already running as external process.
  return if ws_url

  begin
    read_io, write_io = IO.pipe
    process_options = { in: File::NULL }
    process_options[:pgroup] = true unless Ferrum.windows?
    if Ferrum.mri?
      process_options[:out] = process_options[:err] = write_io
    end

    raise Cliver::Dependency::NotFound.new(NOT_FOUND) unless @path

    redirect_stdout(write_io) do
      @cmd = [@path] + @options.map { |k, v| v.nil? ? "--#{k}" : "--#{k}=#{v}" }
      @pid = ::Process.spawn(*@cmd, process_options)
      ObjectSpace.define_finalizer(self, self.class.process_killer(@pid))
    end

    parse_ws_url(read_io, @process_timeout)
  ensure
    close_io(read_io, write_io)
  end
end

#stopObject



163
164
165
166
167
# File 'lib/ferrum/browser/process.rb', line 163

def stop
  return unless @pid
  kill
  ObjectSpace.undefine_finalizer(self)
end