| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154 |
- import json
- import os
- import platform
- import shutil
- import subprocess
- import tempfile
- from dotenv import load_dotenv
- from loguru import logger
- load_dotenv()
- def update_squid():
- squid_bin = shutil.which("squid")
- try:
- if squid_bin:
- pre_check = subprocess.run( # noqa: S603
- [squid_bin, "-v"], capture_output=True, text=True
- )
- squid_instalado = pre_check.returncode == 0
- else:
- squid_instalado = False
- except FileNotFoundError:
- squid_instalado = False
- if squid_instalado:
- logger.info(f"Squid ya está instalado: {pre_check.stdout.strip()}")
- else:
- logger.info(
- "El binario de Squid no se encontró en el sistema (aún no instalado)"
- if not squid_bin
- else "Squid no está instalado o no se detectó instalación previa"
- )
- try:
- os_info = platform.freedesktop_os_release()
- os_id = os_info.get("ID", "").lower()
- codename = os_info.get(
- "VERSION_CODENAME", os_info.get("UBUNTU_CODENAME", "")
- ).lower()
- if os_id not in ["ubuntu", "debian"] or not codename:
- print("Sistema operativo no compatible", "error")
- return False
- proxy_url = os.getenv("HTTP_PROXY", "")
- env = os.environ.copy()
- if proxy_url:
- env["http_proxy"] = proxy_url
- env["https_proxy"] = proxy_url
- wget_bin = shutil.which("wget")
- if not wget_bin:
- logger.error("wget no encontrado en el sistema")
- return False
- version_info = subprocess.run( # noqa: S603
- [
- wget_bin,
- "-qO-",
- "https://api.github.com/repos/cuza/squid/releases/latest",
- ],
- capture_output=True,
- text=True,
- env=env,
- )
- if version_info.returncode != 0:
- logger.error("Error obteniendo información de versión")
- return False
- try:
- latest_version = json.loads(version_info.stdout)["tag_name"]
- except (json.JSONDecodeError, KeyError):
- logger.error("Error procesando versión")
- return False
- package_name = f"squid_{latest_version}-{os_id}-{codename}_amd64.deb"
- download_url = f"https://github.com/cuza/squid/releases/download/{latest_version}/{package_name}"
- check_package = subprocess.run( # noqa: S603
- [wget_bin, "--spider", download_url],
- capture_output=True,
- text=True,
- env=env,
- )
- if check_package.returncode != 0:
- logger.error(
- f"Paquete no disponible para {os_id.capitalize()} {codename.capitalize()}"
- )
- return False
- with tempfile.NamedTemporaryFile(
- delete=False, suffix=f"_{package_name}"
- ) as tmp_pkg:
- package_path = tmp_pkg.name
- download = subprocess.run( # noqa: S603
- [wget_bin, download_url, "-O", package_path],
- capture_output=True,
- text=True,
- env=env,
- )
- if download.returncode != 0:
- logger.error("Error descargando el paquete")
- return False
- apt_env = env.copy()
- if proxy_url:
- apt_conf = "/etc/apt/apt.conf.d/95proxies"
- with open(apt_conf, "w") as f:
- f.write(f'Acquire::http::Proxy "{proxy_url}";\n')
- f.write(f'Acquire::https::Proxy "{proxy_url}";\n')
- apt_bin = shutil.which("apt")
- dpkg_bin = shutil.which("dpkg")
- cp_bin = shutil.which("cp")
- chmod_bin = shutil.which("chmod")
- systemctl_bin = shutil.which("systemctl")
- if apt_bin:
- subprocess.run([apt_bin, "update"], env=apt_env) # noqa: S603
- if dpkg_bin:
- install = subprocess.run( # noqa: S603
- [dpkg_bin, "-i", "--force-overwrite", package_path]
- )
- if install.returncode != 0:
- logger.error("Error instalando el paquete")
- if apt_bin:
- subprocess.run([apt_bin, "install", "-f", "-y"], env=apt_env) # noqa: S603
- if cp_bin:
- subprocess.run([cp_bin, f"{os.getcwd()}/./utils/squid", "/etc/init.d/"]) # noqa: S603
- if chmod_bin:
- subprocess.run([chmod_bin, "+x", "/etc/init.d/squid"]) # noqa: S603
- if systemctl_bin:
- subprocess.run([systemctl_bin, "daemon-reload"]) # noqa: S603
- os.unlink(package_path)
- squid_bin_final = shutil.which("squid")
- if squid_bin_final:
- squid_check = subprocess.run( # noqa: S603
- [squid_bin_final, "-v"], capture_output=True, text=True
- )
- if squid_check.returncode != 0:
- logger.error("Error en instalación final")
- return False
- logger.info(f"Actualización a {latest_version} completada exitosamente")
- return True
- except Exception:
- logger.exception("Error crítico durante la actualización de Squid")
- return False
|