コード例 #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')
コード例 #2
0
    def delete_object(self, object_id):
        self.tasks_pool.stop_operation_thread()

        with Manager.nodes[object_id].mutex:
            Manager.nodes[object_id].flag_removing = True
            Manager.nodes[object_id].handle_before_remove_device()

            def delete_id(id):
                del Manager.components[id]

            map(delete_id, Manager.components_for_device[object_id])
            del Manager.components_for_device[object_id]
            del Manager.nodes[object_id]
            self.tasks_pool.restart_operation_thread()
            self.recover_run_functions()
            log.info('Object {0} removed'.format(object_id))
コード例 #3
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))
コード例 #4
0
ファイル: command.py プロジェクト: Alphaopen/alphalogic_api
    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)))
コード例 #5
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)
コード例 #6
0
def shutdown(signum, frame):
    log.info("Shutdown. Signal is {0}".format(signum))
    raise Exit
コード例 #7
0
                                fun_set=MultiStub.service_fun_set,
                                request=state_w,
                                stub=self.stub_service)

    def call_helper(self, function_name, *args, **kwargs):
        if function_name in kwargs[
                'fun_set']:  # function_name - check availability
            try:
                answer = getattr(kwargs['stub'],
                                 function_name)(kwargs['request'],
                                                timeout=options.args.timeout)
                return answer

            except grpc.RpcError as err:
                if err.code() == grpc.StatusCode.NOT_FOUND:
                    raise ComponentNotFound(err.message + ' ' + err.details())
                elif err.code() == grpc.StatusCode.DEADLINE_EXCEEDED:
                    raise TimeoutError(err.message + ' ' + err.details())
                elif err.code() == grpc.StatusCode.UNAVAILABLE:
                    raise ConnectError(err.message + ' ' + err.details())
                raise RequestError(
                    u'gRPC request failed (code={}): {}, {}'.format(
                        err.code(), err.message, err.details()))
        else:
            raise IncorrectRPCRequest('{0} not found in {1}'.format(
                function_name, kwargs['fun_set']))


log.info("static MultiStub initialization")
MultiStub.static_initialization()
コード例 #8
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)))