6 attr_reader :connection
9 def on_connecting(params=nil)
10 Log.info("TCP Connection attempt %d to %s" % [params[:cur_conattempts], stomp_url(params)])
14 def on_connected(params=nil)
15 Log.info("Conncted to #{stomp_url(params)}")
19 def on_disconnect(params=nil)
20 Log.info("Disconnected from #{stomp_url(params)}")
24 def on_connectfail(params=nil)
25 Log.info("TCP Connection to #{stomp_url(params)} failed on attempt #{params[:cur_conattempts]}")
29 def on_miscerr(params, errstr)
30 Log.error("Unexpected error on connection #{stomp_url(params)}: #{errstr}")
34 def on_ssl_connecting(params)
35 Log.info("Estblishing SSL session with #{stomp_url(params)}")
39 def on_ssl_connected(params)
40 Log.info("SSL session established with #{stomp_url(params)}")
44 def on_ssl_connectfail(params)
45 Log.error("SSL session creation with #{stomp_url(params)} failed: #{params[:ssl_exception]}")
49 "%s://%s@%s:%d" % [ params[:cur_ssl] ? "stomp+ssl" : "stomp", params[:cur_login], params[:cur_host], params[:cur_port]]
54 @config = Config.instance
59 # Connects to the RabbitMQ middleware
60 def connect(connector = ::Stomp::Connection)
62 Log.debug("Already connection, not re-initializing connection")
67 @base64 = get_bool_option("rabbitmq.base64", false)
69 pools = @config.pluginconf["rabbitmq.pool.size"].to_i
72 1.upto(pools) do |poolnum|
75 host[:host] = get_option("rabbitmq.pool.#{poolnum}.host")
76 host[:port] = get_option("rabbitmq.pool.#{poolnum}.port", 61613).to_i
77 host[:login] = get_env_or_option("STOMP_USER", "rabbitmq.pool.#{poolnum}.user")
78 host[:passcode] = get_env_or_option("STOMP_PASSWORD", "rabbitmq.pool.#{poolnum}.password")
79 host[:ssl] = get_bool_option("rabbitmq.pool.#{poolnum}.ssl", false)
81 host[:ssl] = ssl_parameters(poolnum, get_bool_option("rabbitmq.pool.#{poolnum}.ssl.fallback", false)) if host[:ssl]
83 Log.debug("Adding #{host[:host]}:#{host[:port]} to the connection pool")
87 raise "No hosts found for the RabbitMQ connection pool" if hosts.size == 0
89 connection = {:hosts => hosts}
91 # Various STOMP gem options, defaults here matches defaults for 1.1.6 the meaning of
92 # these can be guessed, the documentation isn't clear
93 connection[:initial_reconnect_delay] = Float(get_option("rabbitmq.initial_reconnect_delay", 0.01))
94 connection[:max_reconnect_delay] = Float(get_option("rabbitmq.max_reconnect_delay", 30.0))
95 connection[:use_exponential_back_off] = get_bool_option("rabbitmq.use_exponential_back_off", true)
96 connection[:back_off_multiplier] = Integer(get_option("rabbitmq.back_off_multiplier", 2))
97 connection[:max_reconnect_attempts] = Integer(get_option("rabbitmq.max_reconnect_attempts", 0))
98 connection[:randomize] = get_bool_option("rabbitmq.randomize", false)
99 connection[:backup] = get_bool_option("rabbitmq.backup", false)
100 connection[:timeout] = Integer(get_option("rabbitmq.timeout", -1))
101 connection[:connect_timeout] = Integer(get_option("rabbitmq.connect_timeout", 30))
102 connection[:reliable] = true
104 # RabbitMQ and Stomp supports vhosts, this sets it in a way compatible with RabbitMQ and
105 # force the version to 1.0, 1.1 support will be added in future
106 connection[:connect_headers] = {"accept-version" => '1.0', "host" => get_option("rabbitmq.vhost", "/")}
108 connection[:logger] = EventLogger.new
110 @connection = connector.new(connection)
111 rescue Exception => e
112 raise("Could not connect to RabbitMQ Server: #{e}")
116 # Sets the SSL paramaters for a specific connection
117 def ssl_parameters(poolnum, fallback)
118 params = {:cert_file => get_option("rabbitmq.pool.#{poolnum}.ssl.cert", false),
119 :key_file => get_option("rabbitmq.pool.#{poolnum}.ssl.key", false),
120 :ts_files => get_option("rabbitmq.pool.#{poolnum}.ssl.ca", false)}
122 raise "cert, key and ca has to be supplied for verified SSL mode" unless params[:cert_file] && params[:key_file] && params[:ts_files]
124 raise "Cannot find certificate file #{params[:cert_file]}" unless File.exist?(params[:cert_file])
125 raise "Cannot find key file #{params[:key_file]}" unless File.exist?(params[:key_file])
127 params[:ts_files].split(",").each do |ca|
128 raise "Cannot find CA file #{ca}" unless File.exist?(ca)
132 Stomp::SSLParams.new(params)
134 raise "Stomp gem >= 1.2.2 is needed"
137 rescue Exception => e
139 Log.warn("Failed to set full SSL verified mode, falling back to unverified: #{e.class}: #{e}")
142 Log.error("Failed to set full SSL verified mode: #{e.class}: #{e}")
147 # Receives a message from the RabbitMQ connection
149 Log.debug("Waiting for a message from RabbitMQ")
151 # When the Stomp library > 1.2.0 is mid reconnecting due to its reliable connection
152 # handling it sets the connection to closed. If we happen to be receiving at just
153 # that time we will get an exception warning about the closed connection so handling
154 # that here with a sleep and a retry.
156 msg = @connection.receive
157 rescue ::Stomp::Error::NoCurrentConnection
162 raise "Received a processing error from RabbitMQ: '%s'" % msg.body.chomp if msg.body =~ /Processing error/
164 Message.new(msg.body, msg, :base64 => @base64, :headers => msg.headers)
167 # Sends a message to the RabbitMQ connection
169 msg.base64_encode! if @base64
171 if msg.type == :direct_request
172 msg.discovered_hosts.each do |node|
173 target = target_for(msg, node)
175 Log.debug("Sending a direct message to RabbitMQ target '#{target[:name]}' with headers '#{target[:headers].inspect}'")
177 @connection.publish(target[:name], msg.payload, target[:headers])
180 target = target_for(msg)
182 Log.debug("Sending a broadcast message to RabbitMQ target '#{target[:name]}' with headers '#{target[:headers].inspect}'")
184 @connection.publish(target[:name], msg.payload, target[:headers])
188 def target_for(msg, node=nil)
189 if msg.type == :reply
190 target = {:name => msg.request.headers["reply-to"], :headers => {}, :id => ""}
192 elsif [:request, :direct_request].include?(msg.type)
193 target = make_target(msg.agent, msg.type, msg.collective, msg.reply_to, node)
196 raise "Don't now how to create a target for message type #{msg.type}"
203 def make_target(agent, type, collective, reply_to=nil, node=nil)
204 raise("Unknown target type #{type}") unless [:directed, :broadcast, :reply, :request, :direct_request].include?(type)
205 raise("Unknown collective '#{collective}' known collectives are '#{@config.collectives.join ', '}'") unless @config.collectives.include?(collective)
207 target = {:name => "", :headers => {}, :id => nil}
210 when :reply # receiving replies on a temp queue
211 target[:name] = "/temp-queue/mcollective_reply_%s" % agent
212 target[:id] = "mcollective_%s_replies" % agent
214 when :broadcast, :request # publishing a request to all nodes with an agent
215 target[:name] = "/exchange/%s_broadcast/%s" % [collective, agent]
217 target[:headers]["reply-to"] = reply_to
219 target[:headers]["reply-to"] = "/temp-queue/mcollective_reply_%s" % agent
221 target[:id] = "%s_broadcast_%s" % [collective, agent]
223 when :direct_request # a request to a specific node
224 raise "Directed requests need to have a node identity" unless node
226 target[:name] = "/exchange/%s_directed/%s" % [ collective, node]
227 target[:headers]["reply-to"] = "/temp-queue/mcollective_reply_%s" % agent
229 when :directed # subscribing to directed messages
230 target[:name] = "/exchange/%s_directed/%s" % [ collective, @config.identity ]
231 target[:id] = "%s_directed_to_identity" % @config.identity
237 # Subscribe to a topic or queue
238 def subscribe(agent, type, collective)
239 return if type == :reply
241 source = make_target(agent, type, collective)
243 unless @subscriptions.include?(source[:id])
244 Log.debug("Subscribing to #{source[:name]} with headers #{source[:headers].inspect.chomp}")
245 @connection.subscribe(source[:name], source[:headers], source[:id])
246 @subscriptions << source[:id]
248 rescue ::Stomp::Error::DuplicateSubscription
249 Log.error("Received subscription request for #{source.inspect.chomp} but already had a matching subscription, ignoring")
252 # Subscribe to a topic or queue
253 def unsubscribe(agent, type, collective)
254 return if type == :reply
256 source = make_target(agent, type, collective)
258 Log.debug("Unsubscribing from #{source[:name]}")
259 @connection.unsubscribe(source[:name], source[:headers], source[:id])
260 @subscriptions.delete(source[:id])
263 # Disconnects from the RabbitMQ connection
265 Log.debug("Disconnecting from RabbitMQ")
266 @connection.disconnect
270 # looks in the environment first then in the config file
271 # for a specific option, accepts an optional default.
273 # raises an exception when it cant find a value anywhere
274 def get_env_or_option(env, opt, default=nil)
275 return ENV[env] if ENV.include?(env)
276 return @config.pluginconf[opt] if @config.pluginconf.include?(opt)
277 return default if default
279 raise("No #{env} environment or plugin.#{opt} configuration option given")
282 # looks for a config option, accepts an optional default
284 # raises an exception when it cant find a value anywhere
285 def get_option(opt, default=nil)
286 return @config.pluginconf[opt] if @config.pluginconf.include?(opt)
287 return default unless default.nil?
289 raise("No plugin.#{opt} configuration option given")
292 # gets a boolean option from the config, supports y/n/true/false/1/0
293 def get_bool_option(opt, default)
294 return default unless @config.pluginconf.include?(opt)
296 val = @config.pluginconf[opt]
298 if val =~ /^1|yes|true/
300 elsif val =~ /^0|no|false/
310 # vi:tabstop=4:expandtab:ai