Skip to content

Instantly share code, notes, and snippets.

@maplebed
Created December 5, 2012 05:18
Show Gist options
  • Save maplebed/4212567 to your computer and use it in GitHub Desktop.
Save maplebed/4212567 to your computer and use it in GitHub Desktop.
Sinatra app to expose ganglia data
#!/usr/bin/env ruby
##
## This script exposes ganglia data for use by other apps.
## Ask it for a specific host/metric/time triplet, and it
## hands back a json string with the data.
## eg http://localhost/rrdfetch/web12/load_one/3600
## returns the last hour of the load_one metric.
##
require 'rubygems'
require 'sinatra'
require 'find'
require 'json'
get '/rrdfetch/:host/:metric/:time' do
hostdir = []
Find.find('/var/lib/ganglia/rrds') do |path|
hostdir << path if path =~ /#{params['host']}$/
end
metric = []
Find.find(hostdir[0]) do |path|
metric << path if path =~ /#{params['metric']}.rrd$/
end
#sanitize elements
unless(hostdir[0] =~ /^[a-z0-9\/_.-]+$/)
halt "hostdir #{hostdir[0]} didn't match regex."
end
unless(metric[0] =~ /^[a-z0-9\/_.-]+$/)
halt "metric #{metric[0]} didn't match regex."
end
unless(params['time'] =~ /^\d+$/)
halt "time #{params['time']} didn't match regex."
end
starttime = Time.now - params['time'].to_i
endtime = Time.now
puts "rrdtool fetch #{metric[0]} AVERAGE --start #{starttime.strftime('%s')}"
data = %x{rrdtool fetch #{metric[0]} AVERAGE --start #{starttime.strftime('%s')}}
mungeddata = []
data.split("\n").each() do |line|
(time, val) = line.split(':')
next if time !~ /\d{8}/
val = val.to_f
mungeddata << {:timestamp => Time.at(time.to_i).strftime('%s'), :unit => 'Seconds', :average => val}
end
return mungeddata.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment