Parent

Class/Module Index [+]

Quicksearch

Bunny::Session

Represents AMQP 0.9.1 connection (connection to RabbitMQ). @see rubybunny.info/articles/connecting.html Connecting to RabbitMQ guide

Constants

CONNECT_TIMEOUT

backwards compatibility @private

DEFAULT_CLIENT_PROPERTIES

RabbitMQ client metadata

DEFAULT_CONTINUATION_TIMEOUT

@private

DEFAULT_FRAME_MAX

@private

DEFAULT_HEARTBEAT

Default heartbeat interval, the same value as RabbitMQ 3.0 uses.

DEFAULT_HOST

Default host used for connection

DEFAULT_LOCALE

@private

DEFAULT_NETWORK_RECOVERY_INTERVAL

Default reconnection interval for TCP connection failures

DEFAULT_PASSWORD

Default password used for connection

DEFAULT_USER

Default username used for connection

DEFAULT_VHOST

Default virtual host used for connection

Attributes

channel_id_allocator[R]
continuation_timeout[R]

@return [Integer] Timeout for blocking protocol operations (queue.declare, queue.bind, etc), in milliseconds. Default is 4000.

default_channel[R]
frame_max[R]
heartbeat[R]
host[R]
logger[R]

@return [Logger]

mechanism[R]

Authentication mechanism, e.g. "PLAIN" or "EXTERNAL" @return [String]

mutex_impl[R]

@private

pass[R]
port[R]
server_authentication_mechanisms[R]
server_capabilities[R]
server_locales[R]
server_properties[R]
status[R]
threaded[R]
transport[R]

@return [Bunny::Transport]

user[R]
vhost[R]

Public Class Methods

new(connection_string_or_opts = Hash.new, optz = Hash.new) click to toggle source

@param [String, Hash] connection_string_or_opts Connection string or a hash of connection options @param [Hash] optz Extra options not related to connection

@option connection_string_or_opts [String] :host (“127.0.0.1”) Hostname or IP address to connect to @option connection_string_or_opts [Integer] :port (5672) Port RabbitMQ listens on @option connection_string_or_opts [String] :username (“guest”) Username @option connection_string_or_opts [String] :password (“guest”) Password @option connection_string_or_opts [String] :vhost (“/”) Virtual host to use @option connection_string_or_opts [Integer] :heartbeat (600) Heartbeat interval. 0 means no heartbeat. @option connection_string_or_opts [Boolean] :tls (false) Should TLS/SSL be used? @option connection_string_or_opts [String] :tls_cert (nil) Path to client TLS/SSL certificate file (.pem) @option connection_string_or_opts [String] :tls_key (nil) Path to client TLS/SSL private key file (.pem) @option connection_string_or_opts [Array<String>] :tls_ca_certificates Array of paths to TLS/SSL CA files (.pem), by default detected from OpenSSL configuration

@option optz [String] :auth_mechanism (“PLAIN”) Authentication mechanism, PLAIN or EXTERNAL @option optz [String] :locale (“PLAIN”) Locale RabbitMQ should use

@see rubybunny.info/articles/connecting.html Connecting to RabbitMQ guide @see rubybunny.info/articles/tls.html TLS/SSL guide @api public

