log.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import os
  2. import re
  3. import time
  4. from datetime import datetime
  5. from loguru import logger
  6. from sqlalchemy.exc import IntegrityError, OperationalError, SQLAlchemyError
  7. from database.database import (
  8. Base,
  9. DeniedLog,
  10. LogMetadata,
  11. get_dynamic_models,
  12. get_dynamic_table_names,
  13. get_engine,
  14. get_session,
  15. table_exists,
  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 _is_number(value: str) -> bool:
  106. try:
  107. float(value)
  108. return True
  109. except (TypeError, ValueError):
  110. return False
  111. def _is_integer(value: str) -> bool:
  112. return value.isdigit()
  113. def _response_code(status: str) -> int:
  114. code = status.rsplit("/", 1)[-1]
  115. return int(code) if code.isdigit() else 0
  116. def _bytes_transmitted(value: str) -> int:
  117. return int(value) if _is_integer(value) else 0
  118. def _is_default_line(parts: list[str]) -> bool:
  119. """Recognize Squid's native access.log layout without parsing it twice."""
  120. return bool(
  121. len(parts) >= 7
  122. and _is_number(parts[0])
  123. and _is_number(parts[1])
  124. and "/" in parts[3]
  125. and _is_integer(parts[3].rsplit("/", 1)[-1])
  126. and (parts[4] == "-" or _is_integer(parts[4]))
  127. and parts[5].upper() in HTTP_METHODS
  128. )
  129. def _is_pipe_line(line: str) -> bool:
  130. parts = line.strip().split("|")
  131. return bool(
  132. len(parts) >= 14
  133. and _is_number(parts[0])
  134. and _is_integer(parts[8])
  135. and _is_integer(parts[9])
  136. and parts[5].upper() in HTTP_METHODS
  137. )
  138. def _is_space_detailed_line(parts: list[str]) -> bool:
  139. """Recognize the legacy whitespace-separated DETAILED layout."""
  140. return bool(
  141. len(parts) >= 11
  142. and _is_number(parts[0])
  143. and parts[5].upper() in HTTP_METHODS
  144. and _is_integer(parts[9])
  145. and _is_integer(parts[10])
  146. )
  147. def _is_quoted_detailed_line(line: str):
  148. match = DETAILED_REQUEST_RE.match(line.strip())
  149. return bool(match and match.group("method").upper() in HTTP_METHODS)
  150. def _detect_line_format(line: str) -> str | None:
  151. if not isinstance(line, str) or not line.strip():
  152. return None
  153. if _is_pipe_line(line):
  154. return FORMAT_DETAILED
  155. parts = line.split()
  156. if _is_default_line(parts):
  157. return FORMAT_DEFAULT
  158. if _is_quoted_detailed_line(line) or _is_space_detailed_line(parts):
  159. return FORMAT_DETAILED
  160. return None
  161. def _ignore_log_line(line: str) -> bool:
  162. line_lower = line.lower()
  163. return (
  164. "cache_object://" in line_lower
  165. or "error:transaction-end-before-headers" in line_lower
  166. or "error:invalid-request" in line_lower
  167. )
  168. def parse_log_line(line: str, format_hint: str = FORMAT_AUTO):
  169. """Parse one line using a detected format or safe per-line detection."""
  170. if not isinstance(line, str) or not line.strip():
  171. return None
  172. try:
  173. if _ignore_log_line(line):
  174. return None
  175. except Exception as error:
  176. logger.debug("Unexpected error pre-filtering log line: {}", error)
  177. return None
  178. normalized_hint = (format_hint or FORMAT_AUTO).upper()
  179. if normalized_hint == FORMAT_DEFAULT:
  180. return parse_log_line_default(line)
  181. if normalized_hint == FORMAT_DETAILED:
  182. return parse_log_line_detailed(line)
  183. detected_format = _detect_line_format(line)
  184. if detected_format == FORMAT_DEFAULT:
  185. return parse_log_line_default(line)
  186. if detected_format == FORMAT_DETAILED:
  187. return parse_log_line_detailed(line)
  188. return None
  189. def parse_log_line_default(line: str):
  190. """Parse Squid's standard format.
  191. ``timestamp elapsed client_ip result/status bytes method url user
  192. hierarchy content-type``
  193. """
  194. try:
  195. if _ignore_log_line(line):
  196. return None
  197. parts = line.split()
  198. if not _is_default_line(parts):
  199. return None
  200. status = parts[3]
  201. ip = parts[2]
  202. user_field = parts[7] if len(parts) > 7 else "-"
  203. username = user_field if user_field != "-" else ip
  204. return {
  205. "ip": ip,
  206. "username": username if username != "-" else None,
  207. "url": parts[6],
  208. "response": _response_code(status),
  209. "data_transmitted": _bytes_transmitted(parts[4]),
  210. "method": parts[5].upper(),
  211. "status": status,
  212. "is_denied": "TCP_DENIED" in status,
  213. }
  214. except (IndexError, TypeError, ValueError) as error:
  215. logger.debug("Unable to parse DEFAULT log line: {} ({})", line.strip(), error)
  216. return None
  217. def parse_log_line_detailed(line: str):
  218. """Parse the supported legacy DETAILED variants."""
  219. if _ignore_log_line(line):
  220. return None
  221. if _is_pipe_line(line):
  222. return parse_log_line_pipe_format(line)
  223. quoted_match = DETAILED_REQUEST_RE.match(line.strip())
  224. if quoted_match:
  225. try:
  226. identity = quoted_match.group("identity")
  227. username = quoted_match.group("username")
  228. ip = quoted_match.group("ip")
  229. if username == "-":
  230. username = identity if identity != "-" else ip
  231. if username == "-":
  232. username = None
  233. status = quoted_match.group("status")
  234. return {
  235. "ip": ip,
  236. "username": username,
  237. "url": quoted_match.group("url"),
  238. "response": _response_code(status),
  239. "data_transmitted": _bytes_transmitted(quoted_match.group("bytes")),
  240. "method": quoted_match.group("method").upper(),
  241. "status": status,
  242. "is_denied": "TCP_DENIED" in line,
  243. }
  244. except (IndexError, TypeError, ValueError) as error:
  245. logger.debug(
  246. "Unable to parse quoted DETAILED log line: {} ({})",
  247. line.strip(),
  248. error,
  249. )
  250. return None
  251. return parse_log_line_space_format(line)
  252. def parse_log_line_pipe_format(line):
  253. parts = line.strip().split("|")
  254. if not _is_pipe_line(line):
  255. return None
  256. try:
  257. username = parts[3]
  258. if username == "-":
  259. return None
  260. return {
  261. "ip": parts[1],
  262. "username": username,
  263. "url": parts[6],
  264. "response": int(parts[8]),
  265. "data_transmitted": int(parts[9]),
  266. "method": parts[5].upper(),
  267. "status": parts[13],
  268. "is_denied": "TCP_DENIED" in parts[13],
  269. }
  270. except (IndexError, TypeError, ValueError) as error:
  271. logger.debug("Unable to parse pipe log line: {} ({})", line.strip(), error)
  272. return None
  273. def parse_log_line_space_format(line):
  274. """Parse the legacy whitespace-separated DETAILED variant."""
  275. try:
  276. parts = line.split()
  277. if not _is_space_detailed_line(parts) or parts[3] == "-":
  278. return None
  279. status = parts[4]
  280. return {
  281. "ip": parts[1],
  282. "username": parts[3],
  283. "url": parts[6],
  284. "response": int(parts[9]),
  285. "data_transmitted": int(parts[10]),
  286. "method": parts[5].upper(),
  287. "status": status,
  288. "is_denied": "TCP_DENIED" in line,
  289. }
  290. except (IndexError, TypeError, ValueError) as error:
  291. logger.debug(
  292. "Unable to parse space DETAILED line: {} ({})", line.strip(), error
  293. )
  294. return None
  295. def detect_log_format(log_file, sample_lines=32, start_position=0):
  296. """Detect DEFAULT or DETAILED by validating a small sample of lines."""
  297. try:
  298. with open(log_file, encoding="utf-8", errors="replace") as file:
  299. if start_position:
  300. file.seek(start_position)
  301. counts = {FORMAT_DEFAULT: 0, FORMAT_DETAILED: 0}
  302. for _ in range(sample_lines):
  303. line = file.readline()
  304. if not line:
  305. break
  306. detected = _detect_line_format(line)
  307. if detected:
  308. counts[detected] += 1
  309. # A tail containing only malformed/ignored lines should not force
  310. # a wrong format. Retry from the beginning in that case.
  311. if not any(counts.values()) and start_position:
  312. file.seek(0)
  313. for _ in range(sample_lines):
  314. line = file.readline()
  315. if not line:
  316. break
  317. detected = _detect_line_format(line)
  318. if detected:
  319. counts[detected] += 1
  320. if not any(counts.values()):
  321. return FORMAT_AUTO
  322. if counts[FORMAT_DEFAULT] > counts[FORMAT_DETAILED]:
  323. return FORMAT_DEFAULT
  324. if counts[FORMAT_DETAILED] > counts[FORMAT_DEFAULT]:
  325. return FORMAT_DETAILED
  326. return FORMAT_AUTO
  327. except OSError as error:
  328. logger.warning(
  329. "Unable to detect log format; using per-line detection: {}", error
  330. )
  331. return FORMAT_AUTO
  332. def process_logs(log_file):
  333. if not os.path.exists(log_file):
  334. logger.error(f"File not found: {log_file}")
  335. return
  336. engine = get_engine()
  337. user_table, log_table = get_dynamic_table_names()
  338. if not (table_exists(engine, user_table) and table_exists(engine, log_table)):
  339. logger.warning(
  340. f"User/log tables for date suffix '{datetime.now().strftime('%Y%m%d')}' do not exist. Attempting to recreate..."
  341. )
  342. try:
  343. Base.metadata.create_all(engine, checkfirst=True)
  344. logger.info("Tables created successfully.")
  345. except Exception as e:
  346. logger.error(f"Error creating dynamic tables: {e}")
  347. return
  348. try:
  349. current_inode = get_file_inode(log_file)
  350. file_size = os.path.getsize(log_file)
  351. date_suffix = datetime.now().strftime("%Y%m%d")
  352. DynamicUser, DynamicLog = get_dynamic_models(date_suffix)
  353. with DatabaseManager() as session:
  354. metadata = session.query(LogMetadata).first()
  355. last_position = metadata.last_position if metadata else 0
  356. if metadata:
  357. if metadata.last_inode != current_inode:
  358. logger.info(
  359. f"Inode changed: {metadata.last_inode} -> {current_inode}. Resetting position."
  360. )
  361. last_position = 0
  362. elif file_size < last_position:
  363. logger.warning(
  364. f"File truncated (size: {file_size} < position: {last_position})"
  365. )
  366. last_position = 0
  367. detected_format = detect_log_format(log_file, start_position=last_position)
  368. logger.info(
  369. "Detected Squid log format: {}",
  370. detected_format,
  371. )
  372. # logger.info(f"Reading from position: {last_position}")
  373. user_cache = {}
  374. logs_to_insert, new_users_to_insert, denied_to_insert = [], [], []
  375. processed_lines = inserted_logs = inserted_users = inserted_denied = 0
  376. start_time = time.time()
  377. def commit_batch():
  378. nonlocal inserted_logs, inserted_users, inserted_denied
  379. retry_count = 0
  380. user_table, log_table = get_dynamic_table_names()
  381. while retry_count < MAX_RETRIES:
  382. try:
  383. if new_users_to_insert:
  384. session.bulk_save_objects(new_users_to_insert)
  385. session.flush()
  386. for user in new_users_to_insert:
  387. user_cache[(user.username, user.ip)] = user.id
  388. inserted_users += len(new_users_to_insert)
  389. new_users_to_insert.clear()
  390. if logs_to_insert:
  391. session.bulk_insert_mappings(DynamicLog, logs_to_insert)
  392. inserted_logs += len(logs_to_insert)
  393. logs_to_insert.clear()
  394. if denied_to_insert:
  395. session.bulk_save_objects(denied_to_insert)
  396. inserted_denied += len(denied_to_insert)
  397. denied_to_insert.clear()
  398. session.commit()
  399. return True
  400. except IntegrityError as e:
  401. logger.warning(
  402. f"Integrity error (retry {retry_count + 1}): {e}"
  403. )
  404. session.rollback()
  405. retry_count += 1
  406. if new_users_to_insert:
  407. for user in new_users_to_insert:
  408. key = (user.username, user.ip)
  409. if key in user_cache:
  410. del user_cache[key]
  411. except OperationalError as e:
  412. if "database is locked" in str(e).lower():
  413. retry_count += 1
  414. logger.warning(
  415. f"Database locked, retrying ({retry_count}/{MAX_RETRIES})..."
  416. )
  417. session.rollback()
  418. time.sleep(0.5 * retry_count)
  419. else:
  420. logger.error(f"Database error: {e}")
  421. session.rollback()
  422. break
  423. except SQLAlchemyError as e:
  424. logger.error(f"Database error: {e}")
  425. session.rollback()
  426. break
  427. return False
  428. with open(log_file, encoding="utf-8", errors="replace") as f:
  429. f.seek(last_position)
  430. current_position = last_position
  431. for line in f:
  432. processed_lines += 1
  433. current_position += len(line.encode("utf-8"))
  434. log_data = parse_log_line(line, format_hint=detected_format)
  435. if not log_data:
  436. continue
  437. if log_data["is_denied"]:
  438. denied_entry = DeniedLog(
  439. username=log_data["username"],
  440. ip=log_data["ip"],
  441. url=log_data["url"],
  442. method=log_data.get("method", ""),
  443. status=log_data.get("status", ""),
  444. response=log_data.get("response"),
  445. data_transmitted=log_data.get("data_transmitted", 0),
  446. created_at=datetime.now(),
  447. )
  448. denied_to_insert.append(denied_entry)
  449. if len(denied_to_insert) >= BATCH_SIZE:
  450. if commit_batch():
  451. logger.info(
  452. f"Batch denied_logs inserted successfully. Records: {BATCH_SIZE}"
  453. )
  454. else:
  455. logger.error(
  456. "Error committing denied batch. Continuing with next batch"
  457. )
  458. continue
  459. user_key = (log_data["username"], log_data["ip"])
  460. user_id = user_cache.get(user_key)
  461. if user_id is None:
  462. existing_user = (
  463. session.query(DynamicUser)
  464. .filter_by(username=log_data["username"], ip=log_data["ip"])
  465. .first()
  466. )
  467. if existing_user:
  468. user_id = existing_user.id
  469. user_cache[user_key] = user_id
  470. else:
  471. new_user = DynamicUser(
  472. username=log_data["username"], ip=log_data["ip"]
  473. )
  474. new_users_to_insert.append(new_user)
  475. user_cache[user_key] = None
  476. user_id = None
  477. if user_id is None:
  478. if not commit_batch():
  479. logger.error(
  480. "Critical error committing batch. Aborting batch"
  481. )
  482. continue
  483. existing_user = (
  484. session.query(DynamicUser)
  485. .filter_by(username=log_data["username"], ip=log_data["ip"])
  486. .first()
  487. )
  488. if existing_user:
  489. user_id = existing_user.id
  490. user_cache[user_key] = user_id
  491. else:
  492. logger.error(
  493. f"Usuario no creado: {user_key}. Saltando línea"
  494. )
  495. continue
  496. logs_to_insert.append(
  497. {
  498. "user_id": user_id,
  499. "url": log_data["url"],
  500. "response": log_data["response"],
  501. "request_count": 1,
  502. "data_transmitted": log_data["data_transmitted"],
  503. "created_at": datetime.now(),
  504. }
  505. )
  506. if len(logs_to_insert) >= BATCH_SIZE:
  507. if not commit_batch():
  508. logger.error(
  509. "Error committing batch. Continuing with next batch"
  510. )
  511. # Commit any remaining items that didn't fill a full batch
  512. if logs_to_insert or new_users_to_insert or denied_to_insert:
  513. if not commit_batch():
  514. logger.error("Final commit_batch failed for remaining items")
  515. if not metadata:
  516. metadata = LogMetadata()
  517. session.add(metadata)
  518. metadata.last_position = current_position
  519. metadata.last_inode = current_inode
  520. # Align with LogMetadata model's column
  521. metadata.updated_at = datetime.now()
  522. session.commit()
  523. elapsed = time.time() - start_time
  524. # logger.info(f"Processing completed. Lines: {processed_lines}")
  525. logger.info(
  526. f"Logs inserted: {inserted_logs}, New users: {inserted_users}, Denied: {inserted_denied}"
  527. )
  528. logger.info(
  529. f"Time: {elapsed:.2f}s, Speed: {processed_lines / elapsed:.2f} lps"
  530. )
  531. except Exception as e:
  532. logger.critical(f"Critical error in process_logs: {e}", exc_info=True)
  533. raise