squid_info.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import base64
  2. import os
  3. import re
  4. import socket
  5. from datetime import datetime
  6. from dotenv import load_dotenv
  7. from loguru import logger
  8. from config import Config
  9. load_dotenv()
  10. SQUID_HOST = Config.SQUID_HOST
  11. SQUID_PORT = Config.SQUID_PORT
  12. SQUID_MGR_PASS = os.getenv("SQUID_MGR_PASS")
  13. _SQUID_DATE_FMT = "%a, %d %b %Y %H:%M:%S %Z"
  14. def _manager_auth_header() -> str:
  15. """Return the Cache Manager Basic Auth header when a password is set."""
  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}"
  21. def _parse_squid_date(line: str) -> datetime:
  22. stamp = line.split(":", 1)[1].strip()
  23. return datetime.strptime(stamp, _SQUID_DATE_FMT)
  24. def _re_float(key: str, text: str, default=0.0):
  25. m = re.search(rf"{re.escape(key)}\s*:\s*([0-9.]+)", text)
  26. return float(m.group(1)) if m else default
  27. def _re_int(key: str, text: str, default=0):
  28. return int(_re_float(key, text, default))
  29. def _format_host_header(host: str, port: int) -> str:
  30. # Bracket IPv6 literals
  31. if ":" in host and not host.startswith("["):
  32. return f"[{host}]:{port}"
  33. return f"{host}:{port}"
  34. def _send_http_request(host: str, port: int, request: str, timeout: float = 5.0) -> str:
  35. with socket.create_connection((host, port), timeout=timeout) as s:
  36. s.sendall(request.encode("utf-8"))
  37. response = b""
  38. while True:
  39. chunk = s.recv(4096)
  40. if not chunk:
  41. break
  42. response += chunk
  43. return response.decode("utf-8", errors="replace")
  44. def fetch_squid_info_stats():
  45. default_stats = {
  46. "start_time": None,
  47. "current_time": None,
  48. "elapsed_hours": 0.0,
  49. "clients": 0,
  50. "requests_received": 0,
  51. "avg_requests_per_minute": 0.0,
  52. "median_service_times": {
  53. "http_requests_5m": 0.0,
  54. "http_requests_60m": 0.0,
  55. "cache_misses_5m": 0.0,
  56. "cache_misses_60m": 0.0,
  57. "cache_hits_5m": 0.0,
  58. "cache_hits_60m": 0.0,
  59. "near_hits_5m": 0.0,
  60. "near_hits_60m": 0.0,
  61. "not_modified_replies_5m": 0.0,
  62. "not_modified_replies_60m": 0.0,
  63. "dns_lookups_5m": 0.0,
  64. "dns_lookups_60m": 0.0,
  65. "icp_queries_5m": 0.0,
  66. "icp_queries_60m": 0.0,
  67. },
  68. "resource_usage": {
  69. "up_time_seconds": 0.0,
  70. "cpu_time_seconds": 0.0,
  71. "cpu_usage_percent": 0.0,
  72. "cpu_usage_5min": 0.0,
  73. "cpu_usage_60min": 0.0,
  74. "max_rss_kb": 0,
  75. "page_faults_io": 0,
  76. },
  77. "error": None,
  78. "connection_status": "connected",
  79. }
  80. try:
  81. host_header = _format_host_header(SQUID_HOST, int(SQUID_PORT))
  82. headers = [
  83. f"Host: {host_header}",
  84. "User-Agent: SquidStats/1.0",
  85. "Accept: */*",
  86. "Connection: close",
  87. ]
  88. auth_header = _manager_auth_header()
  89. if auth_header:
  90. headers.append(auth_header)
  91. modern_req = (
  92. "GET /squid-internal-mgr/info HTTP/1.1\r\n"
  93. + "\r\n".join(headers)
  94. + "\r\n\r\n"
  95. )
  96. response_text = _send_http_request(
  97. SQUID_HOST, int(SQUID_PORT), modern_req, timeout=5.0
  98. )
  99. parts = response_text.split("\r\n\r\n", 1)
  100. data = parts[1] if len(parts) > 1 else response_text
  101. except Exception as e:
  102. if isinstance(e, (TimeoutError, ConnectionRefusedError, socket.gaierror)):
  103. logger.warning(
  104. f"Could not reach Squid at {SQUID_HOST}:{SQUID_PORT}: {type(e).__name__}: {e}"
  105. )
  106. else:
  107. logger.exception("Error fetching squid info stats")
  108. default_stats["error"] = "Error obteniendo información de Squid"
  109. if isinstance(e, TimeoutError):
  110. default_stats["connection_status"] = "timeout"
  111. elif isinstance(e, ConnectionRefusedError):
  112. default_stats["connection_status"] = "connection_refused"
  113. elif isinstance(e, socket.gaierror):
  114. default_stats["connection_status"] = "dns_error"
  115. else:
  116. default_stats["connection_status"] = "unknown_error"
  117. return default_stats
  118. try:
  119. start_line = next(
  120. line for line in data.splitlines() if line.startswith("Start Time:")
  121. )
  122. current_line = next(
  123. line for line in data.splitlines() if line.startswith("Current Time:")
  124. )
  125. start_dt = _parse_squid_date(start_line)
  126. current_dt = _parse_squid_date(current_line)
  127. elapsed = current_dt - start_dt
  128. elapsed_hours = elapsed.total_seconds() / 3600
  129. clients = _re_int("Number of clients accessing cache", data)
  130. requests = _re_int("Number of HTTP requests received", data)
  131. avg_rpm = _re_float("Average HTTP requests per minute since start", data)
  132. m = re.search(r"HTTP Requests \(All\):\s+([\d.]+)\s+([\d.]+)", data)
  133. http_5m, http_60m = (float(x) for x in m.groups()) if m else (0, 0)
  134. m = re.search(r"Cache Misses:\s+([\d.]+)\s+([\d.]+)", data)
  135. miss_5m, miss_60m = (float(x) for x in m.groups()) if m else (0, 0)
  136. m = re.search(r"Cache Hits:\s+([\d.]+)\s+([\d.]+)", data)
  137. hit_5m, hit_60m = (float(x) for x in m.groups()) if m else (0, 0)
  138. m = re.search(r"Near Hits:\s+([\d.]+)\s+([\d.]+)", data)
  139. near_5m, near_60m = (float(x) for x in m.groups()) if m else (0, 0)
  140. m = re.search(r"Not-Modified Replies:\s+([\d.]+)\s+([\d.]+)", data)
  141. nmod_5m, nmod_60m = (float(x) for x in m.groups()) if m else (0, 0)
  142. m = re.search(r"DNS Lookups:\s+([\d.]+)\s+([\d.]+)", data)
  143. dns_5m, dns_60m = (float(x) for x in m.groups()) if m else (0, 0)
  144. m = re.search(r"ICP Queries:\s+([\d.]+)\s+([\d.]+)", data)
  145. icp_5m, icp_60m = (float(x) for x in m.groups()) if m else (0, 0)
  146. up_time = _re_float("UP Time", data)
  147. cpu_time = _re_float("CPU Time", data)
  148. cpu_use = _re_float("CPU Usage", data)
  149. cpu_5m = _re_float("CPU Usage, 5 minute avg", data)
  150. cpu_60m = _re_float("CPU Usage, 60 minute avg", data)
  151. max_rss = _re_int("Maximum Resident Size", data)
  152. page_faults = _re_int("Page faults with physical i/o", data)
  153. default_stats.update(
  154. {
  155. "start_time": start_dt,
  156. "current_time": current_dt,
  157. "elapsed_hours": round(elapsed_hours, 2),
  158. "clients": clients,
  159. "requests_received": requests,
  160. "avg_requests_per_minute": avg_rpm,
  161. "median_service_times": {
  162. "http_requests_5m": http_5m,
  163. "http_requests_60m": http_60m,
  164. "cache_misses_5m": miss_5m,
  165. "cache_misses_60m": miss_60m,
  166. "cache_hits_5m": hit_5m,
  167. "cache_hits_60m": hit_60m,
  168. "near_hits_5m": near_5m,
  169. "near_hits_60m": near_60m,
  170. "not_modified_replies_5m": nmod_5m,
  171. "not_modified_replies_60m": nmod_60m,
  172. "dns_lookups_5m": dns_5m,
  173. "dns_lookups_60m": dns_60m,
  174. "icp_queries_5m": icp_5m,
  175. "icp_queries_60m": icp_60m,
  176. },
  177. "resource_usage": {
  178. "up_time_seconds": up_time,
  179. "cpu_time_seconds": cpu_time,
  180. "cpu_usage_percent": cpu_use,
  181. "cpu_usage_5min": cpu_5m,
  182. "cpu_usage_60min": cpu_60m,
  183. "max_rss_kb": max_rss,
  184. "page_faults_io": page_faults,
  185. },
  186. }
  187. )
  188. return default_stats
  189. except Exception as e:
  190. default_stats["error"] = f"Parsing error: {e}"
  191. default_stats["connection_status"] = "connected_but_parse_error"
  192. return default_stats