Обновление консольного клиента

This commit is contained in:
2023-12-09 16:51:22 +03:00
parent 9475338f65
commit 7fe05a3308
2 changed files with 109 additions and 70 deletions
+69 -59
View File
@@ -2,6 +2,15 @@ import json
from modules.transports.client import Client from modules.transports.client import Client
class Settings:
def __init__(self):
self.host = None
self.port = None
class CommandException(Exception):
def __init__(self, message):
super().__init__(message)
class Command: class Command:
def __init__(self, name): def __init__(self, name):
""" """
@@ -9,6 +18,7 @@ class Command:
:param name: Название команды :param name: Название команды
""" """
self.name = name self.name = name
self.settings = None
def do(self, parameters): def do(self, parameters):
""" """
@@ -18,12 +28,45 @@ class Command:
""" """
raise Exception("calling unimplemented method") raise Exception("calling unimplemented method")
def doRequest(self, request: dict):
"""
Выполнение запроса
:param request: Тело запроса
:return: Ответ
"""
# Создаём клиентский сокет и подключаемся к серверу
client = Client()
client.connect(self.settings.host, self.settings.port)
# Отправляем запрос
client.send(json.dumps(request))
# Получаем ответ
response = client.receive()
# Закрываем соединение
client.disconnect()
# Парсим ответ
response = json.loads(response)
# Проверяем статус обработки запроса
status = response["status"]
if status != "ok":
message = response["message"]
raise CommandException(f"status: {status}, message: {message}")
return response["result"]
class CommandManager: class CommandManager:
def __init__(self): def __init__(self, settings):
self.settings = settings
self.commands = [] self.commands = []
self.command_name_to_index = {} self.command_name_to_index = {}
def addCommand(self, command: Command): def addCommand(self, command: Command):
command.settings = self.settings
self.command_name_to_index[command.name] = len(self.commands) self.command_name_to_index[command.name] = len(self.commands)
self.commands.append(command) self.commands.append(command)
@@ -44,23 +87,7 @@ class CommandManager:
if str.isnumeric(name): if str.isnumeric(name):
return self.commands[int(name)] return self.commands[int(name)]
return self.command_name_to_index[name] return self.commands[self.command_name_to_index[name]]
def DoRequest(host: str, port: str, request: dict):
"""
Выполнение запроса
:param host: Хост
:param port: Порт
:param request: Тело запроса
:return: Ответ
"""
client = Client()
client.connect(host, port)
client.send(json.dumps(request))
return json.loads(client.receive())
class GetPipes(Command): class GetPipes(Command):
""" """
@@ -76,22 +103,25 @@ class GetPipes(Command):
"parameters": "" "parameters": ""
} }
host = parameters["host"] # Ответ -- это список пайп
port = parameters["port"] response = self.doRequest(request)
response = DoRequest(host, port, request) if len(response) == 0:
if response["status"] != "ok": print("there are no pipes")
print("error: " + response["message"])
return return
pipes = response["result"] for pipe in response[:-1]:
for pipe in pipes: self.printPipe(pipe)
print(pipe["name"] + ":")
print("- description: " + pipe["description"])
print("- input data type: " + pipe["input_data_type"])
print("- output data type: " + pipe["output_data_type"])
print() print()
self.printPipe(response[-1])
def printPipe(self, pipe):
print(pipe["name"] + ":")
print("- description: " + pipe["description"])
print("- input data type: " + pipe["input_data_type"])
print("- output data type: " + pipe["output_data_type"])
class GetPipelines(Command): class GetPipelines(Command):
""" """
Получение списка пайплайнов Получение списка пайплайнов
@@ -106,21 +136,15 @@ class GetPipelines(Command):
"parameters": "" "parameters": ""
} }
host = parameters["host"] # Ответ -- это список пайплайнов
port = parameters["port"] response = self.doRequest(request)
response = DoRequest(host, port, request) if len(response) == 0:
if response["status"] != "ok": print("there are no pipelines")
print("error: " + response["message"])
return return
pipelines = response["result"] for pipeline in response:
if len(pipelines) == 0: print(pipeline["name"] + ": " + str(pipeline["pipes"]))
print("there are no pipelines")
else:
for pipeline in pipelines:
print(pipeline["name"] + ": " + str(pipeline["pipes"]))
class RunPipeline(Command): class RunPipeline(Command):
""" """
@@ -142,15 +166,8 @@ class RunPipeline(Command):
} }
} }
host = parameters["host"] response = self.doRequest(request)
port = parameters["port"] print("result: " + str(response))
response = DoRequest(host, port, request)
if response["status"] != "ok":
print("error: " + response["message"])
return
print("result: " + str(response["result"]))
class CreatePipeline(Command): class CreatePipeline(Command):
""" """
@@ -172,12 +189,5 @@ class CreatePipeline(Command):
} }
} }
host = parameters["host"] self.doRequest(request)
port = parameters["port"] print("created successfully")
response = DoRequest(host, port, request)
if response["status"] != "ok":
print("error: " + response["message"])
return
print("result: " + str(response["result"]))
+40 -11
View File
@@ -1,7 +1,9 @@
import argparse
from services.console_client.commands import * from services.console_client.commands import *
def CreateCommandManager(): def CreateCommandManager(settings):
manager = CommandManager() manager = CommandManager(settings)
manager.addCommand(GetPipes()) manager.addCommand(GetPipes())
manager.addCommand(GetPipelines()) manager.addCommand(GetPipelines())
manager.addCommand(CreatePipeline()) manager.addCommand(CreatePipeline())
@@ -13,27 +15,54 @@ def PrintHelp(command_manager):
for index, command in enumerate(command_manager.commands): for index, command in enumerate(command_manager.commands):
print(str(index) + ". " + command.name) print(str(index) + ". " + command.name)
def main(): def ParseArguments():
command_manager = CreateCommandManager() parser = argparse.ArgumentParser(description="Console client for Log Analysis")
parameters = { # Хост сервера
"host": "localhost", parser.add_argument("--host", type=str, required=True, help="server's host")
"port": 8081
} # Порт
parser.add_argument("--port", type=int, required=True, help="server's port")
arguments = parser.parse_args()
return arguments
def CreateSettings() -> Settings:
arguments = ParseArguments()
settings = Settings()
settings.host = arguments.host
settings.port = arguments.port
return settings
def main():
settings = CreateSettings()
command_manager = CreateCommandManager(settings)
parameters = {}
PrintHelp(command_manager)
while True: while True:
PrintHelp(command_manager)
command_name = str(input("> ")) command_name = str(input("> "))
if command_name in ["q", "quit", "exit"]: if command_name in ["q", "quit", "exit"]:
break break
if command_name in ["h", "help"]:
PrintHelp(command_manager)
continue
if not command_manager.hasCommand(command_name): if not command_manager.hasCommand(command_name):
print("there is no command with such name") print("there is no command with such name")
continue continue
command = command_manager.getCommand(command_name) command = command_manager.getCommand(command_name)
command.do(parameters)
try:
command.do(parameters)
except Exception as e:
print(f"error: {str(e)}")
print() print()