Beispiel #1
0
def main():
    """main"""
    host = getenv('RABBIT_BROKER')
    port = int(getenv('RABBIT_PORT'))
    user = getenv('RABBIT_USER')
    password = getenv('RABBIT_PWD')
    vhost = getenv('RABBIT_VHOST')
    cert = getenv('CERT', 'cert.pem')

    success = False
    context = rabbitmq.RabbitContext(host,
                                     port,
                                     user,
                                     password,
                                     vhost,
                                     cert=cert)

    try:
        LOGGER.info("Connecting...")

        with rabbitmq.RabbitClient(context) as _:
            success = True
            LOGGER.info("Success.")
    except KeyboardInterrupt:
        LOGGER.info("Stopping")
    except Exception as expt:
        LOGGER.info("Error: %r", expt)

    if success:
        LOGGER.info("SUCCESS - connection to the RabbitMQ service verified.")
    else:
        LOGGER.info(
            "FAILED - connection to the RabbitMQ service not verified.")
def main():
    host = getenv('RABBIT_BROKER')
    port = int(getenv('RABBIT_PORT'))
    user = getenv('RABBIT_USER')
    password = getenv('RABBIT_PWD')
    vhost = getenv('RABBIT_VHOST')
    cert = getenv('CERT', 'cert.pem')
    feed_queue = getenv('PUBLISH_QUEUE')
    reply_queue = getenv('SUBSCRIBE_QUEUE', ' ')

    LOGGER.info("Starting...")

    context = rabbitmq.RabbitContext(host,
                                     port,
                                     user,
                                     password,
                                     vhost,
                                     cert=cert)

    try:
        with rabbitmq.RabbitClient(context) as client:
            client.start(publish=rabbitmq.RabbitQueue(feed_queue, purge=True),
                         subscribe=rabbitmq.RabbitQueue(reply_queue))
            message = {'action': 'Outbound', 'payload': 'some data'}
            LOGGER.info(f'sending {message}')
            client.publish(json.dumps(message))

            with rabbitmq.RabbitClient(context) as server:
                server.start(subscribe=rabbitmq.RabbitQueue(feed_queue))

                mh = ServerMessageHandler()
                server.receive(mh.handler, max_messages=1)

                #And send a reply to the client
                reply = {'action': 'Inbound', 'reply': 'the reply'}
                server.publish(json.dumps(reply),
                               rabbitmq.RabbitQueue(reply_queue))

            #Now catch the reply in the client
            message = client.receive()
            LOGGER.info(f"client got {message}")
    except Exception as err:
        LOGGER.info("Error %r", err)
        raise err
Beispiel #3
0
def main():
    """main"""
    host = getenv('RABBIT_BROKER')
    port = int(getenv('RABBIT_PORT'))
    user = getenv('RABBIT_USER')
    password = getenv('RABBIT_PWD')
    vhost = getenv('RABBIT_VHOST')
    cert = getenv('CERT', 'cert.pem')
    feed_queue = getenv('FEED_QUEUE')
    reply_queue = getenv('REPLY_QUEUE')

    messages = 10
    LOGGER.info("Starting...")

    context = rabbitmq.RabbitContext(host, port, user, password, vhost, cert=cert)

    try:
        start = timeit.default_timer()

        LOGGER.info("Sending requests to: %r", format(feed_queue))

        with rabbitmq.RabbitClient(context) as client:
            client.start_queue(queue=rabbitmq.RabbitQueue(feed_queue))
            message = {"serviceRequest" : "none"}

            for _ in range(0, messages):
                client.publish(json.dumps(message))

        LOGGER.info("Dispatched messages: %r", client.outbound)
        LOGGER.info("Now wait for replies on: %r", reply_queue)

        with rabbitmq.RabbitClient(context) as client:
            client.start_queue(queue=rabbitmq.RabbitQueue(reply_queue))
            client.receive(lambda x: None, max_messages=messages)

        LOGGER.info("Received messages: %r", client.inbound)
        stop = round(timeit.default_timer() - start, 2)
        LOGGER.info("Duration %r", stop)
        LOGGER.info("Done")
    except KeyboardInterrupt:
        LOGGER.info("Stopping")
    except Exception as err:
        LOGGER.info("Error %r", err)
