Module: AMQP::Client

Includes:
EM::Deferrable, RightSupport::Log::Mixin
Defined in:
lib/right_amqp/amqp/client.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.connect(opts = {}) ⇒ Object



283
284
285
286
# File 'lib/right_amqp/amqp/client.rb', line 283

def self.connect opts = {}
  opts = AMQP.settings.merge(opts)
  EM.connect opts[:host], opts[:port], self, opts
end

.included(base) ⇒ Object



76
77
78
# File 'lib/right_amqp/amqp/client.rb', line 76

def self.included(base)
  base.extend(RightSupport::Log::Mixin::ClassMethods)
end

Instance Method Details

#add_channel(mq) ⇒ Object



170
171
172
173
174
175
# File 'lib/right_amqp/amqp/client.rb', line 170

def add_channel mq
  (@_channel_mutex ||= Mutex.new).synchronize do
    channels[ key = (channels.keys.max || 0) + 1 ] = mq
    key
  end
end

#channelsObject



177
178
179
# File 'lib/right_amqp/amqp/client.rb', line 177

def channels
  @channels ||= {}
end

#close(&on_disconnect) ⇒ Object

:stopdoc: def send_data data

log 'send_data', data
super

end :startdoc:



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/right_amqp/amqp/client.rb', line 222

def close &on_disconnect
  @heartbeat_timer.cancel if @heartbeat_timer
  @heartbeat_timer = nil
  if on_disconnect
    @closing = true
    @on_disconnect = proc{
      on_disconnect.call
      @closing = false
    }
  end

  callback{ |c|
    if c.channels.any?
      c.channels.each do |ch, mq|
        mq.close
      end
    else
      send Protocol::Connection::Close.new(:reply_code => 200,
                                           :reply_text => 'Goodbye',
                                           :class_id => 0,
                                           :method_id => 0)
    end
  }
end

#connected?Boolean

Returns:

  • (Boolean)


160
161
162
# File 'lib/right_amqp/amqp/client.rb', line 160

def connected?
  @connected
end

#connection_completedObject



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/right_amqp/amqp/client.rb', line 92

def connection_completed
  start_tls if @settings[:ssl]
  log 'connected'
  # @on_disconnect = proc{ raise Error, 'Disconnected from server' }
  unless @closing
    @on_disconnect = method(:disconnected)
    @reconnecting = false
  end

  @connected = true
  @connection_status.call(:connected) if @connection_status

  @buf = Buffer.new
  send_data HEADER
  send_data [1, 1, VERSION_MAJOR, VERSION_MINOR].pack('C4')

  if heartbeat = @settings[:heartbeat]
    init_heartbeat if (@settings[:heartbeat] = heartbeat.to_i) > 0
  end
end

#connection_status(&blk) ⇒ Object



288
289
290
# File 'lib/right_amqp/amqp/client.rb', line 288

def connection_status &blk
  @connection_status = blk
end

#failedObject



292
293
294
295
296
# File 'lib/right_amqp/amqp/client.rb', line 292

def failed
  @connection_status.call(:failed) if @connection_status
  @has_failed = true
  close_connection
end

#init_heartbeatObject



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/right_amqp/amqp/client.rb', line 113

