Skip to content

Instantly share code, notes, and snippets.

@heffergm
Created October 7, 2011 19:31
Show Gist options
  • Save heffergm/1271166 to your computer and use it in GitHub Desktop.
Save heffergm/1271166 to your computer and use it in GitHub Desktop.
Send mongo op data to graphite
#!/usr/bin/env ruby
## Send Mongo data to graphite
require 'rubygems'
require 'json'
require 'mongo'
graphite_host = File.read("/opt/scripts/etc/graphite_host")
interval = 10 #collect data every x seconds
loop do
time = Time.new
epoch = time.to_i
## Graphite host
begin
s = TCPSocket.open("#{graphite_host}", 2003)
rescue
puts "error: #{$!}"
puts "Sleeping before retrying..."
sleep 10
else
begin
db = Mongo::Connection.new("localhost", 27017, :op_timeout => 3).db("mydb_production")
rescue
puts "error: #{$!}"
puts "Sleeping before retrying..."
sleep 10
else
status = db.command('serverStatus' => 1)
hostname = status['host'].split(/\./)[0]
op_insert1 = status['opcounters']['insert']
op_update1 = status['opcounters']['update']
op_query1 = status['opcounters']['query']
op_delete1 = status['opcounters']['delete']
op_getmore1 = status['opcounters']['getmore']
op_command1 = status['opcounters']['command']
sleep interval
status = db.command('serverStatus' => 1)
op_insert2 = status['opcounters']['insert']
op_update2 = status['opcounters']['update']
op_query2 = status['opcounters']['query']
op_delete2 = status['opcounters']['delete']
op_getmore2 = status['opcounters']['getmore']
op_command2 = status['opcounters']['command']
# Do the math
resultshash = {
"op_insert" => (op_insert2 - op_insert1)/interval.to_f,
"op_update" => (op_update2 - op_update1)/interval.to_f,
"op_query"=> (op_query2 - op_query1)/interval.to_f,
"op_delete" => (op_delete2 - op_delete1)/interval.to_f,
"op_getmore" => (op_getmore2 - op_getmore1)/interval.to_f,
"op_command" => (op_command2 - op_command1)/interval.to_f
}
# write the data
resultshash.each do |metric, result|
s.write("stats.mydb.production.mongo.#{hostname}.#{metric} #{result} #{epoch}\n")
end
end
s.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment