Esempio n. 1
0
def main():
    nc = NATS()

    # Establish connection to the server.
    yield nc.connect(servers=["nats://127.0.0.1:4222"])

    def discover(msg=None):
        print("[Received]: %s" % msg.data)

    sid = yield nc.subscribe("discover", "", discover)

    # Only interested in 2 messages.
    yield nc.auto_unsubscribe(sid, 2)
    yield nc.publish("discover", "A")
    yield nc.publish("discover", "B")

    # Following two messages won't be received.
    yield nc.publish("discover", "C")
    yield nc.publish("discover", "D")

    # Request/Response
    def help_request_handler(msg):
        print("[Received]: %s" % msg.data)
        nc.publish(msg.reply, "OK, I can help!")

    # Susbcription using distributed queue
    yield nc.subscribe("help", "workers", help_request_handler)

    try:
        # Expect a single request and timeout after 500 ms
        response = yield nc.request("help", "Hi, need help!", timeout=0.500)
        print("[Response]: %s" % response.data)
    except tornado.gen.TimeoutError, e:
        print("Timeout! Need to retry...")
Esempio n. 2
0
def main():
    nc = NATS()

    # Establish connection to the server.
    options = { "verbose": True, "servers": ["nats://127.0.0.1:4222"] }
    yield nc.connect(**options)

    def discover(msg=None):
        print("[Received]: %s" % msg.data)

    sid = yield nc.subscribe("discover", "", discover)

    # Only interested in 2 messages.
    yield nc.auto_unsubscribe(sid, 2)
    yield nc.publish("discover", "A")
    yield nc.publish("discover", "B")

    # Following two messages won't be received.
    yield nc.publish("discover", "C")
    yield nc.publish("discover", "D")

    # Request/Response
    def help_request_handler(msg):
        print("[Received]: %s" % msg.data)
        nc.publish(msg.reply, "OK, I can help!")

    # Susbcription using distributed queue
    yield nc.subscribe("help", "workers", help_request_handler)

    try:
        # Expect a single request and timeout after 500 ms
        response = yield nc.timed_request("help", "Hi, need help!", 500)
        print("[Response]: %s" % response.data)
    except tornado.gen.TimeoutError, e:
        print("Timeout! Need to retry...")
Esempio n. 3
0
     def test_close_connection(self):
          nc = Client()
          options = {
               "dont_randomize": True,
               "servers": [
                    "nats://*****:*****@127.0.0.1:4223",
                    "nats://*****:*****@127.0.0.1:4224"
                    ],
               "io_loop": self.io_loop
               }
          yield nc.connect(**options)
          self.assertEqual(True, nc._server_info["auth_required"])

          log = Log()
          sid_1 = yield nc.subscribe("foo",  "", log.persist)
          self.assertEqual(sid_1, 1)
          sid_2 = yield nc.subscribe("bar",  "", log.persist)
          self.assertEqual(sid_2, 2)
          sid_3 = yield nc.subscribe("quux", "", log.persist)
          self.assertEqual(sid_3, 3)
          yield nc.publish("foo", "hello")
          yield tornado.gen.sleep(1.0)

          # Done
          yield nc.close()

          orig_gnatsd = self.server_pool.pop(0)
          orig_gnatsd.finish()

          try:
               a = nc._current_server
               # Wait and assert that we don't reconnect.
               yield tornado.gen.sleep(3)
          finally:
               b = nc._current_server
               self.assertEqual(a.uri, b.uri)

          self.assertFalse(nc.is_connected())
          self.assertFalse(nc.is_reconnecting())
          self.assertTrue(nc.is_closed())

          with(self.assertRaises(ErrConnectionClosed)):
               yield nc.publish("hello", "world")

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

          with(self.assertRaises(ErrConnectionClosed)):
               yield nc.subscribe("hello", "worker")

          with(self.assertRaises(ErrConnectionClosed)):
               yield nc.publish_request("hello", "inbox", "world")

          with(self.assertRaises(ErrConnectionClosed)):
               yield nc.request("hello", "world")

          with(self.assertRaises(ErrConnectionClosed)):
               yield nc.timed_request("hello", "world")
