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



227
228
229
230
231
232
233
234
235
# File 'lib/tasks/ci/common.rb', line 227

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



223
224
225
# File 'lib/tasks/ci/common.rb', line 223

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

.check_port(port) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/tasks/ci/common.rb', line 196

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, EOFError, Errno::ECONNRESET
      return false
    end
  end
rescue Timeout::Error
  return false
end

.check_url(url) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/tasks/ci/common.rb', line 210

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, EOFError, Errno::ECONNRESET
      return false
    end
  end
rescue Timeout::Error
  return false
end

.for(smth, max_timeout = DEFAULT_TIMEOUT) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/tasks/ci/common.rb', line 237

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