Exemple #1
0
  def test_timed_request(self):
    nc = NATS()
    msgs = []
    counter = 0

    @asyncio.coroutine
    def worker_handler(msg):
      nonlocal counter
      counter += 1
      msgs.append(msg)
      yield from nc.publish(msg.reply, 'Reply:{}'.format(counter).encode())

    @asyncio.coroutine
    def slow_worker_handler(msg):
      yield from asyncio.sleep(0.5, loop=self.loop)
      yield from nc.publish(msg.reply, b'timeout by now...')

    yield from nc.connect(io_loop=self.loop)
    yield from nc.subscribe("help", cb=worker_handler)
    yield from nc.subscribe("slow.help", cb=slow_worker_handler)

    response = yield from nc.timed_request("help", b'please', timeout=1)
    self.assertEqual(b'Reply:1', response.data)
    response = yield from nc.timed_request("help", b'please', timeout=1)
    self.assertEqual(b'Reply:2', response.data)

    with self.assertRaises(ErrTimeout):
      yield from nc.timed_request("slow.help", b'please', timeout=0.1)
    yield from asyncio.sleep(1, loop=self.loop)
    yield from nc.close()
Exemple #2
0
def run(loop):
    nc = NATS()

    options = {
        "servers": ["nats://*****:*****@nats-01.cryptoquote.io:4222"],
        "io_loop": loop,
    }

    yield from nc.connect(**options)

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # "*" matches any token, at any level of the subject.
    # list to all markets on binance
    yield from nc.subscribe("hose.*.binance.>", cb=message_handler)

    # full hose
    # yield from nc.subscribe("hose.>", cb=message_handler)

    # listen to BTCUSD system wide
    yield from nc.subscribe("hose.*.*.btcusd", cb=message_handler)
Exemple #3
0
def go(loop):
    nc = NATS()

    try:
        yield from nc.connect(io_loop=loop)
    except:
        pass

    @asyncio.coroutine
    def message_handler(msg):
        print("[Received on '{}']: {}".format(msg.subject, msg.data.decode()))

    try:
        # Interested in receiving 2 messages from the 'discover' subject.
        sid = yield from nc.subscribe("discover", "", message_handler)
        yield from nc.auto_unsubscribe(sid, 2)

        yield from nc.publish("discover", b'hello')
        yield from nc.publish("discover", b'world')

        # Following 2 messages won't be received.
        yield from nc.publish("discover", b'again')
        yield from nc.publish("discover", b'!!!!!')
    except ErrConnectionClosed:
        print("Connection closed prematurely")

    @asyncio.coroutine
    def request_handler(msg):
        print("[Request on '{} {}']: {}".format(msg.subject, msg.reply, msg.data.decode()))
        yield from nc.publish(msg.reply, b'OK')

    if nc.is_connected:
        
        # Subscription using a 'workers' queue so that only a single subscriber
        # gets a request at a time.
        yield from nc.subscribe("help", "workers", cb=request_handler)

        try:
            # Make a request expecting a single response within 500 ms,
            # otherwise raising a timeout error.
            msg = yield from nc.timed_request("help", b'help please', 0.500)
            print("[Response]: {}".format(msg.data))

            # Make a roundtrip to the server to ensure messages
            # that sent messages have been processed already.
            yield from nc.flush(0.500)
        except ErrTimeout:
            print("[Error] Timeout!")

        # Wait a bit for message to be dispatched...
        yield from asyncio.sleep(1, loop=loop)

        # Detach from the server.
        yield from nc.close()

    if nc.last_error is not None:
        print("Last Error: {}".format(nc.last_error))

    if nc.is_closed:
        print("Disconnected.")
Exemple #4
0
def run(loop):
    nc = NATS()

    yield from nc.connect(io_loop=loop)

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(subject=subject, reply=reply, data=data))

    # "*" matches any token, at any level of the subject.
    yield from nc.subscribe("foo.*.baz", cb=message_handler)
    yield from nc.subscribe("foo.bar.*", cb=message_handler)

    # ">" matches any length of the tail of a subject, and can only be the last token
    # E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
    yield from nc.subscribe("foo.>", cb=message_handler)

    # Matches all of the above.
    yield from nc.publish("foo.bar.baz", b"Hello World")

    yield from asyncio.sleep(1, loop=loop)
    yield from nc.close()
Exemple #5
0
def run(loop):
    nc = NATS()

    yield from nc.connect(servers=["nats://127.0.0.1:4222"], io_loop=loop)

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # "*" matches any token, at any level of the subject.
    yield from nc.subscribe("foo.*.baz", cb=message_handler)
    yield from nc.subscribe("foo.bar.*", cb=message_handler)

    # ">" matches any length of the tail of a subject, and can only be the last token
    # E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
    yield from nc.subscribe("foo.>", cb=message_handler)

    # Matches all of the above.
    yield from nc.publish("foo.bar.baz", b'Hello World')

    yield from asyncio.sleep(1, loop=loop)
    yield from nc.close()
def pipeline_p1(loop):
    #####################
    # Connection to NATS
    #####################
    nc = NATS()
    yield from nc.connect("localhost:4222", loop=loop)

    #####################
    # Message Handlers
    #####################
    async def mh_s1(msg):
        correlation_id = str(uuid.uuid4())
        log('info', 'p1', 's0', 'S1 initiated', correlation_id)

        jrequest = json.loads(msg.data.decode())

        # Inject a correlation id into the message to enable analysis across pipeline stages
        jresponse = {}
        jresponse['correlation_id'] = correlation_id
        jresponse['data'] = jrequest

        data = sync_null_transform(jresponse,
                                   test_pauses[0])  # Stage processing

        await nc.publish("p1.s1", json.dumps(data).encode('utf-8'))
        log('info', 'p1', 's1', 'S1 completed', correlation_id)

    async def mh_s2(msg):
        jrequest = json.loads(msg.data.decode())

        data = sync_null_transform(jrequest,
                                   test_pauses[1])  # Stage processing

        log('info', 'p1', 's2', 'S2 completed', data['correlation_id'])
        await nc.publish("p1.s2", msg.data)

    async def mh_s3(msg):
        jrequest = json.loads(msg.data.decode())

        data = sync_null_transform(jrequest,
                                   test_pauses[1])  # Stage processing

        log('info', 'p1', 's3', 'S3 completed', data['correlation_id'])
        await nc.publish("p1.s3", msg.data)

    async def mh_s4(msg):
        jrequest = json.loads(msg.data.decode())

        data = sync_null_transform(jrequest,
                                   test_pauses[1])  # Stage processing

        log('info', 'p1', 's4', 's4 completed', data['correlation_id'])

    ######################
    # Pipeline Creation
    ######################
    yield from nc.subscribe("p1.s0", cb=mh_s1)
    yield from nc.subscribe("p1.s1", cb=mh_s2)
    yield from nc.subscribe("p1.s2", cb=mh_s3)
    yield from nc.subscribe("p1.s3", cb=mh_s4)
Exemple #7
0
    def test_timed_request(self):
        nc = NATS()
        msgs = []
        counter = 0

        @asyncio.coroutine
        def worker_handler(msg):
            nonlocal counter
            counter += 1
            msgs.append(msg)
            yield from nc.publish(msg.reply,
                                  'Reply:{}'.format(counter).encode())

        @asyncio.coroutine
        def slow_worker_handler(msg):
            yield from asyncio.sleep(0.5, loop=self.loop)
            yield from nc.publish(msg.reply, b'timeout by now...')

        yield from nc.connect(io_loop=self.loop)
        yield from nc.subscribe("help", cb=worker_handler)
        yield from nc.subscribe("slow.help", cb=slow_worker_handler)

        response = yield from nc.timed_request("help", b'please', timeout=1)
        self.assertEqual(b'Reply:1', response.data)
        response = yield from nc.timed_request("help", b'please', timeout=1)
        self.assertEqual(b'Reply:2', response.data)

        with self.assertRaises(ErrTimeout):
            yield from nc.timed_request("slow.help", b'please', timeout=0.1)
        yield from asyncio.sleep(1, loop=self.loop)
        yield from nc.close()
Exemple #8
0
def pipeline_p1(loop):
    #####################
    # Connection to NATS
    #####################
    nc = NATS()
    logger.info("Attempting to connect to nats server")
    yield from nc.connect("nats:4222", loop=loop)
    logger.info('Attached to nats server')

    #####################
    # Message Handlers
    #####################
    async def mh_s1(msg):
        logger.info('In S1')
        await nc.publish("p1.s1", msg.data)

    async def mh_s2(msg):
        logger.info('In S2')
        await nc.publish("p1.s2", msg.data)

    async def mh_s3(msg):
        logger.info('In S3')
        await nc.publish("p1.s3", msg.data)

    ######################
    # Pipeline Creation
    ######################
    yield from nc.subscribe("p1.s0", cb=mh_s1)
    yield from nc.subscribe("p1.s1", cb=mh_s2)
    yield from nc.subscribe("p1.s2", cb=mh_s3)
    def test_async_await_messages_delivery_order(self):
        nc = NATS()
        msgs = []
        errors = []

        async def error_handler(e):
            errors.push(e)

        yield from nc.connect(io_loop=self.loop, error_cb=error_handler)

        @asyncio.coroutine
        def handler_foo(msg):
          msgs.append(msg)

          # Should not block other subscriptions from receiving messages.
          yield from asyncio.sleep(0.2, loop=self.loop)
          if msg.reply != "":
            yield from nc.publish(msg.reply, msg.data*2)
        yield from nc.subscribe("foo", cb=handler_foo)

        async def handler_bar(msg):
          msgs.append(msg)
          if msg.reply != "":
            await nc.publish(msg.reply, b'')
        yield from nc.subscribe("bar", cb=handler_bar)

        yield from nc.publish("foo", b'1')
        yield from nc.publish("foo", b'2')
        yield from nc.publish("foo", b'3')

        # Will be processed before the others since no head of line
        # blocking among the subscriptions.
        yield from nc.publish("bar", b'4')

        response = yield from nc.request("foo", b'hello1', 1)
        self.assertEqual(response.data, b'hello1hello1')

        with self.assertRaises(ErrTimeout):
            yield from nc.request("foo", b'hello2', 0.1)

        yield from nc.publish("bar", b'5')
        response = yield from nc.request("foo", b'hello2', 1)
        self.assertEqual(response.data, b'hello2hello2')

        self.assertEqual(msgs[0].data, b'1')
        self.assertEqual(msgs[1].data, b'4')
        self.assertEqual(msgs[2].data, b'2')
        self.assertEqual(msgs[3].data, b'3')
        self.assertEqual(msgs[4].data, b'hello1')
        self.assertEqual(msgs[5].data, b'hello2')
        self.assertEqual(len(errors), 0)
        yield from nc.close()
