Skip to content

Instantly share code, notes, and snippets.

@jewzaam
Created March 4, 2015 14:23
Show Gist options
  • Save jewzaam/ef7b47b8b580263082f3 to your computer and use it in GitHub Desktop.
Save jewzaam/ef7b47b8b580263082f3 to your computer and use it in GitHub Desktop.
dashing graphite job that supports https
require 'open-uri'
require 'json'
require 'date'
# Pull data from Graphite and make available to Dashing Widgets
# Heavily inspired from Thomas Van Machelen's "Bling dashboard article"
# Set the graphite host and port (ip or hostname)
GRAPHITE_URL = 'https://your.graphite.host'
INTERVAL = '30s'
# Job mappings. Define a name and set the metrics name from graphite
job_mapping = {
'host1-load-1min' => '*.*.host1.load.onemin',
'host2-load-1min' => '*.*.host1.load.onemin'
}
# Extend the float to allow better rounding. Too many digits makes a messy dashboard
class Float
def sigfig_to_s(digits)
f = sprintf("%.#{digits - 1}e", self).to_f
i = f.to_i
(i == f ? i : f)
end
end
class Graphite
# Initialize the class
def initialize(url)
@url = url
end
# Use Graphite api to query for the stats, parse the returned JSON and return the result
def query(url, statname, since=nil)
since ||= '1h-ago'
print "SOURCE: #{url}/render?format=json&target=#{statname}&from=#{since}\n"
response = URI.parse("#{url}/render?format=json&target=#{statname}&from=#{since}").read
result = JSON.parse(response, :symbolize_names => true)
return result.first
end
# Gather the datapoints and turn into Dashing graph widget format
def points(name, since=nil)
since ||= '-1min'
stats = query @url, name, since
datapoints = stats[:datapoints]
points = []
count = 1
(datapoints.select { |el| not el[0].nil? }).each do|item|
points << { x: count, y: get_value(item)}
count += 1
end
value = (datapoints.select { |el| not el[0].nil? }).last[0].sigfig_to_s(2)
return points, value
end
def get_value(datapoint)
value = datapoint[0] || 0
return value.round(2)
end
def value(name, since=nil)
since ||= '-10min'
stats = query @url, name, since
last = (stats[:datapoints].select { |el| not el[0].nil? }).last[0].sigfig_to_s(2)
return last
end
end
job_mapping.each do |title, statname|
SCHEDULER.every INTERVAL, :first_in => 0 do
# Create an instance of our Graphite class
q = Graphite.new GRAPHITE_URL
# Get the current points and value. Timespan is static atm
points, current = q.points "#{statname}", "-1hour"
# Send to dashboard, tested supports for number, meter and graph widgets
send_event "#{title}", { current: current, value: current, points: points }
end
end
@jewzaam
Copy link
Author

jewzaam commented Mar 4, 2015

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