def init_heartbeat
  # Randomly offset start of heartbeat timer to help separate heartbeat
  # activity when there are multiple broker connections active
  EM.add_timer(rand(@settings[:heartbeat])) do
    begin
      # While connected, a heartbeat or some other data is expected to be received from
      # the broker at least every 2 x :heartbeat seconds, otherwise the connection is
      # assumed to be broken and therefore is closed to cause an automatic reconnect.
      # While connected, this client will send a heartbeat every :heartbeat
      # seconds regardless of any other send activity. The RabbitMQ broker will behave
      # similarly and drop the connection if it does not receive a heartbeat or other
      # data in time.
      logger.info("[amqp] Initializing heartbeat for broker #{@settings[:identity]} to #{@settings[:heartbeat]} sec")

      timeout_factor = 2
      @heartbeat_timer.cancel if @heartbeat_timer
      @heartbeat_timer = EM::PeriodicTimer.new(@settings[:heartbeat]) do
        begin
          if connected?
            now = Time.now
            if @last_data_received < (now - (@settings[:heartbeat] * timeout_factor))
              data_received = (now - @last_data_received).to_i if @last_data_received
              heartbeat_received = (now - @last_heartbeat_received).to_i if @last_heartbeat_received
              heartbeat_sent = (now - @last_heartbeat_sent).to_i if @last_heartbeat_sent
              logger.info("[amqp] Reconnecting to broker #{@settings[:identity]} due to heartbeat timeout: " +
                          "last data received #{data_received.inspect} sec ago, " +
                          "last heartbeat received #{heartbeat_received.inspect} sec ago, " +
                          "last heartbeat sent #{heartbeat_sent.inspect} sec ago")
              close_connection # which results in an unbind and an automatic reconnect
            else
              logger.debug("[amqp] Sending heartbeat to broker #{@settings[:identity]}")
              send AMQP::Frame::Heartbeat.new, :channel => 0
              @last_heartbeat_sent = Time.now
            end
          else
            logger.debug("[amqp] Skipping heartbeat check for broker #{@settings[:identity]} because disconnected")
          end
        rescue Exception => e
          logger.error("[amqp] Failed heartbeat check (#{e})\n" + e.backtrace.join("\n"))
        end
      end
    rescue Exception => e
      logger.error("[amqp] Failed heartbeat initialization (#{e})\n" + e.backtrace.join("\n"))
    end
  end
end

#initialize(opts = {}) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/right_amqp/amqp/client.rb', line 80

def initialize opts = {}
  @settings = opts
  extend AMQP.client

  @on_disconnect ||= proc{ @connection_status.call(:failed) if @connection_status }

  timeout @settings[:timeout] if @settings[:timeout]
  errback{ @on_disconnect.call } unless @reconnecting

  @connected = false
end

#process_frame(frame) ⇒ Object



201
202
203
204
# File 'lib/right_amqp/amqp/client.rb', line 201

def process_frame frame
  # this is a stub meant to be
  # replaced by the module passed into initialize
end

#receive_data(data) ⇒ Object

Catch exceptions that would otherwise cause EM to stop or be in a bad state if a top level EM error handler was setup. Instead close the connection and leave EM alone. Don’t log an error if the environment variable IGNORE_AMQP_FAILURES is set (used in the enroll script)



186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/right_amqp/amqp/client.rb', line 186

def receive_data data
  begin
    # log 'receive_data', data
    @buf << data

    while frame = Frame.parse(@buf)
      log 'receive', frame
      process_frame frame
    end
  rescue Exception => e
    logger.exception("[amqp] Failed processing frame, closing connection", e, :trace) unless ENV['IGNORE_AMQP_FAILURES']
    failed
  end
end

#reconnect(force = false) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/right_amqp/amqp/client.rb', line 247

def reconnect force = false
  if @reconnecting and not force
    # Wait after first reconnect attempt and in between each subsequent attempt
    EM.add_timer(@settings[:reconnect_interval] || 5) { reconnect(true) }
    return
  end

  unless @reconnecting
    @deferred_status = nil
    initialize(@settings)

    mqs = @channels
    @channels = {}
    mqs.each{ |_,mq| mq.reset } if mqs

    @reconnecting = true

    again = @settings[:reconnect_delay]
    again = again.call if again.is_a?(Proc)
    if again.is_a?(Numeric)
      # Wait before making initial reconnect attempt
      EM.add_timer(again) { reconnect(true) }
      return
    elsif ![nil, true].include?(again)
      raise ::AMQP::Error, "Could not interpret :reconnect_delay => #{again.inspect}; expected nil, true, or Numeric"
    end
  end

  log 'reconnecting'
  logger.info("[amqp] Attempting to reconnect to #{@settings[:identity]}")
  EM.reconnect(@settings[:host], @settings[:port], self)
rescue Exception => e
  logger.exception("[amqp] Failed to reconnect", e, :trace)
  failed
end

#send(data, opts = {}) ⇒ Object



206
207
208
209
210
211
212
213
# File 'lib/right_amqp/amqp/client.rb', line 206

def send data, opts = {}
  channel = opts[:channel] ||= 0
  data = data.to_frame(channel) unless data.is_a? Frame
  data.channel = channel

  log 'send', data
  send_data data.to_s
end

#unbindObject



164
165
166
167
168
# File 'lib/right_amqp/amqp/client.rb', line 164

def unbind
  log 'disconnected'
  @connected = false
  EM.next_tick{ @on_disconnect.call }
end