Class Bunny::Client
In: lib/bunny/client08.rb
Parent: Qrack::Client
StandardError ForcedConnectionCloseError UnsubscribeError ConnectionError ServerDownError AcknowledgementError MessageError ProtocolError ForcedChannelCloseError Qrack::Client Client Client09 Qrack::Channel Channel Channel09 Qrack::Queue Queue09 Queue Qrack::Subscription Subscription09 Subscription Exchange09 Exchange Qrack lib/bunny/exchange09.rb lib/bunny/queue08.rb lib/bunny/exchange08.rb lib/bunny/client09.rb lib/bunny/channel09.rb lib/bunny/queue09.rb lib/bunny/client08.rb lib/bunny.rb lib/bunny/subscription09.rb lib/bunny/subscription08.rb lib/bunny/channel08.rb Bunny dot/m_24_0.png

DESCRIPTION:

The Client class provides the major Bunny API methods.

Methods

Attributes

ticket  [RW] 

Public Class methods

DESCRIPTION:

Sets up a Bunny::Client object ready for connection to a broker/server. Client.status is set to :not_connected.

OPTIONS:

  • :host => ‘hostname’ (default = ‘localhost’)
  • :port => portno (default = 5672 or 5671 if :ssl set to true)
  • :vhost => ‘vhostname’ (default = ’/’)
  • :user => ‘username’ (default = ‘guest’)
  • :pass => ‘password’ (default = ‘guest’)
  • :ssl => true or false (default = false) - If set to true, ssl encryption will be used and port will default to 5671.
  • :verify_ssl => true or false (default = true) - If ssl is enabled, this will cause OpenSSL to validate the server certificate unless this parameter is set to false.
  • :logfile => ‘logfilepath’ (default = nil)
  • :logging => true or false (default) - If set to true, session information is sent to STDOUT if :logfile has not been specified. Otherwise, session information is written to :logfile.
  • :insist => true or false (default) - In a configuration with multiple load-sharing servers, the server may respond to a Connection::Open method with a Connection::Redirect. The insist option, if set to true, tells the server that the client is insisting on a connection to the specified server.
  • :frame_max => maximum frame size in bytes (default = 131072)
  • :channel_max => maximum number of channels (default = 0 no maximum)
  • :heartbeat => number of seconds (default = 0 no heartbeat)
  • :connect_timeout => number of seconds before Qrack::ConnectionTimeout is raised (default = 5)

[Source]

    # File lib/bunny/client08.rb, line 49
49:     def initialize(opts = {})
50:                         super
51:                         @spec = '0-8'
52:                         @port = opts[:port] || (opts[:ssl] ? Qrack::Protocol::SSL_PORT : Qrack::Protocol::PORT)
53:       @insist = opts[:insist]
54:     end

Public Instance methods

DESCRIPTION:

Checks response from AMQP methods and takes appropriate action

[Source]

    # File lib/bunny/client08.rb, line 64
64:                 def check_response(received_method, expected_method, err_msg, err_class = Bunny::ProtocolError)
65:                         case
66:                                 when received_method.is_a?(Qrack::Protocol::Connection::Close)
67:                                         # Clean up the socket
68:                                         close_socket
69:                                         
70:                                         raise Bunny::ForcedConnectionCloseError,
71:                                                 "Error Reply Code: #{received_method.reply_code}\nError Reply Text: #{received_method.reply_text}"
72:                                                 
73:                                 when received_method.is_a?(Qrack::Protocol::Channel::Close)
74:                                         # Clean up the channel
75:                                         channel.active = false
76: 
77:                                         raise Bunny::ForcedChannelCloseError,
78:                                                 "Error Reply Code: #{received_method.reply_code}\nError Reply Text: #{received_method.reply_text}"
79:                                                 
80:                                 when !received_method.is_a?(expected_method)
81:                                         raise err_class, err_msg
82:                                         
83:                                 else
84:                                         :response_ok
85:                         end
86:                 end

