refactor: use utils to handle service actions

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
This commit is contained in:
dw-0
2024-05-01 21:33:12 +02:00
parent b70ac0dfd7
commit be228210bd
4 changed files with 29 additions and 62 deletions

View File

@@ -49,7 +49,7 @@ def run_client_removal(
client_name = client.name client_name = client.name
remove_client_dir(client) remove_client_dir(client)
remove_nginx_config(client_name) remove_nginx_config(client_name)
remove_nginx_logs(client_name) remove_nginx_logs(client_name, kl_instances)
section = f"update_manager {client_name}" section = f"update_manager {client_name}"
remove_config_section(section, mr_instances) remove_config_section(section, mr_instances)

View File

@@ -15,6 +15,7 @@ from typing import List, Optional, Union, TypeVar
from core.instance_manager.base_instance import BaseInstance from core.instance_manager.base_instance import BaseInstance
from utils.constants import SYSTEMD from utils.constants import SYSTEMD
from utils.logger import Logger from utils.logger import Logger
from utils.system_utils import control_systemd_service
T = TypeVar(name="T", bound=BaseInstance, covariant=True) T = TypeVar(name="T", bound=BaseInstance, covariant=True)
@@ -108,14 +109,7 @@ class InstanceManager:
def enable_instance(self) -> None: def enable_instance(self) -> None:
Logger.print_status(f"Enabling {self.instance_service_full} ...") Logger.print_status(f"Enabling {self.instance_service_full} ...")
try: try:
command = [ control_systemd_service(self.instance_service_full, "enable")
"sudo",
"systemctl",
"enable",
self.instance_service_full,
]
if subprocess.run(command, check=True):
Logger.print_ok(f"{self.instance_service_full} enabled.")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
Logger.print_error(f"Error enabling service {self.instance_service_full}:") Logger.print_error(f"Error enabling service {self.instance_service_full}:")
Logger.print_error(f"{e}") Logger.print_error(f"{e}")
@@ -123,14 +117,7 @@ class InstanceManager:
def disable_instance(self) -> None: def disable_instance(self) -> None:
Logger.print_status(f"Disabling {self.instance_service_full} ...") Logger.print_status(f"Disabling {self.instance_service_full} ...")
try: try:
command = [ control_systemd_service(self.instance_service_full, "disable")
"sudo",
"systemctl",
"disable",
self.instance_service_full,
]
if subprocess.run(command, check=True):
Logger.print_ok(f"{self.instance_service_full} disabled.")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
Logger.print_error(f"Error disabling {self.instance_service_full}:") Logger.print_error(f"Error disabling {self.instance_service_full}:")
Logger.print_error(f"{e}") Logger.print_error(f"{e}")
@@ -138,14 +125,7 @@ class InstanceManager:
def start_instance(self) -> None: def start_instance(self) -> None:
Logger.print_status(f"Starting {self.instance_service_full} ...") Logger.print_status(f"Starting {self.instance_service_full} ...")
try: try:
command = [ control_systemd_service(self.instance_service_full, "start")
"sudo",
"systemctl",
"start",
self.instance_service_full,
]
if subprocess.run(command, check=True):
Logger.print_ok(f"{self.instance_service_full} started.")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
Logger.print_error(f"Error starting {self.instance_service_full}:") Logger.print_error(f"Error starting {self.instance_service_full}:")
Logger.print_error(f"{e}") Logger.print_error(f"{e}")
@@ -153,14 +133,7 @@ class InstanceManager:
def restart_instance(self) -> None: def restart_instance(self) -> None:
Logger.print_status(f"Restarting {self.instance_service_full} ...") Logger.print_status(f"Restarting {self.instance_service_full} ...")
try: try:
command = [ control_systemd_service(self.instance_service_full, "restart")
"sudo",
"systemctl",
"restart",
self.instance_service_full,
]
if subprocess.run(command, check=True):
Logger.print_ok(f"{self.instance_service_full} restarted.")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
Logger.print_error(f"Error restarting {self.instance_service_full}:") Logger.print_error(f"Error restarting {self.instance_service_full}:")
Logger.print_error(f"{e}") Logger.print_error(f"{e}")
@@ -178,9 +151,7 @@ class InstanceManager:
def stop_instance(self) -> None: def stop_instance(self) -> None:
Logger.print_status(f"Stopping {self.instance_service_full} ...") Logger.print_status(f"Stopping {self.instance_service_full} ...")
try: try:
command = ["sudo", "systemctl", "stop", self.instance_service_full] control_systemd_service(self.instance_service_full, "stop")
if subprocess.run(command, check=True):
Logger.print_ok(f"{self.instance_service_full} stopped.")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
Logger.print_error(f"Error stopping {self.instance_service_full}:") Logger.print_error(f"Error stopping {self.instance_service_full}:")
Logger.print_error(f"{e}") Logger.print_error(f"{e}")

View File

@@ -11,14 +11,13 @@
import re import re
import shutil import shutil
import subprocess
from pathlib import Path from pathlib import Path
from zipfile import ZipFile from zipfile import ZipFile
from subprocess import run, check_output, CalledProcessError, PIPE, DEVNULL
from typing import List from typing import List
from components.klipper.klipper import Klipper from components.klipper.klipper import Klipper
from core.instance_manager.instance_manager import InstanceManager
from utils import ( from utils import (
NGINX_SITES_AVAILABLE, NGINX_SITES_AVAILABLE,
MODULE_PATH, MODULE_PATH,
@@ -38,9 +37,9 @@ def check_file_exist(file_path: Path, sudo=False) -> bool:
if sudo: if sudo:
try: try:
command = ["sudo", "find", file_path] command = ["sudo", "find", file_path]
subprocess.check_output(command, stderr=subprocess.DEVNULL) check_output(command, stderr=DEVNULL)
return True return True
except subprocess.CalledProcessError: except CalledProcessError:
return False return False
else: else:
if file_path.exists(): if file_path.exists():
@@ -54,8 +53,8 @@ def create_symlink(source: Path, target: Path, sudo=False) -> None:
cmd = ["ln", "-sf", source, target] cmd = ["ln", "-sf", source, target]
if sudo: if sudo:
cmd.insert(0, "sudo") cmd.insert(0, "sudo")
subprocess.run(cmd, stderr=subprocess.PIPE, check=True) run(cmd, stderr=PIPE, check=True)
except subprocess.CalledProcessError as e: except CalledProcessError as e:
Logger.print_error(f"Failed to create symlink: {e}") Logger.print_error(f"Failed to create symlink: {e}")
raise raise
@@ -63,8 +62,8 @@ def create_symlink(source: Path, target: Path, sudo=False) -> None:
def remove_file(file_path: Path, sudo=False) -> None: def remove_file(file_path: Path, sudo=False) -> None:
try: try:
cmd = f"{'sudo ' if sudo else ''}rm -f {file_path}" cmd = f"{'sudo ' if sudo else ''}rm -f {file_path}"
subprocess.run(cmd, stderr=subprocess.PIPE, check=True, shell=True) run(cmd, stderr=PIPE, check=True, shell=True)
except subprocess.CalledProcessError as e: except CalledProcessError as e:
log = f"Cannot remove file {file_path}: {e.stderr.decode()}" log = f"Cannot remove file {file_path}: {e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
raise raise
@@ -90,8 +89,8 @@ def copy_upstream_nginx_cfg() -> None:
target = NGINX_CONFD.joinpath("upstreams.conf") target = NGINX_CONFD.joinpath("upstreams.conf")
try: try:
command = ["sudo", "cp", source, target] command = ["sudo", "cp", source, target]
subprocess.run(command, stderr=subprocess.PIPE, check=True) run(command, stderr=PIPE, check=True)
except subprocess.CalledProcessError as e: except CalledProcessError as e:
log = f"Unable to create upstreams.conf: {e.stderr.decode()}" log = f"Unable to create upstreams.conf: {e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
raise raise
@@ -106,8 +105,8 @@ def copy_common_vars_nginx_cfg() -> None:
target = NGINX_CONFD.joinpath("common_vars.conf") target = NGINX_CONFD.joinpath("common_vars.conf")
try: try:
command = ["sudo", "cp", source, target] command = ["sudo", "cp", source, target]
subprocess.run(command, stderr=subprocess.PIPE, check=True) run(command, stderr=PIPE, check=True)
except subprocess.CalledProcessError as e: except CalledProcessError as e:
log = f"Unable to create upstreams.conf: {e.stderr.decode()}" log = f"Unable to create upstreams.conf: {e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
raise raise
@@ -135,8 +134,8 @@ def create_nginx_cfg(name: str, port: int, root_dir: Path) -> None:
target = NGINX_SITES_AVAILABLE.joinpath(name) target = NGINX_SITES_AVAILABLE.joinpath(name)
try: try:
command = ["sudo", "mv", tmp, target] command = ["sudo", "mv", tmp, target]
subprocess.run(command, stderr=subprocess.PIPE, check=True) run(command, stderr=PIPE, check=True)
except subprocess.CalledProcessError as e: except CalledProcessError as e:
log = f"Unable to create '{target}': {e.stderr.decode()}" log = f"Unable to create '{target}': {e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
raise raise
@@ -182,19 +181,17 @@ def remove_nginx_config(name: str) -> None:
remove_file(NGINX_SITES_AVAILABLE.joinpath(name), True) remove_file(NGINX_SITES_AVAILABLE.joinpath(name), True)
remove_file(NGINX_SITES_ENABLED.joinpath(name), True) remove_file(NGINX_SITES_ENABLED.joinpath(name), True)
except subprocess.CalledProcessError as e: except CalledProcessError as e:
log = f"Unable to remove NGINX config '{name}':\n{e.stderr.decode()}" log = f"Unable to remove NGINX config '{name}':\n{e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
def remove_nginx_logs(name: str) -> None: def remove_nginx_logs(name: str, instances: List[Klipper]) -> None:
Logger.print_status(f"Removing NGINX logs for {name.capitalize()} ...") Logger.print_status(f"Removing NGINX logs for {name.capitalize()} ...")
try: try:
remove_file(Path(f"/var/log/nginx/{name}-access.log"), True) remove_file(Path(f"/var/log/nginx/{name}-access.log"), True)
remove_file(Path(f"/var/log/nginx/{name}-error.log"), True) remove_file(Path(f"/var/log/nginx/{name}-error.log"), True)
im = InstanceManager(Klipper)
instances: List[Klipper] = im.instances
if not instances: if not instances:
return return
@@ -202,5 +199,5 @@ def remove_nginx_logs(name: str) -> None:
remove_file(instance.log_dir.joinpath(f"{name}-access.log")) remove_file(instance.log_dir.joinpath(f"{name}-access.log"))
remove_file(instance.log_dir.joinpath(f"{name}-error.log")) remove_file(instance.log_dir.joinpath(f"{name}-error.log"))
except (OSError, subprocess.CalledProcessError) as e: except (OSError, CalledProcessError) as e:
Logger.print_error(f"Unable to remove NGINX logs:\n{e}") Logger.print_error(f"Unable to remove NGINX logs:\n{e}")

View File

@@ -21,9 +21,9 @@ from typing import List, Literal
import select import select
from utils.filesystem_utils import check_file_exist
from utils.input_utils import get_confirm from utils.input_utils import get_confirm
from utils.logger import Logger from utils.logger import Logger
from utils.filesystem_utils import check_file_exist
def kill(opt_err_msg: str = "") -> None: def kill(opt_err_msg: str = "") -> None:
@@ -240,8 +240,7 @@ def mask_system_service(service_name: str) -> None:
:return: None :return: None
""" """
try: try:
command = ["sudo", "systemctl", "mask", service_name] control_systemd_service(service_name, "mask")
run(command, stderr=PIPE, check=True)
except CalledProcessError as e: except CalledProcessError as e:
log = f"Unable to mask system service {service_name}: {e.stderr.decode()}" log = f"Unable to mask system service {service_name}: {e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
@@ -330,7 +329,7 @@ def set_nginx_permissions() -> None:
def control_systemd_service( def control_systemd_service(
name: str, action: Literal["start", "stop", "restart", "disable"] name: str, action: Literal["start", "stop", "restart", "enable", "disable", "mask"]
) -> None: ) -> None:
""" """
Helper method to execute several actions for a specific systemd service. | Helper method to execute several actions for a specific systemd service. |
@@ -339,12 +338,12 @@ def control_systemd_service(
:return: None :return: None
""" """
try: try:
Logger.print_status(f"{action.capitalize()} {name}.service ...") Logger.print_status(f"{action.capitalize()} {name} ...")
command = ["sudo", "systemctl", action, f"{name}.service"] command = ["sudo", "systemctl", action, name]
run(command, stderr=PIPE, check=True) run(command, stderr=PIPE, check=True)
Logger.print_ok("OK!") Logger.print_ok("OK!")
except CalledProcessError as e: except CalledProcessError as e:
log = f"Failed to {action} {name}.service: {e.stderr.decode()}" log = f"Failed to {action} {name}: {e.stderr.decode()}"
Logger.print_error(log) Logger.print_error(log)
raise raise