log.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. import os
  2. import re
  3. import time
  4. from collections import defaultdict
  5. from datetime import datetime
  6. from math import isfinite
  7. from loguru import logger
  8. from sqlalchemy.exc import IntegrityError, OperationalError, SQLAlchemyError
  9. from database.database import (
  10. DeniedLog,
  11. LogMetadata,
  12. get_dynamic_models,
  13. get_dynamic_table_names,
  14. get_engine,
  15. get_session,
  16. )
  17. class DatabaseManager:
  18. def __init__(self, engine=None, session=None):
  19. self.engine = engine if engine else get_engine()
  20. self.session = session if session else get_session()
  21. def __enter__(self):
  22. return self.session
  23. def __exit__(self, exc_type, exc_val, exc_tb):
  24. try:
  25. if exc_type is None:
  26. self.session.commit()
  27. logger.info("Commit successful")
  28. else:
  29. self.session.rollback()
  30. logger.error(f"Rollback due to error: {exc_val}")
  31. except SQLAlchemyError as e:
  32. logger.error(f"Error during commit/rollback: {e}")
  33. self.session.rollback()
  34. finally:
  35. self.session.close()
  36. # Constants for fields and batch
  37. BATCH_SIZE = 500
  38. MAX_RETRIES = 3
  39. # Supported Squid access-log families. Detection is automatic; these names
  40. # are also used as parser hints after sampling a file.
  41. FORMAT_AUTO = "AUTO"
  42. FORMAT_DEFAULT = "DEFAULT"
  43. FORMAT_DETAILED = "DETAILED"
  44. HTTP_METHODS = frozenset(
  45. {
  46. "CONNECT",
  47. "DELETE",
  48. "GET",
  49. "HEAD",
  50. "OPTIONS",
  51. "PATCH",
  52. "POST",
  53. "PUT",
  54. "TRACE",
  55. "NONE",
  56. }
  57. )
  58. DETAILED_REQUEST_RE = re.compile(
  59. r"^\S+\s+(?P<ip>\S+)\s+(?P<identity>\S+)\s+(?P<username>\S+)\s+"
  60. r"\[[^\]]*\]\s+"
  61. r'"(?P<method>\S+)\s+(?P<url>.*?)\s+HTTP/(?P<http_version>[^"]+)"\s+'
  62. r"(?P<status>\S+)\s+(?P<bytes>\S+)(?:\s+.*)?$"
  63. )
  64. def find_last_parent_proxy(log_file: str, lines_to_check: int = 5000) -> str | None:
  65. if not os.path.exists(log_file):
  66. return None
  67. try:
  68. with open(log_file, "rb") as f:
  69. f.seek(0, os.SEEK_END)
  70. end_pos = f.tell()
  71. line_count = 0
  72. while line_count < lines_to_check + 1 and f.tell() > 0:
  73. try:
  74. f.seek(-1, os.SEEK_CUR)
  75. char = f.read(1)
  76. if char == b"\n":
  77. line_count += 1
  78. f.seek(-1, os.SEEK_CUR)
  79. except OSError:
  80. f.seek(0)
  81. break
  82. last_lines_raw = f.read(end_pos - f.tell())
  83. last_lines = (
  84. last_lines_raw.decode("utf-8", errors="replace").strip().splitlines()
  85. )
  86. for line in reversed(last_lines):
  87. log_data = parse_log_line(line)
  88. if log_data and log_data.get("parent_ip"):
  89. return log_data["parent_ip"]
  90. except Exception as e:
  91. logger.error(f"Error reading last lines of log: {e}", exc_info=False)
  92. return None
  93. def get_table_names():
  94. today = datetime.now().strftime("%Y%m%d")
  95. return f"user_{today}", f"log_{today}", "log_metadata"
  96. def get_file_inode(filepath):
  97. try:
  98. return os.stat(filepath).st_ino
  99. except FileNotFoundError:
  100. logger.error(f"File not found: {filepath}")
  101. raise
  102. except Exception as e:
  103. logger.error(f"Error accessing file: {e}")
  104. raise
  105. def get_log_datetime(line: str) -> datetime | None:
  106. """Return the timestamp stored in a Squid access-log line.
  107. All access-log formats supported by this parser put the Unix timestamp in
  108. the first field. Keeping this separate from the parsed payload lets us
  109. preserve the parser's public response shape while still routing imported
  110. entries to the correct daily table.
  111. """
  112. if not isinstance(line, str) or not line.strip():
  113. return None
  114. try:
  115. timestamp_token = line.lstrip("\ufeff").split(None, 1)[0]
  116. timestamp = float(timestamp_token.split("|", 1)[0])
  117. if not isfinite(timestamp) or timestamp < 0:
  118. return None
  119. return datetime.fromtimestamp(timestamp)
  120. except (IndexError, TypeError, ValueError, OSError, OverflowError):
  121. return None
  122. def _is_number(value: str) -> bool:
  123. try:
  124. float(value)
  125. return True
  126. except (TypeError, ValueError):
  127. return False
  128. def _is_integer(value: str) -> bool:
  129. return value.isdigit()
  130. def _response_code(status: str) -> int:
  131. code = status.rsplit("/", 1)[-1]
  132. return int(code) if code.isdigit() else 0
  133. def _bytes_transmitted(value: str) -> int:
  134. return int(value) if _is_integer(value) else 0
  135. def _is_default_line(parts: list[str]) -> bool:
  136. """Recognize Squid's native access.log layout without parsing it twice."""
  137. return bool(
  138. len(parts) >= 7
  139. and _is_number(parts[0])
  140. and _is_number(parts[1])
  141. and "/" in parts[3]
  142. and _is_integer(parts[3].rsplit("/", 1)[-1])
  143. and (parts[4] == "-" or _is_integer(parts[4]))
  144. and parts[5].upper() in HTTP_METHODS
  145. )
  146. def _is_pipe_line(line: str) -> bool:
  147. parts = line.strip().split("|")
  148. return bool(
  149. len(parts) >= 14
  150. and _is_number(parts[0])
  151. and _is_integer(parts[8])
  152. and _is_integer(parts[9])
  153. and parts[5].upper() in HTTP_METHODS
  154. )
  155. def _is_space_detailed_line(parts: list[str]) -> bool:
  156. """Recognize the legacy whitespace-separated DETAILED layout."""
  157. return bool(
  158. len(parts) >= 11
  159. and _is_number(parts[0])
  160. and parts[5].upper() in HTTP_METHODS
  161. and _is_integer(parts[9])
  162. and _is_integer(parts[10])
  163. )
  164. def _is_quoted_detailed_line(line: str):
  165. match = DETAILED_REQUEST_RE.match(line.strip())
  166. return bool(match and match.group("method").upper() in HTTP_METHODS)
  167. def _detect_line_format(line: str) -> str | None:
  168. if not isinstance(line, str) or not line.strip():
  169. return None
  170. if _is_pipe_line(line):
  171. return FORMAT_DETAILED
  172. parts = line.split()
  173. if _is_default_line(parts):
  174. return FORMAT_DEFAULT
  175. if _is_quoted_detailed_line(line) or _is_space_detailed_line(parts):
  176. return FORMAT_DETAILED
  177. return None
  178. def _ignore_log_line(line: str) -> bool:
  179. line_lower = line.lower()
  180. return (
  181. "cache_object://" in line_lower
  182. or "error:transaction-end-before-headers" in line_lower
  183. or "error:invalid-request" in line_lower
  184. )
  185. def parse_log_line(line: str, format_hint: str = FORMAT_AUTO):
  186. """Parse one line using a detected format or safe per-line detection."""
  187. if not isinstance(line, str) or not line.strip():
  188. return None
  189. try:
  190. if _ignore_log_line(line):
  191. return None
  192. except Exception as error:
  193. logger.debug("Unexpected error pre-filtering log line: {}", error)
  194. return None
  195. normalized_hint = (format_hint or FORMAT_AUTO).upper()
  196. if normalized_hint == FORMAT_DEFAULT:
  197. return parse_log_line_default(line)
  198. if normalized_hint == FORMAT_DETAILED:
  199. return parse_log_line_detailed(line)
  200. detected_format = _detect_line_format(line)
  201. if detected_format == FORMAT_DEFAULT:
  202. return parse_log_line_default(line)
  203. if detected_format == FORMAT_DETAILED:
  204. return parse_log_line_detailed(line)
  205. return None
  206. def parse_log_line_default(line: str):
  207. """Parse Squid's standard format.
  208. ``timestamp elapsed client_ip result/status bytes method url user
  209. hierarchy content-type``
  210. """
  211. try:
  212. if _ignore_log_line(line):
  213. return None
  214. parts = line.split()
  215. if not _is_default_line(parts):
  216. return None
  217. status = parts[3]
  218. ip = parts[2]
  219. user_field = parts[7] if len(parts) > 7 else "-"
  220. username = user_field if user_field != "-" else ip
  221. return {
  222. "ip": ip,
  223. "username": username if username != "-" else None,
  224. "url": parts[6],
  225. "response": _response_code(status),
  226. "data_transmitted": _bytes_transmitted(parts[4]),
  227. "method": parts[5].upper(),
  228. "status": status,
  229. "is_denied": "TCP_DENIED" in status,
  230. }
  231. except (IndexError, TypeError, ValueError) as error:
  232. logger.debug("Unable to parse DEFAULT log line: {} ({})", line.strip(), error)
  233. return None
  234. def parse_log_line_detailed(line: str):
  235. """Parse the supported legacy DETAILED variants."""
  236. if _ignore_log_line(line):
  237. return None
  238. if _is_pipe_line(line):
  239. return parse_log_line_pipe_format(line)
  240. quoted_match = DETAILED_REQUEST_RE.match(line.strip())
  241. if quoted_match:
  242. try:
  243. identity = quoted_match.group("identity")
  244. username = quoted_match.group("username")
  245. ip = quoted_match.group("ip")
  246. if username == "-":
  247. username = identity if identity != "-" else ip
  248. if username == "-":
  249. username = None
  250. status = quoted_match.group("status")
  251. return {
  252. "ip": ip,
  253. "username": username,
  254. "url": quoted_match.group("url"),
  255. "response": _response_code(status),
  256. "data_transmitted": _bytes_transmitted(quoted_match.group("bytes")),
  257. "method": quoted_match.group("method").upper(),
  258. "status": status,
  259. "is_denied": "TCP_DENIED" in line,
  260. }
  261. except (IndexError, TypeError, ValueError) as error:
  262. logger.debug(
  263. "Unable to parse quoted DETAILED log line: {} ({})",
  264. line.strip(),
  265. error,
  266. )
  267. return None
  268. return parse_log_line_space_format(line)
  269. def parse_log_line_pipe_format(line):
  270. parts = line.strip().split("|")
  271. if not _is_pipe_line(line):
  272. return None
  273. try:
  274. username = parts[3]
  275. if username == "-":
  276. return None
  277. return {
  278. "ip": parts[1],
  279. "username": username,
  280. "url": parts[6],
  281. "response": int(parts[8]),
  282. "data_transmitted": int(parts[9]),
  283. "method": parts[5].upper(),
  284. "status": parts[13],
  285. "is_denied": "TCP_DENIED" in parts[13],
  286. }
  287. except (IndexError, TypeError, ValueError) as error:
  288. logger.debug("Unable to parse pipe log line: {} ({})", line.strip(), error)
  289. return None
  290. def parse_log_line_space_format(line):
  291. """Parse the legacy whitespace-separated DETAILED variant."""
  292. try:
  293. parts = line.split()
  294. if not _is_space_detailed_line(parts) or parts[3] == "-":
  295. return None
  296. status = parts[4]
  297. return {
  298. "ip": parts[1],
  299. "username": parts[3],
  300. "url": parts[6],
  301. "response": int(parts[9]),
  302. "data_transmitted": int(parts[10]),
  303. "method": parts[5].upper(),
  304. "status": status,
  305. "is_denied": "TCP_DENIED" in line,
  306. }
  307. except (IndexError, TypeError, ValueError) as error:
  308. logger.debug(
  309. "Unable to parse space DETAILED line: {} ({})", line.strip(), error
  310. )
  311. return None
  312. def detect_log_format(log_file, sample_lines=32, start_position=0):
  313. """Detect DEFAULT or DETAILED by validating a small sample of lines."""
  314. try:
  315. with open(log_file, encoding="utf-8", errors="replace") as file:
  316. if start_position:
  317. file.seek(start_position)
  318. counts = {FORMAT_DEFAULT: 0, FORMAT_DETAILED: 0}
  319. for _ in range(sample_lines):
  320. line = file.readline()
  321. if not line:
  322. break
  323. detected = _detect_line_format(line)
  324. if detected:
  325. counts[detected] += 1
  326. # A tail containing only malformed/ignored lines should not force
  327. # a wrong format. Retry from the beginning in that case.
  328. if not any(counts.values()) and start_position:
  329. file.seek(0)
  330. for _ in range(sample_lines):
  331. line = file.readline()
  332. if not line:
  333. break
  334. detected = _detect_line_format(line)
  335. if detected:
  336. counts[detected] += 1
  337. if not any(counts.values()):
  338. return FORMAT_AUTO
  339. if counts[FORMAT_DEFAULT] > counts[FORMAT_DETAILED]:
  340. return FORMAT_DEFAULT
  341. if counts[FORMAT_DETAILED] > counts[FORMAT_DEFAULT]:
  342. return FORMAT_DETAILED
  343. return FORMAT_AUTO
  344. except OSError as error:
  345. logger.warning(
  346. "Unable to detect log format; using per-line detection: {}", error
  347. )
  348. return FORMAT_AUTO
  349. def _new_import_summary() -> dict:
  350. return {
  351. "processed_lines": 0,
  352. "parsed_lines": 0,
  353. "skipped_lines": 0,
  354. "inserted_logs": 0,
  355. "inserted_users": 0,
  356. "inserted_denied": 0,
  357. "dates": [],
  358. }
  359. def _date_summary(date_summaries: dict, date_suffix: str) -> dict:
  360. if date_suffix not in date_summaries:
  361. user_table, log_table = get_dynamic_table_names(date_suffix)
  362. date_summaries[date_suffix] = {
  363. "date": date_suffix,
  364. "user_table": user_table,
  365. "log_table": log_table,
  366. "inserted_logs": 0,
  367. "inserted_users": 0,
  368. "inserted_denied": 0,
  369. }
  370. return date_summaries[date_suffix]
  371. def _ingest_log_file(log_file, session, start_position: int = 0) -> tuple[dict, int]:
  372. """Ingest a log file into the daily tables selected by each line's date."""
  373. summary = _new_import_summary()
  374. date_summaries = {}
  375. models_by_date = {}
  376. user_cache = {}
  377. pending_users = defaultdict(list)
  378. pending_logs = defaultdict(list)
  379. pending_denied = []
  380. pending_stats = defaultdict(lambda: {"logs": 0, "users": 0, "denied": 0})
  381. start_time = time.time()
  382. detected_format = detect_log_format(log_file, start_position=start_position)
  383. logger.info("Detected Squid log format: {}", detected_format)
  384. def get_models(date_suffix):
  385. if date_suffix not in models_by_date:
  386. models = get_dynamic_models(date_suffix)
  387. if not models or not models[0] or not models[1]:
  388. raise RuntimeError(
  389. f"Could not create daily tables for date suffix {date_suffix}"
  390. )
  391. models_by_date[date_suffix] = models
  392. return models_by_date[date_suffix]
  393. def commit_batch():
  394. if not pending_users and not pending_logs and not pending_denied:
  395. return
  396. for retry_count in range(MAX_RETRIES):
  397. try:
  398. for _date_suffix, users in pending_users.items():
  399. if users:
  400. session.add_all(users)
  401. session.flush()
  402. for date_suffix, entries in pending_logs.items():
  403. if not entries:
  404. continue
  405. _, dynamic_log = get_models(date_suffix)
  406. mappings = []
  407. for user_ref, mapping in entries:
  408. user_id = (
  409. user_ref.id if not isinstance(user_ref, int) else user_ref
  410. )
  411. mappings.append({**mapping, "user_id": user_id})
  412. session.bulk_insert_mappings(dynamic_log, mappings)
  413. if pending_denied:
  414. session.add_all(pending_denied)
  415. session.commit()
  416. for date_suffix, users in pending_users.items():
  417. count = len(users)
  418. if count:
  419. summary["inserted_users"] += count
  420. _date_summary(date_summaries, date_suffix)[
  421. "inserted_users"
  422. ] += count
  423. for date_suffix, entries in pending_logs.items():
  424. count = len(entries)
  425. if count:
  426. summary["inserted_logs"] += count
  427. _date_summary(date_summaries, date_suffix)["inserted_logs"] += (
  428. count
  429. )
  430. for date_suffix, stats in pending_stats.items():
  431. if stats["denied"]:
  432. summary["inserted_denied"] += stats["denied"]
  433. _date_summary(date_summaries, date_suffix)[
  434. "inserted_denied"
  435. ] += stats["denied"]
  436. pending_users.clear()
  437. pending_logs.clear()
  438. pending_denied.clear()
  439. pending_stats.clear()
  440. return
  441. except IntegrityError as error:
  442. session.rollback()
  443. logger.warning(
  444. "Integrity error importing batch (retry {}/{}): {}",
  445. retry_count + 1,
  446. MAX_RETRIES,
  447. error,
  448. )
  449. except OperationalError as error:
  450. session.rollback()
  451. if "database is locked" not in str(error).lower():
  452. raise
  453. logger.warning(
  454. "Database locked while importing; retrying ({}/{})",
  455. retry_count + 1,
  456. MAX_RETRIES,
  457. )
  458. time.sleep(0.5 * (retry_count + 1))
  459. except SQLAlchemyError:
  460. session.rollback()
  461. raise
  462. raise RuntimeError("Could not commit a log import batch")
  463. current_position = start_position
  464. with open(log_file, encoding="utf-8", errors="replace") as file:
  465. file.seek(start_position)
  466. for line in file:
  467. summary["processed_lines"] += 1
  468. current_position += len(line.encode("utf-8"))
  469. log_data = parse_log_line(line, format_hint=detected_format)
  470. log_datetime = get_log_datetime(line)
  471. if not log_data or log_datetime is None:
  472. summary["skipped_lines"] += 1
  473. continue
  474. summary["parsed_lines"] += 1
  475. date_suffix = log_datetime.strftime("%Y%m%d")
  476. DynamicUser, _ = get_models(date_suffix)
  477. date_stats = pending_stats[date_suffix]
  478. date_stats["denied"] += int(bool(log_data.get("is_denied")))
  479. # Some Squid formats use '-' for unauthenticated users. The IP is
  480. # the stable fallback used by the DEFAULT parser as well.
  481. username = log_data.get("username") or log_data.get("ip") or "-"
  482. ip = log_data.get("ip") or "-"
  483. if log_data.get("is_denied"):
  484. pending_denied.append(
  485. DeniedLog(
  486. username=username,
  487. ip=ip,
  488. url=log_data.get("url") or "-",
  489. method=log_data.get("method") or "",
  490. status=log_data.get("status") or "",
  491. response=log_data.get("response"),
  492. data_transmitted=log_data.get("data_transmitted", 0),
  493. created_at=log_datetime,
  494. )
  495. )
  496. else:
  497. user_key = (date_suffix, username, ip)
  498. user_ref = user_cache.get(user_key)
  499. if user_ref is None:
  500. existing_user = (
  501. session.query(DynamicUser)
  502. .filter_by(username=username, ip=ip)
  503. .first()
  504. )
  505. if existing_user:
  506. user_ref = existing_user.id
  507. else:
  508. user_ref = DynamicUser(
  509. username=username,
  510. ip=ip,
  511. created_at=log_datetime,
  512. )
  513. pending_users[date_suffix].append(user_ref)
  514. date_stats["users"] += 1
  515. user_cache[user_key] = user_ref
  516. pending_logs[date_suffix].append(
  517. (
  518. user_ref,
  519. {
  520. "url": log_data.get("url") or "-",
  521. "response": log_data.get("response", 0),
  522. "request_count": 1,
  523. "data_transmitted": log_data.get("data_transmitted", 0),
  524. "created_at": log_datetime,
  525. },
  526. )
  527. )
  528. date_stats["logs"] += 1
  529. if (
  530. sum(len(items) for items in pending_logs.values())
  531. + sum(len(items) for items in pending_users.values())
  532. + len(pending_denied)
  533. >= BATCH_SIZE
  534. ):
  535. commit_batch()
  536. commit_batch()
  537. summary["dates"] = [date_summaries[key] for key in sorted(date_summaries)]
  538. elapsed = time.time() - start_time
  539. logger.info(
  540. "Logs inserted: {}, New users: {}, Denied: {} ({} lines in {:.2f}s)",
  541. summary["inserted_logs"],
  542. summary["inserted_users"],
  543. summary["inserted_denied"],
  544. summary["processed_lines"],
  545. elapsed,
  546. )
  547. return summary, current_position
  548. def import_logs(log_file):
  549. """Import a complete log file, routing entries to their daily tables.
  550. Unlike :func:`process_logs`, this function intentionally does not read or
  551. update ``log_metadata``. It is therefore safe for an administrator to
  552. import a rotated or historical file without changing the live tailer's
  553. cursor.
  554. """
  555. if not os.path.exists(log_file):
  556. raise FileNotFoundError(log_file)
  557. session = get_session()
  558. try:
  559. summary, _ = _ingest_log_file(log_file, session)
  560. if summary["parsed_lines"] == 0:
  561. raise ValueError("The log file contains no valid Squid access entries")
  562. return summary
  563. except Exception:
  564. session.rollback()
  565. logger.exception("Critical error importing log file")
  566. raise
  567. finally:
  568. session.close()
  569. def process_logs(log_file):
  570. """Process only the new tail of the live log and update its cursor."""
  571. if not os.path.exists(log_file):
  572. logger.error(f"File not found: {log_file}")
  573. return _new_import_summary()
  574. current_inode = get_file_inode(log_file)
  575. file_size = os.path.getsize(log_file)
  576. session = get_session()
  577. try:
  578. metadata = session.query(LogMetadata).first()
  579. last_position = metadata.last_position if metadata else 0
  580. if metadata:
  581. if metadata.last_inode != current_inode:
  582. logger.info(
  583. f"Inode changed: {metadata.last_inode} -> {current_inode}. Resetting position."
  584. )
  585. last_position = 0
  586. elif file_size < last_position:
  587. logger.warning(
  588. f"File truncated (size: {file_size} < position: {last_position})"
  589. )
  590. last_position = 0
  591. summary, current_position = _ingest_log_file(
  592. log_file, session, start_position=last_position
  593. )
  594. if metadata is None:
  595. metadata = LogMetadata()
  596. session.add(metadata)
  597. metadata.last_position = current_position
  598. metadata.last_inode = current_inode
  599. metadata.updated_at = datetime.now()
  600. session.commit()
  601. return summary
  602. except Exception as error:
  603. session.rollback()
  604. logger.critical(f"Critical error in process_logs: {error}", exc_info=True)
  605. raise
  606. finally:
  607. session.close()