Esempio n. 4
0
def main():
    nc = NATS()

    # Establish connection to the server.
    options = { "verbose": True, "servers": ["nats://127.0.0.1:4222"] }
    yield nc.connect(**options)

    def discover(msg=None):
        print("[Received]: %s" % msg.data)

    sid = yield nc.subscribe("discover", "", discover)

    # Only interested in 2 messages.
    yield nc.auto_unsubscribe(sid, 2)
    yield nc.publish("discover", "A")
    yield nc.publish("discover", "B")

    # Following two messages won't be received.
    yield nc.publish("discover", "C")
    yield nc.publish("discover", "D")

    # Request/Response
    def help_request_handler(msg):
        print("[Received]: %s" % msg.data)
        nc.publish(msg.reply.decode(), "OK, I can help!")

    # Susbcription using distributed queue
    yield nc.subscribe("help", "workers", help_request_handler)

    try:
        # Expect a single request and timeout after 500 ms
        response = yield nc.timed_request("help", "Hi, need help!", 500)
        print("[Response]: %s" % response.data)
    except tornado.gen.TimeoutError as e:
        print("Timeout! Need to retry...")

    # Customize number of responses to receive
    def many_responses(msg=None):
        print("[Response]: %s" % msg.data)

    yield nc.request("help", "please", expected=2, cb=many_responses)

    # Publish inbox
    my_inbox = new_inbox()
    yield nc.subscribe(my_inbox)
    yield nc.publish_request("help", my_inbox, "I can help too!")

    loop = tornado.ioloop.IOLoop.instance()
    yield tornado.gen.Task(loop.add_timeout, time.time() + 1)
    try:
        start = datetime.now()
        # Make roundtrip to the server and timeout after 1000 ms
        yield nc.flush(1000)
        end = datetime.now()
        print("Latency: %d µs" % (end.microsecond - start.microsecond))
    except tornado.gen.TimeoutError as e:
        print("Timeout! Roundtrip too slow...")
Esempio n. 5
0
def go(loop):
    nc = NATS()

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

    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")

    def request_handler(msg):
        print("[Request on '{} {}']: {}".format(msg.subject, msg.reply, msg.data.decode()))

    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", request_handler)

        try:
            # Make a request expecting a single response within 500 ms,
            # otherwise raising a timeout error.
            response = 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.")
Esempio n. 6
0
def main():
    nc = NATS()

    options = {
        "servers": ["nats://192.168.0.114:4222"],
        "user": "******",
        "password": "******",
        "tcp_nodelay": True
    }

    # Establish connection to the server.
    yield nc.connect(**options)

    @tornado.gen.coroutine
    def message_handler(msg):
        subject = msg.subject
        data = msg.data
        cmd = msgpack.unpackb(data)
        print("[Received on '{}'] : {}".format(subject, cmd))

        print(cmd["gear"])

    # Simple async subscriber
    sid = yield nc.subscribe("cmd", cb=message_handler)

    yield nc.publish("cmd", "test")
Esempio n. 7
0
def main():
    # Parse the command line arguments
    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="")

    # Parse!
    args = parser.parse_args()

    # Create client and connect to server
    nc = NATS()
    servers = args.servers
    if len(args.servers) < 1:
      servers = ["nats://127.0.0.1:4222"]

    opts = { "servers": servers }
    yield nc.connect(**opts)

    def handler(msg):
        print("[Received: {0}] {1}".format(msg.subject, msg.data))

    print("Subscribed to '{0}'".format(args.subject))
    future = nc.subscribe(args.subject, args.queue, handler)
    sid = future.result()