# File lib/bunny/session.rb, line 111
def initialize(connection_string_or_opts = Hash.new, optz = Hash.new)
  opts = case (ENV["RABBITMQ_URL"] || connection_string_or_opts)
         when nil then
           Hash.new
         when String then
           self.class.parse_uri(ENV["RABBITMQ_URL"] || connection_string_or_opts)
         when Hash then
           connection_string_or_opts
         end.merge(optz)

  @opts            = opts
  @host            = self.hostname_from(opts)
  @port            = self.port_from(opts)
  @user            = self.username_from(opts)
  @pass            = self.password_from(opts)
  @vhost           = self.vhost_from(opts)
  @logfile         = opts[:log_file] || opts[:logfile] || STDOUT
  @threaded        = opts.fetch(:threaded, true)

  self.init_logger(opts[:log_level] || ENV["BUNNY_LOG_LEVEL"] || Logger::WARN)

  # should automatic recovery from network failures be used?
  @automatically_recover = if opts[:automatically_recover].nil? && opts[:automatic_recovery].nil?
                             true
                           else
                             opts[:automatically_recover] || opts[:automatic_recovery]
                           end
  @network_recovery_interval = opts.fetch(:network_recovery_interval, DEFAULT_NETWORK_RECOVERY_INTERVAL)
  # in ms
  @continuation_timeout      = opts.fetch(:continuation_timeout, DEFAULT_CONTINUATION_TIMEOUT)

  @status             = :not_connected

  # these are negotiated with the broker during the connection tuning phase
  @client_frame_max   = opts.fetch(:frame_max, DEFAULT_FRAME_MAX)
  @client_channel_max = opts.fetch(:channel_max, 65536)
  @client_heartbeat   = self.heartbeat_from(opts)

  @client_properties   = opts[:properties] || DEFAULT_CLIENT_PROPERTIES
  @mechanism           = opts.fetch(:auth_mechanism, "PLAIN")
  @credentials_encoder = credentials_encoder_for(@mechanism)
  @locale              = @opts.fetch(:locale, DEFAULT_LOCALE)

  @mutex_impl          = @opts.fetch(:mutex_impl, Monitor)

  # mutex for the channel id => channel hash
  @channel_mutex       = @mutex_impl.new
  # transport operations/continuations mutex. A workaround for
  # the non-reentrant Ruby mutexes. MK.
  @transport_mutex     = @mutex_impl.new
  @channels            = Hash.new

  @origin_thread       = Thread.current

  self.reset_continuations
  self.initialize_transport
end
parse_uri(uri) click to toggle source

