Class: Percy::NetworkHelpers

Inherits:
Object
  • Object
show all
Defined in:
lib/percy/network_helpers.rb

Defined Under Namespace

Classes: OpenPortNotFound, ServerDown

Constant Summary collapse

MIN_PORT =

0-1023 are not available without privilege

1_024
MAX_PORT =

(2^16) -1

65_535
MAX_PORT_ATTEMPTS =
50

Class Method Summary collapse

Class Method Details

.port_open?(port) ⇒ Boolean



22
23
24
25
26
27
28
29
# File 'lib/percy/network_helpers.rb', line 22

def self.port_open?(port)
  begin
    TCPServer.new(port).close
    true
  rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::EADDRINUSE
    false
  end
end

.random_open_port(min_port: MIN_PORT, max_port: MAX_PORT) ⇒ Object

Raises:



13
14
15
16
17
18
19
20
# File 'lib/percy/network_helpers.rb', line 13

def self.random_open_port(min_port: MIN_PORT, max_port: MAX_PORT)
  MAX_PORT_ATTEMPTS.times do
    port = rand(min_port..max_port)
    return port if port_open? port
  end

  raise OpenPortNotFound
end

.serve_static_directory(dir, hostname: 'localhost', port: nil) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/percy/network_helpers.rb', line 58

def self.serve_static_directory(dir, hostname: 'localhost', port: nil)
  port ||= random_open_port

  # Note: using this form of popen to keep stdout and stderr silent and captured.
  process = IO.popen(
    [
      'ruby', '-run', '-e', 'httpd', dir, '-p', port.to_s, err: [:child, :out],
    ].flatten,
  )
  verify_http_server_up(hostname, port: port)
  process.pid
end

.verify_healthcheck(url:, expected_body: 'ok', retry_wait_seconds: 0.5, proxy: nil, headers: {}) ⇒ Object

Raises:



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/percy/network_helpers.rb', line 31

def self.verify_healthcheck(url:, expected_body: 'ok', retry_wait_seconds: 0.5, proxy: nil,
  headers: {})
  10.times do
    begin
      response = Excon.get(url, proxy: proxy, headers: headers)
      return true if response.body == expected_body
    rescue Excon::Error::Socket, Excon::Error::Timeout
      sleep retry_wait_seconds
    end
  end
  raise ServerDown, "Healthcheck failed for #{url}"
end

.verify_http_server_up(hostname, port: nil, path: nil, retry_wait_seconds: 0.25, proxy: nil, headers: {}) ⇒ Object

Raises:



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/percy/network_helpers.rb', line 44

def self.verify_http_server_up(hostname, port: nil,
  path: nil, retry_wait_seconds: 0.25, proxy: nil, headers: {})
  10.times do
    begin
      url = "http://#{hostname}#{port.nil? ? '' : ':' + port.to_s}#{path || ''}"
      Excon.get(url, proxy: proxy, headers: headers)
      return true
    rescue Excon::Error::Socket, Excon::Error::Timeout
      sleep retry_wait_seconds
    end
  end
  raise ServerDown, "Server is down: #{hostname}"
end