Esempio n. 8
0
     def test_publish(self):
          nc = Client()
          yield nc.connect(io_loop=self.io_loop)
          self.assertEqual(Client.CONNECTED, nc._status)
          info_keys = nc._server_info.keys()
          self.assertTrue(len(info_keys) > 0)

          log = Log()
          yield nc.subscribe(">", "", log.persist)
          yield nc.publish("one", "hello")
          yield nc.publish("two", "world")
          yield tornado.gen.sleep(1.0)

          http = tornado.httpclient.AsyncHTTPClient()
          response = yield http.fetch('http://127.0.0.1:%d/varz' % self.server_pool[0].http_port)
          varz = json.loads(response.body.decode("utf-8"))
          self.assertEqual(10, varz['in_bytes'])
          self.assertEqual(10, varz['out_bytes'])
          self.assertEqual(2, varz['in_msgs'])
          self.assertEqual(2, varz['out_msgs'])
          self.assertEqual(2, len(log.records.keys()))
          self.assertEqual("hello", log.records[b'one'][0].data.decode())
          self.assertEqual("world", log.records[b'two'][0].data.decode())
          self.assertEqual(10, nc.stats['in_bytes'])
          self.assertEqual(10, nc.stats['out_bytes'])
          self.assertEqual(2, nc.stats['in_msgs'])
          self.assertEqual(2, nc.stats['out_msgs'])
Esempio n. 9
0
def main():
    # Parse the command line arguments
    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="")

    # Parse!
    args = parser.parse_args()

    # Create client and connect to server
    nc = NATS()
    servers = args.servers
    if len(args.servers) < 1:
      servers = ["nats://127.0.0.1:4222"]

    opts = { "servers": servers }
    yield nc.connect(**opts)

    def handler(msg):
        logger.debug("[Received: {%s}] {%s}", msg.subject, str(msg.data))

    logger.debug("Subscribed to '{%s}'", args.subject)
    future = nc.subscribe(args.subject, args.queue, handler)
    sid = future.result()
Esempio n. 10
0
def main():
    nc = NATS()

    # Establish secure connection to the server, tls options parameterize
    # the wrap_socket available from ssl python package.
    options = {
        "verbose": True,
        "servers": ["nats://127.0.0.1:4444"],
        "tls": {
            "cert_reqs": ssl.CERT_REQUIRED,
            "ca_certs": "./tests/configs/certs/ca.pem",
            "keyfile": "./tests/configs/certs/client-key.pem",
            "certfile": "./tests/configs/certs/client-cert.pem"
        }
    }
    yield nc.connect(**options)

    def discover(msg=None):
        print("[Received]: %s" % msg.data)

    sid = yield nc.subscribe("discover", "", discover)

    # Only interested in 2 messages.
    yield nc.auto_unsubscribe(sid, 2)
    yield nc.publish("discover", "A")
    yield nc.publish("discover", "B")

    # Following two messages won't be received.
    yield nc.publish("discover", "C")
    yield nc.publish("discover", "D")

    # Request/Response
    def help_request_handler(msg):
        print("[Received]: %s" % msg.data)
        nc.publish(msg.reply, "OK, I can help!")

    # Susbcription using distributed queue
    yield nc.subscribe("help", "workers", help_request_handler)

    try:
        # Expect a single request and timeout after 500 ms
        response = yield nc.timed_request("help",
                                          "Hi, need help!",
                                          timeout=0.500)
        print("[Response]: %s" % response.data)
    except tornado.gen.TimeoutError, e:
        print("Timeout! Need to retry...")
Esempio n. 11
0
     def test_request(self):
          nc = Client()
          yield nc.connect(io_loop=self.io_loop)

          class Component:
               def __init__(self, nc):
                    self.nc = nc
                    self.replies = []

               def receive_responses(self, msg=None):
                    self.replies.append(msg)

               @tornado.gen.coroutine
               def respond(self, msg=None):
                    yield self.nc.publish(msg.reply.decode(), "ok:1")
                    yield self.nc.publish(msg.reply.decode(), "ok:2")
                    yield self.nc.publish(msg.reply.decode(), "ok:3")

          log = Log()
          c = Component(nc)
          yield nc.subscribe(">", "", log.persist)
          yield nc.subscribe("help", "", c.respond)
          yield nc.request("help", "please", expected=2, cb=c.receive_responses)
          yield tornado.gen.sleep(0.5)

          http = tornado.httpclient.AsyncHTTPClient()
          response = yield http.fetch('http://127.0.0.1:%d/varz' % self.server_pool[0].http_port)
          varz = json.loads(response.body.decode("utf-8"))
          self.assertEqual(18, varz['in_bytes'])
          self.assertEqual(32, varz['out_bytes'])
          self.assertEqual(4, varz['in_msgs'])
          self.assertEqual(7, varz['out_msgs'])
          self.assertEqual(2, len(log.records.keys()))
          self.assertEqual("please", log.records[b'help'][0].data.decode())
          self.assertEqual(2, len(c.replies))
          self.assertEqual(32, nc.stats['in_bytes'])
          self.assertEqual(18, nc.stats['out_bytes'])
          self.assertEqual(7, nc.stats['in_msgs'])
          self.assertEqual(4, nc.stats['out_msgs'])

          full_msg = ''
          for msg in log.records[b'help']:
               full_msg += msg.data.decode("utf-8")

          self.assertEqual('please', full_msg)
          self.assertEqual("ok:1", c.replies[0].data.decode())
          self.assertEqual("ok:2", c.replies[1].data.decode())
