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

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
class Settings:
def __init__(self):
self.host = None
self.port = None
class CommandException(Exception):
def __init__(self, message):
super().__init__(message)
class Command:
def __init__(self, name):
"""
@@ -9,6 +18,7 @@ class Command:
:param name: Название команды
"""
self.name = name
self.settings = None
def do(self, parameters):
"""
@@ -18,12 +28,45 @@ class Command:
"""
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:
def __init__(self):
def __init__(self, settings):
self.settings = settings
self.commands = []
self.command_name_to_index = {}
def addCommand(self, command: Command):
command.settings = self.settings
self.command_name_to_index[command.name] = len(self.commands)
self.commands.append(command)
@@ -44,23 +87,7 @@ class CommandManager:
if str.isnumeric(name):
return self.commands[int(name)]
return 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())
return self.commands[self.command_name_to_index[name]]
class GetPipes(Command):
"""
@@ -76,22 +103,25 @@ class GetPipes(Command):
"parameters": ""
}
host = parameters["host"]
port = parameters["port"]
# Ответ -- это список пайп
response = self.doRequest(request)
response = DoRequest(host, port, request)
if response["status"] != "ok":
print("error: " + response["message"])
if len(response) == 0:
print("there are no pipes")
return
pipes = response["result"]
for pipe in pipes:
print(pipe["name"] + ":")
print("- description: " + pipe["description"])
print("- input data type: " + pipe["input_data_type"])
print("- output data type: " + pipe["output_data_type"])
for pipe in response[:-1]:
self.printPipe(pipe)
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):
"""
Получение списка пайплайнов
@@ -106,21 +136,15 @@ class GetPipelines(Command):
"parameters": ""
}
host = parameters["host"]
port = parameters["port"]
# Ответ -- это список пайплайнов
response = self.doRequest(request)
response = DoRequest(host, port, request)
if response["status"] != "ok":
print("error: " + response["message"])
if len(response) == 0:
print("there are no pipelines")
return
pipelines = response["result"]
if len(pipelines) == 0:
print("there are no pipelines")
else:
for pipeline in pipelines:
print(pipeline["name"] + ": " + str(pipeline["pipes"]))
for pipeline in response:
print(pipeline["name"] + ": " + str(pipeline["pipes"]))
class RunPipeline(Command):
"""
@@ -142,15 +166,8 @@ class RunPipeline(Command):
}
}
host = parameters["host"]
port = parameters["port"]
response = DoRequest(host, port, request)
if response["status"] != "ok":
print("error: " + response["message"])
return
print("result: " + str(response["result"]))
response = self.doRequest(request)
print("result: " + str(response))
class CreatePipeline(Command):
"""
@@ -172,12 +189,5 @@ class CreatePipeline(Command):
}
}
host = parameters["host"]
port = parameters["port"]
response = DoRequest(host, port, request)
if response["status"] != "ok":
print("error: " + response["message"])
return
print("result: " + str(response["result"]))
self.doRequest(request)
print("created successfully")
+40 -11
View File
@@ -1,7 +1,9 @@
import argparse
from services.console_client.commands import *
def CreateCommandManager():
manager = CommandManager()
def CreateCommandManager(settings):
manager = CommandManager(settings)
manager.addCommand(GetPipes())
manager.addCommand(GetPipelines())
manager.addCommand(CreatePipeline())
@@ -13,27 +15,54 @@ def PrintHelp(command_manager):
for index, command in enumerate(command_manager.commands):
print(str(index) + ". " + command.name)
def main():
command_manager = CreateCommandManager()
def ParseArguments():
parser = argparse.ArgumentParser(description="Console client for Log Analysis")
parameters = {
"host": "localhost",
"port": 8081
}
# Хост сервера
parser.add_argument("--host", type=str, required=True, help="server's host")
# Порт
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:
PrintHelp(command_manager)
command_name = str(input("> "))
if command_name in ["q", "quit", "exit"]:
break
if command_name in ["h", "help"]:
PrintHelp(command_manager)
continue
if not command_manager.hasCommand(command_name):
print("there is no command with such name")
continue
command = command_manager.getCommand(command_name)
command.do(parameters)
try:
command.do(parameters)
except Exception as e:
print(f"error: {str(e)}")
print()