cache.py 11 KB

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