require 'yaml' require 'logger' require 'eventmachine' require "uuidtools" require "#{File.dirname(__FILE__)}/../shared/sidekick_logger" require "#{File.dirname(__FILE__)}/../shared/sidekick_queue_publisher" Thread.new { EM.run } unless EM.reactor_running? SIDEKICK_CONFIG = "/etc/vamp/sidekick.conf" unless defined?(SIDEKICK_CONFIG) # TODO: this client must be used from within a rails application right now # because it relies on RAILS_ROOT to find its config file # class SidekickClient attr_reader :logger attr_reader :config def initialize(config_override={}) if File.exists? SIDEKICK_CONFIG @config ||= YAML.load_file(SIDEKICK_CONFIG).with_indifferent_access.merge(config_override) else @config ||= config_override.with_indifferent_access end if @config[:sidekick_log_file] @logger = SidekickLogger.new(@config[:sidekick_log_file].to_s.gsub("sidekick.log","sidekick_client.log")) else @logger = SidekickLogger.new(STDOUT) end @config[:exchange] ||= "amq.direct" @logger.info "Initialized SidekickClient with config #{@config.inspect}" @qconn = SidekickQueuePublisher.new(@config, @logger) end def self.send_and_disconnect(cmd, args={}, queue_name=nil) SidekickClient.new.send_and_disconnect(cmd,args,queue_name) end def self.send_and_receive(cmd, args={}, queue_name=nil) SidekickClient.new.send_and_receive(cmd,args,queue_name) end def send_and_disconnect(cmd, args={}, queue_name=nil) message = { :command => cmd, :args => args} @qconn.publish(message.to_yaml, queue_name || @config[:queue_name]) return true end def send_and_receive(cmd, args={}, queue_name=nil) temp_queue = "tmp-reply-#{UUIDTools::UUID.random_create}" message = { :command => cmd, :args => args, :reply_to => {:exchange => @config[:exchange], :routing_key => temp_queue}} response = @qconn.publish(message.to_yaml, queue_name || @config[:queue_name], temp_queue) return response && YAML.load(response) end end