[Source]

     # File lib/bunny/client08.rb, line 88
 88:                 def close_connection
 89:                         # Set client channel to zero
 90:       switch_channel(0)
 91:                 
 92:                         send_frame(
 93:               Qrack::Protocol::Connection::Close.new(:reply_code => 200, :reply_text => 'Goodbye', :class_id => 0, :method_id => 0)
 94:             )
 95:         
 96:                         method = next_method
 97:                         
 98:                         check_response(method, Qrack::Protocol::Connection::CloseOk, "Error closing connection")
 99:             
100:     end

[Source]

     # File lib/bunny/client08.rb, line 102
102:                 def create_channel
103:                         channels.each do |c|
104:                                 return c if (!c.open? and c.number != 0)
105:                         end
106:                         # If no channel to re-use instantiate new one
107:                         Bunny::Channel.new(self)
108:                 end

DESCRIPTION:

Declares an exchange to the broker/server. If the exchange does not exist, a new one is created using the arguments passed in. If the exchange already exists, the existing object is returned. If an error occurs a Bunny::ProtocolError is raised.

OPTIONS:

  • :type => one of :direct (default), :fanout, :topic, :headers
  • :passive => true or false - If set to true, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state.
  • :durable => true or false (default) - If set to true when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts.
  • :auto_delete => true or false (default) - If set to true, the exchange is deleted when all queues have finished using it.
  • :nowait => true or false (default) - Ignored by Bunny, always false.

RETURNS:

Exchange

[Source]

     # File lib/bunny/client08.rb, line 136
136:                 def exchange(name, opts = {})
137:       exchanges[name] || Bunny::Exchange.new(self, name, opts)
138:                 end

[Source]

     # File lib/bunny/client08.rb, line 140
140:                 def init_connection
141:                         write(Qrack::Protocol::HEADER)
142:       write([1, 1, Qrack::Protocol::VERSION_MAJOR, Qrack::Protocol::VERSION_MINOR].pack('C4'))
143: 
144:                         frame = next_frame
145:                         if frame.nil? or !frame.payload.is_a?(Qrack::Protocol::Connection::Start)
146:                                 raise Bunny::ProtocolError, 'Connection initiation failed'
147:                         end
148:                 end

[Source]

     # File lib/bunny/client08.rb, line 150
150:                 def next_frame(opts = {})
151:       frame = nil
152:                         
153:                         case
154:                                 when channel.frame_buffer.size > 0
155:                                         frame = channel.frame_buffer.shift
156:                                 when opts.has_key?(:timeout)
157:                 Timeout::timeout(opts[:timeout], Qrack::ClientTimeout) do
158:                   frame = Qrack::Transport::Frame.parse(buffer)
159:                 end
160:               else
161:                 frame = Qrack::Transport::Frame.parse(buffer)
162:       end
163:                         
164:                         @logger.info("received") { frame } if @logging
165:                                                 
166:                         raise Bunny::ConnectionError, 'No connection to server' if (frame.nil? and !connecting?)
167:                         
168:                         # Monitor server activity and discard heartbeats
169:                         @message_in = true
170:                         
171:                         case
172:                                 when frame.is_a?(Qrack::Transport::Heartbeat)
173:                                         next_frame(opts)
174:                                 when frame.nil?
175:                                         frame
176:                                 when ((frame.channel != channel.number) and (frame.channel != 0))
177:                                         channel.frame_buffer << frame
178:                                         next_frame(opts)
179:                                 else
180:                                         frame
181:                         end
182:                         
183:     end

[Source]

     # File lib/bunny/client08.rb, line 185
