replace broad exception handling with specific errors and explicit logging
This commit is contained in:
1 parent
c7a50cc7e9
commit
0c3367052c
2 files changed
+38
-40
No files matched your search
+13
-16
@@ -3,11 +3,11 @@
|
|||||||
appctl_engine.py - Homelab Metadata Engine, Orchestration Parser & Git Sync Monitor
|
appctl_engine.py - Homelab Metadata Engine, Orchestration Parser & Git Sync Monitor
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import contextlib
|
||||||
import sys
|
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import shutil
|
import sys
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
SITES_DIR = os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))
|
SITES_DIR = os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))
|
||||||
@@ -77,10 +77,11 @@ def get_all_apps():
|
|||||||
manifest_path = os.path.join(app_dir, "app.yaml")
|
manifest_path = os.path.join(app_dir, "app.yaml")
|
||||||
manifest = {}
|
manifest = {}
|
||||||
if os.path.isfile(manifest_path):
|
if os.path.isfile(manifest_path):
|
||||||
try:
|
with (
|
||||||
manifest = parse_yaml_simple(open(manifest_path).read())
|
contextlib.suppress(OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError),
|
||||||
except Exception:
|
open(manifest_path, encoding="utf-8") as f,
|
||||||
pass
|
):
|
||||||
|
manifest = parse_yaml_simple(f.read())
|
||||||
|
|
||||||
canonical_name = manifest.get("name") or entry.replace("homelab-", "")
|
canonical_name = manifest.get("name") or entry.replace("homelab-", "")
|
||||||
aliases = manifest.get("aliases") or []
|
aliases = manifest.get("aliases") or []
|
||||||
@@ -167,7 +168,7 @@ def get_docker_status(dir_path):
|
|||||||
return f"🟡 Degraded ({running_count}/{total_count})"
|
return f"🟡 Degraded ({running_count}/{total_count})"
|
||||||
else:
|
else:
|
||||||
return "🔴 Stopped"
|
return "🔴 Stopped"
|
||||||
except Exception:
|
except (subprocess.SubprocessError, OSError):
|
||||||
return "❓ Unknown"
|
return "❓ Unknown"
|
||||||
|
|
||||||
|
|
||||||
@@ -229,7 +230,7 @@ def get_git_sync_status(dir_path):
|
|||||||
badge += " *"
|
badge += " *"
|
||||||
|
|
||||||
return badge
|
return badge
|
||||||
except Exception:
|
except (subprocess.SubprocessError, OSError, ValueError):
|
||||||
return "❓ Unknown"
|
return "❓ Unknown"
|
||||||
|
|
||||||
|
|
||||||
@@ -239,7 +240,7 @@ def get_git_diagnostics(dir_path):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
diag = {}
|
diag = {}
|
||||||
try:
|
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
||||||
branch = subprocess.run(
|
branch = subprocess.run(
|
||||||
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
||||||
cwd=dir_path,
|
cwd=dir_path,
|
||||||
@@ -277,15 +278,13 @@ def get_git_diagnostics(dir_path):
|
|||||||
check=False,
|
check=False,
|
||||||
).stdout.strip()
|
).stdout.strip()
|
||||||
diag["dirty_files"] = status_porcelain.splitlines() if status_porcelain else []
|
diag["dirty_files"] = status_porcelain.splitlines() if status_porcelain else []
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return diag
|
return diag
|
||||||
|
|
||||||
|
|
||||||
def fetch_repository(dir_path):
|
def fetch_repository(dir_path):
|
||||||
"""Run git fetch on a single repository with timeout."""
|
"""Run git fetch on a single repository with timeout."""
|
||||||
if os.path.isdir(os.path.join(dir_path, ".git")):
|
if os.path.isdir(os.path.join(dir_path, ".git")):
|
||||||
try:
|
with contextlib.suppress(subprocess.SubprocessError, OSError):
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["git", "fetch", "--quiet"],
|
["git", "fetch", "--quiet"],
|
||||||
cwd=dir_path,
|
cwd=dir_path,
|
||||||
@@ -294,8 +293,6 @@ def fetch_repository(dir_path):
|
|||||||
timeout=10,
|
timeout=10,
|
||||||
check=False,
|
check=False,
|
||||||
)
|
)
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_all_repositories(apps, include_core=True):
|
def fetch_all_repositories(apps, include_core=True):
|
||||||
@@ -332,7 +329,7 @@ def get_core_services():
|
|||||||
svc["status"] = "🟢 Running (1)"
|
svc["status"] = "🟢 Running (1)"
|
||||||
else:
|
else:
|
||||||
svc["status"] = "🔴 Stopped"
|
svc["status"] = "🔴 Stopped"
|
||||||
except Exception:
|
except (subprocess.SubprocessError, OSError):
|
||||||
svc["status"] = "❓ Unknown"
|
svc["status"] = "❓ Unknown"
|
||||||
return core_services
|
return core_services
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ in ~/Sites (via app.yaml) or data vaults (like ~/Brain), and executes the declar
|
|||||||
deployment actions with zero Core restarts.
|
deployment actions with zero Core restarts.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
import json
|
import json
|
||||||
import subprocess
|
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
||||||
@@ -23,6 +23,7 @@ logging.basicConfig(
|
|||||||
format="%(asctime)s [%(levelname)s] [GitOps] %(message)s",
|
format="%(asctime)s [%(levelname)s] [GitOps] %(message)s",
|
||||||
handlers=[logging.StreamHandler(sys.stdout)]
|
handlers=[logging.StreamHandler(sys.stdout)]
|
||||||
)
|
)
|
||||||
|
logger = logging.getLogger("gitops_dispatcher")
|
||||||
|
|
||||||
|
|
||||||
def parse_yaml_simple(text: str) -> dict:
|
def parse_yaml_simple(text: str) -> dict:
|
||||||
@@ -103,8 +104,8 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
|||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
try:
|
try:
|
||||||
manifest = parse_yaml_simple(manifest_file.read_text())
|
manifest = parse_yaml_simple(manifest_file.read_text())
|
||||||
except Exception as e:
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
logging.warning(f"Failed to parse {manifest_file}: {e}")
|
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
||||||
|
|
||||||
deployment_config = manifest.get("deployment")
|
deployment_config = manifest.get("deployment")
|
||||||
if not isinstance(deployment_config, dict):
|
if not isinstance(deployment_config, dict):
|
||||||
@@ -125,8 +126,8 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
|||||||
target_path = Path(entry.get("path", ""))
|
target_path = Path(entry.get("path", ""))
|
||||||
if target_path.is_dir():
|
if target_path.is_dir():
|
||||||
return target_path, entry.get("deployment", {"branch": "main", "actions": ["git_pull"]})
|
return target_path, entry.get("deployment", {"branch": "main", "actions": ["git_pull"]})
|
||||||
except Exception as e:
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
logging.warning(f"Failed to parse custom registry {registry_file}: {e}")
|
logger.warning(f"Failed to parse custom registry {registry_file}: {e}")
|
||||||
|
|
||||||
return None, {}
|
return None, {}
|
||||||
|
|
||||||
@@ -135,16 +136,16 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
"""Execute declared deployment actions sequentially."""
|
"""Execute declared deployment actions sequentially."""
|
||||||
expected_branch = deployment_config.get("branch", "main")
|
expected_branch = deployment_config.get("branch", "main")
|
||||||
if branch and branch != expected_branch:
|
if branch and branch != expected_branch:
|
||||||
logging.info(f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'")
|
logger.info(f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
logging.info(f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})...")
|
logger.info(f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})...")
|
||||||
actions = deployment_config.get("actions", ["git_pull"])
|
actions = deployment_config.get("actions", ["git_pull"])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for action in actions:
|
for action in actions:
|
||||||
if action == "git_pull":
|
if action == "git_pull":
|
||||||
logging.info(f" ↳ [git_pull] Pulling latest '{expected_branch}'...")
|
logger.info(f" ↳ [git_pull] Pulling latest '{expected_branch}'...")
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["git", "-C", str(target_dir), "pull", "--ff-only", "origin", expected_branch],
|
["git", "-C", str(target_dir), "pull", "--ff-only", "origin", expected_branch],
|
||||||
check=True
|
check=True
|
||||||
@@ -152,7 +153,7 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
elif action == "compose_up":
|
elif action == "compose_up":
|
||||||
compose_file = target_dir / "docker-compose.yml"
|
compose_file = target_dir / "docker-compose.yml"
|
||||||
if compose_file.is_file():
|
if compose_file.is_file():
|
||||||
logging.info(" ↳ [compose_up] Recreating containers (docker compose up -d)...")
|
logger.info(" ↳ [compose_up] Recreating containers (docker compose up -d)...")
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
|
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
|
||||||
check=True
|
check=True
|
||||||
@@ -160,7 +161,7 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
elif action == "compose_build":
|
elif action == "compose_build":
|
||||||
compose_file = target_dir / "docker-compose.yml"
|
compose_file = target_dir / "docker-compose.yml"
|
||||||
if compose_file.is_file():
|
if compose_file.is_file():
|
||||||
logging.info(" ↳ [compose_build] Building & recreating containers...")
|
logger.info(" ↳ [compose_build] Building & recreating containers...")
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["docker", "compose", "-f", str(compose_file), "build"],
|
["docker", "compose", "-f", str(compose_file), "build"],
|
||||||
check=True
|
check=True
|
||||||
@@ -172,25 +173,25 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
elif action == "compose_restart":
|
elif action == "compose_restart":
|
||||||
compose_file = target_dir / "docker-compose.yml"
|
compose_file = target_dir / "docker-compose.yml"
|
||||||
if compose_file.is_file():
|
if compose_file.is_file():
|
||||||
logging.info(" ↳ [compose_restart] Restarting containers...")
|
logger.info(" ↳ [compose_restart] Restarting containers...")
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["docker", "compose", "-f", str(compose_file), "restart"],
|
["docker", "compose", "-f", str(compose_file), "restart"],
|
||||||
check=True
|
check=True
|
||||||
)
|
)
|
||||||
elif isinstance(action, dict) and "custom" in action:
|
elif isinstance(action, dict) and "custom" in action:
|
||||||
cmd = action["custom"]
|
cmd = action["custom"]
|
||||||
logging.info(f" ↳ [custom] Executing: {cmd}")
|
logger.info(f" ↳ [custom] Executing: {cmd}")
|
||||||
subprocess.run(cmd, shell=True, cwd=str(target_dir), check=True)
|
subprocess.run(cmd, shell=True, cwd=str(target_dir), check=True)
|
||||||
else:
|
else:
|
||||||
logging.warning(f" ↳ Unknown action '{action}'; skipping.")
|
logger.warning(f" ↳ Unknown action '{action}'; skipping.")
|
||||||
|
|
||||||
logging.info(f"✨ Deployment of '{target_dir.name}' completed successfully.")
|
logger.info(f"✨ Deployment of '{target_dir.name}' completed successfully.")
|
||||||
return True
|
return True
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
logging.error(f"❌ Deployment step failed with exit code {e.returncode}: {e}")
|
logger.error(f"❌ Deployment step failed with exit code {e.returncode}: {e}")
|
||||||
return False
|
return False
|
||||||
except Exception as e:
|
except (subprocess.SubprocessError, OSError, KeyError, TypeError, ValueError, RuntimeError) as e:
|
||||||
logging.error(f"❌ Unexpected deployment error: {e}")
|
logger.error(f"❌ Unexpected deployment error: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
@@ -217,7 +218,7 @@ def main():
|
|||||||
payload_raw = sys.stdin.read().strip()
|
payload_raw = sys.stdin.read().strip()
|
||||||
|
|
||||||
if not payload_raw:
|
if not payload_raw:
|
||||||
logging.error("No webhook payload provided (checked sys.argv and stdin).")
|
logger.error("No webhook payload provided (checked sys.argv and stdin).")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -226,18 +227,18 @@ def main():
|
|||||||
ref = payload.get("ref", "refs/heads/main")
|
ref = payload.get("ref", "refs/heads/main")
|
||||||
branch = ref.replace("refs/heads/", "")
|
branch = ref.replace("refs/heads/", "")
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
logging.error(f"Invalid JSON payload: {e}")
|
logger.error(f"Invalid JSON payload: {e}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
if not repo_name:
|
if not repo_name:
|
||||||
logging.error("No repository name found in payload.")
|
logger.error("No repository name found in payload.")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
logging.info(f"Incoming webhook event: repository='{repo_name}', branch='{branch}'")
|
logger.info(f"Incoming webhook event: repository='{repo_name}', branch='{branch}'")
|
||||||
target_dir, deployment_config = resolve_target(repo_name)
|
target_dir, deployment_config = resolve_target(repo_name)
|
||||||
|
|
||||||
if not target_dir or not target_dir.is_dir():
|
if not target_dir or not target_dir.is_dir():
|
||||||
logging.warning(f"No valid deployment target directory found on host for '{repo_name}'. Ignoring.")
|
logger.warning(f"No valid deployment target directory found on host for '{repo_name}'. Ignoring.")
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
success = execute_deployment(target_dir, deployment_config, branch)
|
success = execute_deployment(target_dir, deployment_config, branch)
|
||||||
|
|||||||
Reference in new issue
Block a user