Esempio n. 12
0
def main():
    nc = NATS()

    # Establish secure connection to the server, tls options parameterize
    # the wrap_socket available from ssl python package.
    options = {
        "verbose": True,
        "servers": ["nats://127.0.0.1:4444"],
        "tls": {
            "cert_reqs": ssl.CERT_REQUIRED,
            "ca_certs": "./tests/configs/certs/ca.pem",
            "keyfile": "./tests/configs/certs/client-key.pem",
            "certfile": "./tests/configs/certs/client-cert.pem"
        }
    }
    yield nc.connect(**options)

    def discover(msg=None):
        print("[Received]: %s" % msg.data)

    sid = yield nc.subscribe("discover", "", discover)

    # Only interested in 2 messages.
    yield nc.auto_unsubscribe(sid, 2)
    yield nc.publish("discover", "A")
    yield nc.publish("discover", "B")

    # Following two messages won't be received.
    yield nc.publish("discover", "C")
    yield nc.publish("discover", "D")

    # Request/Response
    def help_request_handler(msg):
        print("[Received]: %s" % msg.data)
        nc.publish(msg.reply, "OK, I can help!")

    # Susbcription using distributed queue
    yield nc.subscribe("help", "workers", help_request_handler)

    try:
        # Expect a single request and timeout after 500 ms
        response = yield nc.timed_request(
            "help", "Hi, need help!", timeout=0.500)
        print("[Response]: %s" % response.data)
    except tornado.gen.TimeoutError, e:
        print("Timeout! Need to retry...")
Esempio n. 13
0
def main():
    nc = NATS()

    # Set pool servers in the cluster and give a name to the client
    # each with its own auth credentials.
    options = {
        "servers": [
            "nats://*****:*****@127.0.0.1:4222",
            "nats://*****:*****@127.0.0.1:4223",
            "nats://*****:*****@127.0.0.1:4224"
            ]
        }

    # Error callback takes the error type as param.
    def error_cb(e):
        print("Error! ", e)

    def close_cb():
        print("Connection was closed!")

    def disconnected_cb():
        print("Disconnected!")

    def reconnected_cb():
        print("Reconnected!")

    # Set callback to be dispatched whenever we get
    # protocol error message from the server.
    options["error_cb"] = error_cb

    # Called when we are not connected anymore to the NATS cluster.    
    options["close_cb"] = close_cb

    # Called whenever we become disconnected from a NATS server.
    options["disconnected_cb"] = disconnected_cb

    # Called when we connect to a node in the NATS cluster again.
    options["reconnected_cb"] = reconnected_cb

    yield nc.connect(**options)

    @tornado.gen.coroutine
    def subscriber(msg):
        yield nc.publish("pong", "pong:{0}".format(msg.data))

    yield nc.subscribe("ping", "", subscriber)

    for i in range(0, 100):
        yield nc.publish("ping", "ping:{0}".format(i))
        yield tornado.gen.sleep(0.1)

    yield nc.close()

    try:
        yield nc.publish("ping", "ping")
    except ErrConnectionClosed:
        print("No longer connected to NATS cluster.")
