Skip to content

Commit

Permalink
Replaced all logging with rich in commands (#269)
Browse files Browse the repository at this point in the history
  • Loading branch information
Skazza94 committed Jan 31, 2024
1 parent 8df8342 commit c5aa13c
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 74 deletions.
23 changes: 10 additions & 13 deletions src/Kathara/cli/command/CheckCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import sys
from typing import List

from rich.console import Console

from ..ui.utils import create_panel
from ... import utils
from ... import version
Expand Down Expand Up @@ -37,12 +35,11 @@ def __init__(self) -> None:
def run(self, current_path: str, argv: List[str]) -> None:
self.parse_args(argv)

console = Console()
console.print(create_panel("System Check", style="blue bold", justify="center"))
console.print(f"Current Manager is:\t\t[cyan bold]{Kathara.get_instance().get_formatted_manager_name()}")
console.print(f"Manager version is:\t\t[cyan bold]{Kathara.get_instance().get_release_version()}")
console.print("Python version is:\t\t[cyan bold]%s" % sys.version.replace("\n", "- "))
console.print(f"Kathara version is:\t\t[cyan bold]{version.CURRENT_VERSION}")
self.console.print(create_panel("System Check", style="blue bold", justify="center"))
self.console.print(f"Current Manager is:\t\t[cyan bold]{Kathara.get_instance().get_formatted_manager_name()}")
self.console.print(f"Manager version is:\t\t[cyan bold]{Kathara.get_instance().get_release_version()}")
self.console.print("Python version is:\t\t[cyan bold]%s" % sys.version.replace("\n", "- "))
self.console.print(f"Kathara version is:\t\t[cyan bold]{version.CURRENT_VERSION}")

def linux_platform_info():
info = os.uname()
Expand All @@ -51,12 +48,12 @@ def linux_platform_info():
platform_info = utils.exec_by_platform(
linux_platform_info, lambda: platform.platform(), lambda: platform.platform()
)
console.print(f"Operating System version is:\t[cyan bold]{str(platform_info)}")
self.console.print(f"Operating System version is:\t[cyan bold]{str(platform_info)}")

with console.status(
with self.console.status(
f"Trying to run container with `{Setting.get_instance().image}` image...",
spinner="dots"
) as status:
) as _:
Setting.get_instance().open_terminals = False

lab = Lab("kathara_test")
Expand All @@ -66,6 +63,6 @@ def linux_platform_info():
try:
Kathara.get_instance().deploy_machine(machine)
Kathara.get_instance().undeploy_machine(machine)
console.print("[bold green]\u2713 Container run successfully.")
self.console.print("[bold green]\u2713 Container run successfully.")
except Exception as e:
console.print(f"[bold red]\u00d7 Running container failed: {str(e)}")
self.console.print(f"[bold red]\u00d7 Running container failed: {str(e)}")
2 changes: 1 addition & 1 deletion src/Kathara/cli/command/ConnectCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def run(self, current_path: str, argv: List[str]) -> None:
except (Exception, IOError):
lab = Lab(None, path=lab_path)

logging.debug("Executing `connect` command with hash `%s`..." % lab.hash)
logging.debug(f"Executing `connect` command with hash `{lab.hash}`...")

Kathara.get_instance().connect_tty(machine_name=args['machine_name'], lab_hash=lab.hash, shell=args['shell'],
logs=args['logs'])
4 changes: 1 addition & 3 deletions src/Kathara/cli/command/LcleanCommand.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import argparse
from typing import List

from rich import print as rich_print

from ..ui.utils import create_panel
from ... import utils
from ...foundation.cli.command.Command import Command
Expand Down Expand Up @@ -53,7 +51,7 @@ def run(self, current_path: str, argv: List[str]) -> None:
except (Exception, IOError):
lab = Lab(None, path=lab_path)

rich_print(create_panel("Stopping Network Scenario", style="blue bold", justify="center"))
self.console.print(create_panel("Stopping Network Scenario", style="blue bold", justify="center"))

Kathara.get_instance().undeploy_lab(
lab_hash=lab.hash,
Expand Down
17 changes: 11 additions & 6 deletions src/Kathara/cli/command/LconfigCommand.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import argparse
import logging
from typing import List

from ..ui.utils import alphanumeric, cd_mac
from ..ui.utils import alphanumeric, cd_mac, create_panel
from ... import utils
from ...foundation.cli.command.Command import Command
from ...manager.Kathara import Kathara
Expand Down Expand Up @@ -73,10 +72,16 @@ def run(self, current_path: str, argv: List[str]) -> None:
machine_name = args['name']
device = lab.get_machine(machine_name)

self.console.print(
create_panel(
f"Updating Network Scenario Device `{machine_name}`", style="blue bold", justify="center"
)
)

if args['to_add']:
for cd_name, mac_address in args['to_add']:
logging.info(
f"Adding interface to device `{machine_name}` on collision domain `{cd_name}`" +
self.console.print(
f"[green]+ Adding interface to device `{machine_name}` on collision domain `{cd_name}`" +
(f" with MAC Address {mac_address}" if mac_address else "") +
f"..."
)
Expand All @@ -85,7 +90,7 @@ def run(self, current_path: str, argv: List[str]) -> None:

if args['to_remove']:
for cd_to_remove in args['to_remove']:
logging.info(
"Removing interface on collision domain `%s` from device `%s`..." % (cd_to_remove, machine_name)
self.console.print(
f"[red]- Removing interface on collision domain `{cd_to_remove}` from device `{machine_name}`..."
)
Kathara.get_instance().disconnect_machine_from_link(device, lab.get_link(cd_to_remove))
10 changes: 4 additions & 6 deletions src/Kathara/cli/command/LinfoCommand.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import argparse
from typing import List

from rich import print as rich_print

from ..ui.utils import create_panel
from ..ui.utils import create_table
from ... import utils
Expand Down Expand Up @@ -86,7 +84,7 @@ def run(self, current_path: str, argv: List[str]) -> None:
return

if args['name']:
rich_print(
self.console.print(
create_panel(
str(next(Kathara.get_instance().get_machine_stats(args['name'], lab.hash))),
title=f"{args['name']} Information"
Expand Down Expand Up @@ -128,7 +126,7 @@ def _get_lab_live_info(lab: Lab) -> None:
@staticmethod
def _get_conf_info(lab: Lab, machine_name: str = None) -> None:
if machine_name:
rich_print(
self.console.print(
create_panel(
str(lab.machines[machine_name]),
title=f"{machine_name} Information"
Expand All @@ -138,12 +136,12 @@ def _get_conf_info(lab: Lab, machine_name: str = None) -> None:

lab_meta_information = str(lab)
if lab_meta_information:
rich_print(create_panel(lab_meta_information, title="Network Scenario Information"))
self.console.print(create_panel(lab_meta_information, title="Network Scenario Information"))

n_machines = len(lab.machines)
n_links = len(lab.links) if BRIDGE_LINK_NAME not in lab.links else len(lab.links) - 1

rich_print(
self.console.print(
create_panel(
f"There are {n_machines} devices.\nThere are {n_links} collision domains.",
title="Topology Information"
Expand Down
33 changes: 15 additions & 18 deletions src/Kathara/cli/command/LstartCommand.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import argparse
import logging
import os
import sys
from typing import List

from rich import print as rich_print

from ..ui.utils import create_panel
from ..ui.utils import create_table
from ... import utils
Expand Down Expand Up @@ -150,14 +147,7 @@ def run(self, current_path: str, argv: List[str]) -> Lab:
else Setting.get_instance().open_terminals
Setting.get_instance().terminal = args['xterm'] or Setting.get_instance().terminal

if args['privileged']:
if not utils.is_admin():
raise PrivilegeError("You must be root in order to start Kathara devices in privileged mode.")
else:
logging.warning("Running devices with privileged capabilities, terminals won't open!")
Setting.get_instance().open_terminals = False

rich_print(
self.console.print(
create_panel(
"Checking Network Scenario" if args['dry_mode'] else "Starting Network Scenario",
style="blue bold", justify="center"
Expand All @@ -179,7 +169,7 @@ def run(self, current_path: str, argv: List[str]) -> Lab:

lab_meta_information = str(lab)
if lab_meta_information:
rich_print(create_panel(lab_meta_information))
self.console.print(create_panel(lab_meta_information))

if len(lab.machines) <= 0:
raise EmptyLabError()
Expand All @@ -191,7 +181,9 @@ def run(self, current_path: str, argv: List[str]) -> Lab:
raise e

lab_ext_path = os.path.join(lab_path, 'lab.ext')
lab_ext_exists = False
if os.path.exists(lab_ext_path):
lab_ext_exists = True
if utils.is_platform(utils.LINUX) or utils.is_platform(utils.LINUX2):
if utils.is_admin():
external_links = ExtParser.parse(lab_path)
Expand All @@ -208,20 +200,25 @@ def run(self, current_path: str, argv: List[str]) -> Lab:

# If dry mode, we just check if the lab.conf is correct.
if args['dry_mode']:
logging.info("lab.conf file is correct.")
self.console.print("[green]\u2713 [bold]lab.conf[/bold] file is correct.")
if dependencies:
logging.info("lab.dep file is correct.")
if os.path.exists(lab_ext_path):
logging.info("lab.ext file is correct.")

logging.info("Exiting...")
self.console.print("[green]\u2713 [bold]lab.dep[/bold] file is correct.")
if lab_ext_exists:
self.console.print("[green]\u2713 [bold]lab.ext[/bold] file is correct.")

sys.exit(0)

lab.add_option('hosthome_mount', args['hosthome_mount'])
lab.add_option('shared_mount', args['shared_mount'])
lab.add_option('privileged_machines', args['privileged'])

if args['privileged']:
if not utils.is_admin():
raise PrivilegeError("You must be root in order to start Kathara devices in privileged mode.")
else:
self.console.print("[yellow]\u26a0 Running devices with privileged capabilities, terminals won't open!")
Setting.get_instance().open_terminals = False

Kathara.get_instance().deploy_lab(lab, selected_machines=set(args['machine_name']))

if args['list']:
Expand Down
16 changes: 10 additions & 6 deletions src/Kathara/cli/command/LtestCommand.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import argparse
import logging
import os
import shutil
import sys
Expand Down Expand Up @@ -72,7 +71,9 @@ def run(self, current_path: str, argv: List[str]) -> None:
signature_test_path = os.path.join(lab_path, "_test", "signature")

if os.path.exists(signature_test_path) and not args['rebuild_signature']:
logging.error("Signature for current network scenario already exists. Exiting...")
self.console.print(
f"[bold red]\u00d7 Signature for current network scenario already exists."
)
sys.exit(1)

# Tests run without terminals, no shared and /hosthome dirs.
Expand All @@ -85,10 +86,13 @@ def run(self, current_path: str, argv: List[str]) -> None:
try:
sleep_minutes = float(args['wait'])
if sleep_minutes < 0:
raise ValueError()
raise ValueError("--wait value must be greater than zero!")

logging.info("Waiting %s minutes before running tests..." % sleep_minutes)
time.sleep(sleep_minutes * 60)
with self.console.status(
f"Waiting {sleep_minutes} minutes before running tests...",
spinner="dots"
) as _:
time.sleep(sleep_minutes * 60)
except ValueError:
raise ValueError("--wait value is not valid!")

Expand Down Expand Up @@ -118,7 +122,7 @@ def run(self, current_path: str, argv: List[str]) -> None:
if args['verify'] == "user" or args['verify'] == "both":
user_test_passed = user_test.test()
except TestError as e:
logging.error(str(e))
self.console.print(f"[bold red]\u00d7 Tests failed: {str(e)}")

# Clean the lab at the end of the test.
LcleanCommand().run(lab_path, [])
Expand Down
6 changes: 3 additions & 3 deletions src/Kathara/cli/command/VcleanCommand.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import argparse
from typing import List

from rich import print as rich_print

from ..ui.utils import create_panel
from ...foundation.cli.command.Command import Command
from ...manager.Kathara import Kathara
Expand Down Expand Up @@ -41,6 +39,8 @@ def run(self, current_path: str, argv: List[str]) -> None:

lab = Lab("kathara_vlab")

rich_print(create_panel(f"Stopping Device `{args['name']}`", style="blue bold", justify="center"))
self.console.print(
create_panel(f"Stopping Device `{args['name']}`", style="blue bold", justify="center")
)

Kathara.get_instance().undeploy_lab(lab_name=lab.name, selected_machines={args['name']})
21 changes: 12 additions & 9 deletions src/Kathara/cli/command/VconfigCommand.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import argparse
import logging
from typing import List

from ..ui.utils import alphanumeric, cd_mac
from ..ui.utils import alphanumeric, cd_mac, create_panel
from ...foundation.cli.command.Command import Command
from ...manager.Kathara import Kathara
from ...model.Lab import Lab
Expand Down Expand Up @@ -63,10 +62,14 @@ def run(self, current_path: str, argv: List[str]) -> None:
device = lab.get_machine(machine_name)
device.api_object = Kathara.get_instance().get_machine_api_object(machine_name, lab_name=lab.name)

self.console.print(
create_panel(f"Updating Device `{machine_name}`", style="blue bold", justify="center")
)

if args['to_add']:
for cd_name, mac_address in args['to_add']:
logging.info(
f"Adding interface to device `{machine_name}` on collision domain `{cd_name}`" +
self.console.print(
f"[green]+ Adding interface to device `{machine_name}` on collision domain `{cd_name}`" +
(f" with MAC Address {mac_address}" if mac_address else "") +
f"..."
)
Expand All @@ -75,10 +78,10 @@ def run(self, current_path: str, argv: List[str]) -> None:

if args['to_remove']:
for cd_to_remove in args['to_remove']:
logging.info(
"Removing interface on collision domain `%s` from device `%s`..." % (cd_to_remove, machine_name)
self.console.print(
f"[red]- Removing interface on collision domain `{cd_to_remove}` from device `{machine_name}`..."
)
(_, interface) = lab.connect_machine_to_link(machine_name, cd_to_remove)
interface.link.api_object = Kathara.get_instance().get_link_api_object(cd_to_remove, lab_name=lab.name)
link = lab.get_link(cd_to_remove)
link.api_object = Kathara.get_instance().get_link_api_object(cd_to_remove, lab_name=lab.name)

Kathara.get_instance().disconnect_machine_from_link(device, interface.link)
Kathara.get_instance().disconnect_machine_from_link(device, link)
16 changes: 9 additions & 7 deletions src/Kathara/cli/command/VstartCommand.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import argparse
import logging
import sys
from typing import List

from rich import print as rich_print

from ..ui.utils import create_panel, interface_cd_mac
from ... import utils
from ...exceptions import PrivilegeError
Expand Down Expand Up @@ -169,11 +166,16 @@ def run(self, current_path: str, argv: List[str]) -> None:

name = args.pop('name')

self.console.print(
create_panel(
f"Checking Device `{name}`" if args['dry_mode'] else f"Starting Device `{name}`",
style="blue bold", justify="center"
)
)

if args['dry_mode']:
logging.info("Device configuration is correct. Exiting...")
self.console.print(f"[green]\u2713 [bold]{name}[/bold] configuration is correct.")
sys.exit(0)
else:
rich_print(create_panel(f"Starting Device `{name}`", style="blue bold", justify="center"))

Setting.get_instance().open_terminals = args['terminals'] if args['terminals'] is not None \
else Setting.get_instance().open_terminals
Expand All @@ -184,7 +186,7 @@ def run(self, current_path: str, argv: List[str]) -> None:
if not utils.is_admin():
raise PrivilegeError("You must be root in order to start this Kathara device in privileged mode.")
else:
logging.warning("Running device with privileged capabilities, terminal won't open!")
self.console.print("[yellow]\u26a0 Running devices with privileged capabilities, terminals won't open!")
Setting.get_instance().open_terminals = False

lab = Lab("kathara_vlab")
Expand Down
Loading

0 comments on commit c5aa13c

Please sign in to comment.