updateSquidStats.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import os
  2. import shutil
  3. import subprocess
  4. import tempfile
  5. import requests
  6. from dotenv import load_dotenv
  7. from loguru import logger
  8. load_dotenv()
  9. _DEB_INSTALL_PATHS = {"/opt/SquidStats/app", "/usr/share/squidstats"}
  10. def is_deb_installation() -> bool:
  11. """Return True when the app is running from a .deb-managed installation path."""
  12. install_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  13. return install_dir in _DEB_INSTALL_PATHS
  14. def _get_git_binary():
  15. git_bin = shutil.which("git")
  16. if not git_bin:
  17. logger.error("git executable not found on PATH")
  18. return git_bin
  19. def _run_git_command(args, cwd, env, capture_output=True, timeout=120):
  20. git_bin = _get_git_binary()
  21. if not git_bin:
  22. return subprocess.CompletedProcess(
  23. ["git", *args], 1, "", "git executable not found"
  24. )
  25. return subprocess.run( # noqa: S603
  26. [git_bin, *args],
  27. cwd=cwd,
  28. env=env,
  29. stdout=subprocess.PIPE if capture_output else None,
  30. stderr=subprocess.PIPE if capture_output else None,
  31. text=True,
  32. timeout=timeout,
  33. )
  34. def _repo_has_head(install_dir, env):
  35. result = _run_git_command(["rev-parse", "--verify", "HEAD"], install_dir, env)
  36. return result.returncode == 0
  37. def _detect_remote_branch(install_dir, env):
  38. for branch in ("main", "master"):
  39. result = _run_git_command(
  40. ["ls-remote", "--heads", "origin", branch], install_dir, env
  41. )
  42. if result.returncode == 0 and result.stdout.strip():
  43. return branch
  44. return None
  45. def _prepare_deb_git_repo(install_dir, env):
  46. git_dir = os.path.join(install_dir, ".git")
  47. repo_initialized = False
  48. if not os.path.isdir(git_dir):
  49. logger.info(
  50. "Initializing git repository in deb-installed path: %s", install_dir
  51. )
  52. result = _run_git_command(["init"], install_dir, env)
  53. if result.returncode != 0:
  54. logger.error(
  55. "Failed to initialize git repository: %s", result.stderr.strip()
  56. )
  57. return False
  58. repo_initialized = True
  59. result = _run_git_command(["remote", "get-url", "origin"], install_dir, env)
  60. origin_url = result.stdout.strip() if result.returncode == 0 else None
  61. if origin_url != "https://github.com/kaelthasmanu/SquidStats.git":
  62. if origin_url:
  63. logger.info(
  64. "Updating git origin remote URL from %s to %s",
  65. origin_url,
  66. "https://github.com/kaelthasmanu/SquidStats.git",
  67. )
  68. result = _run_git_command(
  69. [
  70. "remote",
  71. "set-url",
  72. "origin",
  73. "https://github.com/kaelthasmanu/SquidStats.git",
  74. ],
  75. install_dir,
  76. env,
  77. )
  78. else:
  79. logger.info(
  80. "Adding git origin remote: %s",
  81. "https://github.com/kaelthasmanu/SquidStats.git",
  82. )
  83. result = _run_git_command(
  84. [
  85. "remote",
  86. "add",
  87. "origin",
  88. "https://github.com/kaelthasmanu/SquidStats.git",
  89. ],
  90. install_dir,
  91. env,
  92. )
  93. if result.returncode != 0:
  94. logger.error(
  95. "Failed to configure git origin remote: %s", result.stderr.strip()
  96. )
  97. return False
  98. result = _run_git_command(["fetch", "--tags", "origin"], install_dir, env)
  99. if result.returncode != 0:
  100. logger.error("Failed to fetch from origin: %s", result.stderr.strip())
  101. return False
  102. branch = _detect_remote_branch(install_dir, env)
  103. if not branch:
  104. logger.error("No supported remote branch found on origin")
  105. return False
  106. if repo_initialized or not _repo_has_head(install_dir, env):
  107. logger.info("Checking out branch %s from origin", branch)
  108. result = _run_git_command(
  109. ["checkout", "-B", branch, f"origin/{branch}"], install_dir, env
  110. )
  111. if result.returncode != 0:
  112. logger.error(
  113. "Failed to checkout branch %s from origin: %s",
  114. branch,
  115. result.stderr.strip(),
  116. )
  117. return False
  118. return True
  119. def _update_deb_installation(install_dir, env):
  120. if not _prepare_deb_git_repo(install_dir, env):
  121. return False
  122. branch = _detect_remote_branch(install_dir, env)
  123. if not branch:
  124. return False
  125. result = _run_git_command(["pull", "--ff-only", "origin", branch], install_dir, env)
  126. if result.returncode == 0:
  127. logger.info("Git pull succeeded on deb installation")
  128. return True
  129. status = _run_git_command(["status", "--porcelain"], install_dir, env)
  130. if status.returncode == 0 and status.stdout.strip():
  131. logger.error(
  132. "Git pull failed because the working tree has modified files:\n%s",
  133. status.stdout.strip(),
  134. )
  135. else:
  136. logger.error(
  137. "Git pull failed: %s",
  138. result.stderr.strip() or result.stdout.strip(),
  139. )
  140. return False
  141. def updateSquidStats():
  142. logger.info("Starting SquidStats web update process")
  143. install_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  144. env = os.environ.copy()
  145. proxy_url = os.getenv("HTTP_PROXY", "")
  146. https_proxy_url = os.getenv("HTTPS_PROXY", proxy_url)
  147. if proxy_url:
  148. logger.debug("HTTP proxy configured")
  149. env["http_proxy"] = proxy_url
  150. if https_proxy_url:
  151. logger.debug("HTTPS proxy configured")
  152. env["https_proxy"] = https_proxy_url
  153. if is_deb_installation():
  154. logger.info("Detected deb-installed SquidStats; updating via git pull")
  155. return _update_deb_installation(install_dir, env)
  156. if not os.path.isdir(os.path.join(install_dir, ".git")):
  157. logger.error(
  158. "No git repository found in %s. Cannot perform automatic update.",
  159. install_dir,
  160. )
  161. return False
  162. try:
  163. proxies = None
  164. if proxy_url or https_proxy_url:
  165. proxies = {
  166. "http": proxy_url or None,
  167. "https": https_proxy_url or None,
  168. }
  169. try:
  170. # Fetch the latest release tag from GitHub API to always use the current version
  171. api_response = requests.get(
  172. "https://api.github.com/repos/kaelthasmanu/SquidStats/releases/latest",
  173. proxies=proxies,
  174. timeout=30,
  175. )
  176. api_response.raise_for_status()
  177. latest_tag = api_response.json().get("tag_name", "")
  178. if not latest_tag:
  179. logger.error("No se pudo obtener la última versión desde GitHub API")
  180. return False
  181. logger.info(f"Latest release tag resolved: {latest_tag}")
  182. script_url = f"https://github.com/kaelthasmanu/SquidStats/releases/download/{latest_tag}/install.sh"
  183. logger.info(f"Downloading update script from {script_url}")
  184. response = requests.get(
  185. script_url,
  186. proxies=proxies,
  187. timeout=30,
  188. )
  189. response.raise_for_status()
  190. sh_bin = "/bin/sh" if os.path.exists("/bin/sh") else shutil.which("sh")
  191. if not sh_bin:
  192. logger.error("sh no encontrado en el sistema")
  193. return False
  194. with tempfile.NamedTemporaryFile(delete=False, suffix=".sh") as tmp_script:
  195. tmp_script.write(response.content)
  196. tmp_script_path = tmp_script.name
  197. logger.debug(f"Written update script to temporary file: {tmp_script_path}")
  198. os.chmod(tmp_script_path, 0o700)
  199. args = [sh_bin, tmp_script_path, "--update"]
  200. logger.info(f"Executing update script with command: {args}")
  201. try:
  202. # The external update script is downloaded from the official GitHub
  203. # release feed, then written to a temporary file and executed.
  204. # This is intentionally executing remote installer content.
  205. subprocess.run(args, env=env, check=True, timeout=600) # noqa: S603
  206. logger.info("Update script executed successfully")
  207. finally:
  208. try:
  209. os.remove(tmp_script_path)
  210. except OSError:
  211. logger.warning(
  212. f"Unable to remove temporary update script: {tmp_script_path}"
  213. )
  214. return True
  215. except Exception:
  216. logger.exception("Error descargando el script de actualización")
  217. return False
  218. except Exception:
  219. logger.exception("Error crítico en updateSquidStats")
  220. return False