185:                 def open_connection
186:                         send_frame(
187:         Qrack::Protocol::Connection::StartOk.new(
188:           {:platform => 'Ruby', :product => 'Bunny', :information => 'http://github.com/celldee/bunny', :version => VERSION},
189:           'AMQPLAIN',
190:           {:LOGIN => @user, :PASSWORD => @pass},
191:           'en_US'
192:         )
193:       )
194: 
195:       frame = next_frame
196:                         raise Bunny::ProtocolError, "Connection failed - user: #{@user}" if frame.nil?
197:                         
198:                         method = frame.payload
199: 
200:       if method.is_a?(Qrack::Protocol::Connection::Tune)
201:         send_frame(
202:           Qrack::Protocol::Connection::TuneOk.new( :channel_max => @channel_max, :frame_max => @frame_max, :heartbeat => @heartbeat)
203:         )
204:       end
205: 
206:       send_frame(
207:         Qrack::Protocol::Connection::Open.new(:virtual_host => @vhost, :capabilities => '', :insist => @insist)
208:       )
209: 
210:       case method = next_method
211:       when Qrack::Protocol::Connection::OpenOk
212:         :ok
213:       when Qrack::Protocol::Connection::Redirect
214:                                 raise Bunny::ConnectionError, "Cannot connect to the specified server - host: #{@host}, port: #{@port}" if @insist
215:                                 
216:         @host, @port = method.host.split(':')
217:         close_socket
218:       else
219:         raise Bunny::ProtocolError, 'Cannot open connection'
220:       end
221:                 end

DESCRIPTION:

Requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a QoS method always depend on the content class semantics. Though the QoS method could in principle apply to both peers, it is currently meaningful only for the server.

Options:

  • :prefetch_size => size in no. of octets (default = 0) - The client can request that

messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement. This field specifies the prefetch window size in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored if the no-ack option is set.

  • :prefetch_count => no. messages (default = 1) - Specifies a prefetch window in terms

of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch-count is ignored if the no-ack option is set.

  • :global => true or false (default) - By default the QoS settings apply to the current channel only. If set to

true, they are applied to the entire connection.

RETURNS:

:qos_ok if successful.

[Source]

     # File lib/bunny/client08.rb, line 255
255:                 def qos(opts = {})
256: 
257:       send_frame(
258:         Qrack::Protocol::Basic::Qos.new({ :prefetch_size => 0, :prefetch_count => 1, :global => false }.merge(opts))
259:       )
260: 
261:                         method = next_method
262:                         
263:                         check_response(method, Qrack::Protocol::Basic::QosOk, "Error specifying Quality of Service")
264: 
265:       # return confirmation
266:       :qos_ok
267:     end

DESCRIPTION:

Declares a queue to the broker/server. If the queue does not exist, a new one is created using the arguments passed in. If the queue already exists, a reference to it is created, provided that the arguments passed in do not conflict with the existing attributes of the queue. If an error occurs a Bunny::ProtocolError is raised.

OPTIONS:

  • :passive => true or false (default) - If set to true, the server will not create the queue. The client can use this to check whether a queue exists without modifying the server state.
  • :durable => true or false (default) - If set to true when creating a new queue, the queue will be marked as durable. Durable queues remain active when a server restarts. Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue.
  • :exclusive => true or false (default) - If set to true, requests an exclusive queue. Exclusive queues may only be consumed from by the current connection. Setting the ‘exclusive’ flag always implies ‘auto-delete’.
  • :auto_delete => true or false (default) - If set to true, the queue is deleted when all consumers have finished using it. Last consumer can be cancelled either explicitly or because its channel is closed. If there has never been a consumer on the queue, it is not deleted.
  • :nowait => true or false (default) - Ignored by Bunny, always false.

RETURNS:

Queue

[Source]

     # File lib/bunny/client08.rb, line 303
303:                 def queue(name = nil, opts = {})
304:       if name.is_a?(Hash)
305:         opts = name
306:         name = nil
307:       end
308: 
309:       # Queue is responsible for placing itself in the list of queues
310:       queues[name] || Bunny::Queue.new(self, name, opts)
311:           end

DESCRIPTION:

Asks the broker to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered.

Options:

  • :requeue => true or false (default) - If set to false, the message will be

redelivered to the original recipient. If set to true, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.

[Source]

     # File lib/bunny/client08.rb, line 328
328:                 def recover(opts = {})
329: 
330:             send_frame(
331:               Qrack::Protocol::Basic::Recover.new({ :requeue => false }.merge(opts))
332:             )
333: 
334:           end

[Source]

     # File lib/bunny/client08.rb, line 336
