fetch_data.py 2.3 KB

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