Exemple #10
0
def run(loop):
    nc = NATS()

    ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
    ssl_ctx.protocol = ssl.PROTOCOL_TLSv1_2
    ssl_ctx.load_verify_locations('../tests/certs/ca.pem')
    ssl_ctx.load_cert_chain(certfile='../tests/certs/client-cert.pem',
                            keyfile='../tests/certs/client-key.pem')
    yield from nc.connect(io_loop=loop, tls=ssl_ctx)

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # Simple publisher and async subscriber via coroutine.
    sid = yield from nc.subscribe("foo", cb=message_handler)

    # Stop receiving after 2 messages.
    yield from nc.auto_unsubscribe(sid, 2)
    yield from nc.publish("foo", b'Hello')
    yield from nc.publish("foo", b'World')
    yield from nc.publish("foo", b'!!!!!')

    @asyncio.coroutine
    def help_request(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        yield from nc.publish(reply, b'I can help')

    # Use queue named 'workers' for distributing requests
    # among subscribers.
    yield from nc.subscribe("help", "workers", help_request)

    # Send a request and expect a single response
    # and trigger timeout if not faster than 50 ms.
    try:
        response = yield from nc.timed_request("help", b'help me', 0.050)
        print("Received response: {message}".format(
            message=response.data.decode()))
    except ErrTimeout:
        print("Request timed out")

    yield from asyncio.sleep(1, loop=loop)
    yield from nc.close()
    def test_subscription_slow_consumer_pending_bytes_limit(self):
        nc = NATS()
        msgs = []
        errors = []

        async def error_handler(e):
            if type(e) is ErrSlowConsumer:
                errors.append(e)

        yield from nc.connect(io_loop=self.loop, error_cb=error_handler)

        @asyncio.coroutine
        def handler_foo(msg):
            yield from asyncio.sleep(0.2, loop=self.loop)

            msgs.append(msg)
            if msg.reply != "":
                yield from nc.publish(msg.reply, msg.data*2)
        yield from nc.subscribe("foo", cb=handler_foo, pending_bytes_limit=10)

        async def handler_bar(msg):
            msgs.append(msg)
            if msg.reply != "":
                await nc.publish(msg.reply, msg.data*3)
        yield from nc.subscribe("bar", cb=handler_bar)

        for i in range(10):
            yield from nc.publish("foo", "AAA{}".format(i).encode())

        # Will be processed before the others since no head of line
        # blocking among the subscriptions.
        yield from nc.publish("bar", b'14')

        response = yield from nc.request("bar", b'hi1', 2)
        self.assertEqual(response.data, b'hi1hi1hi1')
        self.assertEqual(len(msgs), 2)
        self.assertEqual(msgs[0].data, b'14')
        self.assertEqual(msgs[1].data, b'hi1')

        # Consumed a few messages but the rest were slow consumers.
        self.assertTrue(7 <= len(errors) <= 8)
        for e in errors:
            self.assertEqual(type(e), ErrSlowConsumer)
        self.assertEqual(errors[0].sid, 1)

        # Try again a few seconds later and it should have recovered
        yield from asyncio.sleep(3, loop=self.loop)
        response = yield from nc.request("foo", b'B', 1)
        self.assertEqual(response.data, b'BB')
        yield from nc.close()
Exemple #12
0
def run(loop):
    nc = NATS()

    ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
    ssl_ctx.protocol = ssl.PROTOCOL_TLSv1_2
    ssl_ctx.load_verify_locations('../tests/certs/ca.pem')
    ssl_ctx.load_cert_chain(certfile='../tests/certs/client-cert.pem',
                            keyfile='../tests/certs/client-key.pem')
    yield from nc.connect(io_loop=loop, tls=ssl_ctx)

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # Simple publisher and async subscriber via coroutine.
    sid = yield from nc.subscribe("foo", cb=message_handler)

    # Stop receiving after 2 messages.
    yield from nc.auto_unsubscribe(sid, 2)
    yield from nc.publish("foo", b'Hello')
    yield from nc.publish("foo", b'World')
    yield from nc.publish("foo", b'!!!!!')

    @asyncio.coroutine
    def help_request(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        yield from nc.publish(reply, b'I can help')

    # Use queue named 'workers' for distributing requests
    # among subscribers.
    yield from nc.subscribe("help", "workers", help_request)

    # Send a request and expect a single response
    # and trigger timeout if not faster than 50 ms.
    try:
        response = yield from nc.timed_request("help", b'help me', 0.050)
        print("Received response: {message}".format(message=response.data.decode()))
    except ErrTimeout:
        print("Request timed out")

    yield from asyncio.sleep(1, loop=loop)
    yield from nc.close()
Exemple #13
0
def run(loop):
    nc = NATS()

    yield from nc.connect("127.0.0.1:4222", loop=loop)

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # Simple publisher and async subscriber via coroutine.
    sid = yield from nc.subscribe("foo", cb=message_handler)

    # Stop receiving after 2 messages.
    yield from nc.auto_unsubscribe(sid, 2)
    yield from nc.publish("foo", b'Hello')
    yield from nc.publish("foo", b'World')
    yield from nc.publish("foo", b'!!!!!')

    @asyncio.coroutine
    def help_request(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        yield from nc.publish(reply, b'I can help')

    # Use queue named 'workers' for distributing requests
    # among subscribers.
    sid = yield from nc.subscribe("help", "workers", help_request)

    # Send a request and expect a single response
    # and trigger timeout if not faster than 50 ms.
    try:
        response = yield from nc.request("help", b'help me', 0.050)
        print("Received response: {message}".format(
            message=response.data.decode()))
    except ErrTimeout:
        print("Request timed out")

    # Remove interest in subscription.
    yield from nc.unsubscribe(sid)

    yield from nc.close()
Exemple #14
0
def run(loop):
    nc = NATS()

    yield from nc.connect(io_loop=loop, servers=[nats_connection_string])

    @asyncio.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        sys.stdout.flush()

    # "*" matches any token, at any level of the subject.


#  yield from nc.subscribe("vehicle.*", cb=message_handler)

# ">" matches any length of the tail of a subject, and can only be the last token
# E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
    yield from nc.subscribe("*.>", cb=message_handler)

    yield from asyncio.sleep(3600, loop=loop)

    yield from nc.close()
def run(loop):
    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        logging.info("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    options = {"servers": [natsURL], "io_loop": loop, "closed_cb": closed_cb}

    yield from nc.connect(**options)
    logging.info("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        logging.info("Receiving from NATS topic: {}".format(msg.subject))
        json_raw = json.loads(msg.data.decode())
        timestamp = json_raw['timestamp']
        status = json_raw['status']
        logging.info("timestamp: {}, status: {}".format(timestamp, status))

    yield from nc.subscribe(topic, cb=subscribe_handler)
    logging.info("Subscribed to topic: {}".format(topic))

    def signal_handler():
        if nc.is_closed:
            return
        logging.info("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)
Exemple #16
0
    def test_subscribe(self):
        nc = NATS()
        msgs = []

        @asyncio.coroutine
        def subscription_handler(msg):
            msgs.append(msg)

        payload = b'hello world'
        yield from nc.connect(io_loop=self.loop,
                              servers=['nats://localhost:4224'],
                              tls=self.ssl_ctx)
        sid = yield from nc.subscribe("foo", cb=subscription_handler)
        yield from nc.publish("foo", payload)
        yield from nc.publish("bar", payload)

        with self.assertRaises(ErrBadSubject):
            yield from nc.publish("", b'')

        # Wait a bit for message to be received.
        yield from asyncio.sleep(0.2, loop=self.loop)

        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual('foo', msg.subject)
        self.assertEqual('', msg.reply)
        self.assertEqual(payload, msg.data)
        self.assertEqual(1, nc._subs[sid].received)
        yield from nc.close()
Exemple #17
0
    def test_pending_data_size_flush_on_close(self):
        nc = NATS()

        disconnected_count = 0
        reconnected_count = 0
        closed_count = 0
        err_count = 0

        @asyncio.coroutine
        def disconnected_cb():
            nonlocal disconnected_count
            disconnected_count += 1

        @asyncio.coroutine
        def reconnected_cb():
            nonlocal reconnected_count
            reconnected_count += 1

        @asyncio.coroutine
        def closed_cb():
            nonlocal closed_count
            closed_count += 1

        options = {
            'dont_randomize': True,
            'io_loop': self.loop,
            'disconnected_cb': disconnected_cb,
            'closed_cb': closed_cb,
            'reconnected_cb': reconnected_cb,
            'reconnect_time_wait': 0.01
        }
        yield from nc.connect(**options)

        total_received = 0
        future = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def receiver_cb(msg):
            nonlocal total_received
            total_received += 1
            if total_received == 200:
                future.set_result(True)

        # Extra connection which should be receiving all the messages
        nc2 = NATS()
        yield from nc2.connect(**options)
        yield from nc2.subscribe("example.*", cb=receiver_cb)
        yield from nc2.flush()

        for i in range(0, 200):
            yield from nc.publish("example.{}".format(i), b'A' * 20)

        # All pending messages should have been emitted to the server
        # by the first connection at this point.
        yield from nc.close()

        # Wait for the server to flush all the messages back to the receiving client
        yield from asyncio.wait_for(future, 1, loop=self.loop)
        yield from nc2.close()
        self.assertEqual(total_received, 200)
Exemple #18
0
    def test_subscribe(self):
        nc = NATS()
        msgs = []

        @asyncio.coroutine
        def subscription_handler(msg):
            msgs.append(msg)

        payload = b'hello world'
        yield from nc.connect(io_loop=self.loop, servers=['nats://localhost:4224'],
                              tls=self.ssl_ctx)
        sid = yield from nc.subscribe("foo", cb=subscription_handler)
        yield from nc.publish("foo", payload)
        yield from nc.publish("bar", payload)

        with self.assertRaises(ErrBadSubject):
            yield from nc.publish("", b'')

        # Wait a bit for message to be received.
        yield from asyncio.sleep(0.2, loop=self.loop)

        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual('foo', msg.subject)
        self.assertEqual('', msg.reply)
        self.assertEqual(payload, msg.data)
        self.assertEqual(1, nc._subs[sid].received)
        yield from nc.close()
Exemple #19
0
def run(loop):
    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    options = {"servers": [natsURL], "io_loop": loop, "closed_cb": closed_cb}

    yield from nc.connect(**options)
    print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        datastreamMsg = datastream_pb2.DataStreamMessage()
        datastreamMsg.ParseFromString(msg.data)
        print(
            "Received a message on {data}".format(data=datastreamMsg.payload))

    yield from nc.subscribe(topic, cb=subscribe_handler)
    print("Subscribed to topic: {}".format(topic))

    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)
Exemple #20
0
    def run(self, loop, queue_name):
        nc = NATS()
        yield from nc.connect(servers=["nats://SCF_IP:4222"], io_loop=loop)

        @asyncio.coroutine
        def message_handler(msg):
            subject = msg.subject
            reply = msg.reply
            data = msg.data.decode()
            print(
                "Received a message on message_handler'{subject} {reply}': {data}"
                .format(subject=subject, reply=reply, data=data))
            print("\n\ntype of data {}".format(str(type(data))))
            #yield from nc.publish(reply, bytes('I can help', 'utf-8'))

            report = json.loads(data)

            metadata = dict()
            metadata.update({'auditor_type': report['auditor_type']})
            metadata.update({'cluster': report['cluster']})
            post_request_ver2('audit_reports', json.dumps(report), None,
                              metadata)

            print("************* data saved ************** ")

        yield from nc.subscribe(queue_name, 'workers', message_handler)
Exemple #21
0
def run(loop):
    nc = Nats()
    yield from nc.connect(io_loop=loop)

    # Send a request and expect a single response and trigger timeout if not
    # faster than 50 ms.
    try:
        response = yield from nc.timed_request("conf.host", b'host', 0.050)
        print("Received response: {message}".format(message=response.data.decode()))
    except ErrTimeout:
        print("Request timed out")

    yield from nc.publish("log.info", b'initializing')
    yield from nc.publish("log.info", b'scraping item 1')

    @asyncio.coroutine
    def help_request(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data
)       )
        yield from nc.publish(reply, b'I can help')

    # Use queue named 'workers' for distributing requests among subscribers.
    yield from nc.subscribe("cmd.help", "workers", help_request)

    yield from asyncio.sleep(20, loop=loop)
    yield from nc.close()
Exemple #22
0
    def test_pending_data_size_flush_on_close(self):
        nc = NATS()

        disconnected_count = 0
        reconnected_count = 0
        closed_count = 0
        err_count = 0

        @asyncio.coroutine
        def disconnected_cb():
            nonlocal disconnected_count
            disconnected_count += 1

        @asyncio.coroutine
        def reconnected_cb():
            nonlocal reconnected_count
            reconnected_count += 1

        @asyncio.coroutine
        def closed_cb():
            nonlocal closed_count
            closed_count += 1

        options = {
            'dont_randomize': True,
            'io_loop': self.loop,
            'disconnected_cb': disconnected_cb,
            'closed_cb': closed_cb,
            'reconnected_cb': reconnected_cb,
            'reconnect_time_wait': 0.01
        }
        yield from nc.connect(**options)

        total_received = 0
        future = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def receiver_cb(msg):
            nonlocal total_received
            total_received += 1
            if total_received == 200:
                future.set_result(True)

        # Extra connection which should be receiving all the messages
        nc2 = NATS()
        yield from nc2.connect(**options)
        yield from nc2.subscribe("example.*", cb=receiver_cb)
        yield from nc2.flush()

        for i in range(0, 200):
            yield from nc.publish("example.{}".format(i), b'A' * 20)

        # All pending messages should have been emitted to the server
        # by the first connection at this point.
        yield from nc.close()

        # Wait for the server to flush all the messages back to the receiving client
        yield from asyncio.wait_for(future, 1, loop=self.loop)
        yield from nc2.close()
        self.assertEqual(total_received, 200)
Exemple #23
0
  def test_invalid_subscription_type(self):
    nc = NATS()

    with self.assertRaises(NatsError):
      yield from nc.subscribe("hello", cb=None, future=None)

    with self.assertRaises(NatsError):
      yield from nc.subscribe_async("hello", cb=None)
Exemple #24
0
    def test_invalid_subscription_type(self):
        nc = NATS()

        with self.assertRaises(NatsError):
            yield from nc.subscribe("hello", cb=None, future=None)

        with self.assertRaises(NatsError):
            yield from nc.subscribe_async("hello", cb=None)
Exemple #25
0
def main(loop, subject):
    nc = NATS()
    yield from nc.connect(f"{sys.argv[1]}:{sys.argv[2]}", loop=loop)

    async def mh_s1(msg):
        await wire_tap(msg)

    yield from nc.subscribe(subject, cb=wire_tap)
Exemple #26
0
def run(loop):
  nc = NATS()

  yield from nc.connect(io_loop=loop)

  @asyncio.coroutine
  def message_handler(msg):
    subject = msg.subject
    reply = msg.reply
    data = msg.data.decode()
    print("Received a message on '{subject} {reply}': {data}".format(
      subject=subject, reply=reply, data=data))

  # Simple publisher and async subscriber via coroutine.
  sid = yield from nc.subscribe("foo", cb=message_handler)

  # Stop receiving after 2 messages.
  yield from nc.auto_unsubscribe(sid, 2)
  yield from nc.publish("foo", b'Hello')
  yield from nc.publish("foo", b'World')
  yield from nc.publish("foo", b'!!!!!')

  @asyncio.coroutine
  def help_request(msg):
    subject = msg.subject
    reply = msg.reply
    data = msg.data.decode()
    print("Received a message on '{subject} {reply}': {data}".format(
      subject=subject, reply=reply, data=data))
    yield from nc.publish(reply, b'I can help')

  # Use queue named 'workers' for distributing requests
  # among subscribers.
  yield from nc.subscribe("help", "workers", help_request)

  # Send a request and expect a single response
  # and trigger timeout if not faster than 50 ms.
  try:
    response = yield from nc.timed_request("help", b'help me', 0.050)
    print("Received response: {message}".format(message=response.data.decode()))
  except ErrTimeout:
    print("Request timed out")

  yield from asyncio.sleep(1, loop=loop)
  yield from nc.close()
Exemple #27
0
def run(loop):
    parser = argparse.ArgumentParser()

    # e.g. nats-sub hello -s nats://127.0.0.1:4222
    parser.add_argument('subject', default='hello', nargs='?')
    parser.add_argument('-s', '--servers', default=[], action='append')
    parser.add_argument('-q', '--queue', default="")
    args = parser.parse_args()

    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    @asyncio.coroutine
    def reconnected_cb():
        print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    options = {
        "io_loop": loop,
        "closed_cb": closed_cb,
        "reconnected_cb": reconnected_cb
    }

    try:
        if len(args.servers) > 0:
            options['servers'] = args.servers

        yield from nc.connect(**options)
    except Exception as e:
        print(e)
        show_usage_and_die()

    print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)

    yield from nc.subscribe(args.subject, args.queue, subscribe_handler)
Exemple #28
0
    def test_close(self):
        nc = NATS()

        disconnected_count = 0
        reconnected_count = 0
        closed_count = 0
        err_count = 0

        @asyncio.coroutine
        def disconnected_cb():
            nonlocal disconnected_count
            disconnected_count += 1

        @asyncio.coroutine
        def reconnected_cb():
            nonlocal reconnected_count
            reconnected_count += 1

        @asyncio.coroutine
        def closed_cb():
            nonlocal closed_count
            closed_count += 1

        @asyncio.coroutine
        def err_cb(e):
            nonlocal err_count
            err_count += 1

        options = {
            'io_loop': self.loop,
            'disconnected_cb': disconnected_cb,
            'closed_cb': closed_cb,
            'reconnected_cb': reconnected_cb,
            'error_cb': err_cb,
        }

        yield from nc.connect(**options)
        yield from nc.close()

        with self.assertRaises(ErrConnectionClosed):
            yield from nc.publish("foo", b'A')

        with self.assertRaises(ErrConnectionClosed):
            yield from nc.subscribe("bar", "workers")

        with self.assertRaises(ErrConnectionClosed):
            yield from nc.publish_request("bar", "inbox", b'B')

        with self.assertRaises(ErrConnectionClosed):
            yield from nc.flush()

        self.assertEqual(1, closed_count)
        self.assertEqual(1, disconnected_count)
        self.assertEqual(0, reconnected_count)
        self.assertEqual(0, err_count)
def run(loop):
    nc = NATS()
    nats_connection_string = "nats://*****:*****@bike.dowhile.se:4222"

    position_bus = {}
    position_bus["lat"] = 57.709548
    position_bus["lon"] = 11.941056
    position_bus["speed"] = 12.5
    position_bus["course"] = 45
    position_bus["time"] = datetime.datetime.now(
        datetime.timezone.utc).isoformat()
    position_bus["vehicle_type"] = "bus"

    position_bike = {}
    position_bike["lat"] = 57.709627
    position_bike["lon"] = 11.942357
    position_bike["speed"] = 14.5
    position_bike["course"] = 330
    position_bike["time"] = datetime.datetime.now(
        datetime.timezone.utc).isoformat()
    position_bike["vehicle_type"] = "bicycle"

    try:
        yield from nc.connect(io_loop=loop, servers=[nats_connection_string])
    except ErrNoServers as e:
        print(e)
        return

    @asyncio.coroutine
    def message_sender(position, vehicle_id):
        subject = "vehicle." + vehicle_id + ".position"
        yield from nc.publish(subject, json.dumps(position).encode())

    @asyncio.coroutine
    def message_printer(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        sys.stdout.flush()

    yield from nc.subscribe("*.>", cb=message_printer)
    yield from message_sender(position_bus, "testBUS1")
    yield from message_sender(position_bike, "testBIKE1")

    try:
        # Flush connection to server, returns when all messages have been processed.
        # It raises a timeout if roundtrip takes longer than 1 second.
        yield from nc.flush(1)
    except ErrTimeout:
        print("Flush timeout")

    yield from asyncio.sleep(1, loop=loop)
    yield from nc.close()
Exemple #30
0
  def test_close(self):
    nc = NATS()

    disconnected_count = 0
    reconnected_count = 0
    closed_count = 0
    err_count = 0

    @asyncio.coroutine
    def disconnected_cb():
      nonlocal disconnected_count
      disconnected_count += 1

    @asyncio.coroutine
    def reconnected_cb():
      nonlocal reconnected_count
      reconnected_count += 1

    @asyncio.coroutine
    def closed_cb():
      nonlocal closed_count
      closed_count += 1

    @asyncio.coroutine
    def err_cb():
      nonlocal err_count
      err_count += 1

    options = {
      'io_loop': self.loop,
      'disconnected_cb': disconnected_cb,
      'closed_cb': closed_cb,
      'reconnected_cb': reconnected_cb,
      'error_cb': err_cb,
      }

    yield from nc.connect(**options)
    yield from nc.close()

    with self.assertRaises(ErrConnectionClosed):
      yield from nc.publish("foo", b'A')

    with self.assertRaises(ErrConnectionClosed):
      yield from nc.subscribe("bar", "workers")

    with self.assertRaises(ErrConnectionClosed):
      yield from nc.publish_request("bar", "inbox", b'B')

    with self.assertRaises(ErrConnectionClosed):
      yield from nc.flush()

    self.assertEqual(1, closed_count)
    self.assertEqual(1, disconnected_count)
    self.assertEqual(0, reconnected_count)
    self.assertEqual(0, err_count)
Exemple #31
0
def run(loop):
    parser = argparse.ArgumentParser()

    # e.g. nats-sub hello -s nats://127.0.0.1:4222
    parser.add_argument('subject', default='hello', nargs='?')
    parser.add_argument('-s', '--servers', default=[], action='append')
    parser.add_argument('-q', '--queue', default="")
    args = parser.parse_args()

    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    @asyncio.coroutine
    def reconnected_cb():
        print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
          subject=subject, reply=reply, data=data))

    options = {
        "io_loop": loop,
        "closed_cb": closed_cb,
        "reconnected_cb": reconnected_cb
    }

    try:
        if len(args.servers) > 0:
            options['servers'] = args.servers

        yield from nc.connect(**options)
    except Exception as e:
        print(e)
        show_usage_and_die()

    print("Connected to NATS at {}...".format(nc.connected_url.netloc))
    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)

    yield from nc.subscribe(args.subject, args.queue, subscribe_handler)
Exemple #32
0
def run(loop):
    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    options = {
        "servers": ["nats://127.0.0.1:4222"],
        "io_loop": loop,
        "closed_cb": closed_cb
    }

    yield from nc.connect(**options)
    print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
          subject=subject, reply=reply, data=data))

    # Basic subscription to receive all published messages
    # which are being sent to a single topic 'discover'
    yield from nc.subscribe("discover", cb=subscribe_handler)

    # Subscription on queue named 'workers' so that
    # one subscriber handles message a request at a time.
    yield from nc.subscribe("help.*", "workers", subscribe_handler)

    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)