336:                 def request_access
337:                         send_frame(
338:         Qrack::Protocol::Access::Request.new(:realm => '/data', :read => true, :write => true, :active => true, :passive => true)
339:       )
340: 
341:       method = next_method
342:                         
343:                         check_response(method, Qrack::Protocol::Access::RequestOk, "Access denied")
344:       
345:       self.ticket = method.ticket
346:                 end

[Source]

     # File lib/bunny/client08.rb, line 348
348:                 def send_frame(*args)
349:       args.each do |data|
350:         data.ticket  = ticket if ticket and data.respond_to?(:ticket=)
351:         data         = data.to_frame(channel.number) unless data.is_a?(Qrack::Transport::Frame)
352:         data.channel = channel.number
353: 
354:         @logger.info("send") { data } if @logging
355:         write(data.to_s)
356: 
357:                                 # Monitor client activity for heartbeat purposes
358:                                 @message_out = true
359:       end
360: 
361:       nil
362:     end

[Source]

     # File lib/bunny/client08.rb, line 364
364:                 def send_heartbeat
365:                         # Create a new heartbeat frame
366:                         hb = Qrack::Transport::Heartbeat.new('')             
367:                         # Channel 0 must be used
368:                         switch_channel(0) if @channel.number > 0                     
369:                         # Send the heartbeat to server
370:                         send_frame(hb)
371:                 end
start()

Alias for start_session

DESCRIPTION:

Opens a communication channel and starts a connection. If an error occurs, a Bunny::ProtocolError is raised. If successful, Client.status is set to :connected.

RETURNS:

:connected if successful.

[Source]

     # File lib/bunny/client08.rb, line 386
386:                 def start_session
387:                         @connecting = true
388:                         
389:       loop do
390:                                 # Create/get socket
391:                                 socket
392:                                 
393:                                 # Initiate connection
394:                                 init_connection
395: 
396:                                 # Open connection
397:                                 break if open_connection == :ok
398:       end
399: 
400:                         # Open another channel because channel zero is used for specific purposes
401:                         c = create_channel()
402:                         c.open
403:                         
404:                         # Get access ticket
405:                         request_access
406: 
407:                         @connecting = false
408:                         
409:                         # return status
410:                         @status = :connected
411:     end

DESCRIPTION:

This method commits all messages published and acknowledged in the current transaction. A new transaction starts immediately after a commit.

RETURNS:

:commit_ok if successful.

[Source]

     # File lib/bunny/client08.rb, line 428
428:                 def tx_commit
429:                         send_frame(Qrack::Protocol::Tx::Commit.new())
430:                         
431:                         method = next_method
432:                         
433:                         check_response(method, Qrack::Protocol::Tx::CommitOk, "Error commiting transaction")
434: 
435:                         # return confirmation
436:                         :commit_ok
437:                 end

DESCRIPTION:

This method abandons all messages published and acknowledged in the current transaction. A new transaction starts immediately after a rollback.

RETURNS:

:rollback_ok if successful.

[Source]

     # File lib/bunny/client08.rb, line 452
452:                 def tx_rollback
453:                         send_frame(Qrack::Protocol::Tx::Rollback.new())
454: 
455:                         method = next_method
456:                         
457:                         check_response(method, Qrack::Protocol::Tx::RollbackOk, "Error rolling back transaction")
458: 
459:                         # return confirmation
460:                         :rollback_ok
461:                 end

DESCRIPTION:

This method sets the channel to use standard transactions. The client must use this method at least once on a channel before using the Commit or Rollback methods.

RETURNS:

:select_ok if successful.

[Source]

     # File lib/bunny/client08.rb, line 476
476:                 def tx_select
477:                         send_frame(Qrack::Protocol::Tx::Select.new())
478: 
479:                         method = next_method
480:                         
481:                         check_response(method, Qrack::Protocol::Tx::SelectOk, "Error initiating transactions for current channel")
482: 
483:                         # return confirmation
484:                         :select_ok
485:                 end

Private Instance methods

[Source]

     # File lib/bunny/client08.rb, line 489
489:     def buffer
490:       @buffer ||= Qrack::Transport::Buffer.new(self)
491:     end

[Validate]