350 lines
16 KiB
Python
350 lines
16 KiB
Python
import os
|
|
import sys
|
|
import stat
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Optional, Tuple, Dict, Any, List
|
|
|
|
from core.models import GitConfig, TaskGitConfig
|
|
from core.logger import log_info, log_warn, log_err, log_debug, log_setup
|
|
|
|
|
|
class GitUpdater:
|
|
"""
|
|
Модуль управления Git-репозиториями:
|
|
- Поддержка индивидуального Git для КАЖДОЙ задачи (Gitea, GitHub, GitLab, кастомные SSH порты).
|
|
- Поддержка глобального Git-репозитория проекта.
|
|
- Автоматическое клонирование (если папки задачи еще нет на сервере).
|
|
- Автоматическая проверка обновлений, pull, обновление зависимостей и рестарт конкретного бота.
|
|
- Безопасная работа с приватными SSH-ключами (chmod 0600 на Linux, StrictHostKeyChecking=no, BatchMode).
|
|
"""
|
|
|
|
def __init__(self, global_config: GitConfig, notifier, manager):
|
|
self.global_cfg = global_config
|
|
self.notifier = notifier
|
|
self.manager = manager
|
|
self.shutdown_event = threading.Event()
|
|
self._thread: Optional[threading.Thread] = None
|
|
self._lock = threading.Lock()
|
|
self._task_last_check: Dict[str, float] = {}
|
|
self._global_last_check: float = 0.0
|
|
|
|
def update_config(self, new_global_cfg: GitConfig):
|
|
self.global_cfg = new_global_cfg
|
|
|
|
def start(self):
|
|
if self._thread and self._thread.is_alive():
|
|
return
|
|
self._thread = threading.Thread(target=self._run_loop, daemon=True, name="GitUpdaterThread")
|
|
self._thread.start()
|
|
|
|
def get_git_env(self, ssh_key_path: Optional[str] = None) -> Dict[str, str]:
|
|
"""
|
|
Формирует окружение для Git с настройкой OpenSSH.
|
|
Поддерживает Gitea / нестандартные порты (например, ssh://...:2222) и приватные ключи.
|
|
"""
|
|
env = os.environ.copy()
|
|
target_key = ssh_key_path or self.global_cfg.ssh_key_path
|
|
|
|
if target_key:
|
|
key_file = Path(target_key).resolve()
|
|
if not key_file.exists():
|
|
alt_path = Path.cwd() / target_key
|
|
if alt_path.exists():
|
|
key_file = alt_path.resolve()
|
|
|
|
if not key_file.exists():
|
|
log_warn(f"[Git] Приватный SSH-ключ не найден: {key_file}")
|
|
else:
|
|
# На Unix / Linux / Pterodactyl контейнерах выставляем 0600
|
|
if sys.platform != "win32":
|
|
try:
|
|
os.chmod(key_file, stat.S_IRUSR | stat.S_IWUSR)
|
|
except Exception as e:
|
|
log_debug(f"[Git] Не удалось установить chmod 0600 на ключ {key_file}: {e}")
|
|
|
|
devnull = "NUL" if sys.platform == "win32" else "/dev/null"
|
|
# BatchMode=yes не позволяет SSH зависать на интерактивных запросах пароля
|
|
ssh_cmd = (
|
|
f"ssh -i \"{key_file.as_posix()}\" "
|
|
"-o StrictHostKeyChecking=no "
|
|
f"-o UserKnownHostsFile={devnull} "
|
|
"-o IdentitiesOnly=yes "
|
|
"-o BatchMode=yes"
|
|
)
|
|
env["GIT_SSH_COMMAND"] = ssh_cmd
|
|
|
|
return env
|
|
|
|
def run_git_cmd(
|
|
self,
|
|
args: List[str],
|
|
cwd: str = ".",
|
|
ssh_key_path: Optional[str] = None
|
|
) -> Tuple[int, str, str]:
|
|
"""Безопасный вызов команды git в указанной рабочей директории"""
|
|
try:
|
|
env = self.get_git_env(ssh_key_path)
|
|
res = subprocess.run(
|
|
["git"] + args,
|
|
cwd=str(cwd),
|
|
env=env,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=120
|
|
)
|
|
return res.returncode, res.stdout.strip(), res.stderr.strip()
|
|
except subprocess.TimeoutExpired:
|
|
return -1, "", "Таймаут выполнения команды git (120 сек)"
|
|
except Exception as e:
|
|
return -1, "", str(e)
|
|
|
|
def determine_repo_dir(self, task_cfg) -> Path:
|
|
"""Определяет директорию репозитория для задачи"""
|
|
if task_cfg.git.path:
|
|
return Path(task_cfg.git.path).resolve()
|
|
if task_cfg.cwd:
|
|
return Path(task_cfg.cwd).resolve()
|
|
if task_cfg.script:
|
|
script_path = Path(task_cfg.script)
|
|
if script_path.parent != Path("."):
|
|
return script_path.parent.resolve()
|
|
return Path(f"bots/{task_cfg.name}").resolve()
|
|
|
|
def ensure_task_repo_cloned(self, task) -> bool:
|
|
"""
|
|
Проверяет наличие репозитория задачи на диске.
|
|
Если папки нет или она пуста — автоматически клонирует репозиторий.
|
|
"""
|
|
git_cfg: TaskGitConfig = task.cfg.git
|
|
if not git_cfg.enabled or not git_cfg.repo_url:
|
|
return True
|
|
|
|
repo_dir = self.determine_repo_dir(task.cfg)
|
|
dot_git = repo_dir / ".git"
|
|
|
|
if dot_git.exists():
|
|
return True
|
|
|
|
log_setup(f"[Git] Клонирование репозитория для '{task.cfg.name}' из {git_cfg.repo_url} в {repo_dir}...")
|
|
repo_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
branch = git_cfg.branch or "main"
|
|
# Если папка пуста — клонируем в нее
|
|
is_empty = not any(repo_dir.iterdir())
|
|
if is_empty:
|
|
clone_args = ["clone", "--branch", branch, git_cfg.repo_url, "."]
|
|
cwd = str(repo_dir)
|
|
else:
|
|
clone_args = ["clone", "--branch", branch, git_cfg.repo_url, str(repo_dir)]
|
|
cwd = "."
|
|
|
|
code, out, err = self.run_git_cmd(clone_args, cwd=cwd, ssh_key_path=git_cfg.ssh_key_path)
|
|
if code == 0:
|
|
log_setup(f"[Git] Репозиторий задачи '{task.cfg.name}' успешно склонирован!")
|
|
self.notifier.send(
|
|
f"📥 <b>Репозиторий склонирован:</b> <code>{task.cfg.name}</code>\n"
|
|
f"• <b>URL:</b> <code>{git_cfg.repo_url}</code>\n"
|
|
f"• <b>Ветка:</b> <code>{branch}</code>",
|
|
title="Git Clone",
|
|
level="success",
|
|
fields={"Задача": task.cfg.name, "Ветка": branch}
|
|
)
|
|
return True
|
|
else:
|
|
log_err(f"[Git] Ошибка клонирования '{task.cfg.name}': {err}")
|
|
return False
|
|
|
|
def sync_task_repo(self, task, manual: bool = False) -> Tuple[bool, str]:
|
|
"""
|
|
Проверка и подтягивание обновлений для конкретной задачи.
|
|
Возвращает: (было_ли_обновление: bool, сообщение: str)
|
|
"""
|
|
git_cfg: TaskGitConfig = task.cfg.git
|
|
if not git_cfg.enabled or not git_cfg.repo_url:
|
|
return False, f"Git не настроен для задачи '{task.cfg.name}'"
|
|
|
|
repo_dir = self.determine_repo_dir(task.cfg)
|
|
dot_git = repo_dir / ".git"
|
|
|
|
# 1. Если репозиторий еще не склонирован
|
|
if not dot_git.exists():
|
|
success = self.ensure_task_repo_cloned(task)
|
|
if success:
|
|
return True, "Репозиторий успешно склонирован"
|
|
return False, "Не удалось склонировать репозиторий"
|
|
|
|
branch = git_cfg.branch or "main"
|
|
ssh_key = git_cfg.ssh_key_path
|
|
|
|
with self._lock:
|
|
# 2. Проверяем / обновляем URL origin
|
|
code_remote, origin_url, _ = self.run_git_cmd(
|
|
["remote", "get-url", "origin"],
|
|
cwd=str(repo_dir),
|
|
ssh_key_path=ssh_key
|
|
)
|
|
if code_remote != 0:
|
|
self.run_git_cmd(["remote", "add", "origin", git_cfg.repo_url], cwd=str(repo_dir), ssh_key_path=ssh_key)
|
|
elif origin_url != git_cfg.repo_url:
|
|
self.run_git_cmd(["remote", "set-url", "origin", git_cfg.repo_url], cwd=str(repo_dir), ssh_key_path=ssh_key)
|
|
|
|
# 3. Fetch
|
|
if manual:
|
|
log_info(f"[Git] Проверка обновлений '{task.cfg.name}' (ветка: {branch})...")
|
|
|
|
fetch_code, _, fetch_err = self.run_git_cmd(
|
|
["fetch", "origin", branch],
|
|
cwd=str(repo_dir),
|
|
ssh_key_path=ssh_key
|
|
)
|
|
if fetch_code != 0:
|
|
err_msg = f"Ошибка git fetch ({task.cfg.name}): {fetch_err}"
|
|
log_warn(f"[Git] {err_msg}")
|
|
return False, err_msg
|
|
|
|
# 4. Сравнение локального HEAD и origin/branch
|
|
code_head, local_head, _ = self.run_git_cmd(["rev-parse", "HEAD"], cwd=str(repo_dir), ssh_key_path=ssh_key)
|
|
code_remote, remote_head, _ = self.run_git_cmd(["rev-parse", f"origin/{branch}"], cwd=str(repo_dir), ssh_key_path=ssh_key)
|
|
|
|
if code_head != 0 or code_remote != 0:
|
|
return False, f"Не удалось прочесть ревизии веток для '{task.cfg.name}'"
|
|
|
|
if local_head == remote_head:
|
|
if manual:
|
|
log_info(f"[Git] '{task.cfg.name}' уже в актуальном состоянии.")
|
|
return False, f"Задача '{task.cfg.name}' уже актуальна"
|
|
|
|
log_info(f"[Git] '{task.cfg.name}' новые коммиты: {local_head[:7]} -> {remote_head[:7]}")
|
|
|
|
# 5. Git Pull
|
|
pull_code, _, pull_err = self.run_git_cmd(
|
|
["pull", "origin", branch],
|
|
cwd=str(repo_dir),
|
|
ssh_key_path=ssh_key
|
|
)
|
|
if pull_code != 0:
|
|
err_msg = f"Ошибка git pull ({task.cfg.name}): {pull_err}"
|
|
log_err(f"[Git] {err_msg}")
|
|
self.notifier.send(
|
|
f"❌ <b>Ошибка обновления Git:</b> <code>{task.cfg.name}</code>\n<pre>{pull_err}</pre>",
|
|
title="Ошибка Git Auto-Update",
|
|
level="error"
|
|
)
|
|
return False, err_msg
|
|
|
|
# 6. Информация о последнем коммите
|
|
_, commit_info, _ = self.run_git_cmd(
|
|
["log", "-1", "--pretty=format:%h - %s (%an)"],
|
|
cwd=str(repo_dir),
|
|
ssh_key_path=ssh_key
|
|
)
|
|
|
|
msg = f"Задача '{task.cfg.name}' успешно обновлена: {commit_info}"
|
|
log_info(f"[Git] {msg}")
|
|
|
|
# Уведомление в Telegram и Discord
|
|
self.notifier.send(
|
|
f"🔄 <b>Бот обновлен из Git!</b>\n"
|
|
f"• <b>Задача:</b> <code>{task.cfg.name}</code>\n"
|
|
f"• <b>Ветка:</b> <code>{branch}</code>\n"
|
|
f"• <b>Коммит:</b> <code>{commit_info}</code>",
|
|
title="Git Auto-Update",
|
|
level="success",
|
|
fields={"Задача": task.cfg.name, "Ветка": branch, "Коммит": commit_info}
|
|
)
|
|
|
|
# 7. Обновление зависимостей задачи при необходимости
|
|
if git_cfg.auto_install_reqs and task.cfg.requirements_enabled:
|
|
task.check_and_install_requirements(force=False)
|
|
|
|
# 8. Авторестарт только этой конкретной задачи
|
|
if git_cfg.auto_restart and task.is_running():
|
|
log_info(f"[Git] Перезапуск '{task.cfg.name}' после обновления кода...")
|
|
self.manager.restart_task(task.cfg.name)
|
|
|
|
return True, msg
|
|
|
|
def sync_global_repo(self, manual: bool = False) -> Tuple[bool, str]:
|
|
"""Синхронизация глобального репозитория менеджера (если включено в config.yaml)"""
|
|
if not self.global_cfg.enabled or not self.global_cfg.repo_url:
|
|
return False, "Глобальный Git не настроен"
|
|
|
|
branch = self.global_cfg.branch or "main"
|
|
ssh_key = self.global_cfg.ssh_key_path
|
|
|
|
with self._lock:
|
|
code, _, _ = self.run_git_cmd(["rev-parse", "--is-inside-work-tree"])
|
|
if code != 0:
|
|
self.run_git_cmd(["init"])
|
|
self.run_git_cmd(["remote", "add", "origin", self.global_cfg.repo_url], ssh_key_path=ssh_key)
|
|
|
|
fetch_code, _, fetch_err = self.run_git_cmd(["fetch", "origin", branch], ssh_key_path=ssh_key)
|
|
if fetch_code != 0:
|
|
return False, f"Ошибка fetch глобального репо: {fetch_err}"
|
|
|
|
code_head, local_head, _ = self.run_git_cmd(["rev-parse", "HEAD"], ssh_key_path=ssh_key)
|
|
code_remote, remote_head, _ = self.run_git_cmd(["rev-parse", f"origin/{branch}"], ssh_key_path=ssh_key)
|
|
|
|
if code_head == 0 and code_remote == 0 and local_head != remote_head:
|
|
pull_code, _, pull_err = self.run_git_cmd(["pull", "origin", branch], ssh_key_path=ssh_key)
|
|
if pull_code == 0:
|
|
_, commit_info, _ = self.run_git_cmd(["log", "-1", "--pretty=format:%h - %s (%an)"], ssh_key_path=ssh_key)
|
|
if self.global_cfg.auto_restart:
|
|
self.manager.restart_all()
|
|
return True, f"Глобальный репозиторий обновлен: {commit_info}"
|
|
return False, f"Ошибка pull глобального репо: {pull_err}"
|
|
|
|
return False, "Глобальный репозиторий уже актуален"
|
|
|
|
def sync_all(self, manual: bool = False) -> Dict[str, Tuple[bool, str]]:
|
|
"""Обновление всех задач с включенным Git, а также глобального репозитория"""
|
|
results = {}
|
|
|
|
# 1. Глобальный репо
|
|
if self.global_cfg.enabled and self.global_cfg.repo_url:
|
|
results["[global]"] = self.sync_global_repo(manual=manual)
|
|
|
|
# 2. Задачи
|
|
for name, task in self.manager.get_all_tasks().items():
|
|
if task.cfg.git.enabled and task.cfg.git.repo_url:
|
|
results[name] = self.sync_task_repo(task, manual=manual)
|
|
|
|
return results
|
|
|
|
def _run_loop(self):
|
|
"""Периодический фоновый цикл проверки обновлений для задач и глобального репо"""
|
|
while not self.shutdown_event.is_set():
|
|
self.shutdown_event.wait(timeout=10.0)
|
|
now = time.time()
|
|
|
|
# Проверка задач
|
|
for name, task in self.manager.get_all_tasks().items():
|
|
if not task.cfg.git.enabled or not task.cfg.git.repo_url:
|
|
continue
|
|
|
|
interval = task.cfg.git.check_interval if task.cfg.git.check_interval >= 10 else 300.0
|
|
last_time = self._task_last_check.get(name, 0.0)
|
|
|
|
if now - last_time >= interval:
|
|
self._task_last_check[name] = now
|
|
try:
|
|
self.sync_task_repo(task, manual=False)
|
|
except Exception as e:
|
|
log_err(f"[Git] Ошибка автообновления задачи '{name}': {e}")
|
|
|
|
# Проверка глобального репо
|
|
if self.global_cfg.enabled and self.global_cfg.repo_url:
|
|
g_interval = self.global_cfg.check_interval if self.global_cfg.check_interval >= 10 else 300.0
|
|
if now - self._global_last_check >= g_interval:
|
|
self._global_last_check = now
|
|
try:
|
|
self.sync_global_repo(manual=False)
|
|
except Exception as e:
|
|
log_err(f"[Git] Ошибка глобального автообновления: {e}")
|
|
|
|
def shutdown(self):
|
|
self.shutdown_event.set()
|