Exemple #33
0
def run(loop):
    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    options = {
        "servers": ["nats://127.0.0.1:4222"],
        "io_loop": loop,
        "closed_cb": closed_cb
    }

    yield from nc.connect(**options)
    print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
          subject=subject, reply=reply, data=data))

    # Basic subscription to receive all published messages
    # which are being sent to a single topic 'discover'
    yield from nc.subscribe("discover", cb=subscribe_handler)

    # Subscription on queue named 'workers' so that
    # one subscriber handles message a request at a time.
    yield from nc.subscribe("help.*", "workers", subscribe_handler)

    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)
Exemple #34
0
def main(loop):
    parser = argparse.ArgumentParser()
    parser.add_argument('-n', '--count', default=DEFAULT_NUM_MSGS, type=int)
    parser.add_argument('-S', '--subject', default='test')
    parser.add_argument('--servers', default=[], action='append')
    args = parser.parse_args()

    servers = args.servers
    if len(args.servers) < 1:
        servers = ["nats://127.0.0.1:4222"]
    opts = { "servers": servers, "io_loop": loop, "allow_reconnect": False }

    # Make sure we're connected to a server first...
    nc = NATS()
    try:
        yield from nc.connect(**opts)
    except Exception as e:
        sys.stderr.write("ERROR: {0}".format(e))
        show_usage_and_die()

    received = 0
    start = None

    @asyncio.coroutine
    def handler(msg):
        nonlocal received
        nonlocal start
        received += 1

        # Measure time from when we get the first message.
        if received == 1:
            start = time.monotonic()
        if (received % HASH_MODULO) == 0:
            sys.stdout.write("*")
            sys.stdout.flush()

    yield from nc.subscribe(args.subject, cb=handler)

    # Additional roundtrip with server to ensure everything has been
    # processed by the server already.
    yield from nc.flush()

    print("Waiting for {} messages on [{}]...".format(args.count, args.subject))
    try:
        while received < args.count:
            yield from asyncio.sleep(0.1, loop=loop)
    except ErrTimeout:
        print("Server flush timeout after {0}".format(DEFAULT_FLUSH_TIMEOUT))

    elapsed = time.monotonic() - start
    print("\nTest completed : {0} msgs/sec sent".format(args.count/elapsed))

    print("Received {0} messages ({1} msgs/sec)".format(received, received/elapsed))
    yield from nc.close()
