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