Skip to content

Instantly share code, notes, and snippets.

@rlister
Created October 7, 2011 19:50
Show Gist options
  • Save rlister/1271205 to your computer and use it in GitHub Desktop.
Save rlister/1271205 to your computer and use it in GitHub Desktop.
## gather mongo-related stats and jam them into graphite
require 'mongo'
## method to convert nested hash to array of dot-separated properties
class Hash
def propertize(prepend=nil)
self.map do |key,value|
new_key = [prepend, key].compact.join('.')
value.is_a?(Hash) ? value.propertize(new_key) : "#{new_key} #{value.to_s}"
end.flatten
end
end
## get list of socket numbers extracted from mongodb unix socket filenames
sockets = Dir.glob('/tmp/mongodb-*.sock').map{ |file| file[/mongodb-(\d+)\.sock/, 1] }.sort
## remove httpd sockets (which are all 1000 + mongod socket)
sockets.each { |s| sockets.delete( (s.to_i + 1000).to_s ) }
metrics = []
## connect to each mongod and add mongostats
metrics << sockets.map do |socket|
mongo = Mongo::Connection.new("localhost", socket) or next
status = mongo.db('test').command('serverStatus' => 1)
mongo.close
## select just numeric stats, and prepend mongod name
status.propertize.select{ |s| s.match(/\s+[+-]?\d+?(\.\d+)?$/) }.map{ |s| "mongod:#{socket}.#{s}" }
end
metrics.flatten!
## connection to graphite
epoch = Time.now.to_i
TCPSocket.open("vm-149-174-161-42.asset.aol.com", 2003) do |graphite|
metrics.each{ |metric| graphite.write("stats.mq.mongo.#{hostname}.#{metric} #{epoch}\n") }
end
## write to stdout for logging (sanity-check)
puts metrics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment