Module: WaitUtil

Extended by:
WaitUtil
Included in:
WaitUtil
Defined in:
lib/waitutil.rb,
lib/waitutil/version.rb

Defined Under Namespace

Classes: TimeoutError

Constant Summary collapse

DEFAULT_TIMEOUT_SEC =
60
DEFAULT_DELAY_SEC =
1
VERSION =
IO.read(File.expand_path("../../../VERSION", __FILE__))
@@logger =
Logger.new(STDOUT)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.loggerObject



16
17
18
# File 'lib/waitutil.rb', line 16

def self.logger
  @@logger
end

Instance Method Details

#wait_for_condition(description, options = {}, &block) ⇒ Object

Wait until the condition computed by the given block is met. The supplied block may return a boolean or an array of two elements: whether the condition has been met and an additional message to display in case of timeout.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/waitutil.rb', line 23

def wait_for_condition(description, options = {}, &block)
  delay_sec = options.delete(:delay_sec) || DEFAULT_DELAY_SEC
  timeout_sec = options.delete(:timeout_sec) || DEFAULT_TIMEOUT_SEC
  verbose = options.delete(:verbose)
  unless options.empty?
    raise "Invalid options: #{options}"
  end

  if verbose
    @@logger.info("Waiting for #{description} for up to #{timeout_sec} seconds")
  end

  start_time = Time.now
  iteration = 0
  until is_condition_met(condition_result = yield(iteration))
    if Time.now - start_time >= timeout_sec
      raise TimeoutError.new(
        "Timed out waiting for #{description} (#{timeout_sec} seconds elapsed)" +
        get_additional_message(condition_result)
      )
    end
    sleep(delay_sec)
    iteration += 1
  end
  if verbose
    @@logger.info("Success waiting for #{description} (#{Time.now - start_time} seconds)")
  end
  true
end

#wait_for_service(description, host, port, options = {}) ⇒ Object

Wait until a service is available at the given host/port.



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

def wait_for_service(description, host, port, options = {})
  wait_for_condition("#{description} port #{port} to become available on #{host}",
                     options) do
    begin
      s = TCPSocket.new(host, port)
      s.close
      true
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
      false
    end
  end
end