Esempio n. 14
0
class MyNATSClass:
    def __init__(self, t_name, queue, mqtt):
        self._queue = queue
        logger.debug("I am NATS")
        try:
            tmp = os.environ["NATSSERVERURI"]
            logger.debug("nats server uri = %s", tmp)
            self._servers_uri = []
            self._servers_uri.append(tmp)
        except:
            logger.debug("Can not get enviro NATSSERVERURI")
            sys.exit(0)

        self._nats = NATS()
        self._mqtt = mqtt

    @tornado.gen.coroutine
    def _nats_main(self):
        opts = {"servers": self._servers_uri}

        yield self._nats.connect(**opts)
        logger.debug("subscribe ericssion.iot.nats.c3shadow")
        yield self._nats.subscribe("ericssion.iot.nats.c3shadow", "", self._subscribe)

        while gEnd == False:
            sent = self._nats.stats["out_msgs"]
            received = self._nats.stats["in_msgs"]
            yield tornado.gen.sleep(2)
            try:
                tmp = self._queue.get(False)
            except Queue.Empty:
                #                logger.debug("send msg = %d, in_msgs = %d, queue is empty", sent, received)
                continue
            yield self._nats.publish("ericssion.iot.nats.c3engine", tmp)
            yield self._nats.flush()
            logger.debug("nats publish message = %s", tmp)
        logger.debug("I died")

    def _subscribe(self, msg):
        #        logger.debug("get msg subject = %s, data = %s", msg.subject, str(msg.data))
        try:
            tmp = str(msg.data).replace("'", '"')
            mydict = json.loads(tmp)
        except:
            logger.debug("message format is not correct, subject = %s, data = %s", msg.subject, str(msg.data))
            return

        print "NATS:: received %s" % (str(mydict))
        if mydict.has_key("data"):
            print "hello********************"
            # need MQTT publish
            self._mqtt.mqtt_publish(mydict)
        else:
            self._mqtt.mqtt_subscribe(mydict)

    def run(self):
        tornado.ioloop.IOLoop.instance().run_sync(self._nats_main)
Esempio n. 15
0
def main():
    nc = NATS()

    # Set pool servers in the cluster and give a name to the client
    # each with its own auth credentials.
    options = {
        "servers": [
            "nats://*****:*****@127.0.0.1:4222",
            "nats://*****:*****@127.0.0.1:4223",
            "nats://*****:*****@127.0.0.1:4224"
        ]
    }

    # Error callback takes the error type as param.
    def error_cb(e):
        print("Error! ", e)

    def close_cb():
        print("Connection was closed!")

    def disconnected_cb():
        print("Disconnected!")

    def reconnected_cb():
        print("Reconnected!")

    # Set callback to be dispatched whenever we get
    # protocol error message from the server.
    options["error_cb"] = error_cb

    # Called when we are not connected anymore to the NATS cluster.
    options["closed_cb"] = close_cb

    # Called whenever we become disconnected from a NATS server.
    options["disconnected_cb"] = disconnected_cb

    # Called when we connect to a node in the NATS cluster again.
    options["reconnected_cb"] = reconnected_cb

    yield nc.connect(**options)

    @tornado.gen.coroutine
    def subscriber(msg):
        yield nc.publish("pong", "pong:{0}".format(msg.data))

    yield nc.subscribe("ping", "", subscriber)

    for i in range(0, 100):
        yield nc.publish("ping", "ping:{0}".format(i))
        yield tornado.gen.sleep(0.1)

    yield nc.close()

    try:
        yield nc.publish("ping", "ping")
    except ErrConnectionClosed:
        print("No longer connected to NATS cluster.")
Esempio n. 16
0
def main():
    nc = NATS()

    # Establish connection to the server.
    yield nc.connect("nats://demo.nats.io:4222")

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

    # Simple async subscriber
    sid = yield nc.subscribe("foo", cb=message_handler)

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

    # Request/Response
    @tornado.gen.coroutine
    def help_request_handler(msg):
        print("[Received on '{}']: {}".format(msg.subject, msg.data))
        yield nc.publish(msg.reply, "OK, I can help!")

    # Susbcription using distributed queue named 'workers'
    sid = yield nc.subscribe("help", "workers", help_request_handler)

    try:
        # Send a request and expect a single response
        # and trigger timeout if not faster than 200 ms.
        msg = yield nc.request("help", b"Hi, need help!", timeout=0.2)
        print("[Response]: %s" % msg.data)
    except tornado.gen.TimeoutError:
        print("Response Timeout!")

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

    # Terminate connection to NATS.
    yield nc.close()
