Ejemplo n.º 1
0
    def Unsubscribe(self, subscriptionType=None):
        """
        This method takes the topic as argument and unsubscribes to the given topic.
        If topic name is not given as argument (no arguments), this method
        unsubscribes to all the topics which app already subscribed for.

        @param subscriptionType: Notification type that user wants to unsubscribe from.
        @return 0 on successful unsubscription and -1 on failure

        """
        if subscriptionType is None:
            self.mqtt_client.unsubscribe(self.topics_subscribed)
            self.handlers = collections.defaultdict(set)
            LOG.info('Successfully unsubscribed from all notifications')
            return 0
        elif not isinstance(subscriptionType, type):
            message = 'Invalid subscription topic: ' + subscriptionType
            LOG.info(message)
            raise Exception(message)

        else:
            for item in self.topics_subscribed:
                if (item == subscriptionType.topic and subscriptionType.subscribed == 1):
                    self.mqtt_client.unsubscribe(subscriptionType.topic)
                    self.mqtt_client.unsubscribe(subscriptionType.topic)
                    self.handlers.pop(str(subscriptionType.topic), None)
                    LOG.info('Successfully unsubscribed %s' %
                             subscriptionType.topic)
                    return 0

            # Failed case
            LOG.error('You have not subscribed to %s. Failed to unsubscribe' %
                      subscriptionType.topic)
            return -1
Ejemplo n.º 2
0
    def __init__(self,
                 device=DEFAULT_USER_NAME,
                 port=DEFAULT_NOTIFICATION_PORT,
                 user=None,
                 password=None,
                 tls=None,
                 keepalive=DEFAULT_MQTT_TIMEOUT,
                 bind_address="",
                 is_stream=False):
        """
        Create a request response session with the  JET server. Raises exception in case
        of invalid arguments or when JET notification server is not accessible.

        @param device: JET Server IP address. Default is localhost
        @param port: JET Notification port number. Default is 1883
        @param user: Username on the JET server, used for authentication and authorization.
        @param password: Password to access the JET server, used for authentication and authorization.
        @param keepalive: Maximum period in seconds between communications with the broker. Default is 60.
        @param bind_address: Client source address to bind. Can be used to control access at broker side.

        @return: JET Notification object.
        """

        try:
            self.notifier = NotifierMqtt()
            LOG.info('Connecting to JET notification server')
            self.notifier.mqtt_client.connect(device, port, keepalive,
                                              bind_address)
            self.notifier.mqtt_client.loop_start()
            self.notifier.handlers = collections.defaultdict(set)
            if is_stream == True:
                self.notifier.mqtt_client.on_message = self.notifier.on_stream_message_cb
            else:
                self.notifier.mqtt_client.on_message = self.notifier.on_message_cb

        except struct.error as err:
            message = err.message
            err.message = 'Invalid argument value passed in %s at line no. %s\nError: %s' \
                          % (traceback.extract_stack()[0][0], traceback.extract_stack()[0][1], message)
            LOG.error('%s' % (err.message))
            raise err
        except Exception, tx:
            tx.message = 'Could not connect to the JET notification server'
            LOG.error('%s' % (tx.message))
            raise Exception(tx.message)
Ejemplo n.º 3
0
def Main():
    parser = argparse.ArgumentParser(
        prog=os.path.basename(__file__),
        description='Snabb VMX integration JET app')
    parser.add_argument("--host",
                        help="Host address of the JSD server",
                        type=str,
                        default=DEFAULT_RPC_HOST)
    parser.add_argument(
        "--user",
        help="Username for authentication by JET server (default:%(default)s)",
        type=str,
        default=DEFAULT_USER_NAME)
    parser.add_argument(
        "--password",
        help="Password for authentication by JET server (default:%(default)s",
        type=str,
        default=DEFAULT_PASSWORD)
    parser.add_argument(
        "--rpc_port",
        nargs='?',
        help="Port number of the JSD gRPC server. default: %(default)s",
        type=int,
        default=DEFAULT_RPC_PORT)
    parser.add_argument(
        "--notification_port",
        nargs='?',
        help="Port number of the JSD notification server. default: %(default)s",
        type=int,
        default=DEFAULT_NOTIFICATION_PORT)
    parser.add_argument("--config",
                        nargs='?',
                        help="JSON config file",
                        type=str,
                        default=None)

    args = parser.parse_args()
    if args.config is not None:
        try:
            json_cfg = {}
            with open(args.config) as json_cfg_file:
                json_cfg = json.load(json_cfg_file)
            device = Device(json_cfg['host'], json_cfg['user'],
                            json_cfg['password'], json_cfg['rpc_port'],
                            json_cfg['notification_port'])
        except Exception as e:
            LOG.error("exception :%s" % str(e.message))
            sys.exit(0)
    else:
        try:
            device = Device(args.host, args.user, args.password, args.rpc_port,
                            args.notification_port)
        except Exception as e:
            LOG.error("Exception:%s" % e.message)
            sys.exit(0)
    dispatchFunction = ParseNotification(device)
    dispatchThread = Thread(target=dispatchFunction)
    dispatchThread.setDaemon(True)
    dispatchThread.start()
    try:
        device.initialize()
        # log device initialized successfully
        print "Device initialized for the configuration updates"
        opw = OpServer()
        reactor.listenTCP(9191, server.Site(opw))
        LOG.info("Starting the reactor")
        reactor.run()

    except Exception as e:
        # log device initialization failed
        LOG.critical("JET app exiting due to exception: %s" % str(e.message))
        sys.exit(0)
    return