1 2 3 4 5 6 7 8 9 10 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
module Riemann
class AutoState
# Binds together a state hash and a Client. Any change made here
# sends the state to the client. Useful when updates to a state are made
# decoherently, e.g. across many methods. Combine with MetricThread (or
# just Thread.new { loop { autostate.flush; sleep n } }) to ensure regular
# updates.
#
# example:
#
# class Job
# def initialize
# @state = AutoState.new
# @state.service = 'job'
# @state.state = 'starting up'
#
# run
# end
#
# def run
# loop do
# begin
# a
# b
# rescue Exception => e
# @state.once(
# state: 'error',
# description: e.to_s
# )
# end
# end
# end
#
# def a
# @state.state = 'heavy lifting a'
# ...
# end
#
# def b
# @state.state = 'heavy lifting b'
# ...
# end
def initialize(client = Client.new, state = {})
@client = client
@state = state
end
def description=(description)
@state[:description] = description
flush
end
def description
@state[:description]
end
# Send state to client
def flush
@state[:time] = Time.now.to_i
@client << @state
end
def host=(host)
@state[:host] = host
flush
end
def host
@state[:host]
end
def metric=(metric)
@state[:metric] = metric
flush
end
alias metric_f= metric=
def metric
@state[:metric]
end
alias metric_f metric
# Performs multiple updates, followed by flush.
# Example: merge state: critical, metric_f: 10235.3
def merge(opts)
@state.merge! opts
flush
end
alias << merge
# Issues an immediate update of the state with tag "once"
# set, but does not update the local state. Useful for transient errors.
# Opts are merged with the state.
def once(opts)
o = @state.merge opts
o[:time] = Time.now.to_i
o[:tags] = ((o[:tags] | ["once"]) rescue ["once"])
@client << o
end
def state=(state)
@state[:state] = state
flush
end
def state
@state[:state]
end
def service=(service)
@state[:service] = service
flush
end
def service
@state[:service]
end
end
end
|