Exemplo n.º 1
0
 def join(self):
     """
     Wait until all threads within stub process terminate.
     This function provides an infinite communication loop between the adapter core and gRPC stub instance.
     Must be placed in the code of the adapter to keep it working till the process be stopped by the user or an error happens.
     """
     if self.joinable:
         try:
             self.manager.join()
         except Exit:
             log.info('Stub receive exit signal')
         except BaseException as err:
             t = traceback.format_exc()
             log.error('Root join error: {0}'.format(decode_string(t)))
         finally:
             try:
                 self.manager.tasks_pool.stop_operation_thread()
                 self.manager.multi_stub.channel.close()
                 if self.manager.g_thread.is_alive():
                     self.manager.g_thread.join()
             except BaseException as err:
                 t = traceback.format_exc()
                 log.error('Root finally join error: {0}'.format(
                     decode_string(t)))
         log.info('Stub has stopped successfully')
Exemplo n.º 2
0
    def check_command_accordance(self, command_model):
        try:
            id_command = command_model.id
            # 1 check return type
            '''
            model_result_type = command_model.result_type
            if model_result_type is bool and not(command_model.is_bool()):
                raise Exception('Real and model result type are different')
            elif model_result_type is int and not(command_model.is_long()):
                raise Exception('Real and model result type are different')
            elif model_result_type is float and not(command_model.is_double()):
                raise Exception('Real and model result type are different')
            elif model_result_type is datetime.datetime and not(command_model.is_datetime()):
                raise Exception('Real and model result type are different')
            elif model_result_type is unicode and not(command_model.is_string()):
                raise Exception('Real and model result type are different')
            '''

            # 2 check argument list and check type in argument_list
            for arg_name_model, _ in command_model.arguments:
                arg_type_model = command_model.arguments_type[arg_name_model]
                arg_name_real, arg_value = command_model.argument(
                    arg_name_model)
                arg_type_real = type(value_from_rpc(arg_value))
                if arg_name_model != arg_name_real or \
                        not(self.check_value_type_accordance(arg_type_model, arg_type_real)):
                    raise Exception('Real and model arguments are different')

        except Exception, err:
            t = traceback.format_exc()
            log.error('Command discrepancy \'{0}\': {1}'.format(
                command_model.name(), decode_string(t)))
            raise Exit
Exemplo n.º 3
0
 def wrapped(device, *argv, **kwargs):
     try:
         result = func(device, *argv, **kwargs)
         device.__dict__[wrapped.function_name].set_result(result)
         return result
     except Exception as err:
         t = traceback.format_exc()
         log.error(u'Command: function exception: {0}'.format(
             decode_string(t)))
         try:
             device.__dict__[wrapped.function_name].set_exception(
                 decode_string(t))
         except Exception as err:
             t = traceback.format_exc()
             log.error(u'Command: Exception in exception: {0}'.format(
                 decode_string(t)))
Exemplo n.º 4
0
        def wrapped(device, call_again=False):
            with device.mutex:
                if not device.flag_removing:
                    try:
                        status_perform = True
                        time_start = time.time()
                        try:
                            func(device)
                        except Exception as err:
                            t = traceback.format_exc()
                            log.error(u'Run function exception: {0}'.format(
                                decode_string(t)))

                        time_finish = time.time()
                        time_spend = time_finish - time_start
                        log.info(
                            'run function {0} of device {2} was executed for {1} seconds'
                            .format(func.func_name, time_spend, device.id))

                        period = getattr(device, kwargs_r.keys()[0]).val
                        func.__dict__['mem_period'] = period

                    except Exception as err:
                        t = traceback.format_exc()
                        log.error(u'system error in run decorator: {0}'.format(
                            decode_string(t)))
                        status_perform = False
                    finally:
                        if not status_perform:
                            mem_period = func.__dict__['mem_period'] \
                                if 'mem_period' in func.__dict__ \
                                else kwargs_r.values()[0]
                        else:
                            mem_period = period

                        if call_again:
                            if time_spend < mem_period:
                                device.manager.tasks_pool.add_task(
                                    time_finish + mem_period - time_spend,
                                    getattr(device, func.func_name))
                            else:
                                device.manager.tasks_pool.add_task(
                                    time_finish,
                                    getattr(device, func.func_name))
