Module: LogStash::Retryable

Defined in:
lib/logstash/util/retryable.rb

Instance Method Summary collapse

Instance Method Details

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

execute retryable code block

Parameters:

  • options (Hash) (defaults to: {})

    retryable options

Options Hash (options):

  • :tries (Fixnum)

    retries to perform, default 1, set to 0 for infinite retries. 1 means that upon exception the block will be retried once

  • :base_sleep (Fixnum)

    seconds to sleep on first retry, default 1

  • :max_sleep (Fixnum)

    max seconds to sleep upon exponential backoff, default 1

  • :rescue (Exception)

    exception class list to retry on, defaults is Exception, which retries on any Exception.

  • :on_retry (Proc)

    call the given Proc/lambda before each retry with the raised exception as parameter



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/logstash/util/retryable.rb', line 11

def retryable(options = {}, &block)
  options = {
    :tries => 1,
    :rescue => Exception,
    :on_retry => nil,
    :base_sleep => 1,
    :max_sleep => 1,
  }.merge(options)

  rescue_classes = Array(options[:rescue])
  max_sleep_retry = Math.log2(options[:max_sleep] / options[:base_sleep])
  retry_count = 0

  begin
    return yield(retry_count)
  rescue *rescue_classes => e
    raise e if options[:tries] > 0 && retry_count >= options[:tries]

    options[:on_retry].call(retry_count + 1, e) if options[:on_retry]

    # dont compute and maybe overflow exponent on too big a retry count
    seconds = retry_count < max_sleep_retry ? options[:base_sleep] * (2 ** retry_count) : options[:max_sleep]
    sleep(seconds)

    retry_count += 1
    retry
  end
end