Esempio n. 17
0
def subscribe():
    received_message_list = []

    # Parse the command line arguments
    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("-o", "--original", default="hello", nargs="?")
    parser.add_argument("-m", "--maxmsg", default=10000, type=int)
    parser.add_argument("-d", "--dirname")

    # Parse!
    args = parser.parse_args()

    file_time = time.strftime("%d-%m-%Y-%H-%M-%S")
    filename = "nats-run_" +\
               args.subject + "-" + args.original + "_" +\
               file_time + ".txt"  #Filename of message data for the user_id
    completed_user_list = []                 # List of subscribed users who have finished publishing

    # Create client and connect to server
    nc = NATS()
    servers = ["nats://146.148.76.9:4222"]
    #servers = ["nats://127.0.0.1:4222"]
    opts = { "servers": servers }
    yield nc.connect(**opts)

    def handler(msg):
        #print("[Received: {0}] {1}".format(msg.subject, msg.data))

        sub_time = get_time()
        received_message_str = str(msg.data)
        split_message = received_message_str.split(" ")
        message_number = int(split_message[2])
        final_message = split_message[0] + " " +\
                        split_message[1] + " " +\
                        args.original + " " +\
                        sub_time
        received_message_list.append(final_message)

        if message_number == args.maxmsg:
            fd = open(args.dirname + "/" + filename, "a")
            for i in received_message_list:
                print >> fd, i
            fd.close
            del received_message_list[:]
                    
            tornado.ioloop.IOLoop.instance().stop()

    print("Subscribed to '{0}'".format(args.subject))
    future = nc.subscribe(args.subject, "", handler)
    sid = future.result()
Esempio n. 18
0
class MyNATSClass():
    def __init__(self, queue):
        logger.debug("I am NATS")
        self._queue = queue
        self._nats = NATS()
        try:
            tmp = os.environ["NATSSERVERURI"]
            logger.debug("nats server uri = %s", tmp)
            self._servers_uri = []
            self._servers_uri.append(tmp)
        except:
            logger.debug("Can not get enviro NATSSERVERURI")
            sys.exit(0)

    @tornado.gen.coroutine
    def nats_main(self):
        # Create client and connect to server

        opts = { "servers": self._servers_uri }
        yield self._nats.connect(**opts)

        def handler(msg):
            logger.debug("NATS:: [Received: {%s}] {%s}",msg.subject, str(msg.data))
            tmp = str(msg.data).replace("'","\"")
            try:
                my_dict = json.loads(tmp)
            except:
                logger.debug("can not translate data to JSON format, ignore this message, %s", str(msg.data))
                return
            f_set = set(["topic", "clientid", "data", "account"])
            n_set = set(my_dict.keys())
            if f_set == n_set:
                self._queue.put(my_dict)
            else:
                logger.debug("topic payload is not correct format, ignore it %s", str(n_set))

        logger.debug("Subscribed to '%s'", "ericssion.iot.nats.c3engine")
        future = self._nats.subscribe("ericssion.iot.nats.c3engine", "", handler)
        sid = future.result()

    def nats_publish(self, payload):
        logger.debug("NATS::  publish message payload = %s", payload)
        self._nats.publish("ericssion.iot.nats.c3shadow", payload)

    def run(self):
        tornado.ioloop.IOLoop.instance().start()
def main():
    nc = NATS()
    yield nc.connect("nats://127.0.0.1:4222")
    exitCondition = None

    @tornado.gen.coroutine
    def help_request_handler(msg):
        subject = msg.subject
        data = msg.data
        print("[Received on '{}'] : {}".format(subject, data.decode()))
        yield nc.publish(msg.reply, b'OK, I will help!')

    try:
        yield nc.subscribe('agent_aws_1', "workers", help_request_handler)
    except Exception as e:
        print("!!! Exception : {}".format(e))
        exitCondition = True
    while not exitCondition:
        yield tornado.gen.sleep(60)