Exemple #35
0
def run(loop):
    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    options = {
        "servers": ["nats://*****:*****@ingest.albion-data.com:4222"],
        "io_loop": loop,
        "closed_cb": closed_cb
    }

    yield from nc.connect(**options)
    print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
          subject=subject, reply=reply, data=data))

    # Basic subscription to receive all published messages
    # which are being sent to a single topic 'discover'
    yield from nc.subscribe("goldprices.deduped", cb=subscribe_handler)
    yield from nc.subscribe("marketorders.deduped", cb=subscribe_handler)


    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)
Exemple #36
0
def main(loop, subject):
    #####################
    # Connection to NATS
    #####################
    nc = NATS()
    yield from nc.connect("localhost:4222", loop=loop)

    #####################
    # Message Handlers
    #####################
    async def mh_s1(msg):
        await wire_tap(msg)

    yield from nc.subscribe(subject, cb=wire_tap)
Exemple #37
0
def main(loop):
    parser = argparse.ArgumentParser()
    parser.add_argument('-n',
                        '--iterations',
                        default=DEFAULT_ITERATIONS,
                        type=int)
    parser.add_argument('-S', '--subject', default='test')
    parser.add_argument('--servers', default=[], action='append')
    args = parser.parse_args()

    servers = args.servers
    if len(args.servers) < 1:
        servers = ["nats://127.0.0.1:4222"]
    opts = {"servers": servers}

    # Make sure we're connected to a server first...
    nc = NATS()
    try:
        yield from nc.connect(**opts)
    except Exception as e:
        sys.stderr.write("ERROR: {0}".format(e))
        show_usage_and_die()

    @asyncio.coroutine
    def handler(msg):
        yield from nc.publish(msg.reply, b'')

    yield from nc.subscribe(args.subject, cb=handler)

    # Start the benchmark
    start = time.monotonic()
    to_send = args.iterations

    print("Sending {0} request/responses on [{1}]".format(
        args.iterations, args.subject))
    while to_send > 0:
        to_send -= 1
        if to_send == 0:
            break

        yield from nc.timed_request(args.subject, b'')
        if (to_send % HASH_MODULO) == 0:
            sys.stdout.write("#")
            sys.stdout.flush()

    duration = time.monotonic() - start
    ms = "%.3f" % ((duration / args.iterations) * 1000)
    print("\nTest completed : {0} ms avg request/response latency".format(ms))
    yield from nc.close()
    def run(self, loop, queue_name):
        nc = NATS()
        yield from nc.connect(servers=["nats://127.0.0.1:4222"], io_loop=loop)

        @asyncio.coroutine
        def message_handler(msg):
            subject = msg.subject
            reply = msg.reply
            data = msg.data.decode()
            print(
                "Received a message on message_handler'{subject} {reply}': {data}"
                .format(subject=subject, reply=reply, data=data))
            yield from nc.publish(reply, bytes('I can help', 'utf-8'))

        yield from nc.subscribe(queue_name, "workers", message_handler)
Exemple #39
0
    def test_subscribe(self):
        nc = NATS()
        msgs = []

        @asyncio.coroutine
        def subscription_handler(msg):
            msgs.append(msg)

        payload = b'hello world'
        yield from nc.connect(io_loop=self.loop)
        sid = yield from nc.subscribe("foo", cb=subscription_handler)
        yield from nc.publish("foo", payload)
        yield from nc.publish("bar", payload)

        with self.assertRaises(ErrBadSubject):
            yield from nc.publish("", b'')

        # Wait a bit for message to be received.
        yield from asyncio.sleep(0.2, loop=self.loop)

        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual('foo', msg.subject)
        self.assertEqual('', msg.reply)
        self.assertEqual(payload, msg.data)
        self.assertEqual(1, nc._subs[sid].received)
        yield from nc.close()

        # After close, the subscription is gone
        with self.assertRaises(KeyError):
            nc._subs[sid]

        self.assertEqual(1,  nc.stats['in_msgs'])
        self.assertEqual(11, nc.stats['in_bytes'])
        self.assertEqual(2,  nc.stats['out_msgs'])
        self.assertEqual(22, nc.stats['out_bytes'])

        endpoint = '127.0.0.1:{port}'.format(
            port=self.server_pool[0].http_port)
        httpclient = http.client.HTTPConnection(endpoint, timeout=5)
        httpclient.request('GET', '/connz')
        response = httpclient.getresponse()
        connz = json.loads((response.read()).decode())
        self.assertEqual(1, len(connz['connections']))
        self.assertEqual(2,  connz['connections'][0]['in_msgs'])
        self.assertEqual(22, connz['connections'][0]['in_bytes'])
        self.assertEqual(1,  connz['connections'][0]['out_msgs'])
        self.assertEqual(11, connz['connections'][0]['out_bytes'])
Exemple #40
0
    def test_subscribe(self):
        nc = NATS()
        msgs = []

        @asyncio.coroutine
        def subscription_handler(msg):
            msgs.append(msg)

        payload = b'hello world'
        yield from nc.connect(io_loop=self.loop)
        sid = yield from nc.subscribe("foo", cb=subscription_handler)
        yield from nc.publish("foo", payload)
        yield from nc.publish("bar", payload)

        with self.assertRaises(ErrBadSubject):
            yield from nc.publish("", b'')

        # Wait a bit for message to be received.
        yield from asyncio.sleep(0.2, loop=self.loop)

        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual('foo', msg.subject)
        self.assertEqual('', msg.reply)
        self.assertEqual(payload, msg.data)
        self.assertEqual(1, nc._subs[sid].received)
        yield from nc.close()

        # After close, the subscription is gone
        with self.assertRaises(KeyError):
            nc._subs[sid]

        self.assertEqual(1, nc.stats['in_msgs'])
        self.assertEqual(11, nc.stats['in_bytes'])
        self.assertEqual(2, nc.stats['out_msgs'])
        self.assertEqual(22, nc.stats['out_bytes'])

        endpoint = '127.0.0.1:{port}'.format(
            port=self.server_pool[0].http_port)
        httpclient = http.client.HTTPConnection(endpoint, timeout=5)
        httpclient.request('GET', '/connz')
        response = httpclient.getresponse()
        connz = json.loads((response.read()).decode())
        self.assertEqual(1, len(connz['connections']))
        self.assertEqual(2, connz['connections'][0]['in_msgs'])
        self.assertEqual(22, connz['connections'][0]['in_bytes'])
        self.assertEqual(1, connz['connections'][0]['out_msgs'])
        self.assertEqual(11, connz['connections'][0]['out_bytes'])
Exemple #41
0
    def test_unsubscribe(self):
        nc = NATS()
        msgs = []

        @asyncio.coroutine
        def subscription_handler(msg):
            msgs.append(msg)

        yield from nc.connect(io_loop=self.loop)
        sid = yield from nc.subscribe("foo", cb=subscription_handler)
        yield from nc.publish("foo", b'A')
        yield from nc.publish("foo", b'B')

        # Wait a bit to receive the messages
        yield from asyncio.sleep(0.5, loop=self.loop)
        self.assertEqual(2, len(msgs))
        yield from nc.unsubscribe(sid)
        yield from nc.publish("foo", b'C')
        yield from nc.publish("foo", b'D')

        # Ordering should be preserverd in these at least
        self.assertEqual(b'A', msgs[0].data)
        self.assertEqual(b'B', msgs[1].data)

        # Should not exist by now
        with self.assertRaises(KeyError):
            nc._subs[sid].received

        yield from asyncio.sleep(1, loop=self.loop)
        endpoint = '127.0.0.1:{port}'.format(
            port=self.server_pool[0].http_port)
        httpclient = http.client.HTTPConnection(endpoint, timeout=5)
        httpclient.request('GET', '/connz')
        response = httpclient.getresponse()
        connz = json.loads((response.read()).decode())
        self.assertEqual(1, len(connz['connections']))
        self.assertEqual(0, connz['connections'][0]['subscriptions'])
        self.assertEqual(4, connz['connections'][0]['in_msgs'])
        self.assertEqual(4, connz['connections'][0]['in_bytes'])
        self.assertEqual(2, connz['connections'][0]['out_msgs'])
        self.assertEqual(2, connz['connections'][0]['out_bytes'])

        yield from nc.close()
        self.assertEqual(2, nc.stats['in_msgs'])
        self.assertEqual(2, nc.stats['in_bytes'])
        self.assertEqual(4, nc.stats['out_msgs'])
        self.assertEqual(4, nc.stats['out_bytes'])
Exemple #42
0
    def test_unsubscribe(self):
        nc = NATS()
        msgs = []

        @asyncio.coroutine
        def subscription_handler(msg):
            msgs.append(msg)

        yield from nc.connect(io_loop=self.loop)
        sid = yield from nc.subscribe("foo", cb=subscription_handler)
        yield from nc.publish("foo", b'A')
        yield from nc.publish("foo", b'B')

        # Wait a bit to receive the messages
        yield from asyncio.sleep(0.5, loop=self.loop)
        self.assertEqual(2, len(msgs))
        yield from nc.unsubscribe(sid)
        yield from nc.publish("foo", b'C')
        yield from nc.publish("foo", b'D')

        # Ordering should be preserverd in these at least
        self.assertEqual(b'A', msgs[0].data)
        self.assertEqual(b'B', msgs[1].data)

        # Should not exist by now
        with self.assertRaises(KeyError):
            nc._subs[sid].received

        yield from asyncio.sleep(1, loop=self.loop)
        endpoint = '127.0.0.1:{port}'.format(
            port=self.server_pool[0].http_port)
        httpclient = http.client.HTTPConnection(endpoint, timeout=5)
        httpclient.request('GET', '/connz')
        response = httpclient.getresponse()
        connz = json.loads((response.read()).decode())
        self.assertEqual(1, len(connz['connections']))
        self.assertEqual(0,  connz['connections'][0]['subscriptions'])
        self.assertEqual(4,  connz['connections'][0]['in_msgs'])
        self.assertEqual(4,  connz['connections'][0]['in_bytes'])
        self.assertEqual(2,  connz['connections'][0]['out_msgs'])
        self.assertEqual(2,  connz['connections'][0]['out_bytes'])

        yield from nc.close()
        self.assertEqual(2, nc.stats['in_msgs'])
        self.assertEqual(2, nc.stats['in_bytes'])
        self.assertEqual(4, nc.stats['out_msgs'])
        self.assertEqual(4, nc.stats['out_bytes'])
def main(loop, subject):
    #####################
    # Connection to NATS
    #####################
    nc = NATS()
    yield from nc.connect("localhost:4222", loop=loop)

    #####################
    # Message Handlers
    #####################
    async def mh_markets(msg):
        resp = calculate(msg)
        print("Response returned to caller:", resp)
        await nc.publish(msg.reply, json.dumps(resp).encode())
        print("Published response to reply queue:", resp)

    yield from nc.subscribe(subject, cb=mh_markets)
def run(loop):
    nc = NATS()

    @asyncio.coroutine
    def closed_cb():
        print("Connection to NATS is closed.")
        yield from asyncio.sleep(0.1, loop=loop)
        loop.stop()

    options = {
        "servers": [
            "nats://{0}@nats1.polygon.io:30401".format(sys.argv[1]),
            "nats://{0}@nats2.polygon.io:30402".format(sys.argv[1]),
            "nats://{0}@nats3.polygon.io:30403".format(sys.argv[1])
        ],
        "io_loop":
        loop,
        "closed_cb":
        closed_cb
    }
    print(str(options))

    yield from nc.connect(**options)
    print("Connected to NATS at {}...".format(nc.connected_url.netloc))

    @asyncio.coroutine
    def subscribe_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # Basic subscription to receive all published messages
    # which are being sent to a single topic 'discover'
    yield from nc.subscribe("C.*", cb=subscribe_handler)

    def signal_handler():
        if nc.is_closed:
            return
        print("Disconnecting...")
        loop.create_task(nc.close())

    for sig in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, sig), signal_handler)
