コード例 #1
0
def onDeviceDeleted(object, event):
    # Clean up any AMQP queues we may have created for this device.

    if not IObjectWillBeAddedEvent.providedBy(event):
        connectionInfo = getUtility(IAMQPConnectionInfo)
        queueSchema = getUtility(IQueueSchema)

        # For some reason, if an error gets thrown by queue_delete, it seems
        # to break the connection, so we'll just use a separate connection
        # for each call to it.
        for queue in ('$OpenStackInboundEvent', '$OpenStackInboundPerf'):
            queueName = substitute_replacements(queueSchema._queue_nodes[queue].name,
                                                {'device': object.id})

            amqpClient = BlockingPublisher(connectionInfo, queueSchema)
            channel = amqpClient.getChannel()
            try:
                LOG.debug("Removing AMQP queue %s" % queueName)
                channel.queue_delete(queueName)
                LOG.info("Removed AMQP queue %s successfully." % queueName)
            except AMQPChannelException, e:
                # if the queue doesn't exist, don't worry about it.
                if e.amqp_reply_code == 404:
                    LOG.debug('Queue %s did not exist', queueName)
                else:
                    LOG.exception(e)

            amqpClient.close()
コード例 #2
0
ファイル: publisher.py プロジェクト: zenoss/zenoss-prodbin
class BlockingQueuePublisher(object):
    """
    Class that is responsible for sending messages to the amqp exchange.
    """
    implements(IQueuePublisher)

    def __init__(self):
        self.reconnect()

    def reconnect(self):
        connectionInfo = getUtility(IAMQPConnectionInfo)
        queueSchema = getUtility(IQueueSchema)
        self._client = BlockingPublisher(connectionInfo, queueSchema)

    def publish(self, exchange, routing_key, message, createQueues=None,
                mandatory=False, headers=None,
                declareExchange=True):
        if createQueues:
            for queue in createQueues:
                if not self._client.queueExists(queue):
                    self.reconnect()
                    self._client.createQueue(queue)
        self._client.publish(exchange, routing_key, message,
                             mandatory=mandatory, headers=headers,
                             declareExchange=declareExchange)

    @property
    def channel(self):
        return self._client.getChannel()

    def close(self):
        """
        Closes the channel and connection
        """
        self._client.close()
コード例 #3
0
ファイル: zenqdump.py プロジェクト: jhanson/zenoss-protocols
def main():
    from optparse import OptionParser
    import sys
    parser = OptionParser(usage=usage())

    parser.add_option("-A", '--ack', action="store_true", dest="acknowledge",
                       help="Acknowledge the message, acknowledging a message will remove it from the queue")
    parser.add_option('-F', '--format', type='string', dest='format', default='json',
                       help='Format to dump the messages in (%s)' % ', '.join(_FORMATTERS.keys()))
    parser.add_option('-M', '--max', type='int', dest='max_items',
                       help='Maximum items to dump')
    parser.add_option('-S', '--skip', action="store_true", dest="skip",
                      help="Skip processing messages on the queue - use with --ack to clear a queue.")

    parser = AMQPConfig.addOptionsToParser(parser)
    parser = addLoggingOptions(parser)

    options, args = parser.parse_args()
    if not args:
        parser.error("Require one or more queues as arguments")
    
    if options.skip and not options.acknowledge:
        parser.error("Option --skip must be used with --ack")

    schemas = [SCHEMA]
    schemas.extend(get_zenpack_schemas())

    amqpConnectionInfo = AMQPConfig()
    amqpConnectionInfo.update(options)
    schema = Schema(*schemas)

    try:
        formatter = _FORMATTERS[options.format.lower()]
    except KeyError:
        parser.error('Invalid format "%s"' % options.format)

    initLogging(options)

    publisher = Publisher(amqpConnectionInfo, schema)
    dumper = Dumper(sys.stdout, formatter, publisher.getChannel(), schema, acknowledge=options.acknowledge,
                    skip=options.skip)
    dumper.dumpQueues(args, limit=options.max_items)
