import os import sys import shutil import tarfile import platform import subprocess from pathlib import Path from typing import Optional, Tuple, List, Dict import requests from core.logger import log_info, log_warn, log_err, log_debug, log_setup class PythonEnvManager: """ Менеджер сред исполнения Python: - Вариант А: поиск установленных версий Python в системе / контейнере - Вариант Б (Резерв): автоматическая докачка Portable CPython (python-build-standalone) - Автоматическое создание изолированных .venv и установка pip/requirements """ DEFAULT_RELEASE_TAG = "20261021" RUNTIMES_DIR = Path(".runtimes") @classmethod def get_platform_info(cls) -> Tuple[str, str, str]: """ Определение параметров платформы: (os_name, arch, libc) os_name: linux, windows, darwin arch: x86_64, aarch64 libc: gnu, musl (только для linux) """ # OS if sys.platform.startswith("linux"): os_name = "unknown-linux" elif sys.platform == "win32": os_name = "pc-windows-msvc" elif sys.platform == "darwin": os_name = "apple-darwin" else: os_name = sys.platform # Arch machine = platform.machine().lower() if machine in ("x86_64", "amd64"): arch = "x86_64" elif machine in ("aarch64", "arm64"): arch = "aarch64" elif machine.startswith("arm"): arch = "armv7" else: arch = machine # Libc (для Linux: glibc vs musl/Alpine) libc = "gnu" if os_name == "unknown-linux": try: lib_path = Path("/lib") if lib_path.exists() and any(p.name.startswith("ld-musl") for p in lib_path.glob("ld-musl*")): libc = "musl" else: libc_name, _ = platform.libc_ver() if "musl" in libc_name.lower(): libc = "musl" except Exception: pass return os_name, arch, libc @classmethod def find_system_python(cls, target_version: str) -> Optional[str]: """ Вариант А: Поиск нужной версии Python в операционной системе / контейнере. Проверяет PATH, системные папки (/usr/bin/pythonX.Y) и команду py на Windows. """ target_version = target_version.strip() ver_parts = target_version.split(".") if len(ver_parts) >= 2: short_ver = f"{ver_parts[0]}.{ver_parts[1]}" no_dot_ver = f"{ver_parts[0]}{ver_parts[1]}" else: short_ver = target_version no_dot_ver = target_version # 1. Проверяем текущий запущенный Python curr_ver = f"{sys.version_info.major}.{sys.version_info.minor}" if curr_ver == short_ver: log_debug(f"[PythonEnv] Текущий интерпретатор соответствует версии {short_ver}") return sys.executable # 2. Список возможных кандидатов на исполнение candidates = [] if sys.platform == "win32": candidates.extend([ f"python{short_ver}", f"python{no_dot_ver}", f"python{ver_parts[0]}", "python" ]) # Windows Python Launcher (py -X.Y) try: res = subprocess.run( ["py", f"-{short_ver}", "-c", "import sys; print(sys.executable)"], capture_output=True, text=True, timeout=5 ) if res.returncode == 0 and res.stdout.strip(): exe_path = res.stdout.strip() if os.path.exists(exe_path): log_info(f"[PythonEnv] Найдена версия {short_ver} через Windows Launcher: {exe_path}") return exe_path except Exception: pass else: # Linux / Pterodactyl Container candidates.extend([ f"/usr/bin/python{short_ver}", f"/usr/local/bin/python{short_ver}", f"/usr/bin/python{no_dot_ver}", f"python{short_ver}", f"python{no_dot_ver}", ]) for cand in candidates: resolved = shutil.which(cand) or (cand if os.path.isabs(cand) and os.path.exists(cand) else None) if resolved: try: res = subprocess.run( [resolved, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"], capture_output=True, text=True, timeout=5 ) if res.returncode == 0 and res.stdout.strip() == short_ver: log_info(f"[PythonEnv] Найден системный Python {short_ver}: {resolved}") return resolved except Exception: pass return None @classmethod def get_download_url(cls, target_version: str) -> Optional[Tuple[str, str]]: """ Поиск ссылки на скачивание нужной версии в python-build-standalone. Возвращает: (download_url, asset_filename) """ os_name, arch, libc = cls.get_platform_info() target_version = target_version.strip() short_ver = ".".join(target_version.split(".")[:2]) # Формируем паттерн для поиска ассета if os_name == "unknown-linux": target_pattern = f"-{arch}-{os_name}-{libc}-install_only" else: target_pattern = f"-{arch}-{os_name}-install_only" # Пробуем запросить последний релиз через GitHub API try: api_url = "https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest" headers = {"User-Agent": "PyTaskManager"} r = requests.get(api_url, headers=headers, timeout=8) if r.status_code == 200: assets = r.json().get("assets", []) for a in assets: name = a.get("name", "") if f"cpython-{short_ver}." in name and target_pattern in name and not name.endswith(".sha256"): return a.get("browser_download_url"), name except Exception as e: log_debug(f"[PythonEnv] GitHub API request failed: {e}") # Fallback: известные ссылки по умолчанию tag = cls.DEFAULT_RELEASE_TAG ver_map = { "3.10": "3.10.15", "3.11": "3.11.10", "3.12": "3.12.7", "3.9": "3.9.20", "3.13": "3.13.0" } patch_ver = ver_map.get(short_ver, f"{short_ver}.0") filename = f"cpython-{patch_ver}+{tag}{target_pattern}.tar.gz" fallback_url = f"https://github.com/astral-sh/python-build-standalone/releases/download/{tag}/{filename}" return fallback_url, filename @classmethod def download_portable_python(cls, target_version: str) -> Optional[str]: """ Вариант Б (Резерв): Загрузка и распаковка автономного CPython. Сохраняется в .runtimes/python-/ """ short_ver = ".".join(target_version.split(".")[:2]) dest_dir = cls.RUNTIMES_DIR / f"python-{short_ver}" cls.RUNTIMES_DIR.mkdir(parents=True, exist_ok=True) # Проверяем, не скачан ли он уже existing_bin = cls._find_python_in_dir(dest_dir) if existing_bin: log_debug(f"[PythonEnv] Использован ранее скачанный Python {short_ver}: {existing_bin}") return existing_bin download_info = cls.get_download_url(short_ver) if not download_info: log_err(f"[PythonEnv] Не найдена сборка для скачивания Python {short_ver}") return None url, filename = download_info log_setup(f"[PythonEnv] Вариант Б: Загрузка переносимого Python {short_ver} ({filename})...") temp_archive = cls.RUNTIMES_DIR / filename try: with requests.get(url, stream=True, timeout=120) as resp: if resp.status_code != 200: log_err(f"[PythonEnv] Ошибка скачивания (HTTP {resp.status_code}) по URL: {url}") return None total_size = int(resp.headers.get("content-length", 0)) downloaded = 0 with open(temp_archive, "wb") as f: for chunk in resp.iter_content(chunk_size=1024 * 1024): if chunk: f.write(chunk) downloaded += len(chunk) log_setup(f"[PythonEnv] Распаковка {filename} в {dest_dir}...") dest_dir.mkdir(parents=True, exist_ok=True) with tarfile.open(temp_archive, "r:*") as tar: # В архиве папка 'python', распакуем ее содержимое tar.extractall(path=cls.RUNTIMES_DIR) extracted_python = cls.RUNTIMES_DIR / "python" if extracted_python.exists() and extracted_python != dest_dir: if dest_dir.exists(): shutil.rmtree(dest_dir, ignore_errors=True) extracted_python.rename(dest_dir) temp_archive.unlink(missing_ok=True) py_bin = cls._find_python_in_dir(dest_dir) if py_bin: log_info(f"[PythonEnv] Portable Python {short_ver} успешно установлен: {py_bin}") return py_bin else: log_err(f"[PythonEnv] Бинарник Python не найден после распаковки в {dest_dir}") return None except Exception as e: log_err(f"[PythonEnv] Ошибка при докачке/распаковке Python {short_ver}: {e}") if temp_archive.exists(): temp_archive.unlink(missing_ok=True) return None @classmethod def _find_python_in_dir(cls, directory: Path) -> Optional[str]: """Поиск бинарника python в папке рантайма""" if not directory.exists(): return None candidates = [ directory / "bin" / "python3", directory / "bin" / "python", directory / "python.exe", directory / "bin" / "python.exe" ] for c in candidates: if c.exists() and c.is_file(): return str(c.resolve()) return None @classmethod def resolve_python_binary( cls, requested_version: Optional[str] = None, allow_download: bool = True ) -> str: """ Разрешение базового интерпретатора Python: 1. Если версия не указана -> текущий sys.executable 2. Вариант А: поиск в системе / контейнере 3. Вариант Б: резервная докачка Portable Python 4. Fallback -> sys.executable """ if not requested_version: return sys.executable # 1. Вариант А: Системный Python found = cls.find_system_python(requested_version) if found: return found # 2. Вариант Б: Докачка if allow_download: log_warn(f"[PythonEnv] Python {requested_version} не найден в системе. Переход к Варианту Б (докачка)...") downloaded = cls.download_portable_python(requested_version) if downloaded: return downloaded log_warn(f"[PythonEnv] Не удалось найти или скачать Python {requested_version}. Используем текущий: {sys.executable}") return sys.executable @classmethod def ensure_task_environment( cls, venv_path_str: Optional[str], python_version: Optional[str] = None, auto_create_venv: bool = True, allow_download: bool = True, requirements_path: Optional[str] = None, requirements_enabled: bool = False ) -> Tuple[str, Optional[str]]: """ Гарантирует готовность среды исполнения для задачи: - Если venv существует -> возвращает его интерпретатор - Если venv нет, но включено автосоздание -> находит/докачивает Python, создает venv, ставит pip - Возвращает: (путь_к_python, путь_к_папке_bin_для_PATH) """ # Если venv вообще не настроен if not venv_path_str: base_py = cls.resolve_python_binary(python_version, allow_download) return base_py, None venv_path = Path(venv_path_str).resolve() # Пути к интерпретатору внутри venv bin_dir = venv_path / ("Scripts" if sys.platform == "win32" else "bin") py_name = "python.exe" if sys.platform == "win32" else "python" py_in_venv = bin_dir / py_name # 1. Если venv уже создан и рабочий if py_in_venv.exists(): return str(py_in_venv), str(bin_dir) # 2. Если venv не существует и автосоздание отключено if not auto_create_venv: log_warn(f"[PythonEnv] venv '{venv_path_str}' не найден, а auto_create_venv=false. Используем базовый.") return cls.resolve_python_binary(python_version, allow_download), None # 3. Автоматическое создание venv log_setup(f"[PythonEnv] Виртуальное окружение {venv_path.name} не найдено. Автоматическое создание...") base_python = cls.resolve_python_binary(python_version, allow_download) log_setup(f"[PythonEnv] Создание venv в '{venv_path}' с использованием базового Python: {base_python}...") try: res = subprocess.run( [base_python, "-m", "venv", str(venv_path)], capture_output=True, text=True, timeout=120 ) if res.returncode != 0: log_err(f"[PythonEnv] Ошибка создания venv: {res.stderr}") return base_python, None if not py_in_venv.exists(): log_err(f"[PythonEnv] Интерпретатор не найден внутри созданного venv: {py_in_venv}") return base_python, None log_setup(f"[PythonEnv] venv успешно создан! Обновление pip...") # Тихо обновляем pip в новом venv subprocess.run( [str(py_in_venv), "-m", "pip", "install", "--upgrade", "pip"], capture_output=True, timeout=90 ) # Если включены requirements, сразу устанавливаем if requirements_enabled and requirements_path and os.path.exists(requirements_path): log_setup(f"[PythonEnv] Первичная установка зависимостей из {requirements_path}...") req_res = subprocess.run( [str(py_in_venv), "-m", "pip", "install", "-r", str(requirements_path)], capture_output=True, text=True, timeout=300 ) if req_res.returncode == 0: log_setup(f"[PythonEnv] Зависимости задачи успешно установлены в новый venv!") else: log_warn(f"[PythonEnv] Ошибка установки зависимостей: {req_res.stderr.strip()}") return str(py_in_venv), str(bin_dir) except Exception as e: log_err(f"[PythonEnv] Исключение при создании виртуального окружения: {e}") return base_python, None