Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created March 13, 2018 00:08
Show Gist options
  • Save SegFaultAX/3e541f76e7d7824c5fd0d8019d4d862c to your computer and use it in GitHub Desktop.
Save SegFaultAX/3e541f76e7d7824c5fd0d8019d4d862c to your computer and use it in GitHub Desktop.
Dead simple Sensu API wrapper [Ruby]
require 'rest-client'
require 'json'
module Sensu
class Server
attr_reader :name, :hostname, :port
def initialize(name, hostname, port = 4567)
@name = name
@hostname = hostname
@port = port
end
def results
raw_results.map { |r| SensuResult.new(self, r) }
end
def raw_results
fetch('/results')
end
def events
raw_events.map { |e| SensuEvent.new(self, e) }
end
def raw_events
fetch('/events')
end
def silenced
raw_silenced.map { |s| SensuSilenced.new(self, s) }
end
def raw_silenced
fetch('/silenced')
end
private
def fetch(endpoint)
url = "http://#{hostname}:#{port}#{endpoint}"
result = ::RestClient.get(url)
::JSON.parse(result.body, :symbolize_names => true)
end
end
class SensuObject
attr_reader :sensu, :content
def initialize(sensu, content)
@sensu = sensu
@content = content
end
def at(*path, default: nil)
root = content
path.each do |p|
root = root[p]
return default if root.nil?
end
root
end
end
class SensuResult < SensuObject
def check(*path, **kwargs)
at(:check, *path, **kwargs)
end
def client_name
at(:client)
end
def check_command
check(:command)
end
def argus
check(:argus, default: false)
end
def service_name
check(:service_name)
end
def business_group
check(:business_group)
end
end
class SensuEvent < SensuObject
def client(*path, **kwargs)
at(:client, *path, **kwargs)
end
def check(*path, **kwargs)
at(:check, *path, **kwargs)
end
def client_name
client(:name)
end
def check_command
check(:command)
end
def check_output
check(:output)
end
def argus
check(:argus, default: false)
end
def service_name
check(:service_name)
end
def business_group
check(:business_group)
end
def to_s
"[#{sensu.name}] #{client_name} - #{business_group}/#{service_name}"
end
end
class SensuSilenced < SensuObject
end
class SensuCache
def initialize(*servers)
@servers = Hash[servers.map { |s| [s.name, s] }]
end
def servers
@servers.dup.freeze
end
def add_server(name, server)
@servers[name] = server
end
def results
@results ||= fetch(&:results)
end
def events
@events ||= fetch(&:events)
end
def silenced
@silenced ||= fetch(&:silenced)
end
def clear_all!
@results = @events = @silenced = nil
end
private
def fetch(&block)
@servers.values.flat_map(&block)
end
end
end
@SegFaultAX
Copy link
Author

Usage is something like this

require './sensu'

s1 = Sensu::Server.new("server1", "sensu01.example.com")
s2 = Sensu::Server.new("server2", "sensu02.example.com")
cache = Sensu::SensuCache.new(s1, s2)

puts cache.events
# Note: Future calls to `cache.events` will used the cached value until `#clear_all!` is called

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment