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

Returns:

  • (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_portObject

Raises:



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

def self.random_open_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



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/percy/network_helpers.rb', line 55

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) ⇒ Object

Raises:



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

def self.verify_healthcheck(url:, expected_body: 'ok', retry_wait_seconds: 0.5)
  10.times do
    begin
      response = Excon.get(url)
      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) ⇒ Object

Raises:



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

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