Skip to content

Instantly share code, notes, and snippets.

@eric
Created July 30, 2012 19:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric/3209414 to your computer and use it in GitHub Desktop.
Save eric/3209414 to your computer and use it in GitHub Desktop.
require 'lazy'
require 'system_timer'
class LibratoMetric
COUNT = 10
RESOLUTION = 1
def initialize(metric_name, timeout = 4)
@metric_name = metric_name
@timeout = timeout
# Start loading data
data
end
def data
@data ||= Lazy.future do
begin
with_timeout do
fetch(@metric_name, :count => COUNT, :resolution => RESOLUTION, :summarize_time => true)
end
rescue Timeout::Error, Librato::Metrics::CredentialsMissing
nil
end
end
end
def value
@value ||= begin
if d = Lazy.demand(data)
d.sum { |source, data| data[0]['value'] }
end
end
end
def time
if measure_time
measure_time + COUNT.minutes
end
end
def measure_time
@measure_time ||= begin
if d = Lazy.demand(data)
Time.at(d.collect { |source, data| data[0]['measure_time'] }.min)
end
end
end
def with_timeout(&block)
SystemTimer.timeout_after(@timeout, Timeout::Error, &block)
end
def fetch(*args)
client = Librato::Metrics::Client.new
client.authenticate(Librato::Metrics.client.email, Librato::Metrics.client.api_key)
client.fetch(*args)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment