class Statsd::Server::Daemon

Public Instance Methods

run(options) click to toggle source
# File lib/statsd/server.rb, line 47
def run(options)
  config = YAML::load(ERB.new(IO.read(options[:config])).result)

  if options[:mongo]
    require 'statsd/mongo'
    # Setup retention store
    db = ::Mongo::Connection.new(config['mongo_host']).db(config['mongo_database'])
    config['retentions'].each do |retention|
      collection_name = retention['name']
      unless db.collection_names.include?(collection_name)
        db.create_collection(collection_name, :capped => retention['capped'], :size => retention['cap_bytes']) 
      end
      db.collection(collection_name).ensure_index([['ts', ::Mongo::ASCENDING]])
    end        
    Statsd::Mongo.hostname = config['mongo_host']
    Statsd::Mongo.database = config['mongo_database']
    Statsd::Mongo.retentions = config['retentions']
    Statsd::Mongo.flush_interval = config['flush_interval']
  end

  if options[:graphite]
    require 'statsd/graphite' 
  end

  # Start the server
  EventMachine::run do
    EventMachine::open_datagram_socket(config['bind'], config['port'], Statsd::Server)  

    # Periodically Flush
    EventMachine::add_periodic_timer(config['flush_interval']) do
      counters,timers = Statsd::Server.get_and_clear_stats!

       # Flush Adapters
      if options[:mongo]
        EM.defer { Statsd::Mongo.flush_stats(counters,timers) } 
      end

      if options[:graphite]
        EventMachine.connect config['graphite_host'], config['graphite_port'], Statsd::Graphite do |conn|
          conn.counters = counters
          conn.timers = timers
          conn.flush_interval = config['flush_interval']
          conn.flush_stats
        end     
      end
    
    end

  end

end