Beispiel #4
0
def main(args):
    activation = os.getenv('__OW_ACTIVATION_ID', None)

    try:
        messages = 0

        cfg = [
            'broker_host', 'broker_vhost', 'broker_port', 'broker_user',
            'broker_password', 'publish_queue'
        ]
        for key in cfg:
            if args.get(key) is None:
                raise Exception('{} is missing'.format(key))

        host = args['broker_host']
        vhost = args['broker_vhost']
        port = args['broker_port']
        user = args['broker_user']
        password = args['broker_password']
        publish_queue = args['publish_queue']

        context = rabbitmq.RabbitContext(host, port, user, password, vhost)

        if 'messages' in args:
            with rabbitmq.RabbitClient(context) as client:
                client.start_queue(queue=rabbitmq.RabbitQueue(publish_queue))

                for msg in args['messages']:
                    messages += 1
                    print(msg)
                    client.publish(json.dumps({'count': messages}))

        result = {'messages': messages}
    except Exception as err:
        result = {'result': str(err)}
        print("Error: %r" % err)

    result.update({"activation": activation})
    print(result)
    return result
Beispiel #5
0
def main():
    """main"""
    signal.signal(signal.SIGTERM, handle_sig)

    host = getenv('RABBIT_BROKER')
    port = int(getenv('RABBIT_PORT'))
    user = getenv('RABBIT_USER')
    password = getenv('RABBIT_PWD')
    vhost = getenv('RABBIT_VHOST')
    cert = getenv('CERT', 'cert.pem')
    subscribe = getenv('FEED_QUEUE')
    num_threads = min(int(getenv('RABBIT_CONNECTIONS', '1')), 32)
    timeout_seconds = int(getenv('SUBSCRIBE_TIMEOUT', '3600'))
    whisk_action = getenv('WHISK_ACTION')
    whisk_retries = int(getenv('WHISK_RETRIES', '10'))

    api_url = getenv('WHISK_URL', None)
    auth_key = getenv('WHISK_AUTH', None)
    namespace = getenv('WHISK_SPACE', None)

    LOGGER.info("Starting...")
    LOGGER.info(" %s, %d, %s, %s, %s.", host, port, user, vhost, subscribe)

    thread_pool = ThreadPoolExecutor(max_workers=num_threads)

    try:
        threads = {}
        rabbit_context = rabbitmq.RabbitContext(host,
                                                port,
                                                user,
                                                password,
                                                vhost,
                                                cert=cert)
        whisk_context = whisk.WhiskContext(api_url, auth_key, namespace)

        for _ in range(0, num_threads):
            handler = MessageHandlerThread(whisk_context, rabbit_context,
                                           subscribe, timeout_seconds,
                                           whisk_retries, whisk_action)
            future = thread_pool.submit(handler.listen)
            threads[future] = handler

        while True:
            try:
                stopped_threads, running_threads = wait(
                    threads, timeout=3600, return_when=FIRST_COMPLETED)
                LOGGER.info("Running threads: %r, Stopped threads: %r",
                            len(running_threads), len(stopped_threads))

                # Ordinarily, a thread should never finish; if one has, remove it and start replacement thread.
                for stopped_thread in stopped_threads:
                    LOGGER.error("Thread stopped; starting replacement...")
                    handler = threads[stopped_thread]
                    future = thread_pool.submit(handler.listen)
                    threads[future] = handler
                    del threads[stopped_thread]
            except KeyboardInterrupt:
                break
            except Exception as expt:
                LOGGER.error("Main Loop: %r", expt)
    except Exception as expt:
        LOGGER.error("Exception: %r", expt)
        traceback.print_exc()
    finally:
        LOGGER.info("Stopping...")

        global SHUTTING_DOWN
        SHUTTING_DOWN = True

        for future, handler in threads.items():
            handler.stop()

        thread_pool.shutdown()
        LOGGER.info("Stopped.")