fetch_data.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import base64
  2. import os
  3. import socket
  4. from dotenv import load_dotenv
  5. from config import Config
  6. load_dotenv()
  7. SQUID_HOST = Config.SQUID_HOST
  8. SQUID_PORT = Config.SQUID_PORT
  9. SQUID_MGR_USER = os.getenv("SQUID_MGR_USER")
  10. SQUID_MGR_PASS = os.getenv("SQUID_MGR_PASS")
  11. def _format_host_header(host: str, port: int) -> str:
  12. if ":" in host and not host.startswith("["):
  13. # likely IPv6 literal
  14. return f"[{host}]:{port}"
  15. return f"{host}:{port}"
  16. def _send_http_request(host: str, port: int, request: str, timeout: float = 5.0) -> str:
  17. with socket.create_connection((host, port), timeout=timeout) as s:
  18. s.sendall(request.encode("utf-8"))
  19. response = b""
  20. while True:
  21. chunk = s.recv(4096)
  22. if not chunk:
  23. break
  24. response += chunk
  25. return response.decode("utf-8", errors="replace")
  26. def fetch_squid_data():
  27. try:
  28. # Build HTTP/1.1 request similar to curl
  29. host_header = _format_host_header(SQUID_HOST, SQUID_PORT)
  30. headers = [
  31. f"Host: {host_header}",
  32. "User-Agent: SquidStats/1.0",
  33. "Accept: */*",
  34. "Connection: close",
  35. ]
  36. if SQUID_MGR_USER and SQUID_MGR_PASS:
  37. token = base64.b64encode(
  38. f"{SQUID_MGR_USER}:{SQUID_MGR_PASS}".encode()
  39. ).decode()
  40. headers.append(f"Authorization: Basic {token}")
  41. path_request = (
  42. "GET /squid-internal-mgr/active_requests HTTP/1.1\r\n"
  43. + "\r\n".join(headers)
  44. + "\r\n\r\n"
  45. )
  46. response_text = _send_http_request(
  47. SQUID_HOST, SQUID_PORT, path_request, timeout=5.0
  48. )
  49. # If Squid returns 400 Bad Request, try legacy cache_object form
  50. first_line = response_text.splitlines()[0] if response_text else ""
  51. if " 400 " in first_line or "Bad Request" in response_text:
  52. legacy_request = (
  53. f"GET cache_object://{SQUID_HOST}/active_requests HTTP/1.0\r\n"
  54. f"Host: {host_header}\r\n"
  55. "User-Agent: SquidStats/1.0\r\n"
  56. "Accept: */*\r\n\r\n"
  57. )
  58. response_text = _send_http_request(
  59. SQUID_HOST, SQUID_PORT, legacy_request, timeout=5.0
  60. )
  61. return response_text
  62. except Exception as e:
  63. return str(e)