def create_exchanges():
    print "Verifying exchanges"

    # Create all the AMQP exchanges we require.   This should be run before we try
    # to have ceilometer send zenoss any events.
    zcml.load_config('meta.zcml', zope.component)
    zcml.load_config('configure.zcml', zope.component)
    zcml.load_config('configure.zcml', Products.ZenMessaging.queuemessaging)

    connectionInfo = getUtility(IAMQPConnectionInfo)
    queueSchema = getUtility(IQueueSchema)
    amqpClient = BlockingPublisher(connectionInfo, queueSchema)
    channel = amqpClient.getChannel()

    for exchange in ('$OpenStackInbound', ):
        exchangeConfig = queueSchema.getExchange(exchange)
        print "Verifying configuration of exchange '%s' (%s)" % (exchange, exchangeConfig.name)

        # Declare the exchange to which the message is being sent
        getAdapter(channel, IAMQPChannelAdapter).declareExchange(exchangeConfig)

    amqpClient.close()
コード例 #5
0
def removeZenPackQueuesExchanges(path):
    """
    Attempts to remove all the queues that the zenpack registered

    @type  Path: string
    @param Path: Absolute path to the zenpack (from zenpack.path())
    """
    schema = _loadQjs(path)
    if not schema:
        # no queues to remove
        return

    connectionInfo = getUtility(IAMQPConnectionInfo)
    queueSchema = getUtility(IQueueSchema)
    amqpClient = BlockingPublisher(connectionInfo, queueSchema)
    channel = amqpClient.getChannel()
    queues = schema[0].get('queues', [])
    exchanges = schema[0].get('exchanges', [])
    log = logging.getLogger('zen.ZenMessaging')

    # queues
    for identifier, queue  in queues.iteritems():
        name = queue['name']
        try:
            substitute_replacements(name, None)
        except MissingReplacementException:
            # Ignore these - they can't be automatically deleted
            continue
        try:
            log.info("Removing queue %s", name)
            channel.queue_delete(name)
        except Exception, e:
            # the queue might already be deleted etc, do not fail if we can't
            # remove it
            log.debug(e)
            log.info("Unable to remove queue %s", name)
import zope.component
from zope.component import getUtility, getAdapter
from Products.Five import zcml

import Products.ZenMessaging.queuemessaging
from zenoss.protocols.interfaces import IAMQPConnectionInfo, IQueueSchema, IAMQPChannelAdapter
from zenoss.protocols.amqp import Publisher as BlockingPublisher

# Create all the AMQP exchanges we require.   This should be run before we try
# to have ceilometer send zenoss any events.

if __name__ == '__main__':
    zcml.load_config('meta.zcml', zope.component)
    zcml.load_config('configure.zcml', zope.component)
    zcml.load_config('configure.zcml', Products.ZenMessaging.queuemessaging)

    connectionInfo = getUtility(IAMQPConnectionInfo)
    queueSchema = getUtility(IQueueSchema)
    amqpClient = BlockingPublisher(connectionInfo, queueSchema)
    channel = amqpClient.getChannel()

    for exchange in ('$OpenStackInbound', '$OpenStackInboundHeartbeats',):
        exchangeConfig = queueSchema.getExchange(exchange)
        print "Verifying configuration of exchange '%s' (%s)" % (exchange, exchangeConfig.name) 

        # Declare the exchange to which the message is being sent
        getAdapter(channel, IAMQPChannelAdapter).declareExchange(exchangeConfig)

    amqpClient.close()

コード例 #7
0
ファイル: publisher.py プロジェクト: zenoss/zenoss-prodbin
 def reconnect(self):
     connectionInfo = getUtility(IAMQPConnectionInfo)
     queueSchema = getUtility(IQueueSchema)
     self._client = BlockingPublisher(connectionInfo, queueSchema)