admin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import logging
  2. import os
  3. from dotenv import load_dotenv
  4. # Configurar logging para este módulo
  5. logger = logging.getLogger(__name__)
  6. load_dotenv()
  7. SQUID_CONFIG_PATH = os.getenv("SQUID_CONFIG_PATH", "/etc/squid/squid.conf")
  8. ACL_FILES_DIR = os.getenv("ACL_FILES_DIR", "/etc/squid/acls")
  9. def validate_paths():
  10. errors = []
  11. # Verificar archivo de configuración
  12. if not os.path.exists(SQUID_CONFIG_PATH):
  13. errors.append(f"Configuration file not found: {SQUID_CONFIG_PATH}")
  14. elif not os.access(SQUID_CONFIG_PATH, os.R_OK):
  15. errors.append(f"No read permissions for: {SQUID_CONFIG_PATH}")
  16. elif not os.access(SQUID_CONFIG_PATH, os.W_OK):
  17. errors.append(f"No write permissions for: {SQUID_CONFIG_PATH}")
  18. # Verificar directorio de backups
  19. """ if not os.path.exists(BACKUP_DIR):
  20. errors.append(f"Backup directory not found: {BACKUP_DIR}")
  21. elif not os.access(BACKUP_DIR, os.W_OK):
  22. errors.append(f"No write permissions in backup directory: {BACKUP_DIR}") """
  23. # Verificar directorio de ACLs
  24. if not os.path.exists(ACL_FILES_DIR):
  25. errors.append(f"ACL directory not found: {ACL_FILES_DIR}")
  26. elif not os.access(ACL_FILES_DIR, os.W_OK):
  27. errors.append(f"No write permissions in ACL directory: {ACL_FILES_DIR}")
  28. return errors
  29. class SquidConfigManager:
  30. def __init__(self, config_path=SQUID_CONFIG_PATH):
  31. self.config_path = config_path
  32. self.config_content = ""
  33. self.is_valid = False
  34. self.errors = []
  35. # Validar entorno antes de cargar
  36. self._validate_environment()
  37. # Solo cargar si no hay errores críticos
  38. if self.is_valid:
  39. self.load_config()
  40. def _validate_environment(self):
  41. self.errors = validate_paths()
  42. if self.errors:
  43. for error in self.errors:
  44. logger.error(error)
  45. self.is_valid = False
  46. logger.error(
  47. "SquidConfigManager cannot be initialized due to configuration errors"
  48. )
  49. else:
  50. self.is_valid = True
  51. logger.info("SquidConfigManager initialized successfully")
  52. def load_config(self):
  53. if not self.is_valid:
  54. logger.error("Cannot load configuration: invalid environment")
  55. return False
  56. try:
  57. with open(self.config_path, encoding="utf-8") as f:
  58. self.config_content = f.read()
  59. logger.debug(f"Configuration loaded from: {self.config_path}")
  60. return True
  61. except FileNotFoundError:
  62. logger.error(f"Configuration file not found: {self.config_path}")
  63. self.config_content = ""
  64. return False
  65. except PermissionError:
  66. logger.error(f"No read permissions for: {self.config_path}")
  67. self.config_content = ""
  68. return False
  69. except UnicodeDecodeError as e:
  70. logger.error(f"File encoding error: {e}")
  71. self.config_content = ""
  72. return False
  73. except Exception as e:
  74. logger.error(f"Unexpected error loading configuration: {e}")
  75. self.config_content = ""
  76. return False
  77. def save_config(self, content):
  78. if not self.is_valid:
  79. logger.error("Cannot save configuration: invalid environment")
  80. return False
  81. try:
  82. # Intentar crear backup antes de guardar
  83. backup_created = self.create_backup()
  84. if not backup_created:
  85. logger.warning("Could not create backup, but continuing with save...")
  86. # Guardar nueva configuración
  87. with open(self.config_path, "w", encoding="utf-8") as f:
  88. f.write(content)
  89. self.config_content = content
  90. logger.info(f"Configuration saved successfully to: {self.config_path}")
  91. return True
  92. except PermissionError:
  93. logger.error(f"No write permissions for: {self.config_path}")
  94. return False
  95. except OSError as e:
  96. logger.error(f"System error saving configuration: {e}")
  97. return False
  98. except Exception as e:
  99. logger.error(f"Unexpected error saving configuration: {e}")
  100. return False
  101. def create_backup(self):
  102. if not self.is_valid:
  103. logger.error("Cannot create backup: invalid environment")
  104. return False
  105. """ try:
  106. # Verificar que el directorio de backup existe
  107. if not os.path.exists(BACKUP_DIR):
  108. logger.error(f"Backup directory does not exist: {BACKUP_DIR}")
  109. return False
  110. # Verificar permisos de escritura
  111. if not os.access(BACKUP_DIR, os.W_OK):
  112. logger.error(f"No write permissions in backup directory: {BACKUP_DIR}")
  113. return False
  114. # Verificar que el archivo fuente existe
  115. if not os.path.exists(self.config_path):
  116. logger.warning("No configuration file exists to backup")
  117. return False
  118. # Crear backup con timestamp
  119. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  120. backup_filename = f"squid.conf.backup_{timestamp}"
  121. backup_path = os.path.join(BACKUP_DIR, backup_filename)
  122. shutil.copy2(self.config_path, backup_path)
  123. logger.info(f"Backup created: {backup_path}")
  124. return True
  125. except PermissionError:
  126. logger.error(f"No permissions to create backup in: {BACKUP_DIR}")
  127. return False
  128. except OSError as e:
  129. logger.error(f"System error creating backup: {e}")
  130. return False
  131. except Exception as e:
  132. logger.error(f"Unexpected error creating backup: {e}")
  133. return False """
  134. def get_acls(self):
  135. if not self.is_valid:
  136. logger.error("Cannot get ACLs: invalid environment")
  137. return []
  138. if not self.config_content:
  139. logger.warning("No configuration content available")
  140. return []
  141. try:
  142. acls = []
  143. lines = self.config_content.split("\n")
  144. acl_index = 0
  145. for line_num, line in enumerate(lines, 1):
  146. try:
  147. line = line.strip()
  148. if line.startswith("acl ") and not line.startswith("#"):
  149. parts = line.split()
  150. if len(parts) >= 3:
  151. acl_name = parts[1]
  152. acl_type = parts[2]
  153. acl_value = " ".join(parts[3:]) if len(parts) > 3 else ""
  154. acls.append(
  155. {
  156. "id": acl_index,
  157. "name": acl_name,
  158. "type": acl_type,
  159. "value": acl_value,
  160. "full_line": line,
  161. }
  162. )
  163. acl_index += 1
  164. except Exception as e:
  165. logger.warning(f"Error processing ACL at line {line_num}: {e}")
  166. continue
  167. logger.debug(f"Found {len(acls)} ACLs")
  168. return acls
  169. except Exception as e:
  170. logger.error(f"Unexpected error extracting ACLs: {e}")
  171. return []
  172. def get_delay_pools(self):
  173. if not self.is_valid:
  174. logger.error("Cannot get delay pools: invalid environment")
  175. return []
  176. if not self.config_content:
  177. logger.warning("No configuration content available")
  178. return []
  179. try:
  180. delay_pools = []
  181. lines = self.config_content.split("\n")
  182. for line_num, line in enumerate(lines, 1):
  183. try:
  184. line = line.strip()
  185. if line.startswith("delay_pools "):
  186. parts = line.split()
  187. if len(parts) >= 2:
  188. delay_pools.append(
  189. {"directive": "delay_pools", "value": parts[1]}
  190. )
  191. elif line.startswith("delay_class "):
  192. parts = line.split()
  193. if len(parts) >= 3:
  194. delay_pools.append(
  195. {
  196. "directive": "delay_class",
  197. "pool": parts[1],
  198. "class": parts[2],
  199. }
  200. )
  201. elif line.startswith("delay_parameters "):
  202. parts = line.split()
  203. if len(parts) >= 3:
  204. delay_pools.append(
  205. {
  206. "directive": "delay_parameters",
  207. "pool": parts[1],
  208. "parameters": " ".join(parts[2:]),
  209. }
  210. )
  211. elif line.startswith("delay_access "):
  212. parts = line.split()
  213. if len(parts) >= 4:
  214. delay_pools.append(
  215. {
  216. "directive": "delay_access",
  217. "pool": parts[1],
  218. "action": parts[2],
  219. "acl": " ".join(parts[3:]),
  220. }
  221. )
  222. except Exception as e:
  223. logger.warning(
  224. f"Error processing delay pool at line {line_num}: {e}"
  225. )
  226. continue
  227. logger.debug(f"Found {len(delay_pools)} delay pool configurations")
  228. return delay_pools
  229. except Exception as e:
  230. logger.error(f"Unexpected error extracting delay pools: {e}")
  231. return []
  232. def get_http_access_rules(self):
  233. if not self.is_valid:
  234. logger.error("Cannot get HTTP rules: invalid environment")
  235. return []
  236. if not self.config_content:
  237. logger.warning("No configuration content available")
  238. return []
  239. try:
  240. rules = []
  241. lines = self.config_content.split("\n")
  242. for line_num, line in enumerate(lines, 1):
  243. try:
  244. line = line.strip()
  245. if line.startswith("http_access ") and not line.startswith("#"):
  246. parts = line.split()
  247. if len(parts) >= 3:
  248. rules.append(
  249. {"action": parts[1], "acl": " ".join(parts[2:])}
  250. )
  251. except Exception as e:
  252. logger.warning(
  253. f"Error processing HTTP rule at line {line_num}: {e}"
  254. )
  255. continue
  256. logger.debug(f"Found {len(rules)} HTTP access rules")
  257. return rules
  258. except Exception as e:
  259. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  260. return []
  261. def get_status(self):
  262. return {
  263. "is_valid": self.is_valid,
  264. "errors": self.errors,
  265. "config_loaded": bool(self.config_content),
  266. "config_path": self.config_path,
  267. # "backup_dir": BACKUP_DIR,
  268. "acl_files_dir": ACL_FILES_DIR,
  269. }