Exemplo n.º 5
0
    def call_function(self):
        """
        Call function when command executed

        :rtype: The return type depends on the function code
        """
        try:
            arg_list = self.argument_list()
            function_dict = {}
            info = []
            for name_arg in arg_list:
                type_arg = self.arguments_type[name_arg]
                function_dict[name_arg] = utils.value_from_rpc(self.argument(name_arg)[1])
                info.append('{0}({1}): {2}'.format(name_arg, type_arg, function_dict[name_arg]))

            log.info('Execute command \'{0}\' with arguments [{1}] from device \'{2}\''
                     .format(self.name(), '; '.join(info), self.device.id))
            self.function(self.device, **function_dict)

        except Exception as err:
            t = traceback.format_exc()
            log.error('Command \'{0}\' raise exception: {1}'.format(self.name(), decode_string(t)))
Exemplo n.º 6
0
    def __init__(self):
        try:
            host, port = init()

            self.manager.start_threads()
            self.joinable = False
            self.manager.configure_multi_stub(host + ':' + unicode(port))
            id_root = self.manager.root_id()
            type_device = self.manager.get_type(id_root)
            super(Root, self).__init__(type_device, id_root)

            log.info('Connecting to ' + host + ':' + unicode(port))
            self.init(id_root)
            self.joinable = True
            log.info('Root connected OK')

        except Exception as err:
            t = traceback.format_exc()
            log.error(decode_string(
                t))  # cause Exception can raise before super(Root)
            self.manager.tasks_pool.stop_operation_thread()
            log.info('The attempt of stub\'s run was failed')
            sys.exit(2)
Exemplo n.º 7
0
    def check_event_accordance(self, event_model):
        try:
            id_event = event_model.id
            # 1 check priority
            if event_model.priority == Priority.blocker and not (
                    event_model.is_blocker()):
                raise Exception('Real and model priority are different')
            elif event_model.priority == Priority.critical and not (
                    event_model.is_critical()):
                raise Exception('Real and model priority are different')
            elif event_model.priority == Priority.major and not (
                    event_model.is_major()):
                raise Exception('Real and model priority are different')
            elif event_model.priority == Priority.minor and not (
                    event_model.is_minor()):
                raise Exception('Real and model priority are different')

            # 2 check argument list in code and configuration
            code_arguments_list = set([x[0] for x in event_model.arguments])
            conf_arguments_list = set(event_model.argument_list())
            if code_arguments_list != conf_arguments_list:
                raise Exception('Event arguments list mismathcing: {0}'.format(
                    conf_arguments_list ^ code_arguments_list))

            # 3 check argument list and check type in argument_list
            for arg_name_model, arg_type_model in event_model.arguments:
                arg_name_real, arg_value = event_model.argument(arg_name_model)
                arg_type_real = type(value_from_rpc(arg_value))
                if arg_name_model != arg_name_real or \
                        not(self.check_value_type_accordance(arg_type_model, arg_type_real)):
                    raise Exception('Real and model arguments are different')

        except Exception, err:
            t = traceback.format_exc()
            log.error('Event discrepancy \'{0}\'\n{1}'.format(
                event_model.name(), decode_string(t)))
            raise Exit
