Created
July 30, 2012 19:30
-
-
Save eric/3209414 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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