Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def mock_publish_exception(exchange, key, msg, properties, mandatory):
"""
Method mocks RabbitMQ's basic_publish which throws a ChannelClosed
exception to simulate a channel failure or conn. failure
"""
raise pika.exceptions.ChannelClosed
def ask_exam_enrollment_form(stud, off_year):
if 'exam_enrollment' in settings.INSTALLED_APPS:
if hasattr(settings, 'QUEUES') and settings.QUEUES:
try:
message_published = ask_queue_for_exam_enrollment_form(stud, off_year)
except (RuntimeError, pika.exceptions.ConnectionClosed, pika.exceptions.ChannelClosed,
pika.exceptions.AMQPError):
return HttpResponse(status=400)
if message_published:
return HttpResponse(status=200)
return HttpResponse(status=405)
def _consume_queue(self):
currently = util.create_deferred_state_watcher(self, '_consuming')
queue, consumer_tag = yield currently(self.consume_channel.basic_consume(queue=self.response_queue.method.queue, **self.consumer_config))
try:
self.consuming_dependency.fire_on_ready()
while self.running:
# don't get from the queue unless our dependency is ready
yield currently(self.dependency.wait_for_resource())
channel, method, properties, body = yield currently(queue.get())
self.process_response(channel, method, properties, body)
except pika_exceptions.ChannelClosed as cc:
logger.warn('AMQP channel closed.', exc_info=True)
self.consuming_dependency.fire_on_lost('channel closed')
self._handle_disconnect()
# wait a little before reopening the channel
reactor.callLater(self.reopen_consumer_channel_interval, self._consider_starting)
except defer.CancelledError as ce:
return
finally:
self.consuming_dependency.fire_on_lost('stopped consuming')
# of sync connection.
current_events = self._event_counter
self.drain_events(timeout=timeout)
if self._event_counter <= current_events:
raise socket.timeout("timed out")
def on_data_available(self, buf):
self._event_counter += 1
self.Super.on_data_available(self, buf)
class SyncTransport(base.Transport):
default_port = DEFAULT_PORT
connection_errors = (exceptions.ConnectionClosed,
exceptions.ChannelClosed,
exceptions.LoginError,
exceptions.NoFreeChannels,
exceptions.DuplicateConsumerTag,
exceptions.UnknownConsumerTag,
exceptions.RecursiveOperationDetected,
exceptions.ContentTransmissionForbidden,
exceptions.ProtocolSyntaxError)
channel_errors = (exceptions.ChannelClosed,
exceptions.DuplicateConsumerTag,
exceptions.UnknownConsumerTag,
exceptions.ProtocolSyntaxError)
Message = Message
Connection = BlockingConnection
def close(self, reply_code=0, reply_text="Normal Shutdown"):
"""Will invoke a clean shutdown of the channel with the AMQP Broker.
:param int reply_code: The reply code to close the channel with
:param str reply_text: The reply text to close the channel with
"""
LOGGER.info('Channel.close(%s, %s)', reply_code, reply_text)
if not self.is_open:
raise exceptions.ChannelClosed()
# Cancel the generator if it's running
if self._generator:
self.cancel()
# If there are any consumers, cancel them as well
if self._consumers:
LOGGER.debug('Cancelling %i consumers', len(self._consumers))
for consumer_tag in self._consumers.keys():
self.basic_cancel(consumer_tag=consumer_tag)
self._set_state(self.CLOSING)
self._rpc(spec.Channel.Close(reply_code, reply_text, 0, 0),
None,
[spec.Channel.CloseOk])
self._set_state(self.CLOSED)
self._cleanup()
if not params.uuid:
raise MissingArgumentError('uuid')
with self.context() as connection:
try:
self.config.logger.debug(
'Inserting priority job into RabbitMQ %s', params.uuid
)
connection.channel.basic_publish(
exchange='',
routing_key=self.config.priority_queue_name,
body=params.uuid,
properties=pika.BasicProperties(delivery_mode=2)
)
except ChannelClosed:
self.config.logger.error(
"Failed inserting priorityjobs data into RabbitMQ",
exc_info=True
)
return False
return True
def disconnect(self):
"""
Disconnect from channel i.e, stop consuming from the channel
:return:
"""
try:
if self.channel and self.channel.is_open:
self.channel.basic_cancel(self.on_cancel_ok, self._consumer_tag)
except (pika.exceptions.ConnectionClosed, pika.exceptions.ChannelClosed) as exc:
_log.error("Connection to RabbitMQ broker or Channel is already closed.")
self._connection.ioloop.stop()
properties = pika.BasicProperties(
delivery_mode = 2, # make messages persistent
type = msg_type
)
ok = False
try_again = True
while not ok and try_again:
try:
self._channel.basic_publish(
exchange=self.config.exchange or "",
routing_key=self._queue_name or "", # Fanout exchange will ignore this
body=data,
properties=properties)
ok = True
except (pika.exceptions.ChannelClosed, pika.exceptions.ConnectionClosed) as e:
if try_again:
self.log.debug("No open connection to RabbitMQ. Trying to reconnect.")
try_again = self._reconnect(3, 3)
if not ok:
self.log.warning("Missing connection to RabbitMQ. Max retries exceeded. Document lost. Aborting.")
self.abort()
return False
else:
return True
:param str exchange: the exchange to publish to
:param str routing_key: the routing key to publish with
:param str|unicode body: the message body to publish
:param pikachewie.data.Properties properties: the message properties
"""
if properties:
properties = self._build_basic_properties(properties)
try:
self.channel.basic_publish(
exchange=exchange,
routing_key=routing_key,
properties=properties,
body=body,
)
except (ConnectionClosed, ChannelClosed) as exc:
log.warn('Cannot publish on existing channel')
log.info('Attempting to republish on new channel')
self._channel = None
self.channel.basic_publish(
exchange=exchange,
routing_key=routing_key,
properties=properties,
body=body,
)
def unregister_websocket(self, sess_id):
try:
del self.websockets[sess_id]
except KeyError:
log.exception("Non-existent websocket")
if sess_id in self.out_channels:
try:
self.out_channels[sess_id].close()
except ChannelClosed:
log.exception("Pika client (out) channel already closed")