Exemplo n.º 8
0
    def check_parameter_accordance(self, parameter_model):
        try:
            id_parameter = parameter_model.id
            #1 check value_type
            if parameter_model.value_type is bool and not (
                    parameter_model.is_bool()):
                raise Exception('Real and model type are different')
            elif parameter_model.value_type is int and not (
                    parameter_model.is_long()):
                raise Exception('Real and model type are different')
            elif parameter_model.value_type is float and not (
                    parameter_model.is_double()):
                raise Exception('Real and model type are different')
            elif parameter_model.value_type is datetime.datetime and not (
                    parameter_model.is_datetime()):
                raise Exception('Real and model type are different')
            elif parameter_model.value_type is unicode and not (
                    parameter_model.is_string()):
                raise Exception('Real and model type are different')

            #2 check visible
            if parameter_model.visible == Visible.runtime and not (
                    parameter_model.is_runtime()):
                raise Exception('Real and model visible are different')
            elif parameter_model.visible == Visible.setup and not (
                    parameter_model.is_setup()):
                raise Exception('Real and model visible are different')
            elif parameter_model.visible == Visible.hidden and not (
                    parameter_model.is_hidden()):
                raise Exception('Real and model visible are different')
            elif parameter_model.visible == Visible.common and not (
                    parameter_model.is_common()):
                raise Exception('Real and model visible are different')

            # 3 check access
            if parameter_model.access == Access.read_only and not (
                    parameter_model.is_read_only()):
                raise Exception('Real and model access are different')
            elif parameter_model.access == Access.read_write and not (
                    parameter_model.is_read_write()):
                raise Exception('Real and model access are different')

            # 4 check enums
            '''
            model_choices = parameter_model.choices
            real_choices = parameter_model.enums()
            if model_choices is None and len(real_choices) != 0:
                raise Exception('Real and model enums are different')
            elif model_choices is not None:
                if len(model_choices) != len(real_choices):
                    raise Exception('Real and model enums are different')
                else:
                    if type(model_choices[0]) is not tuple:
                        model_vals = sorted(model_choices)
                        real_vals  = sorted(zip(*real_choices)[0])
                        if model_vals != real_vals:
                            raise Exception('Real and model enums are different')
                    else:
                        model_vals, model_keys = zip(*model_choices)
                        model_vals, model_keys = sorted(model_vals), sorted(model_keys)
                        real_vals, real_keys = zip(*real_choices)
                        real_vals, real_keys = sorted(real_vals), sorted(real_keys)
                        if model_vals != real_vals or model_keys != real_keys:
                            raise Exception('Real and model enums are different')
            '''
        except Exception, err:
            t = traceback.format_exc()
            log.error('Parameter discrepancy \'{0}\':\n{1}'.format(
                parameter_model.name(), decode_string(t)))
            raise Exit
Exemplo n.º 9
0
    def grpc_thread(self):
        """
        Infinity loop: get state from adapter
        """
        try:
            for r in self.multi_stub.stub_service.states(rpc_pb2.Empty()):
                try:
                    if r.state == rpc_pb2.StateStream.AFTER_CREATING_OBJECT:
                        log.info('Create device {0}'.format(r.id))
                        id_name = self.parameter(r.id, 'type_when_create')
                        rpc_value = self.multi_stub.parameter_call(
                            'get', id=id_name).value
                        user_name_display = utils.value_from_rpc(rpc_value)
                        self.create_object(r.id, user_name_display)

                    elif r.state == rpc_pb2.StateStream.BEFORE_REMOVING_OBJECT:
                        log.info('Remove device {0}'.format(r.id))
                        if r.id in Manager.nodes:
                            self.delete_object(r.id)
                        else:
                            log.warn('Object {0} not found'.format(r.id))

                    elif r.state == rpc_pb2.StateStream.GETTING_AVAILABLE_CHILDREN:
                        log.info('Get available children of {0}'.format(r.id))
                        self.get_available_children(r.id)

                    elif r.state == rpc_pb2.StateStream.AFTER_SETTING_PARAMETER:
                        if r.id in Manager.components:
                            if Manager.components[r.id].callback:
                                try:
                                    param = Manager.components[
                                        r.id]  # TODO check
                                    device = Manager.nodes[
                                        param.owner()]  # TODO check
                                    Manager.components[r.id].callback(
                                        device, param)
                                except Exception as err:
                                    t = traceback.format_exc()
                                    log.error(
                                        'After set parameter value callback error:\n{0}'
                                        .format(decode_string(t)))
                        else:
                            log.warn('Parameter {0} not found'.format(r.id))

                    elif r.state == rpc_pb2.StateStream.EXECUTING_COMMAND:
                        if r.id in Manager.components:
                            Manager.components[
                                r.id].call_function()  # try except inside
                        else:
                            log.warn('Command {0} not found'.format(r.id))

                except Exception as err:
                    t = traceback.format_exc()
                    try:
                        log.error('grpc_thread error: {0}'.format(
                            decode_string(t)))
                    except Exception as ultimate_error:  # can't fall here
                        pass

                finally:
                    self.multi_stub.state_call('ack', id=r.id, state=r.state)

        except Exception as err:
            t = traceback.format_exc()
            log.error('grpc_thread error2: {0}'.format(decode_string(t)))