示例#1
0
    def run(self, server_args):
        ret = 0
        if self.socket is None:
            raise exceptions.ClientException('Not connected')

        # check if the first non -- argument is server-stop
        positional_args = [a for a in server_args if not a.startswith('--')]
        if positional_args and positional_args[0] ==  'server-stop':
            self.send(RequestFormatter.format_stop_request())
            try:
                reply = json.loads(self.receive())  # this will fail when the server stopped
                if 'error' in reply:
                    print('Error: ' + reply['error']['reason'])
                    return 1
            except:
                pass
            return 0

        self.send(RequestFormatter.format_tree_request())
        reply = json.loads(self.receive())

        if 'error' in reply:
            print('Error: ' + reply['error']['reason'])
            ret = 1
        elif 'tree' in reply:
            ap = arguments.get_argument_parser(reply['tree'], debug=True)
            user_args = vars(ap.parse_args(server_args))
            self.send(RequestFormatter.format_run_request(user_args))
            run_id = None
            while True:
                data = self.receive()
                if not data:
                    break

                finished = False
                for line in data.splitlines():
                    json_data = json.loads(line)
                    if 'run' in json_data:
                        run_id = json_data['run']['id']
                        print('Executing assistant...')
                    elif 'log' in json_data:
                        self.handle_log(json_data['log']['level'], json_data['log']['message'])
                    elif 'error' in json_data:
                        self.handle_error(json_data['error']['reason'])
                    elif 'finished' in json_data:
                        self.handle_finish(json_data['finished']['status'])
                        ret = self.retcode_finish(json_data['finished']['status'])
                        finished = True
                        break
                    elif 'question' in json_data:
                        self.handle_question(run_id, json_data)
                    else:
                        raise exceptions.ClientException('Invalid message: ' + str(json_data))
                if finished:
                    break
        else:
            print('Wrong reply: ' + reply)
            ret = 1
        return ret
示例#2
0
def run():
    cmd_tree = [] # We do not know the tree of server commands yet

    # Processing of the help flags is turned off here because if the
    # connection to the server succeeds, the user will see the help message
    # from the argument parser instantiated in the clients.*Client's run()
    # method (that parser has all the arguments this one does, plus the ones
    # from the server assistant tree).
    #
    # If the connection to the server fails, the help message of this
    # argument parser will be shown when ConnectionError is caught at the end
    # of this routine.
    ap = arguments.get_argument_parser(cmd_tree, add_help=False)
    args = ap.parse_known_args()
    comm_dict = vars(args[0])
    da_args = args[1]

    # LOGGING
    if comm_dict.get('__comm_debug__'):
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    # GET SERVER ADDRESS
    if '__tcp__' in comm_dict:
        try:
            host, port = (comm_dict['__tcp__'] or '{}:{}'.format(settings.SOCKET_HOST, settings.SOCKET_PORT)).split(':')
        except ValueError:
            ap.error('Invalid TCP address: "{}", must be HOST:PORT'.format(comm_dict['__tcp__']))
            sys.exit(2)
        client = clients.TCPClient(host=host, port=int(port))
    else:
        filename = comm_dict.get('__unix__') or settings.SOCKET_FILENAME
        client = clients.UNIXClient(filename)

    # RUN
    try:
        client.start()
        sys.exit(client.run(da_args))
    except KeyboardInterrupt:
        sys.exit(130)
    except PermissionError:
        ap.error('Permission denied: {}' + client.filename)
        sys.exit(2)
    except FileNotFoundError as e:
        ap.error('File not found: ' + client.filename)
        sys.exit(2)
    except (ConnectionError, OSError) as e:
        logger.error(client.format_connection_error())
        logger.error('The message was: {}'.format(e))
        # Show help if everything fails
        ap.print_help()
        sys.exit(1)
示例#3
0
    def run(self, server_args):
        ret = 0
        if self.socket is None:
            raise exceptions.ClientException('Not connected')

        # check if the first non -- argument is server-stop
        positional_args = [a for a in server_args if not a.startswith('--')]
        if positional_args and positional_args[0] == 'server-stop':
            self.send(RequestFormatter.format_stop_request())
            try:
                reply = json.loads(
                    self.receive())  # this will fail when the server stopped
                if 'error' in reply:
                    print('Error: ' + reply['error']['reason'])
                    return 1
            except:
                pass
            return 0

        self.send(RequestFormatter.format_tree_request())
        reply = json.loads(self.receive())

        if 'error' in reply:
            print('Error: ' + reply['error']['reason'])
            ret = 1
        elif 'tree' in reply:
            ap = arguments.get_argument_parser(reply['tree'], debug=True)
            user_args = vars(ap.parse_args(server_args))
            self.send(RequestFormatter.format_run_request(user_args))
            run_id = None
            while True:
                data = self.receive()
                if not data:
                    break

                finished = False
                for line in data.splitlines():
                    json_data = json.loads(line)
                    if 'run' in json_data:
                        run_id = json_data['run']['id']
                        print('Executing assistant...')
                    elif 'log' in json_data:
                        self.handle_log(json_data['log']['level'],
                                        json_data['log']['message'])
                    elif 'error' in json_data:
                        self.handle_error(json_data['error']['reason'])
                    elif 'finished' in json_data:
                        self.handle_finish(json_data['finished']['status'])
                        ret = self.retcode_finish(
                            json_data['finished']['status'])
                        finished = True
                        break
                    elif 'question' in json_data:
                        self.handle_question(run_id, json_data)
                    else:
                        raise exceptions.ClientException('Invalid message: ' +
                                                         str(json_data))
                if finished:
                    break
        else:
            print('Wrong reply: ' + reply)
            ret = 1
        return ret