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

View File

@@ -11,14 +11,13 @@
import re
import shutil
import subprocess
from pathlib import Path
from zipfile import ZipFile
from subprocess import run, check_output, CalledProcessError, PIPE, DEVNULL
from typing import List
from components.klipper.klipper import Klipper
from core.instance_manager.instance_manager import InstanceManager
from utils import (
NGINX_SITES_AVAILABLE,
MODULE_PATH,
@@ -38,9 +37,9 @@ def check_file_exist(file_path: Path, sudo=False) -> bool:
if sudo:
try:
command = ["sudo", "find", file_path]
subprocess.check_output(command, stderr=subprocess.DEVNULL)
check_output(command, stderr=DEVNULL)
return True
except subprocess.CalledProcessError:
except CalledProcessError:
return False
else:
if file_path.exists():
@@ -54,8 +53,8 @@ def create_symlink(source: Path, target: Path, sudo=False) -> None:
cmd = ["ln", "-sf", source, target]
if sudo:
cmd.insert(0, "sudo")
subprocess.run(cmd, stderr=subprocess.PIPE, check=True)
except subprocess.CalledProcessError as e:
run(cmd, stderr=PIPE, check=True)
except CalledProcessError as e:
Logger.print_error(f"Failed to create symlink: {e}")
raise
@@ -63,8 +62,8 @@ def create_symlink(source: Path, target: Path, sudo=False) -> None:
def remove_file(file_path: Path, sudo=False) -> None:
try:
cmd = f"{'sudo ' if sudo else ''}rm -f {file_path}"
subprocess.run(cmd, stderr=subprocess.PIPE, check=True, shell=True)
except subprocess.CalledProcessError as e:
run(cmd, stderr=PIPE, check=True, shell=True)
except CalledProcessError as e:
log = f"Cannot remove file {file_path}: {e.stderr.decode()}"
Logger.print_error(log)
raise
@@ -90,8 +89,8 @@ def copy_upstream_nginx_cfg() -> None:
target = NGINX_CONFD.joinpath("upstreams.conf")
try:
command = ["sudo", "cp", source, target]
subprocess.run(command, stderr=subprocess.PIPE, check=True)
except subprocess.CalledProcessError as e:
run(command, stderr=PIPE, check=True)
except CalledProcessError as e:
log = f"Unable to create upstreams.conf: {e.stderr.decode()}"
Logger.print_error(log)
raise
@@ -106,8 +105,8 @@ def copy_common_vars_nginx_cfg() -> None:
target = NGINX_CONFD.joinpath("common_vars.conf")
try:
command = ["sudo", "cp", source, target]
subprocess.run(command, stderr=subprocess.PIPE, check=True)
except subprocess.CalledProcessError as e:
run(command, stderr=PIPE, check=True)
except CalledProcessError as e:
log = f"Unable to create upstreams.conf: {e.stderr.decode()}"
Logger.print_error(log)
raise
@@ -135,8 +134,8 @@ def create_nginx_cfg(name: str, port: int, root_dir: Path) -> None:
target = NGINX_SITES_AVAILABLE.joinpath(name)
try:
command = ["sudo", "mv", tmp, target]
subprocess.run(command, stderr=subprocess.PIPE, check=True)
except subprocess.CalledProcessError as e:
run(command, stderr=PIPE, check=True)
except CalledProcessError as e:
log = f"Unable to create '{target}': {e.stderr.decode()}"
Logger.print_error(log)
raise
@@ -182,19 +181,17 @@ def remove_nginx_config(name: str) -> None:
remove_file(NGINX_SITES_AVAILABLE.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()}"
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()} ...")
try:
remove_file(Path(f"/var/log/nginx/{name}-access.log"), True)
remove_file(Path(f"/var/log/nginx/{name}-error.log"), True)
im = InstanceManager(Klipper)
instances: List[Klipper] = im.instances
if not instances:
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}-error.log"))
except (OSError, subprocess.CalledProcessError) as e:
except (OSError, CalledProcessError) as 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
from utils.filesystem_utils import check_file_exist
from utils.input_utils import get_confirm
from utils.logger import Logger
from utils.filesystem_utils import check_file_exist
def kill(opt_err_msg: str = "") -> None:
@@ -240,8 +240,7 @@ def mask_system_service(service_name: str) -> None:
:return: None
"""
try:
command = ["sudo", "systemctl", "mask", service_name]
run(command, stderr=PIPE, check=True)
control_systemd_service(service_name, "mask")
except CalledProcessError as e:
log = f"Unable to mask system service {service_name}: {e.stderr.decode()}"
Logger.print_error(log)
@@ -330,7 +329,7 @@ def set_nginx_permissions() -> None:
def control_systemd_service(
name: str, action: Literal["start", "stop", "restart", "disable"]
name: str, action: Literal["start", "stop", "restart", "enable", "disable", "mask"]
) -> None:
"""
Helper method to execute several actions for a specific systemd service. |
@@ -339,12 +338,12 @@ def control_systemd_service(
:return: None
"""
try:
Logger.print_status(f"{action.capitalize()} {name}.service ...")
command = ["sudo", "systemctl", action, f"{name}.service"]
Logger.print_status(f"{action.capitalize()} {name} ...")
command = ["sudo", "systemctl", action, name]
run(command, stderr=PIPE, check=True)
Logger.print_ok("OK!")
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)
raise