cache.py 11 KB

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