Parses an amqp URI into a hash that {Bunny::Session#initialize} accepts.

@param [String] uri amqp or amqps URI to parse @return [Hash] Parsed URI as a hash

# File lib/bunny/session.rb, line 384
def self.parse_uri(uri)
  AMQ::Settings.parse_amqp_url(uri)
end

Public Instance Methods

automatically_recover?() click to toggle source

@return [Boolean] true if this connection has automatic recovery from network failure enabled

# File lib/bunny/session.rb, line 314
def automatically_recover?
  @automatically_recover
end
blocked?() click to toggle source

@return [Boolean] true if the connection is currently blocked by RabbitMQ because it’s running low on

RAM, disk space, or other resource; false otherwise

@see on_blocked @see on_unblocked

# File lib/bunny/session.rb, line 376
def blocked?
  @blocked
end
channel(n = nil, consumer_pool_size = 1) click to toggle source
Alias for: create_channel
close() click to toggle source

Closes the connection. This involves closing all of its channels.

# File lib/bunny/session.rb, line 271
def close
  if @transport.open?
    close_all_channels

    Bunny::Timeout.timeout(@transport.disconnect_timeout, ClientTimeout) do
      self.close_connection(true)
    end

    maybe_shutdown_reader_loop
    close_transport

    @status = :closed
  end
end
Also aliased as: stop
close_all_channels() click to toggle source

@private

# File lib/bunny/session.rb, line 419
def close_all_channels
  @channels.reject {|n, ch| n == 0 || !ch.open? }.each do |_, ch|
    Bunny::Timeout.timeout(@transport.disconnect_timeout, ClientTimeout) { ch.close }
  end
end
close_channel(ch) click to toggle source

@private

# File lib/bunny/session.rb, line 407
def close_channel(ch)
  n = ch.number

  @transport.send_frame(AMQ::Protocol::Channel::Close.encode(n, 200, "Goodbye", 0, 0))
  @last_channel_close_ok = wait_on_continuations
  raise_if_continuation_resulted_in_a_connection_error!

  self.unregister_channel(ch)
  @last_channel_close_ok
end
close_connection(sync = true) click to toggle source

@private

# File lib/bunny/session.rb, line 426
def close_connection(sync = true)
  if @transport.open?
    @transport.send_frame(AMQ::Protocol::Connection::Close.encode(200, "Goodbye", 0, 0))

    maybe_shutdown_heartbeat_sender
    @status   = :not_connected

    if sync
      @last_connection_close_ok = wait_on_continuations
    end
  end
end
close_transport() click to toggle source

@private

# File lib/bunny/session.rb, line 694
def close_transport
  begin
    @transport.close
  rescue StandardError => e
    @logger.error "Exception when closing transport:"
    @logger.error e.class.name
    @logger.error e.message
    @logger.error e.backtrace
  end
end
closed?() click to toggle source
# File lib/bunny/session.rb, line 304
def closed?
  status == :closed
end
configure_socket(&block) click to toggle source

Provides a way to fine tune the socket used by connection. Accepts a block that the socket will be yielded to.

# File lib/bunny/session.rb, line 203
def configure_socket(&block)
  raise ArgumentError, "No block provided!" if block.nil?

  @transport.configure_socket(&block)
end
connected?() click to toggle source
Alias for: open?
connecting?() click to toggle source

@return [Boolean] true if this connection is still not fully open

# File lib/bunny/session.rb, line 300
def connecting?
  status == :connecting
end
create_channel(n = nil, consumer_pool_size = 1) click to toggle source

Opens a new channel and returns it. This method will block the calling thread until the response is received and the channel is guaranteed to be opened (this operation is very fast and inexpensive).

@return [Bunny::Channel] Newly opened channel

# File lib/bunny/session.rb, line 259
def create_channel(n = nil, consumer_pool_size = 1)
  if n && (ch = @channels[n])
    ch
  else
    ch = Bunny::Channel.new(self, n, ConsumerWorkPool.new(consumer_pool_size || 1))
    ch.open
    ch
  end
end
Also aliased as: channel
direct(*args) click to toggle source

@private

# File lib/bunny/session.rb, line 328
def direct(*args)
  @default_channel.direct(*args)
end
exchange(*args) click to toggle source

@private

# File lib/bunny/session.rb, line 348
def exchange(*args)
  @default_channel.exchange(*args)
end
fanout(*args) click to toggle source

@private

# File lib/bunny/session.rb, line 333
def fanout(*args)
  @default_channel.fanout(*args)
end
handle_frame(ch_number, method) click to toggle source

@private

# File lib/bunny/session.rb, line 440
def handle_frame(ch_number, method)
  @logger.debug "Session#handle_frame on #{ch_number}: #{method.inspect}"
  case method
  when AMQ::Protocol::Channel::OpenOk then
    @continuations.push(method)
  when AMQ::Protocol::Channel::CloseOk then
    @continuations.push(method)
  when AMQ::Protocol::Connection::Close then
    @last_connection_error = instantiate_connection_level_exception(method)
    @continuations.push(method)

    @origin_thread.raise(@last_connection_error)
  when AMQ::Protocol::Connection::CloseOk then
    @last_connection_close_ok = method
    begin
      @continuations.clear
    rescue StandardError => e
      @logger.error e.class.name
      @logger.error e.message
      @logger.error e.backtrace
    ensure
      @continuations.push(:__unblock__)
    end
  when AMQ::Protocol::Channel::Close then
    begin
      ch = @channels[ch_number]
      ch.handle_method(method)
    ensure
      self.unregister_channel(ch)
    end
  when AMQ::Protocol::Basic::GetEmpty then
    @channels[ch_number].handle_basic_get_empty(method)
  else
    if ch = @channels[ch_number]
      ch.handle_method(method)
    else
      @logger.warn "Channel #{ch_number} is not open on this connection!"
    end
  end
end
handle_frameset(ch_number, frames) click to toggle source

@private

# File lib/bunny/session.rb, line 487
def handle_frameset(ch_number, frames)
  method = frames.first

  case method
  when AMQ::Protocol::Basic::GetOk then
    @channels[ch_number].handle_basic_get_ok(*frames)
  when AMQ::Protocol::Basic::GetEmpty then
    @channels[ch_number].handle_basic_get_empty(*frames)
  when AMQ::Protocol::Basic::Return then
    @channels[ch_number].handle_basic_return(*frames)
  else
    @channels[ch_number].handle_frameset(*frames)
  end
end
handle_network_failure(exception) click to toggle source

@private

# File lib/bunny/session.rb, line 503
def handle_network_failure(exception)
  raise NetworkErrorWrapper.new(exception) unless @threaded

  @status = :disconnected

  if !recovering_from_network_failure?
    @recovering_from_network_failure = true
    if recoverable_network_failure?(exception)
      @logger.warn "Recovering from a network failure..."
      @channels.each do |n, ch|
        ch.maybe_kill_consumer_work_pool!
      end
      maybe_shutdown_heartbeat_sender

      recover_from_network_failure
    else
      # TODO: investigate if we can be a bit smarter here. MK.
    end
  end
end
headers(*args) click to toggle source

@private

# File lib/bunny/session.rb, line 343
def headers(*args)
  @default_channel.headers(*args)
end
heartbeat_from(options) click to toggle source

@private

# File lib/bunny/session.rb, line 626
def heartbeat_from(options)
  options[:heartbeat] || options[:heartbeat_interval] || options[:requested_heartbeat] || DEFAULT_HEARTBEAT
end
heartbeat_interval() click to toggle source

@return [Integer] Heartbeat interval used

# File lib/bunny/session.rb, line 179
def heartbeat_interval; self.heartbeat; end
hostname() click to toggle source

@return [String] RabbitMQ hostname (or IP address) used

# File lib/bunny/session.rb, line 170
def hostname;     self.host;  end
hostname_from(options) click to toggle source

@private

# File lib/bunny/session.rb, line 595
def hostname_from(options)
  options[:host] || options[:hostname] || DEFAULT_HOST
end
instantiate_connection_level_exception(frame) click to toggle source

@private

# File lib/bunny/session.rb, line 568
def instantiate_connection_level_exception(frame)
  case frame
  when AMQ::Protocol::Connection::Close then
    klass = case frame.reply_code
            when 320 then
              ConnectionForced
            when 501 then
              FrameError
            when 503 then
              CommandInvalid
            when 504 then
              ChannelError
            when 505 then
              UnexpectedFrame
            when 506 then
              ResourceError
            when 541 then
              InternalError
            else
              raise "Unknown reply code: #{frame.reply_code}, text: #{frame.reply_text}"
            end

    klass.new("Connection-level error: #{frame.reply_text}", self, frame)
  end
end
maybe_shutdown_reader_loop() click to toggle source

@private

# File lib/bunny/session.rb, line 668
def maybe_shutdown_reader_loop
  if @reader_loop
    @reader_loop.stop
    if threaded?
      # this is the easiest way to wait until the loop
      # is guaranteed to have terminated
      @reader_loop.raise(ShutdownSignal)
      # joining the thread here may take forever
      # on JRuby because sun.nio.ch.KQueueArrayWrapper#kevent0 is
      # a native method that cannot be (easily) interrupted.
      # So we use this ugly hack or else our test suite takes forever
      # to run on JRuby (a new connection is opened/closed per example). MK.
      if defined?(JRUBY_VERSION)
        sleep 0.075
      else
        @reader_loop.join
      end
    else
      # single threaded mode, nothing to do. MK.
    end
  end

  @reader_loop = nil
end
next_channel_id() click to toggle source

@private

# File lib/bunny/session.rb, line 631
def next_channel_id
  @channel_id_allocator.next_channel_id
end
on_blocked(&block) click to toggle source

Defines a callback that will be executed when RabbitMQ blocks the connection because it is running low on memory or disk space (as configured via config file and/or rabbitmqctl).

@yield [AMQ::Protocol::Connection::Blocked] connection.blocked method which provides a reason for blocking

@api public

# File lib/bunny/session.rb, line 359
def on_blocked(&block)
  @block_callback = block
end
on_unblocked(&block) click to toggle source

Defines a callback that will be executed when RabbitMQ unblocks the connection that was previously blocked, e.g. because the memory or disk space alarm has cleared.

@see on_blocked @api public

# File lib/bunny/session.rb, line 368
def on_unblocked(&block)
  @unblock_callback = block
end
open?() click to toggle source
# File lib/bunny/session.rb, line 308
def open?
  (status == :open || status == :connected || status == :connecting) && @transport.open?
end
Also aliased as: connected?
open_channel(ch) click to toggle source

@private

# File lib/bunny/session.rb, line 393
def open_channel(ch)
  n = ch.number
  self.register_channel(ch)

  @transport_mutex.synchronize do
    @transport.send_frame(AMQ::Protocol::Channel::Open.encode(n, AMQ::Protocol::EMPTY_STRING))
  end
  @last_channel_open_ok = wait_on_continuations
  raise_if_continuation_resulted_in_a_connection_error!

  @last_channel_open_ok
end
password() click to toggle source

@return [String] Password used

# File lib/bunny/session.rb, line 174
def password;     self.pass;  end
password_from(options) click to toggle source

@private

# File lib/bunny/session.rb, line 621
def password_from(options)
  options[:password] || options[:pass] || options [:pwd] || DEFAULT_PASSWORD
end
port_from(options) click to toggle source

@private

# File lib/bunny/session.rb, line 600
def port_from(options)
  fallback = if options[:tls] || options[:ssl]
               AMQ::Protocol::TLS_PORT
             else
               AMQ::Protocol::DEFAULT_PORT
             end

  options.fetch(:port, fallback)
end
queue(*args) click to toggle source

@private

# File lib/bunny/session.rb, line 323
def queue(*args)
  @default_channel.queue(*args)
end
raise_if_continuation_resulted_in_a_connection_error!() click to toggle source

@private

# File lib/bunny/session.rb, line 482
def raise_if_continuation_resulted_in_a_connection_error!
  raise @last_connection_error if @last_connection_error
end
read_write_timeout() click to toggle source

Socket operation timeout used by this connection @return [Integer] @private

# File lib/bunny/session.rb, line 250
def read_write_timeout
  @transport.read_write_timeout
end
reader_loop() click to toggle source

@private

# File lib/bunny/session.rb, line 663
def reader_loop
  @reader_loop ||= ReaderLoop.new(@transport, self, Thread.current)
end
recover_channels() click to toggle source

@private

# File lib/bunny/session.rb, line 556
def recover_channels
  # default channel is reopened right after connection
  # negotiation is completed, so make sure we do not try to open
  # it twice. MK.
  @channels.reject { |n, ch| ch == @default_channel }.each do |n, ch|
    ch.open

    ch.recover_from_network_failure
  end
end
recover_from_network_failure() click to toggle source

@private

# File lib/bunny/session.rb, line 536
def recover_from_network_failure
  begin
    sleep @network_recovery_interval
    @logger.debug "About to start connection recovery..."
    self.initialize_transport
    self.start

    if open?
      @recovering_from_network_failure = false

      recover_channels
    end
  rescue TCPConnectionFailed, AMQ::Protocol::EmptyResponseError => e
    @logger.warn "TCP connection failed, reconnecting in 5 seconds"
    sleep @network_recovery_interval
    retry if recoverable_network_failure?(e)
  end
end
recoverable_network_failure?(exception) click to toggle source

@private

# File lib/bunny/session.rb, line 525
def recoverable_network_failure?(exception)
  # TODO: investigate if we can be a bit smarter here. MK.
  true
end
recovering_from_network_failure?() click to toggle source

@private

# File lib/bunny/session.rb, line 531
def recovering_from_network_failure?
  @recovering_from_network_failure
end
register_channel(ch) click to toggle source

@private

# File lib/bunny/session.rb, line 641
def register_channel(ch)
  @channel_mutex.synchronize do
    @channels[ch.number] = ch
  end
end
release_channel_id(i) click to toggle source

@private

# File lib/bunny/session.rb, line 636
def release_channel_id(i)
  @channel_id_allocator.release_channel_id(i)
end
send_frame(frame, signal_activity = true) click to toggle source

Sends frame to the peer, checking that connection is open. Exposed primarily for Bunny::Channel

@raise [ConnectionClosedError] @private

# File lib/bunny/session.rb, line 716
def send_frame(frame, signal_activity = true)
  if open?
    @transport.write(frame.encode)
    signal_activity! if signal_activity
  else
    raise ConnectionClosedError.new(frame)
  end
end
send_frame_without_timeout(frame, signal_activity = true) click to toggle source

Sends frame to the peer, checking that connection is open. Uses transport implementation that does not perform timeout control. Exposed primarily for Bunny::Channel.

@raise [ConnectionClosedError] @private

# File lib/bunny/session.rb, line 731
def send_frame_without_timeout(frame, signal_activity = true)
  if open?
    @transport.write_without_timeout(frame.encode)
    signal_activity! if signal_activity
  else
    raise ConnectionClosedError.new(frame)
  end
end
send_frameset(frames, channel) click to toggle source

Sends multiple frames, one by one. For thread safety this method takes a channel object and synchronizes on it.

@private

# File lib/bunny/session.rb, line 744
def send_frameset(frames, channel)
  # some developers end up sharing channels between threads and when multiple
  # threads publish on the same channel aggressively, at some point frames will be
  # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception.
  # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained
  # locking. Note that "single frame" methods do not need this kind of synchronization. MK.
  channel.synchronize do
    frames.each { |frame| self.send_frame(frame, false) }
    signal_activity!
  end
end
send_frameset_without_timeout(frames, channel) click to toggle source

Sends multiple frames, one by one. For thread safety this method takes a channel object and synchronizes on it. Uses transport implementation that does not perform timeout control.

@private

# File lib/bunny/session.rb, line 761
def send_frameset_without_timeout(frames, channel)
  # some developers end up sharing channels between threads and when multiple
  # threads publish on the same channel aggressively, at some point frames will be
  # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception.
  # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained
  # locking. Note that "single frame" methods do not need this kind of synchronization. MK.
  channel.synchronize do
    frames.each { |frame| self.send_frame_without_timeout(frame, false) }
    signal_activity!
  end
end
signal_activity!() click to toggle source

@private

# File lib/bunny/session.rb, line 706
def signal_activity!
  @heartbeat_sender.signal_activity! if @heartbeat_sender
end
ssl?() click to toggle source
Alias for: uses_ssl?
start() click to toggle source

Starts the connection process.

@see rubybunny.info/articles/getting_started.html @see rubybunny.info/articles/connecting.html @api public

# File lib/bunny/session.rb, line 214
def start
  return self if connected?

  @status        = :connecting
  self.reset_continuations

  begin
    # close existing transport if we have one,
    # to not leak sockets
    @transport.maybe_initialize_socket

    @transport.post_initialize_socket
    @transport.connect

    if @socket_configurator
      @transport.configure_socket(&@socket_configurator)
    end

    self.init_connection
    self.open_connection

    @reader_loop = nil
    self.start_reader_loop if threaded?

    @default_channel = self.create_channel
  rescue Exception => e
    @status = :not_connected
    raise e
  end

  self
end
start_reader_loop() click to toggle source

@private

# File lib/bunny/session.rb, line 658
def start_reader_loop
  reader_loop.start
end
stop() click to toggle source
Alias for: close
threaded?() click to toggle source

@return [Boolean] true if this connection uses a separate thread for I/O activity

# File lib/bunny/session.rb, line 194
def threaded?
  @threaded
end
tls?() click to toggle source
Alias for: uses_tls?
to_s() click to toggle source

@return [String] @api public

# File lib/bunny/session.rb, line 775
def to_s
  "#<#{self.class.name}:#{object_id} #{@user}@#{@host}:#{@port}, vhost=#{@vhost}>"
end
topic(*args) click to toggle source

@private

# File lib/bunny/session.rb, line 338
def topic(*args)
  @default_channel.topic(*args)
end
unregister_channel(ch) click to toggle source

@private

# File lib/bunny/session.rb, line 648
def unregister_channel(ch)
  @channel_mutex.synchronize do
    n = ch.number

    self.release_channel_id(n)
    @channels.delete(ch.number)
  end
end
username() click to toggle source

@return [String] Username used

# File lib/bunny/session.rb, line 172
def username;     self.user;  end
username_from(options) click to toggle source

@private

# File lib/bunny/session.rb, line 616
def username_from(options)
  options[:username] || options[:user] || DEFAULT_USER
end
uses_ssl?() click to toggle source

@return [Boolean] true if this connection uses TLS (SSL)

# File lib/bunny/session.rb, line 188
def uses_ssl?
  @transport.uses_ssl?
end
Also aliased as: ssl?
uses_tls?() click to toggle source

@return [Boolean] true if this connection uses TLS (SSL)

# File lib/bunny/session.rb, line 182
def uses_tls?
  @transport.uses_tls?
end
Also aliased as: tls?
vhost_from(options) click to toggle source

@private

# File lib/bunny/session.rb, line 611
def vhost_from(options)
  options[:virtual_host] || options[:vhost] || DEFAULT_VHOST
end
virtual_host() click to toggle source

@return [String] Virtual host used

# File lib/bunny/session.rb, line 176
def virtual_host; self.vhost; end
with_channel(n = nil) click to toggle source

Creates a temporary channel, yields it to the block given to this method and closes it.

@return [Bunny::Session] self

# File lib/bunny/session.rb, line 291
def with_channel(n = nil)
  ch = create_channel(n)
  yield ch
  ch.close

  self
end

Protected Instance Methods

credentials_encoder_for(mechanism) click to toggle source

@private

# File lib/bunny/session.rb, line 907
def credentials_encoder_for(mechanism)
  Authentication::CredentialsEncoder.for_session(self)
end
encode_credentials(username, password) click to toggle source

@private

# File lib/bunny/session.rb, line 902
def encode_credentials(username, password)
  @credentials_encoder.encode_credentials(username, password)
end
heartbeat_disabled?(val) click to toggle source
# File lib/bunny/session.rb, line 856
def heartbeat_disabled?(val)
  0 == val || val.nil?
end
init_connection() click to toggle source

@private

# File lib/bunny/session.rb, line 782
def init_connection
  self.send_preamble

  connection_start = @transport.read_next_frame.decode_payload

  @server_properties                = connection_start.server_properties
  @server_capabilities              = @server_properties["capabilities"]

  @server_authentication_mechanisms = (connection_start.mechanisms || "").split(" ")
  @server_locales                   = Array(connection_start.locales)

  @status = :connected
end
init_logger(level) click to toggle source

@private

# File lib/bunny/session.rb, line 933
def init_logger(level)
  @logger          = ::Logger.new(@logfile)
  @logger.level    = normalize_log_level(level)
  @logger.progname = self.to_s

  @logger
end
initialize_heartbeat_sender() click to toggle source

@private

# File lib/bunny/session.rb, line 872
def initialize_heartbeat_sender
  @logger.debug "Initializing heartbeat sender..."
  @heartbeat_sender = HeartbeatSender.new(@transport, @logger)
  @heartbeat_sender.start(@heartbeat)
end
initialize_transport() click to toggle source

@private

# File lib/bunny/session.rb, line 884
def initialize_transport
  @transport = Transport.new(self, @host, @port, @opts.merge(:session_thread => @origin_thread))
end
maybe_close_transport() click to toggle source

@private

# File lib/bunny/session.rb, line 889
def maybe_close_transport
  @transport.close if @transport
end
maybe_shutdown_heartbeat_sender() click to toggle source

@private

# File lib/bunny/session.rb, line 879
def maybe_shutdown_heartbeat_sender
  @heartbeat_sender.stop if @heartbeat_sender
end
negotiate_value(client_value, server_value) click to toggle source

@private

# File lib/bunny/session.rb, line 861
def negotiate_value(client_value, server_value)
  return server_value if client_value == :server

  if client_value == 0 || server_value == 0
    [client_value, server_value].max
  else
    [client_value, server_value].min
  end
end
normalize_log_level(level) click to toggle source

@private

# File lib/bunny/session.rb, line 942
def normalize_log_level(level)
  case level
  when :debug, Logger::DEBUG, "debug" then Logger::DEBUG
  when :info,  Logger::INFO,  "info"  then Logger::INFO
  when :warn,  Logger::WARN,  "warn"  then Logger::WARN
  when :error, Logger::ERROR, "error" then Logger::ERROR
  when :fatal, Logger::FATAL, "fatal" then Logger::FATAL
  else
    Logger::WARN
  end
end
open_connection() click to toggle source

@private

# File lib/bunny/session.rb, line 797
def open_connection
  @transport.send_frame(AMQ::Protocol::Connection::StartOk.encode(@client_properties, @mechanism, self.encode_credentials(username, password), @locale))
  @logger.debug "Sent connection.start-ok"

  frame = begin
            @transport.read_next_frame
            # frame timeout means the broker has closed the TCP connection, which it
            # does per 0.9.1 spec.
          rescue Errno::ECONNRESET, ClientTimeout, AMQ::Protocol::EmptyResponseError, EOFError, IOError => e
            nil
          end
  if frame.nil?
    @state = :closed
    @logger.error "RabbitMQ closed TCP connection before AMQP 0.9.1 connection was finalized. Most likely this means authentication failure."
    raise Bunny::PossibleAuthenticationFailureError.new(self.user, self.vhost, self.password.size)
  end

  connection_tune       = frame.decode_payload

  @frame_max            = negotiate_value(@client_frame_max, connection_tune.frame_max)
  @channel_max          = negotiate_value(@client_channel_max, connection_tune.channel_max)
  # this allows for disabled heartbeats. MK.
  @heartbeat            = if heartbeat_disabled?(@client_heartbeat)
                            0
                          else
                            negotiate_value(@client_heartbeat, connection_tune.heartbeat)
                          end
  @logger.debug "Heartbeat interval negotiation: client = #{@client_heartbeat}, server = #{connection_tune.heartbeat}, result = #{@heartbeat}"
  @logger.info "Heartbeat interval used (in seconds): #{@heartbeat}"

  @channel_id_allocator = ChannelIdAllocator.new(@channel_max)

  @transport.send_frame(AMQ::Protocol::Connection::TuneOk.encode(@channel_max, @frame_max, @heartbeat))
  @logger.debug "Sent connection.tune-ok with heartbeat interval = #{@heartbeat}, frame_max = #{@frame_max}, channel_max = #{@channel_max}"
  @transport.send_frame(AMQ::Protocol::Connection::Open.encode(self.vhost))
  @logger.debug "Sent connection.open with vhost = #{self.vhost}"

  frame2 = begin
             @transport.read_next_frame
             # frame timeout means the broker has closed the TCP connection, which it
             # does per 0.9.1 spec.
           rescue Errno::ECONNRESET, ClientTimeout, AMQ::Protocol::EmptyResponseError, EOFError => e
             nil
           end
  if frame2.nil?
    @state = :closed
    @logger.warn "RabbitMQ closed TCP connection before AMQP 0.9.1 connection was finalized. Most likely this means authentication failure."
    raise Bunny::PossibleAuthenticationFailureError.new(self.user, self.vhost, self.password.size)
  end
  connection_open_ok = frame2.decode_payload

  @status = :open
  if @heartbeat && @heartbeat > 0
    initialize_heartbeat_sender
  end

  raise "could not open connection: server did not respond with connection.open-ok" unless connection_open_ok.is_a?(AMQ::Protocol::Connection::OpenOk)
end
reset_continuations() click to toggle source

@private

# File lib/bunny/session.rb, line 913
def reset_continuations
  @continuations = Concurrent::LinkedContinuationQueue.new
end
send_preamble() click to toggle source

Sends AMQ protocol header (also known as preamble). @private

# File lib/bunny/session.rb, line 895
def send_preamble
  @transport.write(AMQ::Protocol::PREAMBLE)
  @logger.debug "Sent protocol preamble"
end
wait_on_continuations() click to toggle source

@private

# File lib/bunny/session.rb, line 924
def wait_on_continuations
  unless @threaded
    reader_loop.run_once until @continuations.length > 0
  end

  @continuations.poll(@continuation_timeout)
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.