Skip to content

Instantly share code, notes, and snippets.

@christopher-b
Last active December 11, 2015 17:39
Show Gist options
  • Save christopher-b/4636430 to your computer and use it in GitHub Desktop.
Save christopher-b/4636430 to your computer and use it in GitHub Desktop.
Report Redis stats from (INFO) to Graphite
#!/usr/bin/env ruby
require 'socket'
require 'optparse'
# Collect INFO from Redis, report it to Graphite
opts = OptionParser.new do |opts|
opts.banner = "Usage: redis-graphite.rb redis-host[:redis-port] graphite-host"
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
opts.parse!
redis_server = ARGV.shift
graphite_host = ARGV.shift
unless graphite_host && redis_server
puts opts
exit 1
end
class Graphite
def initialize(host)
@host = host
end
def socket
return @socket if @socket && !@socket.closed?
@socket = TCPSocket.new(@host, 2003)
end
def report(key, value, time = Time.now)
begin
socket.write("#{key} #{value.to_f} #{time.to_i}\n")
rescue Errno::EPIPE, Errno::EHOSTUNREACH, Errno::ECONNREFUSED
@socket = nil
nil
end
end
def close_socket
@socket.close if @socket
@socket = nil
end
end
class String
def numeric?
return true if self =~ /^\d+$/
true if Float(self) rescue false
end
end
redis_host, redis_port = *redis_server.split(':')
redis_port ||= 6379
info = `redis-cli -h #{redis_host} -p #{redis_port} INFO`
exit 2 unless $?.success?
begin
graphite_client = Graphite.new(graphite_host)
info.each_line do |line|
key, value = *line.split(':')
# The db* fields have interesing info, but they need extra processing
if(key.rindex(/db[\d]+/) == 0)
db_info = value.split(',')
db_info.each do |db_detail|
db_key, db_value = *db_detail.split('=')
db_key = "#{key}-#{db_key}"
graphite_key = "redis.#{redis_host.gsub('.', '_')}:#{redis_port}.#{db_key}"
graphite_client.report(graphite_key, db_value) if db_value.numeric?
end
else
graphite_key = "redis.#{redis_host.gsub('.', '_')}:#{redis_port}.#{key}"
graphite_client.report(graphite_key, value) if value.numeric?
end
end
graphite_client.close_socket
rescue => err
puts "Error: #{err}"
exit 4
graphite_client.close_socket
end
@mattkanwisher
Copy link

There is the cases where redis will return blank lines or lines that start with # and it seems to break the code, I have a fix here https://gist.github.com/mattkanwisher/5644778

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