58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
from app.models import Mirror
|
|
from app.services.host import host_path, run_on_host
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DAEMON_JSON = "etc/docker/daemon.json"
|
|
MIRROR_MANAGER_KEY = "mirror-manager"
|
|
|
|
|
|
def read_current_docker() -> dict:
|
|
path = host_path(DAEMON_JSON)
|
|
if not path.exists():
|
|
return {"exists": False, "config": {}}
|
|
try:
|
|
return {"exists": True, "config": json.loads(path.read_text(encoding="utf-8"))}
|
|
except json.JSONDecodeError:
|
|
return {"exists": True, "config": {}, "parse_error": True}
|
|
|
|
|
|
def apply_docker(mirror: Mirror) -> dict:
|
|
if not mirror.url:
|
|
return {"success": False, "error": "URL رجیstry داکر تعریف نشده"}
|
|
|
|
path = host_path(DAEMON_JSON)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
config: dict = {}
|
|
if path.exists():
|
|
try:
|
|
config = json.loads(path.read_text(encoding="utf-8"))
|
|
except json.JSONDecodeError:
|
|
config = {}
|
|
|
|
config["registry-mirrors"] = [mirror.url.rstrip("/")]
|
|
config["_mirror_manager"] = MIRROR_MANAGER_KEY
|
|
|
|
path.write_text(json.dumps(config, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
|
|
result = run_on_host(["systemctl", "restart", "docker"], timeout=120)
|
|
if result.returncode != 0:
|
|
return {
|
|
"success": False,
|
|
"error": (result.stderr or "خطا در restart docker")[:500],
|
|
}
|
|
|
|
return {
|
|
"success": True,
|
|
"message": f"Docker registry mirror اعمال شد: {mirror.name}",
|
|
"url": mirror.url,
|
|
"warning": "سرویس Docker restart شد — containerها موقتاً قطع میشوند",
|
|
}
|