fetch_data.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import base64
  2. import os
  3. import socket
  4. from concurrent.futures import ThreadPoolExecutor, as_completed
  5. from dotenv import load_dotenv
  6. from loguru import logger
  7. from config import Config
  8. load_dotenv()
  9. SQUID_HOST = Config.SQUID_HOST
  10. SQUID_PORT = Config.SQUID_PORT
  11. SQUID_MGR_USER = os.getenv("SQUID_MGR_USER")
  12. SQUID_MGR_PASS = os.getenv("SQUID_MGR_PASS")
  13. def get_squid_hosts() -> list[tuple[str, int]]:
  14. """Return list of (host, port) for all configured Squid proxies.
  15. Uses SQUID_HOSTS (comma-separated host:port) when available, otherwise
  16. falls back to the single SQUID_HOST / SQUID_PORT.
  17. """
  18. if Config.SQUID_HOSTS:
  19. result = []
  20. for entry in Config.SQUID_HOSTS:
  21. entry = entry.strip()
  22. if not entry:
  23. continue
  24. if ":" in entry:
  25. # handle IPv6 like [::1]:3128
  26. if entry.startswith("["):
  27. bracket_end = entry.rfind("]")
  28. host = entry[1:bracket_end]
  29. port = (
  30. int(entry[bracket_end + 2 :])
  31. if bracket_end + 2 < len(entry)
  32. else 3128
  33. )
  34. else:
  35. last_colon = entry.rfind(":")
  36. host = entry[:last_colon]
  37. port_str = entry[last_colon + 1 :]
  38. try:
  39. port = int(port_str)
  40. except ValueError:
  41. port = 3128
  42. else:
  43. host = entry
  44. port = 3128
  45. result.append((host, port))
  46. return result
  47. return [(SQUID_HOST, SQUID_PORT)]
  48. def _format_host_header(host: str, port: int) -> str:
  49. if ":" in host and not host.startswith("["):
  50. # likely IPv6 literal
  51. return f"[{host}]:{port}"
  52. return f"{host}:{port}"
  53. def _send_http_request(host: str, port: int, request: str, timeout: float = 5.0) -> str:
  54. with socket.create_connection((host, port), timeout=timeout) as s:
  55. s.sendall(request.encode("utf-8"))
  56. response = b""
  57. while True:
  58. chunk = s.recv(4096)
  59. if not chunk:
  60. break
  61. response += chunk
  62. return response.decode("utf-8", errors="replace")
  63. def _squid_error_response(host: str, port: int) -> str:
  64. logger.exception(f"Error fetching Squid data from {host}:{port}")
  65. return "error: unable to fetch squid data"
  66. def fetch_squid_data():
  67. try:
  68. # Build HTTP/1.1 request similar to curl
  69. host_header = _format_host_header(SQUID_HOST, SQUID_PORT)
  70. headers = [
  71. f"Host: {host_header}",
  72. "User-Agent: SquidStats/1.0",
  73. "Accept: */*",
  74. "Connection: close",
  75. ]
  76. if SQUID_MGR_USER and SQUID_MGR_PASS:
  77. token = base64.b64encode(
  78. f"{SQUID_MGR_USER}:{SQUID_MGR_PASS}".encode()
  79. ).decode()
  80. headers.append(f"Authorization: Basic {token}")
  81. path_request = (
  82. "GET /squid-internal-mgr/active_requests HTTP/1.1\r\n"
  83. + "\r\n".join(headers)
  84. + "\r\n\r\n"
  85. )
  86. response_text = _send_http_request(
  87. SQUID_HOST, SQUID_PORT, path_request, timeout=5.0
  88. )
  89. # If Squid returns 400 Bad Request, try legacy cache_object form
  90. first_line = response_text.splitlines()[0] if response_text else ""
  91. if " 400 " in first_line or "Bad Request" in response_text:
  92. legacy_request = (
  93. f"GET cache_object://{SQUID_HOST}/active_requests HTTP/1.0\r\n"
  94. f"Host: {host_header}\r\n"
  95. "User-Agent: SquidStats/1.0\r\n"
  96. "Accept: */*\r\n\r\n"
  97. )
  98. response_text = _send_http_request(
  99. SQUID_HOST, SQUID_PORT, legacy_request, timeout=5.0
  100. )
  101. return response_text
  102. except Exception:
  103. return _squid_error_response(SQUID_HOST, SQUID_PORT)
  104. def fetch_squid_data_from_host(host: str, port: int) -> str:
  105. """Fetch active_requests from a specific Squid host:port."""
  106. try:
  107. host_header = _format_host_header(host, port)
  108. headers = [
  109. f"Host: {host_header}",
  110. "User-Agent: SquidStats/1.0",
  111. "Accept: */*",
  112. "Connection: close",
  113. ]
  114. if SQUID_MGR_USER and SQUID_MGR_PASS:
  115. token = base64.b64encode(
  116. f"{SQUID_MGR_USER}:{SQUID_MGR_PASS}".encode()
  117. ).decode()
  118. headers.append(f"Authorization: Basic {token}")
  119. path_request = (
  120. "GET /squid-internal-mgr/active_requests HTTP/1.1\r\n"
  121. + "\r\n".join(headers)
  122. + "\r\n\r\n"
  123. )
  124. response_text = _send_http_request(host, port, path_request, timeout=5.0)
  125. first_line = response_text.splitlines()[0] if response_text else ""
  126. if " 400 " in first_line or "Bad Request" in response_text:
  127. legacy_request = (
  128. f"GET cache_object://{host}/active_requests HTTP/1.0\r\n"
  129. f"Host: {host_header}\r\n"
  130. "User-Agent: SquidStats/1.0\r\n"
  131. "Accept: */*\r\n\r\n"
  132. )
  133. response_text = _send_http_request(host, port, legacy_request, timeout=5.0)
  134. return response_text
  135. except Exception:
  136. return _squid_error_response(host, port)
  137. def fetch_all_squid_data() -> list[dict]:
  138. """Fetch active_requests from all configured Squid proxies concurrently.
  139. Returns a list of dicts:
  140. {
  141. "host": str,
  142. "port": int,
  143. "label": str, # "host:port"
  144. "data": str, # raw response or error string
  145. "ok": bool,
  146. }
  147. """
  148. hosts = get_squid_hosts()
  149. results: list[dict] = []
  150. def _fetch(host: str, port: int) -> dict:
  151. label = f"{host}:{port}"
  152. raw = fetch_squid_data_from_host(host, port)
  153. ok = (
  154. bool(raw)
  155. and not raw.strip().lower().startswith("error")
  156. and not raw.strip().lower().startswith("[errno")
  157. )
  158. return {"host": host, "port": port, "label": label, "data": raw, "ok": ok}
  159. if len(hosts) == 1:
  160. results.append(_fetch(*hosts[0]))
  161. else:
  162. with ThreadPoolExecutor(max_workers=min(len(hosts), 10)) as executor:
  163. futures = {executor.submit(_fetch, h, p): (h, p) for h, p in hosts}
  164. for future in as_completed(futures):
  165. results.append(future.result())
  166. return results