#!/usr/bin/env ruby require 'optparse' require 'ostruct' require 'oj' Oj.default_options = { :indent => 0, :mode => :strict } 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 = Flapjack::Configuration::DEFAULT_CONFIG_PATH exe = File.basename(__FILE__) optparse = OptionParser.new do |opts| opts.banner = "Usage: #{exe} COMMAND [OPTIONS]" opts.separator "" opts.separator "Commands:" opts.separator " import-entities" opts.separator " import-contacts" opts.separator " purge-events purge queued monitoring events" opts.separator "" opts.separator "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 optparse.parse!(ARGV) if options.help puts optparse exit elsif options.version puts Flapjack::VERSION exit elsif !["import-contacts", "import-entities", "purge-events"].include?(ARGV[0]) if ARGV.nil? || ARGV.empty? puts "No command provided" else puts "Unknown command provided: '#{ARGV[0]}'" end puts "\n#{optparse}" exit 1 end FLAPJACK_ENV = ENV['FLAPJACK_ENV'] || 'production' config = Flapjack::Configuration.new config.load(options.config) config_env = config.all redis_options = config.for_redis 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 case ARGV[0] when "import-contacts" contacts = Oj.load(file) if contacts && contacts.is_a?(Enumerable) && contacts.any? {|e| !e['id'].nil?} @persistence = Redis.new(redis_options) 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 @persistence.quit end when "import-entities" entities = Oj.load(file) if entities && entities.is_a?(Enumerable) && entities.any? {|e| !e['id'].nil?} @persistence = Redis.new(redis_options) 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.quit end when "purge-events" @persistence = Redis.new(redis_options) events_size = @persistence.llen('events') puts "purging #{events_size} events..." etq = "events.#{Time.now.to_i}" puts "renaming 'events' to '#{etq}'" @persistence.rename('events', etq) puts "setting expiry of '#{etq}' to 8 hours" @persistence.expire(etq, (60 * 60 * 8)) @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