Class: LogStash::Inputs::BeatsSupport::CircuitBreaker

Inherits:
Object
  • Object
show all
Defined in:
lib/logstash/inputs/beats_support/circuit_breaker.rb

Overview

Largely inspired by Martin’s fowler circuit breaker

Defined Under Namespace

Classes: HalfOpenBreaker, OpenBreaker

Constant Summary collapse

DEFAULT_ERROR_THRESHOLD =

Error threshold before opening the breaker, if the breaker is open it wont execute the code.

5
DEFAULT_TIME_BEFORE_RETRY =

Recover time after the breaker is open to start executing the method again.

30
DEFAULT_EXCEPTION_RESCUED =

Exceptions catched by the circuit breaker, too much errors and the breaker will trip.

[StandardError]

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &block) ⇒ CircuitBreaker

Returns a new instance of CircuitBreaker.



25
26
27
28
29
30
31
32
33
# File 'lib/logstash/inputs/beats_support/circuit_breaker.rb', line 25

def initialize(name, options = {}, &block)
  @exceptions = Array(options.fetch(:exceptions, [StandardError]))
  @error_threshold = options.fetch(:error_threshold, DEFAULT_ERROR_THRESHOLD)
  @time_before_retry = options.fetch(:time_before_retry, DEFAULT_TIME_BEFORE_RETRY)
  @block = block
  @name = name
  @mutex = Mutex.new
  reset
end

Instance Method Details

#closed?Boolean

Returns:

  • (Boolean)


59
60
61
62
63
# File 'lib/logstash/inputs/beats_support/circuit_breaker.rb', line 59

def closed?
  current_state = state

  current_state == :close || current_state == :half_open
end

#execute(args = nil) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/logstash/inputs/beats_support/circuit_breaker.rb', line 35

def execute(args = nil)
  case state
  when :open
    logger.warn("CircuitBreaker::Open", :name => @name)
    raise OpenBreaker, "for #{@name}"
  when :close, :half_open
    if block_given?
      yield args
    else
      @block.call(args)
    end

    if state == :half_open
      logger.warn("CircuitBreaker::Close", :name => @name)
      reset
    end
  end
rescue *@exceptions => e
  logger.warn("CircuitBreaker::rescuing exceptions", :name => @name, :exception => e.class)
  increment_errors(e)

  raise HalfOpenBreaker
end