Esempio n. 20
0
     def test_subscribe(self):
          nc = Client()
          options = {
               "io_loop": self.io_loop
               }
          yield nc.connect(**options)
          self.assertEqual(Client.CONNECTED, nc._status)
          info_keys = nc._server_info.keys()
          self.assertTrue(len(info_keys) > 0)

          inbox = new_inbox()
          yield nc.subscribe("help.1")
          yield nc.subscribe("help.2")
          yield tornado.gen.sleep(0.5)

          http = tornado.httpclient.AsyncHTTPClient()
          response = yield http.fetch('http://127.0.0.1:%d/connz' % self.server_pool[0].http_port)
          result = json.loads(response.body.decode("utf-8"))
          connz = result['connections'][0]
          self.assertEqual(2, connz['subscriptions'])
Esempio n. 21
0
     def test_auth_connect(self):
          nc = Client()
          options = {
               "dont_randomize": True,
               "servers": [
                    "nats://*****:*****@127.0.0.1:4223",
                    "nats://*****:*****@127.0.0.1:4224"
                    ],
               "io_loop": self.io_loop
               }
          yield nc.connect(**options)
          self.assertEqual(True, nc._server_info["auth_required"])

          log = Log()
          sid_1 = yield nc.subscribe("foo",  "", log.persist)
          self.assertEqual(sid_1, 1)
          sid_2 = yield nc.subscribe("bar",  "", log.persist)
          self.assertEqual(sid_2, 2)
          sid_3 = yield nc.subscribe("quux", "", log.persist)
          self.assertEqual(sid_3, 3)
          yield nc.publish("foo", "hello")
          yield tornado.gen.sleep(1.0)

          http = tornado.httpclient.AsyncHTTPClient()
          response = yield http.fetch('http://127.0.0.1:8223/connz')
          result = json.loads(response.body.decode("utf-8"))
          connz = result['connections'][0]
          self.assertEqual(3, connz['subscriptions'])
          self.assertEqual(1, connz['in_msgs'])
          self.assertEqual(5, connz['in_bytes'])

          yield nc.publish("foo", "world")
          yield tornado.gen.sleep(0.5)
          response = yield http.fetch('http://127.0.0.1:8223/connz')
          result = json.loads(response.body.decode("utf-8"))
          connz = result['connections'][0]
          self.assertEqual(3, connz['subscriptions'])
          self.assertEqual(2, connz['in_msgs'])
          self.assertEqual(10, connz['in_bytes'])

          orig_gnatsd = self.server_pool.pop(0)
          orig_gnatsd.finish()

          try:
               a = nc._current_server
               # Wait for reconnect logic kick in...
               yield tornado.gen.sleep(5)
          finally:
               b = nc._current_server
               self.assertNotEqual(a.uri, b.uri)

          self.assertTrue(nc.is_connected())
          self.assertFalse(nc.is_reconnecting())

          http = tornado.httpclient.AsyncHTTPClient()
          response = yield http.fetch('http://127.0.0.1:8224/connz')
          result = json.loads(response.body.decode("utf-8"))
          connz = result['connections'][0]
          self.assertEqual(3, connz['subscriptions'])
          self.assertEqual(0, connz['in_msgs'])
          self.assertEqual(0, connz['in_bytes'])

          yield nc.publish("foo", "!!!")
          yield tornado.gen.sleep(0.5)
          response = yield http.fetch('http://127.0.0.1:8224/connz')
          result = json.loads(response.body.decode("utf-8"))
          connz = result['connections'][0]
          self.assertEqual(3, connz['subscriptions'])
          self.assertEqual(1, connz['in_msgs'])
          self.assertEqual(3, connz['in_bytes'])

          full_msg = ''
          for msg in log.records[b'foo']:
               full_msg += msg.data.decode("utf-8")

          self.assertEqual('helloworld!!!', full_msg)