log.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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 _normalize_log_line(line: str) -> str:
  65. """Remove transport wrappers that can surround a Squid log line."""
  66. normalized = line.lstrip("\ufeff").strip()
  67. if normalized.startswith('"') and len(normalized) > 1:
  68. timestamp_start = normalized[1:].split(None, 1)[0]
  69. if _is_number(timestamp_start):
  70. normalized = normalized[1:].lstrip()
  71. if '\\"' in normalized:
  72. normalized = normalized.replace('\\"', '"')
  73. return normalized
  74. def find_last_parent_proxy(log_file: str, lines_to_check: int = 5000) -> str | None:
  75. if not os.path.exists(log_file):
  76. return None
  77. try:
  78. with open(log_file, "rb") as f:
  79. f.seek(0, os.SEEK_END)
  80. end_pos = f.tell()
  81. line_count = 0
  82. while line_count < lines_to_check + 1 and f.tell() > 0:
  83. try:
  84. f.seek(-1, os.SEEK_CUR)
  85. char = f.read(1)
  86. if char == b"\n":
  87. line_count += 1
  88. f.seek(-1, os.SEEK_CUR)
  89. except OSError:
  90. f.seek(0)
  91. break
  92. last_lines_raw = f.read(end_pos - f.tell())
  93. last_lines = (
  94. last_lines_raw.decode("utf-8", errors="replace").strip().splitlines()
  95. )
  96. for line in reversed(last_lines):
  97. log_data = parse_log_line(line)
  98. if log_data and log_data.get("parent_ip"):
  99. return log_data["parent_ip"]
  100. except Exception as e:
  101. logger.error(f"Error reading last lines of log: {e}", exc_info=False)
  102. return None
  103. def get_table_names():
  104. today = datetime.now().strftime("%Y%m%d")
  105. return f"user_{today}", f"log_{today}", "log_metadata"
  106. def get_file_inode(filepath):
  107. try:
  108. return os.stat(filepath).st_ino
  109. except FileNotFoundError:
  110. logger.error(f"File not found: {filepath}")
  111. raise
  112. except Exception as e:
  113. logger.error(f"Error accessing file: {e}")
  114. raise
  115. def get_log_datetime(line: str) -> datetime | None:
  116. """Return the timestamp stored in a Squid access-log line.
  117. All access-log formats supported by this parser put the Unix timestamp in
  118. the first field. Keeping this separate from the parsed payload lets us
  119. preserve the parser's public response shape while still routing imported
  120. entries to the correct daily table.
  121. """
  122. if not isinstance(line, str) or not line.strip():
  123. return None
  124. try:
  125. timestamp_token = _normalize_log_line(line).split(None, 1)[0]
  126. timestamp = float(timestamp_token.split("|", 1)[0])
  127. if not isfinite(timestamp) or timestamp < 0:
  128. return None
  129. return datetime.fromtimestamp(timestamp)
  130. except (IndexError, TypeError, ValueError, OSError, OverflowError):
  131. return None
  132. def _is_number(value: str) -> bool:
  133. try:
  134. float(value)
  135. return True
  136. except (TypeError, ValueError):
  137. return False
  138. def _is_integer(value: str) -> bool:
  139. return value.isdigit()
  140. def _response_code(status: str) -> int:
  141. code = status.rsplit("/", 1)[-1]
  142. return int(code) if code.isdigit() else 0
  143. def _bytes_transmitted(value: str) -> int:
  144. return int(value) if _is_integer(value) else 0
  145. def _is_default_line(parts: list[str]) -> bool:
  146. """Recognize Squid's native access.log layout without parsing it twice."""
  147. return bool(
  148. len(parts) >= 7
  149. and _is_number(parts[0])
  150. and _is_number(parts[1])
  151. and "/" in parts[3]
  152. and _is_integer(parts[3].rsplit("/", 1)[-1])
  153. and (parts[4] == "-" or _is_integer(parts[4]))
  154. and parts[5].upper() in HTTP_METHODS
  155. )
  156. def _is_pipe_line(line: str) -> bool:
  157. parts = _normalize_log_line(line).split("|")
  158. return bool(
  159. len(parts) >= 14
  160. and _is_number(parts[0])
  161. and _is_integer(parts[8])
  162. and _is_integer(parts[9])
  163. and parts[5].upper() in HTTP_METHODS
  164. )
  165. def _is_space_detailed_line(parts: list[str]) -> bool:
  166. """Recognize the legacy whitespace-separated DETAILED layout."""
  167. return bool(
  168. len(parts) >= 11
  169. and _is_number(parts[0])
  170. and parts[5].upper() in HTTP_METHODS
  171. and _is_integer(parts[9])
  172. and _is_integer(parts[10])
  173. )
  174. def _is_quoted_detailed_line(line: str):
  175. match = DETAILED_REQUEST_RE.match(_normalize_log_line(line))
  176. return bool(match and match.group("method").upper() in HTTP_METHODS)
  177. def _detect_line_format(line: str) -> str | None:
  178. if not isinstance(line, str) or not line.strip():
  179. return None
  180. if _is_pipe_line(line):
  181. return FORMAT_DETAILED
  182. normalized_line = _normalize_log_line(line)
  183. parts = normalized_line.split()
  184. if _is_default_line(parts):
  185. return FORMAT_DEFAULT
  186. if _is_quoted_detailed_line(normalized_line) or _is_space_detailed_line(parts):
  187. return FORMAT_DETAILED
  188. return None
  189. def _ignore_log_line(line: str) -> bool:
  190. line_lower = line.lower()
  191. return (
  192. "cache_object://" in line_lower
  193. or "error:transaction-end-before-headers" in line_lower
  194. or "error:invalid-request" in line_lower
  195. )
  196. def _preview_log_line(line: str | None, max_chars: int = 180) -> str:
  197. if line is None:
  198. return "<none>"
  199. text = str(line).rstrip("\r\n")
  200. if len(text) <= max_chars:
  201. return text
  202. return text[: max_chars - 3] + "..."
  203. def _count_lines(log_file: str) -> int:
  204. try:
  205. with open(log_file, encoding="utf-8", errors="replace") as file:
  206. return sum(1 for _ in file)
  207. except OSError as error:
  208. logger.warning("Unable to count lines in {}: {}", log_file, error)
  209. return 0
  210. def parse_log_line(line: str, format_hint: str = FORMAT_AUTO):
  211. """Parse one line using a detected format or safe per-line detection."""
  212. if not isinstance(line, str) or not line.strip():
  213. return None
  214. normalized_line = _normalize_log_line(line)
  215. try:
  216. if _ignore_log_line(normalized_line):
  217. return None
  218. except Exception as error:
  219. logger.debug("Unexpected error pre-filtering log line: {}", error)
  220. return None
  221. normalized_hint = (format_hint or FORMAT_AUTO).upper()
  222. if normalized_hint == FORMAT_DEFAULT:
  223. return parse_log_line_default(normalized_line)
  224. if normalized_hint == FORMAT_DETAILED:
  225. return parse_log_line_detailed(normalized_line)
  226. detected_format = _detect_line_format(normalized_line)
  227. if detected_format == FORMAT_DEFAULT:
  228. return parse_log_line_default(normalized_line)
  229. if detected_format == FORMAT_DETAILED:
  230. return parse_log_line_detailed(normalized_line)
  231. return None
  232. def parse_log_line_default(line: str):
  233. """Parse Squid's standard format.
  234. ``timestamp elapsed client_ip result/status bytes method url user
  235. hierarchy content-type``
  236. """
  237. try:
  238. normalized_line = _normalize_log_line(line)
  239. if _ignore_log_line(normalized_line):
  240. return None
  241. parts = normalized_line.split()
  242. if not _is_default_line(parts):
  243. return None
  244. status = parts[3]
  245. ip = parts[2]
  246. user_field = parts[7] if len(parts) > 7 else "-"
  247. username = user_field if user_field != "-" else ip
  248. return {
  249. "ip": ip,
  250. "username": username if username != "-" else None,
  251. "url": parts[6],
  252. "response": _response_code(status),
  253. "data_transmitted": _bytes_transmitted(parts[4]),
  254. "method": parts[5].upper(),
  255. "status": status,
  256. "is_denied": "TCP_DENIED" in status,
  257. }
  258. except (IndexError, TypeError, ValueError) as error:
  259. logger.debug("Unable to parse DEFAULT log line: {} ({})", line.strip(), error)
  260. return None
  261. def parse_log_line_detailed(line: str):
  262. """Parse the supported legacy DETAILED variants."""
  263. normalized_line = _normalize_log_line(line)
  264. if _ignore_log_line(normalized_line):
  265. return None
  266. if _is_pipe_line(normalized_line):
  267. return parse_log_line_pipe_format(normalized_line)
  268. quoted_match = DETAILED_REQUEST_RE.match(normalized_line)
  269. if quoted_match:
  270. try:
  271. identity = quoted_match.group("identity")
  272. username = quoted_match.group("username")
  273. ip = quoted_match.group("ip")
  274. if username == "-":
  275. username = identity if identity != "-" else ip
  276. if username == "-":
  277. username = None
  278. status = quoted_match.group("status")
  279. return {
  280. "ip": ip,
  281. "username": username,
  282. "url": quoted_match.group("url"),
  283. "response": _response_code(status),
  284. "data_transmitted": _bytes_transmitted(quoted_match.group("bytes")),
  285. "method": quoted_match.group("method").upper(),
  286. "status": status,
  287. "is_denied": "TCP_DENIED" in normalized_line,
  288. }
  289. except (IndexError, TypeError, ValueError) as error:
  290. logger.debug(
  291. "Unable to parse quoted DETAILED log line: {} ({})",
  292. line.strip(),
  293. error,
  294. )
  295. return None
  296. return parse_log_line_space_format(normalized_line)
  297. def parse_log_line_pipe_format(line):
  298. normalized_line = _normalize_log_line(line)
  299. parts = normalized_line.split("|")
  300. if not _is_pipe_line(normalized_line):
  301. return None
  302. try:
  303. username = parts[3]
  304. if username == "-":
  305. return None
  306. return {
  307. "ip": parts[1],
  308. "username": username,
  309. "url": parts[6],
  310. "response": int(parts[8]),
  311. "data_transmitted": int(parts[9]),
  312. "method": parts[5].upper(),
  313. "status": parts[13],
  314. "is_denied": "TCP_DENIED" in parts[13],
  315. }
  316. except (IndexError, TypeError, ValueError) as error:
  317. logger.debug("Unable to parse pipe log line: {} ({})", line.strip(), error)
  318. return None
  319. def parse_log_line_space_format(line):
  320. """Parse the legacy whitespace-separated DETAILED variant."""
  321. try:
  322. normalized_line = _normalize_log_line(line)
  323. parts = normalized_line.split()
  324. if not _is_space_detailed_line(parts) or parts[3] == "-":
  325. return None
  326. status = parts[4]
  327. return {
  328. "ip": parts[1],
  329. "username": parts[3],
  330. "url": parts[6],
  331. "response": int(parts[9]),
  332. "data_transmitted": int(parts[10]),
  333. "method": parts[5].upper(),
  334. "status": status,
  335. "is_denied": "TCP_DENIED" in normalized_line,
  336. }
  337. except (IndexError, TypeError, ValueError) as error:
  338. logger.debug(
  339. "Unable to parse space DETAILED line: {} ({})", line.strip(), error
  340. )
  341. return None
  342. def detect_log_format(log_file, sample_lines=32, start_position=0):
  343. """Detect DEFAULT or DETAILED by validating a small sample of lines."""
  344. try:
  345. with open(log_file, encoding="utf-8", errors="replace") as file:
  346. if start_position:
  347. file.seek(start_position)
  348. counts = {FORMAT_DEFAULT: 0, FORMAT_DETAILED: 0}
  349. for _ in range(sample_lines):
  350. line = file.readline()
  351. if not line:
  352. break
  353. detected = _detect_line_format(line)
  354. if detected:
  355. counts[detected] += 1
  356. # A tail containing only malformed/ignored lines should not force
  357. # a wrong format. Retry from the beginning in that case.
  358. if not any(counts.values()) and start_position:
  359. file.seek(0)
  360. for _ in range(sample_lines):
  361. line = file.readline()
  362. if not line:
  363. break
  364. detected = _detect_line_format(line)
  365. if detected:
  366. counts[detected] += 1
  367. if not any(counts.values()):
  368. return FORMAT_AUTO
  369. if counts[FORMAT_DEFAULT] > counts[FORMAT_DETAILED]:
  370. return FORMAT_DEFAULT
  371. if counts[FORMAT_DETAILED] > counts[FORMAT_DEFAULT]:
  372. return FORMAT_DETAILED
  373. return FORMAT_AUTO
  374. except OSError as error:
  375. logger.warning(
  376. "Unable to detect log format; using per-line detection: {}", error
  377. )
  378. return FORMAT_AUTO
  379. def _new_import_summary() -> dict:
  380. return {
  381. "processed_lines": 0,
  382. "parsed_lines": 0,
  383. "skipped_lines": 0,
  384. "inserted_logs": 0,
  385. "inserted_users": 0,
  386. "inserted_denied": 0,
  387. "dates": [],
  388. }
  389. def _date_summary(date_summaries: dict, date_suffix: str) -> dict:
  390. if date_suffix not in date_summaries:
  391. user_table, log_table = get_dynamic_table_names(date_suffix)
  392. date_summaries[date_suffix] = {
  393. "date": date_suffix,
  394. "user_table": user_table,
  395. "log_table": log_table,
  396. "inserted_logs": 0,
  397. "inserted_users": 0,
  398. "inserted_denied": 0,
  399. }
  400. return date_summaries[date_suffix]
  401. def _ingest_log_file(log_file, session, start_position: int = 0) -> tuple[dict, int]:
  402. """Ingest a log file into the daily tables selected by each line's date."""
  403. summary = _new_import_summary()
  404. date_summaries = {}
  405. models_by_date = {}
  406. user_cache = {}
  407. pending_users = defaultdict(list)
  408. pending_logs = defaultdict(list)
  409. pending_denied = []
  410. pending_stats = defaultdict(lambda: {"logs": 0, "users": 0, "denied": 0})
  411. start_time = time.time()
  412. total_lines = _count_lines(log_file)
  413. last_line_seen = None
  414. last_valid_line = None
  415. last_skipped_line = None
  416. detected_format = detect_log_format(log_file, start_position=start_position)
  417. logger.info(
  418. "LOG_IMPORT_START file={} total_lines={} start_position={} detected_format={} size_bytes={}",
  419. log_file,
  420. total_lines,
  421. start_position,
  422. detected_format,
  423. os.path.getsize(log_file),
  424. )
  425. def get_models(date_suffix):
  426. if date_suffix not in models_by_date:
  427. models = get_dynamic_models(date_suffix)
  428. if not models or not models[0] or not models[1]:
  429. raise RuntimeError(
  430. f"Could not create daily tables for date suffix {date_suffix}"
  431. )
  432. models_by_date[date_suffix] = models
  433. return models_by_date[date_suffix]
  434. def commit_batch():
  435. if not pending_users and not pending_logs and not pending_denied:
  436. return
  437. for retry_count in range(MAX_RETRIES):
  438. try:
  439. for _date_suffix, users in pending_users.items():
  440. if users:
  441. session.add_all(users)
  442. session.flush()
  443. for date_suffix, entries in pending_logs.items():
  444. if not entries:
  445. continue
  446. _, dynamic_log = get_models(date_suffix)
  447. mappings = []
  448. for user_ref, mapping in entries:
  449. user_id = (
  450. user_ref.id if not isinstance(user_ref, int) else user_ref
  451. )
  452. mappings.append({**mapping, "user_id": user_id})
  453. session.bulk_insert_mappings(dynamic_log, mappings)
  454. if pending_denied:
  455. session.add_all(pending_denied)
  456. session.commit()
  457. for date_suffix, users in pending_users.items():
  458. count = len(users)
  459. if count:
  460. summary["inserted_users"] += count
  461. _date_summary(date_summaries, date_suffix)[
  462. "inserted_users"
  463. ] += count
  464. for date_suffix, entries in pending_logs.items():
  465. count = len(entries)
  466. if count:
  467. summary["inserted_logs"] += count
  468. _date_summary(date_summaries, date_suffix)["inserted_logs"] += (
  469. count
  470. )
  471. for date_suffix, stats in pending_stats.items():
  472. if stats["denied"]:
  473. summary["inserted_denied"] += stats["denied"]
  474. _date_summary(date_summaries, date_suffix)[
  475. "inserted_denied"
  476. ] += stats["denied"]
  477. pending_users.clear()
  478. pending_logs.clear()
  479. pending_denied.clear()
  480. pending_stats.clear()
  481. return
  482. except IntegrityError as error:
  483. session.rollback()
  484. logger.warning(
  485. "Integrity error importing batch (retry {}/{}): {}",
  486. retry_count + 1,
  487. MAX_RETRIES,
  488. error,
  489. )
  490. except OperationalError as error:
  491. session.rollback()
  492. if "database is locked" not in str(error).lower():
  493. raise
  494. logger.warning(
  495. "Database locked while importing; retrying ({}/{})",
  496. retry_count + 1,
  497. MAX_RETRIES,
  498. )
  499. time.sleep(0.5 * (retry_count + 1))
  500. except SQLAlchemyError:
  501. session.rollback()
  502. raise
  503. raise RuntimeError("Could not commit a log import batch")
  504. current_position = start_position
  505. with open(log_file, encoding="utf-8", errors="replace") as file:
  506. file.seek(start_position)
  507. for line in file:
  508. last_line_seen = line.rstrip("\r\n")
  509. summary["processed_lines"] += 1
  510. current_position += len(line.encode("utf-8"))
  511. log_data = parse_log_line(line, format_hint=detected_format)
  512. log_datetime = get_log_datetime(line)
  513. if not log_data or log_datetime is None:
  514. summary["skipped_lines"] += 1
  515. last_skipped_line = last_line_seen
  516. if summary["processed_lines"] % 500 == 0:
  517. logger.warning(
  518. "LOG_IMPORT_PROGRESS file={} processed={} parsed={} skipped={} current_position={} last_skipped_line={}",
  519. log_file,
  520. summary["processed_lines"],
  521. summary["parsed_lines"],
  522. summary["skipped_lines"],
  523. current_position,
  524. _preview_log_line(last_skipped_line),
  525. )
  526. continue
  527. last_valid_line = last_line_seen
  528. summary["parsed_lines"] += 1
  529. date_suffix = log_datetime.strftime("%Y%m%d")
  530. DynamicUser, _ = get_models(date_suffix)
  531. date_stats = pending_stats[date_suffix]
  532. date_stats["denied"] += int(bool(log_data.get("is_denied")))
  533. # Some Squid formats use '-' for unauthenticated users. The IP is
  534. # the stable fallback used by the DEFAULT parser as well.
  535. username = log_data.get("username") or log_data.get("ip") or "-"
  536. ip = log_data.get("ip") or "-"
  537. if log_data.get("is_denied"):
  538. pending_denied.append(
  539. DeniedLog(
  540. username=username,
  541. ip=ip,
  542. url=log_data.get("url") or "-",
  543. method=log_data.get("method") or "",
  544. status=log_data.get("status") or "",
  545. response=log_data.get("response"),
  546. data_transmitted=log_data.get("data_transmitted", 0),
  547. created_at=log_datetime,
  548. )
  549. )
  550. else:
  551. user_key = (date_suffix, username, ip)
  552. user_ref = user_cache.get(user_key)
  553. if user_ref is None:
  554. existing_user = (
  555. session.query(DynamicUser)
  556. .filter_by(username=username, ip=ip)
  557. .first()
  558. )
  559. if existing_user:
  560. user_ref = existing_user.id
  561. else:
  562. user_ref = DynamicUser(
  563. username=username,
  564. ip=ip,
  565. created_at=log_datetime,
  566. )
  567. pending_users[date_suffix].append(user_ref)
  568. date_stats["users"] += 1
  569. user_cache[user_key] = user_ref
  570. pending_logs[date_suffix].append(
  571. (
  572. user_ref,
  573. {
  574. "url": log_data.get("url") or "-",
  575. "response": log_data.get("response", 0),
  576. "request_count": 1,
  577. "data_transmitted": log_data.get("data_transmitted", 0),
  578. "created_at": log_datetime,
  579. },
  580. )
  581. )
  582. date_stats["logs"] += 1
  583. if (
  584. sum(len(items) for items in pending_logs.values())
  585. + sum(len(items) for items in pending_users.values())
  586. + len(pending_denied)
  587. >= BATCH_SIZE
  588. ):
  589. commit_batch()
  590. logger.info(
  591. "LOG_IMPORT_BATCH_COMMIT file={} processed={} parsed={} skipped={} pending_users={} pending_logs={} pending_denied={} current_position={} last_valid_line={}",
  592. log_file,
  593. summary["processed_lines"],
  594. summary["parsed_lines"],
  595. summary["skipped_lines"],
  596. sum(len(items) for items in pending_users.values()),
  597. sum(len(items) for items in pending_logs.values()),
  598. len(pending_denied),
  599. current_position,
  600. _preview_log_line(last_valid_line),
  601. )
  602. commit_batch()
  603. summary["dates"] = [date_summaries[key] for key in sorted(date_summaries)]
  604. elapsed = time.time() - start_time
  605. logger.info(
  606. "LOG_IMPORT_SUMMARY file={} total_lines={} processed={} parsed={} skipped={} inserted_logs={} inserted_users={} inserted_denied={} current_position={} last_line_seen={} last_valid_line={} last_skipped_line={} elapsed_seconds={:.2f}",
  607. log_file,
  608. total_lines,
  609. summary["processed_lines"],
  610. summary["parsed_lines"],
  611. summary["skipped_lines"],
  612. summary["inserted_logs"],
  613. summary["inserted_users"],
  614. summary["inserted_denied"],
  615. current_position,
  616. _preview_log_line(last_line_seen),
  617. _preview_log_line(last_valid_line),
  618. _preview_log_line(last_skipped_line),
  619. elapsed,
  620. )
  621. return summary, current_position
  622. def import_logs(log_file):
  623. """Import a complete log file, routing entries to their daily tables.
  624. Unlike :func:`process_logs`, this function intentionally does not read or
  625. update ``log_metadata``. It is therefore safe for an administrator to
  626. import a rotated or historical file without changing the live tailer's
  627. cursor.
  628. """
  629. if not os.path.exists(log_file):
  630. raise FileNotFoundError(log_file)
  631. session = get_session()
  632. try:
  633. summary, _ = _ingest_log_file(log_file, session)
  634. if summary["parsed_lines"] == 0:
  635. raise ValueError("The log file contains no valid Squid access entries")
  636. return summary
  637. except Exception:
  638. session.rollback()
  639. logger.exception("Critical error importing log file")
  640. raise
  641. finally:
  642. session.close()
  643. def process_logs(log_file):
  644. """Process only the new tail of the live log and update its cursor."""
  645. if not os.path.exists(log_file):
  646. logger.error(f"File not found: {log_file}")
  647. return _new_import_summary()
  648. current_inode = get_file_inode(log_file)
  649. file_size = os.path.getsize(log_file)
  650. line_count = _count_lines(log_file)
  651. session = get_session()
  652. try:
  653. metadata = session.query(LogMetadata).first()
  654. last_position = metadata.last_position if metadata else 0
  655. last_inode = metadata.last_inode if metadata else None
  656. last_updated = metadata.updated_at if metadata else None
  657. logger.info(
  658. "LOG_TAIL_CHECK file={} size_bytes={} inode={} line_count={} metadata_exists={} metadata_last_position={} metadata_last_inode={} metadata_updated_at={} start_position={}",
  659. log_file,
  660. file_size,
  661. current_inode,
  662. line_count,
  663. bool(metadata),
  664. last_position,
  665. last_inode,
  666. last_updated,
  667. last_position,
  668. )
  669. if metadata:
  670. if metadata.last_inode != current_inode:
  671. logger.info(
  672. "LOG_TAIL_RESET_INODE file={} old_inode={} new_inode={} reason=inode_changed",
  673. log_file,
  674. metadata.last_inode,
  675. current_inode,
  676. )
  677. last_position = 0
  678. elif file_size < last_position:
  679. logger.warning(
  680. "LOG_TAIL_RESET_TRUNCATE file={} size_bytes={} last_position={} reason=file_truncated",
  681. log_file,
  682. file_size,
  683. last_position,
  684. )
  685. last_position = 0
  686. summary, current_position = _ingest_log_file(
  687. log_file, session, start_position=last_position
  688. )
  689. if metadata is None:
  690. metadata = LogMetadata()
  691. session.add(metadata)
  692. metadata.last_position = current_position
  693. metadata.last_inode = current_inode
  694. metadata.updated_at = datetime.now()
  695. session.commit()
  696. logger.info(
  697. "LOG_TAIL_SAVE file={} size_bytes={} inode={} line_count={} final_position={} previous_position={} meta_updated_at={} inserted_logs={} inserted_users={} inserted_denied={}",
  698. log_file,
  699. file_size,
  700. current_inode,
  701. line_count,
  702. current_position,
  703. last_position,
  704. metadata.updated_at,
  705. summary["inserted_logs"],
  706. summary["inserted_users"],
  707. summary["inserted_denied"],
  708. )
  709. return summary
  710. except Exception as error:
  711. session.rollback()
  712. logger.critical(f"Critical error in process_logs: {error}", exc_info=True)
  713. raise
  714. finally:
  715. session.close()