def main(loop):
  parser = argparse.ArgumentParser()
  parser.add_argument('-n', '--iterations', default=DEFAULT_ITERATIONS, type=int)
  parser.add_argument('-S', '--subject', default='test')
  parser.add_argument('--servers', default=[], action='append')
  args = parser.parse_args()

  servers = args.servers
  if len(args.servers) < 1:
    servers = ["nats://127.0.0.1:4222"]
  opts = { "servers": servers }

  # Make sure we're connected to a server first...
  nc = NATS()
  try:
    yield from nc.connect(**opts)
  except Exception as e:
    sys.stderr.write("ERROR: {0}".format(e))
    show_usage_and_die()

  @asyncio.coroutine
  def handler(msg):
    yield from nc.publish(msg.reply, b'')
  yield from nc.subscribe(args.subject, cb=handler)

  # Start the benchmark
  start = time.monotonic()
  to_send = args.iterations

  print("Sending {0} request/responses on [{1}]".format(
      args.iterations, args.subject))
  while to_send > 0:
    to_send -= 1
    if to_send == 0:
      break

    yield from nc.timed_request(args.subject, b'')
    if (to_send % HASH_MODULO) == 0:
      sys.stdout.write("#")
      sys.stdout.flush()

  duration = time.monotonic() - start
  ms = "%.3f" % ((duration/args.iterations) * 1000)
  print("\nTest completed : {0} ms avg request/response latency".format(ms))
  yield from nc.close()
Exemple #46
0
def run(loop):
    nc = NATS()
    yield from nc.connect(io_loop=loop)

    @asyncio.coroutine
    def message_handler(msg):
        print('received something')
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

    # Simple publisher and async subscriber via coroutine.
    sid = yield from nc.subscribe("foo", cb=message_handler)

    # Stop receiving after 2 messages.
    #yield from nc.auto_unsubscribe(sid, 2)
    #yield from nc.publish("foo", b'Hello')
    #yield from nc.publish("foo", b'World')
    #yield from nc.publish("foo", b'!!!!!')
    '''
  @asyncio.coroutine
  def help_request(msg):
    subject = msg.subject
    reply = msg.reply
    data = msg.data.decode()
    print("Received a message on '{subject} {reply}': {data}".format(
      subject=subject, reply=reply, data=data))
    yield from nc.publish(reply, b'I can help')
  '''
    # Use queue named 'workers' for distributing requests
    # among subscribers.
    #yield from nc.subscribe("help", "workers", help_request)

    # Send a request and expect a single response
    # and trigger timeout if not faster than 50 ms.
    #try:
    #  response = yield from nc.timed_request("help", b'help me', 10.050)
    #  print("Received response: {message}".format(message=response.data.decode()))
    #except ErrTimeout:
    #  print("Request timed out")

    yield from asyncio.sleep(1, loop=loop)
Exemple #47
0
  def test_invalid_subscribe_error(self):
    nc = NATS()
    msgs = []
    future_error = asyncio.Future(loop=self.loop)

    @asyncio.coroutine
    def subscription_handler(msg):
      msgs.append(msg)

    @asyncio.coroutine
    def closed_cb():
      nonlocal future_error
      future_error.set_result(nc.last_error)

    yield from nc.connect(io_loop=self.loop, closed_cb=closed_cb)
    yield from nc.subscribe("foo.", cb=subscription_handler)
    yield from asyncio.wait_for(future_error, 1.0, loop=self.loop)
    nats_error = future_error.result()
    self.assertEqual(type(nats_error), NatsError)
    self.assertEqual(str(nats_error), "nats: 'Invalid Subject'")
Exemple #48
0
  def test_subscribe_sync_call_soon(self):
    nc = NATS()
    msgs = []

    def subscription_handler(msg):
      msgs.append(msg)

    yield from nc.connect(io_loop=self.loop)
    sid = yield from nc.subscribe("tests.>", cb=subscription_handler)

    for i in range(0, 5):
      yield from nc.publish("tests.{}".format(i), b'bar')

    # Wait a bit for messages to be received.
    yield from asyncio.sleep(1, loop=self.loop)
    self.assertEqual(5, len(msgs))

    # Check that they were received sequentially.
    self.assertEqual("tests.1", msgs[1].subject)
    self.assertEqual("tests.3", msgs[3].subject)
    yield from nc.close()
Exemple #49
0
def run(loop):
  nc = NATS()

  try:
    yield from nc.connect(io_loop=loop)
  except ErrNoServers as e:
    print(e)
    return

  @asyncio.coroutine
  def message_handler(msg):
    subject = msg.subject
    reply = msg.reply
    data = msg.data.decode()
    for i in range(0, 20):
      yield from nc.publish(reply, "i={i}".format(i=i).encode())

  yield from nc.subscribe("help.>", cb=message_handler)

  @asyncio.coroutine
  def request_handler(msg):
    subject = msg.subject
    reply = msg.reply
    data = msg.data.decode()
    print("Received a message on '{subject} {reply}': {data}".format(
      subject=subject, reply=reply, data=data))

  # Signal the server to stop sending messages after we got 10 already.
  yield from nc.request("help.please", b'help', expected=10, cb=request_handler)

  try:
    # Flush connection to server, returns when all messages have been processed.
    # It raises a timeout if roundtrip takes longer than 1 second.
    yield from nc.flush(1)
  except ErrTimeout:
    print("Flush timeout")

  yield from asyncio.sleep(1, loop=loop)
  yield from nc.close()
  def test_async_await_subscribe_async(self):
    nc = NATS()
    msgs = []

    async def subscription_handler(msg):
      if msg.subject == "tests.1":
        await asyncio.sleep(0.5, loop=self.loop)
      if msg.subject == "tests.3":
        await asyncio.sleep(0.2, loop=self.loop)
      msgs.append(msg)

    yield from nc.connect(io_loop=self.loop)
    sid = yield from nc.subscribe("tests.>", cb=subscription_handler)

    for i in range(0, 5):
      yield from nc.publish("tests.{}".format(i), b'bar')

    # Wait a bit for messages to be received.
    yield from asyncio.sleep(1, loop=self.loop)
    self.assertEqual(5, len(msgs))
    self.assertEqual("tests.1", msgs[1].subject)
    self.assertEqual("tests.3", msgs[3].subject)
    yield from nc.close()
Exemple #51
0
def main(loop):
    parser = argparse.ArgumentParser()
    parser.add_argument('-n', '--count', default=DEFAULT_NUM_MSGS, type=int)
    parser.add_argument('-s', '--size', default=DEFAULT_MSG_SIZE, type=int)
    parser.add_argument('-S', '--subject', default='test')
    parser.add_argument('-b', '--batch', default=DEFAULT_BATCH_SIZE, type=int)
    parser.add_argument('--servers', default=[], action='append')
    args = parser.parse_args()

    data = []
    for i in range(0, args.size):
        s = "%01x" % randint(0, 15)
        data.append(s.encode())
    payload = b''.join(data)

    servers = args.servers
    if len(args.servers) < 1:
        servers = ["nats://127.0.0.1:4222"]
    opts = { "servers": servers, "io_loop": loop }

    # Make sure we're connected to a server first...
    nc = NATS()
    try:
        yield from nc.connect(**opts)
    except Exception as e:
        sys.stderr.write("ERROR: {0}".format(e))
        show_usage_and_die()

    received = 0
    @asyncio.coroutine
    def handler(msg):
        nonlocal received
        received += 1
        if (received % HASH_MODULO) == 0:
            sys.stdout.write("*")
            sys.stdout.flush()
    yield from nc.subscribe(args.subject, cb=handler)

    # Start the benchmark
    start = time.time()
    to_send = args.count

    print("Sending {0} messages of size {1} bytes on [{2}]".format(
        args.count, args.size, args.subject))
    while to_send > 0:
        for i in range(0, args.batch):
            to_send -= 1
            yield from nc.publish(args.subject, payload)
            if (to_send % HASH_MODULO) == 0:
                sys.stdout.write("#")
                sys.stdout.flush()
            if to_send == 0:
                break

        # Minimal pause in between batches of commands sent to server
        yield from asyncio.sleep(0.00001, loop=loop)

    # Additional roundtrip with server to ensure everything has been
    # processed by the server already.
    try:
        while received < args.count:
            yield from nc.flush(DEFAULT_FLUSH_TIMEOUT)
    except ErrTimeout:
        print("Server flush timeout after {0}".format(DEFAULT_FLUSH_TIMEOUT))

    elapsed = time.time() - start
    mbytes = "%.1f" % (((args.size * args.count)/elapsed) / (1024*1024))
    print("\nTest completed : {0} msgs/sec sent ({1}) MB/sec".format(
        args.count/elapsed,
        mbytes))

    print("Received {0} messages ({1} msgs/sec)".format(received, received/elapsed))
    yield from nc.close()
Exemple #52
0
  def test_auth_reconnect(self):
    nc = NATS()
    disconnected_count = 0
    reconnected_count = 0
    closed_count = 0
    err_count = 0

    @asyncio.coroutine
    def disconnected_cb():
      nonlocal disconnected_count
      disconnected_count += 1

    @asyncio.coroutine
    def reconnected_cb():
      nonlocal reconnected_count
      reconnected_count += 1

    @asyncio.coroutine
    def closed_cb():
      nonlocal closed_count
      closed_count += 1

    @asyncio.coroutine
    def err_cb():
      nonlocal err_count
      err_count += 1

    counter = 0
    @asyncio.coroutine
    def worker_handler(msg):
      nonlocal counter
      counter += 1
      if msg.reply != "":
        yield from nc.publish(msg.reply, 'Reply:{}'.format(counter).encode())

    options = {
      'servers': [
        "nats://*****:*****@127.0.0.1:4223",
        "nats://*****:*****@127.0.0.1:4224"
        ],
      'io_loop': self.loop,
      'disconnected_cb': disconnected_cb,
      'closed_cb': closed_cb,
      'reconnected_cb': reconnected_cb,
      'error_cb': err_cb,
      'dont_randomize': True,
      }
    yield from nc.connect(**options)
    self.assertTrue(nc.is_connected)

    yield from nc.subscribe("one", cb=worker_handler)
    yield from nc.subscribe("two", cb=worker_handler)
    yield from nc.subscribe("three", cb=worker_handler)

    response = yield from nc.timed_request("one", b'Help!', timeout=1)
    self.assertEqual(b'Reply:1', response.data)

    # Stop the first server and connect to another one asap.
    yield from self.loop.run_in_executor(None, self.server_pool[0].stop)

    # FIXME: Find better way to wait for the server to be stopped.
    yield from asyncio.sleep(0.5, loop=self.loop)

    response = yield from nc.timed_request("three", b'Help!', timeout=1)
    self.assertEqual('Reply:2'.encode(), response.data)
    yield from asyncio.sleep(0.5, loop=self.loop)
    yield from nc.close()
    self.assertEqual(1, nc.stats['reconnects'])
    self.assertEqual(1, closed_count)
    self.assertEqual(2, disconnected_count)
    self.assertEqual(1, reconnected_count)
    self.assertEqual(0, err_count)
Exemple #53
0
    def test_tls_reconnect(self):

        nc = NATS()
        disconnected_count = 0
        reconnected_count = 0
        closed_count = 0
        err_count = 0

        @asyncio.coroutine
        def disconnected_cb():
            nonlocal disconnected_count
            disconnected_count += 1

        @asyncio.coroutine
        def reconnected_cb():
            nonlocal reconnected_count
            reconnected_count += 1

        @asyncio.coroutine
        def closed_cb():
            nonlocal closed_count
            closed_count += 1

        @asyncio.coroutine
        def err_cb(e):
            nonlocal err_count
            err_count += 1

        counter = 0

        @asyncio.coroutine
        def worker_handler(msg):
            nonlocal counter
            counter += 1
            if msg.reply != "":
                yield from nc.publish(msg.reply, 'Reply:{}'.format(counter).encode())

        options = {
            'servers': [
                "nats://*****:*****@localhost:4223",
                "nats://*****:*****@localhost:4224"
            ],
            'io_loop': self.loop,
            'disconnected_cb': disconnected_cb,
            'closed_cb': closed_cb,
            'reconnected_cb': reconnected_cb,
            'error_cb': err_cb,
            'dont_randomize': True,
            'tls': self.ssl_ctx
        }
        yield from nc.connect(**options)
        self.assertTrue(nc.is_connected)

        yield from nc.subscribe("example", cb=worker_handler)
        response = yield from nc.request("example", b'Help!', timeout=1)
        self.assertEqual(b'Reply:1', response.data)

        # Trigger a reconnnect and should be fine
        yield from self.loop.run_in_executor(None, self.server_pool[0].stop)
        yield from asyncio.sleep(1, loop=self.loop)

        yield from nc.subscribe("example", cb=worker_handler)
        response = yield from nc.request("example", b'Help!', timeout=1)
        self.assertEqual(b'Reply:2', response.data)

        yield from nc.close()
        self.assertTrue(nc.is_closed)
        self.assertFalse(nc.is_connected)
        self.assertEqual(1, nc.stats['reconnects'])
        self.assertEqual(1, closed_count)
        self.assertEqual(2, disconnected_count)
        self.assertEqual(1, reconnected_count)
        self.assertEqual(1, err_count)
