4
0

fetch_data.py 5.4 KB

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