Class: Wait

Inherits:
Object
  • Object
show all
Defined in:
lib/tasks/ci/common.rb

Overview

helper class to wait for TCP/HTTP services to boot

Constant Summary collapse

DEFAULT_TIMEOUT =
10

Class Method Summary collapse

Class Method Details

.check(smth) ⇒ Object



158
159
160
161
162
163
164
165
166
# File 'lib/tasks/ci/common.rb', line 158

def self.check(smth)
  if smth.is_a? Integer
    check_port smth
  elsif smth.include? 'http'
    check_url smth
  else
    check_file smth
  end
end

.check_file(file_path) ⇒ Object



154
155
156
# File 'lib/tasks/ci/common.rb', line 154

def self.check_file(file_path)
  File.exist?(file_path)
end

.check_port(port) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/tasks/ci/common.rb', line 127

def self.check_port(port)
  Timeout.timeout(0.5) do
    begin
      s = TCPSocket.new('localhost', port)
      s.close
      return true
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
      return false
    end
  end
rescue Timeout::Error
  return false
end

.check_url(url) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/tasks/ci/common.rb', line 141

def self.check_url(url)
  Timeout.timeout(0.5) do
    begin
      r = HTTParty.get(url)
      return (200...300).cover? r.code
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
      return false
    end
  end
rescue Timeout::Error
  return false
end

.for(smth, max_timeout = DEFAULT_TIMEOUT) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/tasks/ci/common.rb', line 168

def self.for(smth, max_timeout = DEFAULT_TIMEOUT)
  start_time = Time.now
  status = false
  n = 1
  puts "Trying #{smth}"
  loop do
    puts n.to_s
    status = check(smth)
    break if status || Time.now > start_time + max_timeout
    n += 1
    sleep 0.25
  end
  raise "Still not up after #{max_timeout}s" unless status
  puts 'Found!'
  status
end