Exemple #54
0
def run(loop):

  nc = NATS()

  # Setup pool of servers from a NATS cluster.
  options = {
    "servers": [
      "nats://*****:*****@127.0.0.1:4222",
      "nats://*****:*****@127.0.0.1:4223",
      "nats://*****:*****@127.0.0.1:4224",
      ],
    "io_loop": loop,
  }

  # Will try to connect to servers in order of configuration,
  # by defaults it connect to one in the pool randomly.
  options["dont_randomize"] = True

  # Optionally set reconnect wait and max reconnect attempts.
  # This example means 10 seconds total per backend.
  options["max_reconnect_attempts"] = 5
  options["reconnect_time_wait"] = 2

  @asyncio.coroutine
  def disconnected_cb():
    print("Got disconnected!")

  @asyncio.coroutine
  def reconnected_cb():
    # See who we are connected to on reconnect.    
    print("Got reconnected to {url}".format(url=nc.connected_url.netloc))

  # Setup callbacks to be notified on disconnects and reconnects    
  options["disconnected_cb"] = disconnected_cb    
  options["reconnected_cb"]  = reconnected_cb

  @asyncio.coroutine
  def error_cb(e):
    print("There was an error: {}".format(e))

  @asyncio.coroutine
  def closed_cb():
    print("Connection is closed")

  # Setup callbacks to be notified when there is an error
  # or connection is closed.
  options["error_cb"] = error_cb
  options["closed_cb"] = closed_cb  

  try:
    yield from nc.connect(**options)
  except ErrNoServers as e:
    # Could not connect to any server in the cluster.
    print(e)
    return

  if nc.is_connected:
    yield from nc.subscribe("help.*")

    max_messages = 1000000
    start_time = datetime.now()
    print("Sending {} messages to NATS...".format(max_messages))

    for i in range(0, max_messages):
      try:
        yield from nc.publish("help.{}".format(i), b'A')
        yield from nc.flush(0.500)
      except ErrConnectionClosed as e:
        print("Connection closed prematurely.")
        break
      except ErrTimeout as e:
        print("Timeout occured when publishing msg i={}: {}".format(i, e))

    end_time = datetime.now()
    yield from nc.close()
    duration = end_time - start_time
    print("Duration: {}".format(duration))

    try:
      yield from nc.publish("help", b"hello world")
    except ErrConnectionClosed:
      print("Can't publish since no longer connected.")

  err = nc.last_error
  if err is not None:
    print("Last Error: {}".format(err))
Exemple #55
0
    def test_reconnect_with_auth_token(self):
        nc = NATS()

        disconnected_count = 0
        reconnected_count = 0
        closed_count = 0
        err_count = 0

        @asyncio.coroutine
        def disconnected_cb():
            nonlocal disconnected_count
            disconnected_count += 1

        @asyncio.coroutine
        def reconnected_cb():
            nonlocal reconnected_count
            reconnected_count += 1

        @asyncio.coroutine
        def closed_cb():
            nonlocal closed_count
            closed_count += 1

        counter = 0

        @asyncio.coroutine
        def worker_handler(msg):
            nonlocal counter
            counter += 1
            if msg.reply != "":
                yield from nc.publish(msg.reply, 'Reply:{}'.format(counter).encode())

        options = {
            'servers': [
                "nats://[email protected]:4223",
                "nats://[email protected]:4224",
            ],
            'disconnected_cb': disconnected_cb,
            'closed_cb': closed_cb,
            'reconnected_cb': reconnected_cb,
            'dont_randomize': True,
            'io_loop': self.loop
        }
        yield from nc.connect(**options)
        yield from nc.subscribe("test", cb=worker_handler)
        self.assertIn('auth_required', nc._server_info)
        self.assertTrue(nc.is_connected)

        # Trigger a reconnnect
        yield from self.loop.run_in_executor(None, self.server_pool[0].stop)
        yield from asyncio.sleep(1, loop=self.loop)

        yield from nc.subscribe("test", cb=worker_handler)
        response = yield from nc.request("test", b'data', timeout=1)
        self.assertEqual(b'Reply:1', response.data)

        yield from nc.close()
        self.assertTrue(nc.is_closed)
        self.assertFalse(nc.is_connected)
        self.assertEqual(1, closed_count)
        self.assertEqual(2, disconnected_count)
        self.assertEqual(1, reconnected_count)
Exemple #56
0
    def test_custom_flush_queue_reconnect(self):
        nc = NATS()

        disconnected_count = 0
        reconnected_count = 0
        closed_count = 0
        err_count = 0

        @asyncio.coroutine
        def disconnected_cb():
            nonlocal disconnected_count
            disconnected_count += 1

        @asyncio.coroutine
        def reconnected_cb():
            nonlocal reconnected_count
            reconnected_count += 1

        @asyncio.coroutine
        def closed_cb():
            nonlocal closed_count
            closed_count += 1

        options = {
            'servers': [
                "nats://*****:*****@127.0.0.1:4223",
                "nats://*****:*****@127.0.0.1:4224"
            ],
            'dont_randomize': True,
            'io_loop': self.loop,
            'disconnected_cb': disconnected_cb,
            'closed_cb': closed_cb,
            'reconnected_cb': reconnected_cb,
            'flusher_queue_size': 100,
            'reconnect_time_wait': 0.01
        }
        yield from nc.connect(**options)
        largest_pending_data_size = 0
        post_flush_pending_data = None
        done_once = False

        @asyncio.coroutine
        def cb(msg):
            pass

        yield from nc.subscribe("example.*", cb=cb)

        for i in range(0, 500):
            yield from nc.publish("example.{}".format(i), b'A' * 20)
            if nc.pending_data_size > 0:
                largest_pending_data_size = nc.pending_data_size
            if nc.pending_data_size > 100:
                # Stop the first server and connect to another one asap.
                if not done_once:
                    yield from nc.flush(2)
                    post_flush_pending_data = nc.pending_data_size
                    yield from self.loop.run_in_executor(None, self.server_pool[0].stop)
                    done_once = True

        self.assertTrue(largest_pending_data_size > 0)
        self.assertTrue(post_flush_pending_data == 0)

        # Confirm we have reconnected eventually
        for i in range(0, 10):
            yield from asyncio.sleep(0, loop=self.loop)
            yield from asyncio.sleep(0.2, loop=self.loop)
            yield from asyncio.sleep(0, loop=self.loop)
        self.assertEqual(1, nc.stats['reconnects'])
        try:
            yield from nc.flush(2)
        except ErrTimeout:
            # If disconnect occurs during this flush, then we will have a timeout here
            pass
        finally:
            yield from nc.close()

        self.assertTrue(disconnected_count >= 1)
        self.assertTrue(closed_count >= 1)
