Module: DeadMan::Switch

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

Constant Summary collapse

INTERVAL_THRESHOLD =

20% padding

0.2
SWITCHES =
{}
CALLBACKS =
[]

Instance Method Summary collapse

Instance Method Details

#adjusted_interval(interval) ⇒ Object

Gives an INTERVAL_THRESHOLD padding on interval e.g. 60.seconds -> 72.seconds



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

def adjusted_interval(interval)
  interval + interval * INTERVAL_THRESHOLD
end

#alert(switch, timestamp) ⇒ Object



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

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

#alertable?(heartbeat_at, interval) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#check(switch) ⇒ Object



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

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



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

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

#notify(message) ⇒ Object



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

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

#register_callback(callback) ⇒ Object



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

def register_callback(callback)
  CALLBACKS << callback
end

#register_switch(name, interval) ⇒ Object



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

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

#runObject



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

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