Module: Jenkins2::Util

Extended by:
Util
Included in:
Util
Defined in:
lib/jenkins2/util.rb

Instance Method Summary collapse

Instance Method Details

#try(retries: 3, retry_delay: 5) ⇒ Object

Tries a block several times, if raised exception is Net::HTTPFatalError, Errno::ECONNREFUSED or Net::ReadTimeout.

retries

Number of retries.

retry_delay

Seconds to sleep, before attempting next retry.

&block

Code to run inside retry loop.

Returns the result of a block, if it eventually succeeded or throws the exception, thown by the block on last try.

Note that this is both a method of module Util, so you can include Jenkins::Util into your classes so they have a #try method, as well as a module method, so you can call it directly as ::try().



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

def try(retries: 3, retry_delay: 5)
  yield
rescue Errno::ECONNREFUSED, Net::HTTPFatalError, Net::ReadTimeout => e
  i ||= 0
  unless (i += 1) == retries
    Log.warn{ "Received error: #{e}." }
    Log.warn{ "Retry request in #{retry_delay} seconds. Retry number #{i}." }
    sleep retry_delay
    retry
  end
  Log.error{ "Received error: #{e}." }
  Log.error{ "Reached maximum number of retries (#{retries}). Give up." }
  raise e
end

#wait(max_wait_minutes: 60) ⇒ Object

Waits for a block to return truthful value. Useful, for example, when you set a node temporarily offline, and then wait for it to become idle.

max_wait_minutes

Maximum wait time in minutes.

&block

Run this block until it returs true, max_wait_minutes pass or block throws some

kind of exception.

Returns the result of a block, if it eventually succeeded or nil in case of timeout.

Note that this is both a method of module Util, so you can include Jenkins::Util into your classes so they have a #wait method, as well as a module method, so you can call it directly as ::wait().



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/jenkins2/util.rb', line 22

def wait(max_wait_minutes: 60)
  [3, 5, 7, 15, 30, [60] * (max_wait_minutes - 1)].flatten.each do |sec|
    begin
      result = yield
      return result if result
      Log.warn{ "Received result is not truthy: #{result}." }
      Log.warn{ "Retry request in #{sec} seconds." }
      sleep sec
    rescue Jenkins2::NotFoundError, Jenkins2::ServiceUnavailableError => e
      Log.warn{ "Received error: #{e}." }
      Log.warn{ "Retry request in #{sec} seconds." }
      sleep sec
    end
  end
  Log.error{ "Tired of waiting (#{max_wait_minutes} minutes). Give up." }
  nil
end