cache.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import base64
  2. import os
  3. import re
  4. import re as _re
  5. import socket
  6. from dotenv import load_dotenv
  7. from loguru import logger
  8. from config import Config
  9. # Load environment variables from .env file
  10. load_dotenv()
  11. SQUID_HOST = Config.SQUID_HOST
  12. SQUID_PORT = Config.SQUID_PORT
  13. SQUID_MGR_PASS = os.getenv("SQUID_MGR_PASS")
  14. def _manager_auth_header() -> str:
  15. """Return the Cache Manager Basic Auth header with trailing CRLF."""
  16. if not SQUID_MGR_PASS:
  17. return ""
  18. credentials = f":{SQUID_MGR_PASS}".encode()
  19. token = base64.b64encode(credentials).decode("ascii")
  20. return f"Authorization: Basic {token}\r\n"
  21. def fetch_squid_cache_stats():
  22. default_stats = {
  23. "store_entries": 0,
  24. "max_swap_size": 0,
  25. "current_swap_size": 0.0,
  26. "capacity_used": 0.0,
  27. "capacity_free": 100.0,
  28. "store_directory": "No disponible",
  29. "fs_block_size": 4096,
  30. "first_level_dirs": 0,
  31. "second_level_dirs": 0,
  32. "filemap_bits_used": 0,
  33. "filemap_bits_total": 0,
  34. "fs_space_used": 0,
  35. "fs_space_total": 0,
  36. "fs_inodes_used": 0,
  37. "fs_inodes_total": 0,
  38. "removal_policy": "lru",
  39. "lru_age_days": 0.0,
  40. "error": None,
  41. "connection_status": "connected",
  42. }
  43. try:
  44. auth_header = _manager_auth_header()
  45. requests_to_try = [
  46. (
  47. f"GET /squid-internal-mgr/storedir HTTP/1.1\r\n"
  48. f"Host: {SQUID_HOST}:{SQUID_PORT}\r\n"
  49. f"{auth_header}"
  50. "Connection: close\r\n\r\n"
  51. ),
  52. (
  53. f"GET /storedir HTTP/1.1\r\n"
  54. f"Host: {SQUID_HOST}\r\n"
  55. f"{auth_header}"
  56. "Connection: close\r\n\r\n"
  57. ),
  58. f"GET mgr:storedir HTTP/1.0\r\n{auth_header}\r\n",
  59. (
  60. "GET mgr:storedir HTTP/1.1\r\n"
  61. f"Host: {SQUID_HOST}\r\n"
  62. f"{auth_header}"
  63. "Connection: close\r\n\r\n"
  64. ),
  65. ]
  66. response = b""
  67. last_status = None
  68. for idx, request in enumerate(requests_to_try):
  69. try:
  70. with socket.create_connection((SQUID_HOST, SQUID_PORT), timeout=5) as s:
  71. s.sendall(request.encode())
  72. response = b""
  73. while chunk := s.recv(4096):
  74. response += chunk
  75. except (TimeoutError, ConnectionRefusedError, OSError) as conn_err:
  76. logger.debug(
  77. f"[cache] Connection attempt {idx + 1} failed: {type(conn_err).__name__}: {conn_err}"
  78. )
  79. # Host is unreachable — no point trying other request variants
  80. response = b""
  81. break
  82. except Exception as conn_err:
  83. logger.debug(f"[cache] Attempt {idx + 1} failed: {conn_err}")
  84. response = b""
  85. continue
  86. if not response:
  87. continue
  88. try:
  89. parts = _re.split(rb"\r\n\r\n|\n\n", response, maxsplit=1)
  90. headers_bytes = parts[0]
  91. body_bytes = parts[1] if len(parts) > 1 else b""
  92. headers_text = headers_bytes.decode("utf-8", errors="replace")
  93. first_line = (
  94. headers_text.splitlines()[0] if headers_text.splitlines() else ""
  95. )
  96. headers_lines = headers_text.splitlines()[1:]
  97. headers_dict = {}
  98. for line in headers_lines:
  99. if ":" in line:
  100. k, v = line.split(":", 1)
  101. headers_dict[k.strip().lower()] = v.strip()
  102. def _dechunk(b: bytes) -> bytes:
  103. out = bytearray()
  104. i = 0
  105. L = len(b)
  106. while i < L:
  107. j = b.find(b"\r\n", i)
  108. if j == -1:
  109. break
  110. line = b[i:j].strip()
  111. try:
  112. size = int(line.split(b";", 1)[0], 16)
  113. except Exception:
  114. break
  115. i = j + 2
  116. if size == 0:
  117. # fin de chunks
  118. break
  119. chunk = b[i : i + size]
  120. out.extend(chunk)
  121. i = i + size
  122. if b[i : i + 2] == b"\r\n":
  123. i += 2
  124. else:
  125. break
  126. return bytes(out)
  127. if (
  128. "transfer-encoding" in headers_dict
  129. and "chunked" in headers_dict.get("transfer-encoding", "")
  130. ):
  131. try:
  132. body_clean = _dechunk(body_bytes)
  133. data = body_clean.decode("utf-8", errors="replace")
  134. except Exception:
  135. data = body_bytes.decode("utf-8", errors="replace")
  136. else:
  137. data = body_bytes.decode("utf-8", errors="replace")
  138. http_status = None
  139. try:
  140. parts_status = first_line.split()
  141. if len(parts_status) >= 2 and parts_status[1].isdigit():
  142. http_status = int(parts_status[1])
  143. except Exception:
  144. http_status = None
  145. if (
  146. http_status == 400
  147. or " 400 " in first_line
  148. or "400 Bad" in first_line
  149. ):
  150. last_status = 400
  151. continue
  152. else:
  153. # éxito o otro código; usaremos esta respuesta
  154. last_status = http_status or 200
  155. default_stats["http_status"] = last_status
  156. default_stats["raw_response"] = response.decode(
  157. "utf-8", errors="replace"
  158. )
  159. break
  160. except Exception:
  161. logger.debug(
  162. f"[cache] Error decoding response on attempt {idx + 1}",
  163. exc_info=True,
  164. )
  165. response = b""
  166. continue
  167. # Si después de todos los intentos no tenemos datos, preparar error
  168. if not response:
  169. default_stats["error"] = (
  170. f"No response from {SQUID_HOST}:{SQUID_PORT} using tried request variants"
  171. )
  172. default_stats["connection_status"] = "no_response"
  173. return default_stats
  174. parsed_stats = parse_squid_cache_data(data)
  175. if parsed_stats and not parsed_stats.get("error"):
  176. default_stats.update(parsed_stats)
  177. default_stats["connection_status"] = "connected"
  178. else:
  179. # Si hubo error en el parsing, mantener defaults pero indicar el error
  180. default_stats["error"] = parsed_stats.get("error", "Error parsing data")
  181. default_stats["connection_status"] = "connected_but_parse_error"
  182. return default_stats
  183. except TimeoutError:
  184. default_stats["error"] = f"Timeout connecting to {SQUID_HOST}:{SQUID_PORT}"
  185. default_stats["connection_status"] = "timeout"
  186. return default_stats
  187. except ConnectionRefusedError:
  188. default_stats["error"] = f"Connection refused to {SQUID_HOST}:{SQUID_PORT}"
  189. default_stats["connection_status"] = "connection_refused"
  190. return default_stats
  191. except socket.gaierror:
  192. logger.exception("DNS resolution error when contacting Squid host")
  193. default_stats["error"] = "DNS resolution error"
  194. default_stats["connection_status"] = "dns_error"
  195. return default_stats
  196. except UnicodeDecodeError:
  197. default_stats["error"] = "Error decoding response from Squid"
  198. default_stats["connection_status"] = "decode_error"
  199. return default_stats
  200. except Exception:
  201. logger.exception("Unexpected error fetching cache stats")
  202. default_stats["error"] = "Unexpected error"
  203. default_stats["connection_status"] = "unknown_error"
  204. return default_stats
  205. def parse_squid_cache_data(data):
  206. stats = {}
  207. patterns = {
  208. "store_entries": r"Store Entries\s+: (\d+)",
  209. "max_swap_size": r"Maximum Swap Size\s+: (\d+) KB",
  210. "current_swap_size": r"Current Store Swap Size: ([\d\.]+) KB",
  211. "capacity_used": r"Current Capacity\s+: ([\d\.]+)% used",
  212. "capacity_free": r"Current Capacity\s+: [\d\.]+% used, ([\d\.]+)% free",
  213. "store_directory": r"Store Directory #\d+ \(.*\): (.+)",
  214. "fs_block_size": r"FS Block Size (\d+) Bytes",
  215. "first_level_dirs": r"First level subdirectories: (\d+)",
  216. "second_level_dirs": r"Second level subdirectories: (\d+)",
  217. "filemap_bits_used": r"Filemap bits in use: (\d+) of (\d+)",
  218. "filemap_bits_total": r"Filemap bits in use: \d+ of (\d+)",
  219. "fs_space_used": r"Filesystem Space in use: (\d+)/(\d+) KB",
  220. "fs_space_total": r"Filesystem Space in use: \d+/(\d+) KB",
  221. "fs_inodes_used": r"Filesystem Inodes in use: (\d+)/(\d+)",
  222. "fs_inodes_total": r"Filesystem Inodes in use: \d+/(\d+)",
  223. "removal_policy": r"Removal policy: (\w+)",
  224. "lru_age_days": r"LRU reference age: ([\d\.]+) days",
  225. }
  226. for key, pattern in patterns.items():
  227. match = re.search(pattern, data)
  228. if match:
  229. stats[key] = (
  230. match.group(1) if key != "current_swap_size" else float(match.group(1))
  231. )
  232. # Robustecer: asegurar que todas las claves esperadas existan, con valor 0 o None si no se encontraron
  233. defaults = {
  234. "store_entries": 0,
  235. "max_swap_size": 0,
  236. "current_swap_size": 0.0,
  237. "capacity_used": 0.0,
  238. "capacity_free": 0.0,
  239. "store_directory": None,
  240. "fs_block_size": 0,
  241. "first_level_dirs": 0,
  242. "second_level_dirs": 0,
  243. "filemap_bits_used": 0,
  244. "filemap_bits_total": 0,
  245. "fs_space_used": 0,
  246. "fs_space_total": 0,
  247. "fs_inodes_used": 0,
  248. "fs_inodes_total": 0,
  249. "removal_policy": None,
  250. "lru_age_days": 0.0,
  251. }
  252. for key, default in defaults.items():
  253. if key not in stats or stats[key] is None:
  254. stats[key] = default
  255. for key in [
  256. "store_entries",
  257. "max_swap_size",
  258. "fs_block_size",
  259. "first_level_dirs",
  260. "second_level_dirs",
  261. "filemap_bits_used",
  262. "filemap_bits_total",
  263. "fs_space_used",
  264. "fs_space_total",
  265. "fs_inodes_used",
  266. "fs_inodes_total",
  267. ]:
  268. try:
  269. stats[key] = int(stats[key])
  270. except (ValueError, TypeError):
  271. stats[key] = 0
  272. for key in ["current_swap_size", "capacity_used", "capacity_free", "lru_age_days"]:
  273. try:
  274. stats[key] = float(stats[key])
  275. except (ValueError, TypeError):
  276. stats[key] = 0.0
  277. return stats