Class: Bluepill::Trigger

Inherits:
Object
  • Object
show all
Defined in:
lib/bluepill/trigger.rb

Direct Known Subclasses

Bluepill::Triggers::Flapping

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(process, options = {}) ⇒ Trigger

Returns a new instance of Trigger.



14
15
16
17
18
19
# File 'lib/bluepill/trigger.rb', line 14

def initialize(process, options = {})
  self.process = process
  self.logger = options[:logger]
  self.mutex = Mutex.new
  self.scheduled_events = []
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



12
13
14
# File 'lib/bluepill/trigger.rb', line 12

def logger
  @logger
end

#mutexObject

Returns the value of attribute mutex.



12
13
14
# File 'lib/bluepill/trigger.rb', line 12

def mutex
  @mutex
end

#processObject

Returns the value of attribute process.



12
13
14
# File 'lib/bluepill/trigger.rb', line 12

def process
  @process
end

#scheduled_eventsObject

Returns the value of attribute scheduled_events.



12
13
14
# File 'lib/bluepill/trigger.rb', line 12

def scheduled_events
  @scheduled_events
end

Class Method Details

.[](name) ⇒ Object



8
9
10
# File 'lib/bluepill/trigger.rb', line 8

def self.[](name)
  @implementations[name]
end

.inherited(klass) ⇒ Object



4
5
6
# File 'lib/bluepill/trigger.rb', line 4

def self.inherited(klass)
  @implementations[klass.name.split('::').last.underscore.to_sym] = klass
end

Instance Method Details

#cancel_all_eventsObject



52
53
54
55
56
57
# File 'lib/bluepill/trigger.rb', line 52

def cancel_all_events
  self.logger.info "Canceling all scheduled events"
  self.mutex.synchronize do
    self.scheduled_events.each {|_, thread| thread.kill}
  end
end

#dispatch!(event) ⇒ Object



29
30
31
# File 'lib/bluepill/trigger.rb', line 29

def dispatch!(event)
  self.process.dispatch!(event, self.class.name.split("::").last)
end

#notify(transition) ⇒ Object



25
26
27
# File 'lib/bluepill/trigger.rb', line 25

def notify(transition)
  raise "Implement in subclass"
end

#reset!Object



21
22
23
# File 'lib/bluepill/trigger.rb', line 21

def reset!
  self.cancel_all_events
end

#schedule_event(event, delay) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/bluepill/trigger.rb', line 33

def schedule_event(event, delay)
  # TODO: maybe wrap this in a ScheduledEvent class with methods like cancel
  thread = Thread.new(self) do |trigger|
    begin
      sleep delay.to_f
      trigger.logger.info("Retrying from flapping")
      trigger.dispatch!(event)
      trigger.mutex.synchronize do
        trigger.scheduled_events.delete_if { |_, thread| thread == Thread.current }
      end
    rescue StandardError => e
      trigger.logger.err(e)
      trigger.logger.err(e.backtrace.join("\n"))
    end
  end
  
  self.scheduled_events.push([event, thread])
end