Class: WarmBlanket::WaitForPort

Inherits:
Object
  • Object
show all
Defined in:
lib/warm_blanket/wait_for_port.rb

Overview

Waits for given port to be available

Constant Summary collapse

InvalidPort =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(hostname: 'localhost', port:, time_deadline: (Time.now + 90), logger: WarmBlanket.config.logger) ⇒ WaitForPort

Returns a new instance of WaitForPort.

Raises:



37
38
39
40
41
42
43
44
45
# File 'lib/warm_blanket/wait_for_port.rb', line 37

def initialize(hostname: 'localhost', port:, time_deadline: (Time.now + 90), logger: WarmBlanket.config.logger)
  port = Integer(port) rescue nil
  raise InvalidPort, "Invalid port (#{port.inspect})" unless (1...2**16).include?(port)

  @hostname = hostname
  @port = port
  @logger = logger
  @time_deadline = time_deadline
end

Instance Method Details

#callObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/warm_blanket/wait_for_port.rb', line 47

def call
  logger.debug "Waiting for #{hostname}:#{port} to be available"

  while true
    socket = nil
    begin
      socket = TCPSocket.new(hostname, port)
      logger.debug "Service at #{hostname}:#{port} is up"
      return true
    rescue StandardError => e
      logger.debug "Exception while waiting for port to be available #{e.class}: #{e.message}"
    ensure
      socket&.close
    end

    return false if Time.now >= time_deadline
    sleep 1
  end
end