Module: DeadMan::Switch

Extended by:
Switch
Included in:
Switch
Defined in:
lib/dead_man/switch.rb

Constant Summary collapse

SWITCHES =
{}
CALLBACKS =
[]

Instance Method Summary collapse

Instance Method Details

#adjusted_interval(interval) ⇒ Object

Gives a padding on interval e.g. 1 minute -> 6 minutes



47
48
49
# File 'lib/dead_man/switch.rb', line 47

def adjusted_interval(interval)
  interval + 5.minutes
end

#alert(switch, timestamp) ⇒ Object



51
52
53
# File 'lib/dead_man/switch.rb', line 51

def alert(switch, timestamp)
  notify("#{switch} died. The switch was last triggered at #{timestamp}")
end

#alertable?(heartbeat_at, interval) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/dead_man/switch.rb', line 41

def alertable?(heartbeat_at, interval)
  heartbeat_at < adjusted_interval(interval).ago
end

#check(switch) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/dead_man/switch.rb', line 21

def check(switch)
  if SWITCHES.has_key?(switch)
    timestamp = last_heartbeat_at(switch)
    raise 'Unrecorded switch' if timestamp.nil?
    alert(switch, timestamp) if alertable?(timestamp, SWITCHES[switch])
  else
    return false
  end
rescue
  notify("Check failed for #{switch}. This is usually because an improper heartbeat timestamp was stored.")
end

#last_heartbeat_at(switch) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/dead_man/switch.rb', line 33

def last_heartbeat_at(switch)
  key = DeadMan.key(switch)
  timestamp = DeadMan.redis.get(key)
  Time.parse(timestamp)
rescue
  return nil
end

#notify(message) ⇒ Object



55
56
57
58
59
# File 'lib/dead_man/switch.rb', line 55

def notify(message)
  CALLBACKS.each do |callback|
    callback.call(message)
  end
end

#register_callback(callback) ⇒ Object



13
14
15
# File 'lib/dead_man/switch.rb', line 13

def register_callback(callback)
  CALLBACKS << callback
end

#register_switch(name, interval) ⇒ Object



17
18
19
# File 'lib/dead_man/switch.rb', line 17

def register_switch(name, interval)
  SWITCHES[name] = interval
end

#runObject



7
8
9
10
11
# File 'lib/dead_man/switch.rb', line 7

def run
  SWITCHES.each_key do |switch|
    check(switch)
  end
end