class Requester(pykka.ThreadingActor):
    """
    NATS requester implementation
    :param my_args: dict like {connection, request_q}
    """

    def __init__(self, my_args=None, connection_args=None):
        """
        NATS requester constructor
        :param my_args: dict like {connection, request_q}
        :param connection_args: dict like {user, password, host[, port, client_properties]}
        :return: self
        """
        LOGGER.debug("natsd.Requester.__init__")
        if my_args is None:
            raise exceptions.ArianeConfError("requestor arguments")
        if 'request_q' not in my_args or my_args['request_q'] is None or not my_args['request_q']:
            raise exceptions.ArianeConfError("request_q")
        if 'fire_and_forget' not in my_args or my_args['fire_and_forget'] is None or not my_args['fire_and_forget']:
            self.fire_and_forget = False
        else:
            self.fire_and_forget = True
        if 'rpc_timeout' not in connection_args or connection_args['rpc_timeout'] is None or \
                not connection_args['rpc_timeout']:
            # default timeout = no timeout
            self.rpc_timeout = 0
        else:
            self.rpc_timeout = connection_args['rpc_timeout']

        if 'rpc_timeout_err_count_max' not in connection_args or connection_args['rpc_timeout_err_count_max'] is None \
                or not connection_args['rpc_timeout_err_count_max']:
            self.rpc_retry_timeout_err_count_max = 3
        else:
            self.rpc_retry_timeout_err_count_max = connection_args['rpc_timeout_err_count_max']
        self.rpc_retry_timeout_err_count = 0

        if 'rpc_retry' not in connection_args or connection_args['rpc_retry'] is None or \
                not connection_args['rpc_retry']:
            # default retry = no retry
            self.rpc_retry = 0
        else:
            self.rpc_retry = connection_args['rpc_retry']

        Driver.validate_driver_conf(connection_args)

        super(Requester, self).__init__()
        self.connection_args = copy.deepcopy(connection_args)
        self.servers = [
            "nats://" + connection_args['user'] + ":" + connection_args['password'] + "@" +
            connection_args['host']+":"+str(connection_args['port'])
        ]
        self.name = self.connection_args['client_properties']['ariane.app'] + "@" + socket.gethostname() + \
            " - requestor on " + my_args['request_q']
        self.loop = None
        self.options = None
        self.service = None
        self.nc = Client()
        self.requestQ = my_args['request_q']
        self.responseQ = None
        self.responseQS = None
        self.response = None
        self.split_responses = None
        self.split_responses_mid = None
        self.is_started = False
        self.trace = False
        self.max_payload = 0

        if not self.fire_and_forget:
            self.responseQ = new_inbox()
            self.response = None
            self.corr_id = None

    def connect(self):
        LOGGER.debug("natsd.Requester.connect")
        try:
            yield from self.nc.connect(**self.options)
            if not self.fire_and_forget:
                self.responseQS = yield from self.nc.subscribe(self.responseQ, cb=self.on_response)
            self.max_payload = self.nc._max_payload
            self.is_started = True
        except ErrNoServers as e:
            print(e)
            return

    def run_event_loop(self):
        LOGGER.debug("natsd.Requester.run_event_loop")
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        self.options = {
            "servers": self.servers,
            "name": self.name,
            # "disconnected_cb": self.disconnected_cb,
            # "reconnected_cb": self.reconnected_cb,
            # "error_cb": self.error_cb,
            # "closed_cb": self.closed_cb,
            "io_loop": self.loop,
        }
        self.loop.create_task(self.connect())
        self.loop.run_forever()

    def on_start(self):
        """
        start requester
        """
        LOGGER.debug("natsd.Requester.on_start")
        self.service = threading.Thread(target=self.run_event_loop, name=self.requestQ + " requestor thread")
        self.service.start()
        while not self.is_started:
            time.sleep(0.01)

    def on_stop(self):
        """
        stop requester
        """
        LOGGER.debug("natsd.Requester.on_stop")
        self.is_started = False
        try:
            LOGGER.debug("natsd.Requester.on_stop - unsubscribe from " + str(self.responseQS))
            next(self.nc.unsubscribe(self.responseQS))
        except StopIteration as e:
            pass
        try:
            LOGGER.debug("natsd.Requester.on_stop - close nats connection")
            next(self.nc.close())
        except StopIteration as e:
            pass
        LOGGER.debug("natsd.Requester.on_stop - nc is closed: " + str(self.nc.is_closed))
        try:
            LOGGER.debug("natsd.Requester.on_stop - cancelling aio tasks loop")
            loop_to_stop = self.loop
            for task in asyncio.Task.all_tasks(loop_to_stop):
                LOGGER.debug("natsd.Requester.on_stop - cancelling task " + str(task))
                task.cancel()
            LOGGER.debug("natsd.Requester.on_stop - stopping aio loop stop")
            loop_to_stop.stop()
            count = 0
            while loop_to_stop.is_running():
                count += 1
                if count % 10 == 0:
                    LOGGER.debug("natsd.Requester.on_stop - waiting aio loop to be stopped (" +
                                 str(asyncio.Task.all_tasks(loop_to_stop).__len__()) + " tasks left; " +
                                 "current task: " + str(asyncio.Task.current_task(loop_to_stop)) + ")")
                    for task in asyncio.Task.all_tasks(loop_to_stop):
                        LOGGER.debug("natsd.Requester.on_stop - cancelling task " + str(task))
                        task.cancel()
                time.sleep(1)
                if count == 120:
                    LOGGER.error("natsd.Requester.on_stop - unable to stop aio loop after 120 sec (" +
                                 str(asyncio.Task.all_tasks(loop_to_stop).__len__()) + " tasks left; " +
                                 "current task: " + str(asyncio.Task.current_task(loop_to_stop)) + ")")
                    break
            if not loop_to_stop.is_running():
                LOGGER.debug("natsd.Requester.on_stop - close aio loop")
                loop_to_stop.close()
        except Exception as e:
            LOGGER.warn("natsd.Requester.on_stop - exception on aio clean : "
                        + traceback.format_exc())

    def _restart_on_error(self):
        LOGGER.debug("natsd.Requester._restart_on_error - restart begin !")
        stop_thread = threading.Thread(target=self.on_stop, name=self.requestQ + " restarter.stop on error thread")
        stop_thread.start()
        while not self.nc.is_closed:
            LOGGER.debug("natsd.Requester._restart_on_error - waiting nc to be closed")
            time.sleep(1)
        self.on_start()
        self.rpc_retry_timeout_err_count = 0
        LOGGER.debug("natsd.Requester._restart_on_error - restart end !")

    def _restart_after_max_timeout_err_count(self):
        restarter = threading.Thread(target=self._restart_on_error, name=self.requestQ + " restarter on error thread")
        restarter.start()

    def on_failure(self, exception_type, exception_value, traceback_):
        LOGGER.error("natsd.Requester.on_failure - " + exception_type.__str__() + "/" + exception_value.__str__())
        LOGGER.error("natsd.Requester.on_failure - " + traceback_.format_exc())
        self.is_started = False
        try:
            next(self.nc.unsubscribe(self.responseQS))
        except StopIteration as e:
            pass
        try:
            next(self.nc.close())
        except StopIteration as e:
            pass
        try:
            loop_to_stop = self.loop
            for task in asyncio.Task.all_tasks(loop_to_stop):
                task.cancel()
            loop_to_stop.stop()
            while loop_to_stop.is_running():
                time.sleep(1)
            loop_to_stop.close()
        except Exception as e:
            LOGGER.debug("natsd.Requester.on_failure - exception on aio clean : "
                         + traceback.format_exc())

    def on_response(self, msg):
        """
        setup response if correlation id is the good one
        """
        LOGGER.debug("natsd.Requester.on_response: " + str(sys.getsizeof(msg)) + " bytes received")
        working_response = json.loads(msg.data.decode())
        working_properties = DriverTools.json2properties(working_response['properties'])
        working_body = b''+bytes(working_response['body'], 'utf8') if 'body' in working_response else None
        if DriverTools.MSG_CORRELATION_ID in working_properties:
            if self.corr_id == working_properties[DriverTools.MSG_CORRELATION_ID]:
                if DriverTools.MSG_SPLIT_COUNT in working_properties and \
                        int(working_properties[DriverTools.MSG_SPLIT_COUNT]) > 1:
                    working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
                    if self.split_responses is None:
                        self.split_responses = []
                        self.split_responses_mid = working_properties[DriverTools.MSG_SPLIT_MID]
                    if working_properties[DriverTools.MSG_SPLIT_MID] == self.split_responses_mid:
                        response = {
                            'properties': working_properties,
                            'body': working_body_decoded
                        }
                        self.split_responses.insert(int(working_properties[DriverTools.MSG_SPLIT_OID]), response)

                        if self.split_responses.__len__() == int(working_properties[DriverTools.MSG_SPLIT_COUNT]):
                            properties = {}
                            body = b''
                            for num in range(0, self.split_responses.__len__()):
                                properties.update(self.split_responses[num]['properties'])
                                body += self.split_responses[num]['body']
                            self.response = {
                                'properties': properties,
                                'body': body
                            }
                            self.split_responses = None
                            self.split_responses_mid = None

                    else:
                        LOGGER.warn("natsd.Requester.on_response - discarded response : (" +
                                    str(working_properties[DriverTools.MSG_CORRELATION_ID]) + "," +
                                    str(working_properties[DriverTools.MSG_SPLIT_MID]) + ")")
                        LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
                            'properties': working_properties,
                            'body': working_body_decoded
                        }))
                else:
                    working_body_decoded = base64.b64decode(working_body) if working_body is not None else \
                        bytes(json.dumps({}), 'utf8')
                    self.response = {
                        'properties': working_properties,
                        'body': working_body_decoded
                    }
            else:
                working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
                LOGGER.warn("natsd.Requester.on_response - discarded response : " +
                            str(working_properties[DriverTools.MSG_CORRELATION_ID]))
                LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
                    'properties': working_properties,
                    'body': working_body_decoded
                }))
        else:
            working_body_decoded = base64.b64decode(working_body) if working_body is not None else None
            LOGGER.warn("natsd.Requester.on_response - discarded response (no correlation ID)")
            LOGGER.debug("natsd.Requester.on_response - discarded response : " + str({
                'properties': working_properties,
                'body': working_body_decoded
            }))

    def _split_msg(self, split_mid, properties, body):
        messages = []
        in_progress_messages = []
        msg_counter = 0

        in_progress_properties_field = copy.deepcopy(properties)
        if DriverTools.MSG_MESSAGE_ID in in_progress_properties_field:
            in_progress_properties_field.pop(DriverTools.MSG_MESSAGE_ID)
        if DriverTools.MSG_CORRELATION_ID in in_progress_properties_field:
            in_progress_properties_field.pop(DriverTools.MSG_CORRELATION_ID)
        if DriverTools.MSG_TRACE in in_progress_properties_field:
            in_progress_properties_field.pop(DriverTools.MSG_TRACE)
        if DriverTools.MSG_REPLY_TO in in_progress_properties_field:
            in_progress_properties_field.pop(DriverTools.MSG_REPLY_TO)

        wip_body = body
        wip_body_len = sys.getsizeof(wip_body)
        consumed_body_offset = 0

        while (wip_body_len - consumed_body_offset) > 0 or in_progress_properties_field.__len__() > 0:
            # consume properties first :
            splitted_msg_size = 0
            splitted_properties = {}
            if DriverTools.MSG_MESSAGE_ID in properties:
                splitted_properties[DriverTools.MSG_MESSAGE_ID] = properties[DriverTools.MSG_MESSAGE_ID]
            if DriverTools.MSG_CORRELATION_ID in properties:
                splitted_properties[DriverTools.MSG_CORRELATION_ID] = properties[DriverTools.MSG_CORRELATION_ID]
            if DriverTools.MSG_TRACE in properties:
                splitted_properties[DriverTools.MSG_TRACE] = properties[DriverTools.MSG_TRACE]
            if DriverTools.MSG_REPLY_TO in properties:
                splitted_properties[DriverTools.MSG_REPLY_TO] = properties[DriverTools.MSG_REPLY_TO]
            splitted_properties[DriverTools.MSG_SPLIT_MID] = split_mid
            splitted_properties[DriverTools.MSG_SPLIT_COUNT] = sys.maxsize
            splitted_properties[DriverTools.MSG_SPLIT_OID] = msg_counter

            splitted_typed_properties = None
            for key, value in properties.items():
                if key in in_progress_properties_field.keys():
                    splitted_properties[key] = value
                    tmp_splitted_typed_properties = []
                    for skey, svalue in splitted_properties.items():
                        tmp_splitted_typed_properties.append(DriverTools.property_params(skey, svalue))
                    msg_data = json.dumps({
                        'properties': tmp_splitted_typed_properties
                    })
                    msgb = b''+bytes(msg_data, 'utf8')
                    tmp_splitted_msg_size = sys.getsizeof(msgb)
                    if tmp_splitted_msg_size < self.max_payload:
                        splitted_typed_properties = tmp_splitted_typed_properties
                        in_progress_properties_field.pop(key)
                    else:
                        splitted_properties.pop(key)

            msg_data = json.dumps({
                'properties': splitted_typed_properties
            })
            msgb = b''+bytes(msg_data, 'utf8')
            splitted_msg_size = sys.getsizeof(msgb)

            # then body
            splitted_body = None
            if wip_body_len > 0:
                chunk_size = self.max_payload - splitted_msg_size
                if chunk_size > (wip_body_len - consumed_body_offset):
                    chunk_size = wip_body_len - consumed_body_offset
                splitted_body = wip_body[consumed_body_offset:consumed_body_offset+chunk_size]
                msg_data = json.dumps({
                    'properties': splitted_typed_properties,
                    'body': base64.b64encode(b''+bytes(splitted_body, 'utf8')).decode("utf-8")
                })
                msgb = b''+bytes(msg_data, 'utf8')
                tmp_splitted_msg_size = sys.getsizeof(msgb)
                while tmp_splitted_msg_size > self.max_payload:
                    chunk_size -= (tmp_splitted_msg_size - self.max_payload + 1)
                    splitted_body = wip_body[consumed_body_offset:consumed_body_offset+chunk_size]
                    msg_data = json.dumps({
                        'properties': splitted_typed_properties,
                        'body': base64.b64encode(b''+bytes(splitted_body, 'utf8')).decode("utf-8")
                    })
                    msgb = b''+bytes(msg_data, 'utf8')
                    tmp_splitted_msg_size = sys.getsizeof(msgb)
                consumed_body_offset += chunk_size

            # add splitted message into in_progress_messages
            if splitted_body is not None:
                in_progress_messages.append({
                    'properties': splitted_properties,
                    'body': base64.b64encode(b''+bytes(splitted_body, 'utf8')).decode("utf-8")
                })
            else:
                in_progress_messages.append({
                    'properties': splitted_properties,
                    'body': ''
                })
            msg_counter += 1

        for message in in_progress_messages:
            message['properties'][DriverTools.MSG_SPLIT_COUNT] = msg_counter
            typed_properties = []
            for skey, svalue in message['properties'].items():
                typed_properties.append(DriverTools.property_params(skey, svalue))
            if 'body' in message:
                msg_data = json.dumps({
                    'properties': typed_properties,
                    'body': message['body']
                })
            else:
                msg_data = json.dumps({
                    'properties': typed_properties,
                    'body': ''
                })
            msgb = b''+bytes(msg_data, 'utf8')
            messages.append(msgb)

        return messages

    def _init_split_msg_group(self, split_mid, msg_split_dest):
        args = {'properties': {DriverTools.OPERATION_FDN: DriverTools.OP_MSG_SPLIT_FEED_INIT,
                               DriverTools.PARAM_MSG_SPLIT_MID: split_mid,
                               DriverTools.PARAM_MSG_SPLIT_FEED_DEST: msg_split_dest}}
        fire_and_forget_changed = False
        if self.fire_and_forget:
            fire_and_forget_changed = True
            self.fire_and_forget = False
        previous_corr_id = self.corr_id
        self.call(my_args=args)
        self.response = None
        self.corr_id = previous_corr_id
        if fire_and_forget_changed:
            self.fire_and_forget = True

    def _end_split_msg_group(self, split_mid):
        args = {'properties': {DriverTools.OPERATION_FDN: DriverTools.OP_MSG_SPLIT_FEED_END,
                               DriverTools.PARAM_MSG_SPLIT_MID: split_mid}}
        fire_and_forget_changed = False
        if self.fire_and_forget:
            fire_and_forget_changed = True
            self.fire_and_forget = False
        previous_corr_id = self.corr_id
        self.call(my_args=args)
        self.response = None
        self.corr_id = previous_corr_id
        if fire_and_forget_changed:
            self.fire_and_forget = True

    def call(self, my_args=None):
        """
        setup the request and call the remote service. Wait the answer (blocking call)
        :param my_args: dict like {properties, body}
        :return response
        """
        if not self.is_started:
            raise ArianeError('natsd.Requester.call',
                              'Requester not started !')

        LOGGER.debug("natsd.Requester.call")
        if my_args is None:
            raise exceptions.ArianeConfError("requestor call arguments")
        if 'properties' not in my_args or my_args['properties'] is None:
            raise exceptions.ArianeConfError('requestor call properties')
        if 'body' not in my_args or my_args['body'] is None:
            my_args['body'] = ''

        self.response = None

        if not self.fire_and_forget:
            if DriverTools.MSG_CORRELATION_ID not in my_args['properties']:
                self.corr_id = str(uuid.uuid4())
                properties = my_args['properties']
                properties[DriverTools.MSG_CORRELATION_ID] = self.corr_id
            else:
                properties = my_args['properties']
                self.corr_id = properties[DriverTools.MSG_CORRELATION_ID]
        else:
            properties = my_args['properties']

        if 'sessionID' in properties and properties['sessionID'] is not None and properties['sessionID']:
            request_q = str(properties['sessionID']) + '-' + self.requestQ
        else:
            request_q = self.requestQ

        if self.trace:
            properties[DriverTools.MSG_TRACE] = True

        typed_properties = []
        for key, value in properties.items():
            typed_properties.append(DriverTools.property_params(key, value))

        body = my_args['body']
        if body:
            body = base64.b64encode(b''+bytes(body, 'utf8')).decode("utf-8")

        msg_data = json.dumps({
            'properties': typed_properties,
            'body': body
        })
        msgb = b''+bytes(msg_data, 'utf8')

        split_mid = None
        messages = []
        if sys.getsizeof(msgb) > self.max_payload:
            split_mid = str(uuid.uuid4())
            messages = self._split_msg(split_mid, properties, my_args['body'])
        else:
            messages.append(msgb)

        if not self.fire_and_forget:
            if split_mid is not None and ('sessionID' not in properties or properties['sessionID'] is None or
                                          not properties['sessionID']):
                request_q += "_" + split_mid
                self._init_split_msg_group(split_mid, request_q)

            for msgb in messages:
                try:
                    LOGGER.debug("natsd.Requester.call - publish splitted request " + str(typed_properties) +
                                 " (size: " + str(sys.getsizeof(msgb)) + " bytes) on " + request_q)
                    next(self.nc.publish_request(request_q, self.responseQ, msgb))
                except StopIteration as e:
                    pass
                LOGGER.debug("natsd.Requester.call - waiting answer from " + self.responseQ)
        else:
            try:
                LOGGER.debug("natsd.Requester.call - publish request " + str(typed_properties) + " on " + request_q)
                next(self.nc.publish(request_q, b''+bytes(msg_data, 'utf8')))
            except StopIteration as e:
                pass

        try:
            next(self.nc.flush(1))
        except StopIteration as e:
            pass

        start_time = timeit.default_timer()
        if not self.fire_and_forget:
            # Wait rpc_timeout sec before raising error
            if self.rpc_timeout > 0:
                exit_count = self.rpc_timeout * 100
            else:
                exit_count = 1
            while self.response is None and exit_count > 0:
                time.sleep(0.01)
                if self.rpc_timeout > 0:
                    exit_count -= 1

            if self.response is None:
                if self.rpc_retry > 0:
                    if 'retry_count' not in my_args:
                        my_args['retry_count'] = 1
                        LOGGER.debug("natsd.Requester.call - Retry (" + str(my_args['retry_count']) + ")")
                        return self.call(my_args)
                    elif 'retry_count' in my_args and (self.rpc_retry - my_args['retry_count']) > 0:
                        LOGGER.warn("natsd.Requester.call - No response returned from request on " + request_q +
                                    " queue after " + str(self.rpc_timeout) + '*' +
                                    str(self.rpc_retry) + " sec ...")
                        self.trace = True
                        my_args['retry_count'] += 1
                        LOGGER.warn("natsd.Requester.call - Retry (" + str(my_args['retry_count']) + ")")
                        return self.call(my_args)
                    else:
                        self.rpc_retry_timeout_err_count += 1
                        if self.rpc_retry_timeout_err_count >= self.rpc_retry_timeout_err_count_max:
                            self._restart_after_max_timeout_err_count()
                        raise ArianeMessagingTimeoutError('natsd.Requester.call',
                                                          'Request timeout (' + str(self.rpc_timeout) + '*' +
                                                          str(self.rpc_retry) + ' sec) occured')
                else:
                    self.rpc_retry_timeout_err_count += 1
                    if self.rpc_retry_timeout_err_count >= self.rpc_retry_timeout_err_count_max:
                        self._restart_after_max_timeout_err_count()
                    raise ArianeMessagingTimeoutError('natsd.Requester.call',
                                                      'Request timeout (' + str(self.rpc_timeout) + '*' +
                                                      str(self.rpc_retry) + ' sec) occured')

            rpc_time = timeit.default_timer()-start_time
            LOGGER.debug('natsd.Requester.call - RPC time : ' + str(rpc_time))
            if self.rpc_timeout > 0 and rpc_time > self.rpc_timeout*3/5:
                LOGGER.debug('natsd.Requester.call - slow RPC time (' + str(rpc_time) + ') on request ' +
                             str(typed_properties))
            self.trace = False
            self.rpc_retry_timeout_err_count = 0
            rc_ = int(self.response['properties']['RC'])

            if rc_ != 0:
                try:
                    content = json.loads(self.response['body'].decode("UTF-8"))
                except ValueError:
                    content = self.response['body'].decode("UTF-8")
                dr = DriverResponse(
                    rc=rc_,
                    error_message=self.response['properties']['SERVER_ERROR_MESSAGE']
                    if 'SERVER_ERROR_MESSAGE' in self.response['properties'] else '',
                    response_content=content
                )
            else:
                try:
                    if DriverTools.MSG_PROPERTIES in self.response['properties']:
                        props = json.loads(self.response['properties'][DriverTools.MSG_PROPERTIES])
                    else:
                        props = None
                except ValueError:
                    if DriverTools.MSG_PROPERTIES in self.response['properties']:
                        props = self.response['props'][DriverTools.MSG_PROPERTIES]
                    else:
                        props = None
                try:
                    content = json.loads(self.response['body'].decode("UTF-8"))
                except ValueError:
                    content = self.response['body'].decode("UTF-8")
                dr = DriverResponse(
                    rc=rc_,
                    response_properties=props,
                    response_content=content
                )

            if split_mid is not None and ('sessionID' not in properties or properties['sessionID'] is None or
                                              not properties['sessionID']):
                self._end_split_msg_group(split_mid)
                request_q = request_q.split("_" + split_mid)[0]

            return dr
