Skip to content

Instantly share code, notes, and snippets.

@mattkanwisher
Forked from christopher-b/redis-graphite.rb
Created May 24, 2013 16:38
Show Gist options
  • Save mattkanwisher/5644778 to your computer and use it in GitHub Desktop.
Save mattkanwisher/5644778 to your computer and use it in GitHub Desktop.
#!/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|
if line.length < 4
next
end
if line.start_with?("#")
next
end
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment