4
0

system_service.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import shutil
  2. import subprocess # nosec B404
  3. from loguru import logger
  4. DOCKER_CONTAINER_NAME = "squid_proxy"
  5. def _get_bin(name: str) -> str | None:
  6. """Return the absolute path of *name* in PATH, or None if not found."""
  7. return shutil.which(name)
  8. def _docker_container_exists(docker_bin: str, container_name: str) -> bool:
  9. try:
  10. result = subprocess.run( # nosec B603 # noqa: S603
  11. [
  12. docker_bin,
  13. "ps",
  14. "--filter",
  15. f"name=^{container_name}$",
  16. "--format",
  17. "{{.Names}}",
  18. ],
  19. check=True,
  20. capture_output=True,
  21. text=True,
  22. timeout=30,
  23. )
  24. return container_name in result.stdout.splitlines()
  25. except subprocess.CalledProcessError as e:
  26. logger.warning(
  27. "docker ps falló al verificar el contenedor %s: %s", container_name, e
  28. )
  29. return False
  30. except Exception as e:
  31. logger.exception(
  32. "Error verificando contenedor Docker %s: %s", container_name, e
  33. )
  34. return False
  35. def _docker_reconfigure() -> tuple[bool, str]:
  36. docker_bin = _get_bin("docker")
  37. if docker_bin is None:
  38. return False, "Docker no encontrado"
  39. if not _docker_container_exists(docker_bin, DOCKER_CONTAINER_NAME):
  40. return False, f"Contenedor {DOCKER_CONTAINER_NAME} no encontrado"
  41. try:
  42. subprocess.run( # nosec B603 # noqa: S603
  43. [docker_bin, "exec", DOCKER_CONTAINER_NAME, "squid", "-k", "reconfigure"],
  44. check=True,
  45. capture_output=True,
  46. text=True,
  47. timeout=30,
  48. )
  49. return (
  50. True,
  51. "Squid reconfigure a través de docker exec squid_proxy squid -k reconfigure",
  52. )
  53. except subprocess.CalledProcessError as e:
  54. logger.warning("docker reconfigure falló con estado %s: %s", e.returncode, e)
  55. return False, str(e)
  56. except Exception as e:
  57. logger.exception("Error ejecutando reconfigure en Docker: %s", e)
  58. return False, str(e)
  59. def _docker_restart() -> tuple[bool, str]:
  60. docker_bin = _get_bin("docker")
  61. if docker_bin is None:
  62. return False, "Docker no encontrado"
  63. if not _docker_container_exists(docker_bin, DOCKER_CONTAINER_NAME):
  64. return False, f"Contenedor {DOCKER_CONTAINER_NAME} no encontrado"
  65. try:
  66. subprocess.run( # nosec B603 # noqa: S603
  67. [docker_bin, "restart", DOCKER_CONTAINER_NAME],
  68. check=True,
  69. capture_output=True,
  70. text=True,
  71. timeout=30,
  72. )
  73. return (
  74. True,
  75. f"Squid Docker container '{DOCKER_CONTAINER_NAME}' restarted successfully",
  76. )
  77. except subprocess.CalledProcessError as e:
  78. logger.warning("docker restart falló con estado %s: %s", e.returncode, e)
  79. return False, str(e)
  80. except Exception as e:
  81. logger.exception("Error reiniciando contenedor Docker: %s", e)
  82. return False, str(e)
  83. def _local_reconfigure() -> tuple[bool, str]:
  84. squid_bin = _get_bin("squid")
  85. if squid_bin is None:
  86. return False, "Squid no encontrado"
  87. try:
  88. subprocess.run( # nosec B603 # noqa: S603
  89. [squid_bin, "-k", "reconfigure"],
  90. check=True,
  91. capture_output=True,
  92. text=True,
  93. timeout=30,
  94. )
  95. return True, "Squid reconfigure a través de squid -k reconfigure (local)"
  96. except subprocess.CalledProcessError as e:
  97. logger.warning(
  98. "Local squid reconfigure falló con estado %s: %s", e.returncode, e
  99. )
  100. return False, str(e)
  101. except FileNotFoundError as e:
  102. logger.warning("Squid no encontrado: %s", e)
  103. return False, str(e)
  104. except Exception as e:
  105. logger.exception("Error ejecutando reconfigure local: %s", e)
  106. return False, str(e)
  107. def restart_squid() -> tuple[bool, str, str]:
  108. systemctl_bin = _get_bin("systemctl")
  109. if systemctl_bin:
  110. try:
  111. subprocess.run([systemctl_bin, "restart", "squid"], check=True) # nosec B603 # noqa: S603
  112. return True, "Squid restarted successfully", None
  113. except subprocess.CalledProcessError as e:
  114. logger.warning(
  115. "systemctl restart squid falló con estado %s: %s", e.returncode, e
  116. )
  117. except Exception as e:
  118. logger.warning("Error systemctl restart squid: %s", e)
  119. # Fallback Docker si existe, y luego local.
  120. success, msg = _docker_restart()
  121. if success:
  122. return True, msg, None
  123. success, msg = _docker_reconfigure()
  124. if success:
  125. return True, msg, None
  126. success, msg = _local_reconfigure()
  127. if success:
  128. return True, msg, None
  129. return False, "Internal server error", None
  130. def reload_squid() -> tuple[bool, str, str]:
  131. systemctl_bin = _get_bin("systemctl")
  132. if systemctl_bin:
  133. try:
  134. subprocess.run([systemctl_bin, "reload", "squid"], check=True) # nosec B603 # noqa: S603
  135. return True, "Configuration reloaded successfully", None
  136. except subprocess.CalledProcessError as e:
  137. logger.warning(
  138. "systemctl reload squid falló con estado %s: %s", e.returncode, e
  139. )
  140. except Exception as e:
  141. logger.warning("Error systemctl reload squid: %s", e)
  142. # Fallback Docker si existe, y luego local.
  143. success, msg = _docker_reconfigure()
  144. if success:
  145. return True, msg, None
  146. success, msg = _local_reconfigure()
  147. if success:
  148. return True, msg, None
  149. return False, "Internal server error", None