#!/usr/bin/env ruby require 'optparse' require 'ostruct' require 'yajl/json_gem' require 'redis' # add lib to the default include path unless $:.include?(File.dirname(__FILE__) + '/../lib/') $: << File.dirname(__FILE__) + '/../lib' end require 'flapjack/configuration' require 'flapjack/data/contact' require 'flapjack/data/entity' require 'flapjack/data/event' options = OpenStruct.new options.config = File.join('etc', 'flapjack_config.yaml') options.daemonize = nil command = ARGV.shift banner = "Usage: flapjack-populator command [options]\n" banner += "\n" banner += " commands:\n" banner += " - import-entities\n" banner += " - import-contacts\n" banner += " - purge-events (purge queued monitoring events)\n" OptionParser.new do |opts| opts.banner = "Usage: flapjack-populator command [options]" opts.on("-c", "--config [PATH]", String, "PATH to the config file to use") do |c| options.config = c end opts.on("-f", "--from [FILE]", String, "path to the FILE to import") do |f| options.from = f end end.parse!(ARGV) FLAPJACK_ENV = ENV['FLAPJACK_ENV'] || 'development' config_env = Flapjack::Configuration.new.load(options.config) if config_env.nil? || config_env.empty? puts "No config data for environment '#{FLAPJACK_ENV}' found in '#{options.config}'" exit(false) end if options.from filename = options.from file = File.new(filename) end def get_redis_connection(cfg) opts = cfg['path'] ? {:path => cfg['path']} : {:host => cfg['host'], :port => cfg['port']} Redis.new(opts.merge(:db => cfg['db'])) end case command when "import-contacts" contacts = JSON.parse(file) if contacts && contacts.is_a?(Enumerable) && contacts.any? {|e| !e['id'].nil?} @persistence = get_redis_connection(config_env['redis']) @persistence.multi do contacts.each do |contact| unless contact['id'] puts "Contact not imported as it has no id: " + contact.inspect next end Flapjack::Data::Contact.add(contact, :redis => @persistence) end end @persistence.quit end when "import-entities" entities = JSON.parse(file) if entities && entities.is_a?(Enumerable) && entities.any? {|e| !e['id'].nil?} @persistence = get_redis_connection(config_env['redis']) @persistence.multi entities.each do |entity| unless entity['id'] puts "Entity not imported as it has no id: " + entity.inspect next end Flapjack::Data::Entity.add(entity, :redis => @persistence) end @persistence.exec @persistence.quit end when "purge-events" @persistence = get_redis_connection(config_env['redis']) Flapjack::Data::Event.purge_all(:redis => @persistence) @persistence.quit else puts "you need to give me something to do, eg a command like 'import-entities' or 'import-clients' etc" raise ArgumentError end