class Service(pykka.ThreadingActor):
    """
    NATS service implementation.
    :param my_args: dict like {connection, service_q, treatment_callback[, service_name]}
    :param connection_args: dict like {user, password, host[, port, client_properties]}
    """

    def __init__(self, my_args=None, connection_args=None):
        """
        NATS service constructor
        :param my_args: dict like {connection, service_q, treatment_callback[, service_name]}
        :param connection_args: dict like {user, password, host[, port, client_properties]}
        :return: self
        """
        LOGGER.debug("natsd.Service.__init__")
        if my_args is None or connection_args is None:
            raise exceptions.ArianeConfError("service arguments")
        if 'service_q' not in my_args or my_args['service_q'] is None or not my_args['service_q']:
            raise exceptions.ArianeConfError("service_q")
        if 'treatment_callback' not in my_args or my_args['treatment_callback'] is None:
            raise exceptions.ArianeConfError("treatment_callback")
        if 'service_name' not in my_args or my_args['service_name'] is None or not my_args['service_name']:
            LOGGER.warn("natsd.Service.__init__ - service_name is not defined ! Use default : " +
                        self.__class__.__name__)
            my_args['service_name'] = self.__class__.__name__

        Driver.validate_driver_conf(connection_args)

        super(Service, self).__init__()
        self.connection_args = copy.deepcopy(connection_args)
        self.servers = [
            "nats://" + connection_args['user'] + ":" + connection_args['password'] + "@" +
            connection_args['host']+":"+str(connection_args['port'])
        ]
        self.name = self.connection_args['client_properties']['ariane.app'] + "@" + socket.gethostname() + \
            " - service on " + my_args['service_q']
        self.loop = None
        self.options = None
        self.nc = Client()
        self.serviceQ = my_args['service_q']
        self.serviceQS = None
        self.service_name = my_args['service_name']
        self.service = None
        self.cb = my_args['treatment_callback']
        self.is_started = False

    def on_request(self, msg):
        """
        message consumed treatment through provided callback and basic ack
        """
        LOGGER.debug("natsd.Service.on_request - request " + str(msg) + " received")
        try:
            working_response = json.loads(msg.data.decode())
            working_properties = DriverTools.json2properties(working_response['properties'])
            working_body = b''+bytes(working_response['body'], 'utf8') if 'body' in working_response else None
            working_body_decoded = base64.b64decode(working_body) if working_body is not None else \
                bytes(json.dumps({}), 'utf8')
            self.cb(working_properties, working_body_decoded)
        except Exception as e:
            LOGGER.warn("natsd.Service.on_request - Exception raised while treating msg {"+str(msg)+","+str(msg)+"}")
        LOGGER.debug("natsd.Service.on_request - request " + str(msg) + " treated")

    def connect(self):
        LOGGER.debug("natsd.Service.connect")
        try:
            yield from self.nc.connect(**self.options)
            self.serviceQS = yield from self.nc.subscribe(self.serviceQ, cb=self.on_request)
            self.is_started = True
        except ErrNoServers as e:
            print(e)
            return

    def run_event_loop(self):
        LOGGER.debug("natsd.Service.run_event_loop")
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        self.options = {
            "servers": self.servers,
            "name": self.name,
            # "disconnected_cb": self.disconnected_cb,
            # "reconnected_cb": self.reconnected_cb,
            # "error_cb": self.error_cb,
            # "closed_cb": self.closed_cb,
            "io_loop": self.loop,
        }
        self.loop.create_task(self.connect())
        self.loop.run_forever()

    def on_start(self):
        """
        start the service
        """
        LOGGER.debug("natsd.Service.on_start")
        self.service = threading.Thread(target=self.run_event_loop, name=self.serviceQ + " service thread")
        self.service.start()
        while not self.is_started:
            time.sleep(0.01)

    def on_stop(self):
        """
        stop the service
        """
        LOGGER.debug("natsd.Service.on_stop")
        self.is_started = False
        try:
            next(self.nc.unsubscribe(self.serviceQS))
        except StopIteration as e:
            pass
        try:
            next(self.nc.close())
        except StopIteration as e:
            pass
        try:
            for task in asyncio.Task.all_tasks(self.loop):
                task.cancel()
            self.loop.stop()
            while self.loop.is_running():
                time.sleep(1)
            self.loop.close()
        except Exception as e:
            LOGGER.debug("natsd.Service.on_stop - Exception aio clean up : "
                         + traceback.format_exc())

    def on_failure(self, exception_type, exception_value, traceback_):
        LOGGER.error("natsd.Requester.on_failure - " + exception_type.__str__() + "/" + exception_value.__str__())
        LOGGER.error("natsd.Requester.on_failure - " + traceback_.format_exc())
        self.is_started = False
        try:
            next(self.nc.unsubscribe(self.serviceQS))
        except StopIteration as e:
            pass
        try:
            next(self.nc.close())
        except StopIteration as e:
            pass
        try:
            for task in asyncio.Task.all_tasks(self.loop):
                task.cancel()
            self.loop.stop()
            while self.loop.is_running():
                time.sleep(1)
            self.loop.close()
        except Exception as e:
            LOGGER.debug("natsd.Service.on_failure - Exception aio clean up : "
                         + traceback.format_exc())