250 lines
9.4 KiB
Python
250 lines
9.4 KiB
Python
"""nginx 접근 로그 → site_requests 수집.
|
|
|
|
웹 프로세스 lifespan 에서 도는 루프(run_forever)가 주기마다 ingest_once 를 부른다. 수동 실행은
|
|
POST /internal/traffic/ingest. gunicorn 워커가 여럿이면 루프도 여럿이지만, 커서 행(site_log_cursor id=1)을
|
|
SELECT … FOR UPDATE SKIP LOCKED 로 잡은 하나만 그 회차를 읽고 나머지는 건너뛴다.
|
|
|
|
로그 형식은 docs/deploy/traffic-nginx.md 의 `log_format ado2_traffic` (escape=json, 한 줄 = JSON 하나).
|
|
로테이션: 파일 inode 가 바뀌면 이전 파일(`<경로>.1`)의 남은 줄을 먼저 읽고 새 파일 처음으로 넘어간다.
|
|
copytruncate 로 크기가 줄었으면 처음부터 다시 읽는다(그 사이 줄은 잃는다).
|
|
"""
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
from dataclasses import asdict, dataclass, field
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.database.session import BackgroundSessionLocal
|
|
from app.traffic.detect.crawler_detect import classify
|
|
from app.traffic.detect.paths import request_of
|
|
from app.traffic.detect.visit_detect import referrer_host, visitor_hash
|
|
from app.traffic.models import SiteLogCursor, SiteRequest
|
|
from app.utils.logger import get_logger
|
|
from app.utils.timezone import now as kst_now
|
|
from config import TIMEZONE, internal_settings, traffic_settings
|
|
|
|
logger = get_logger("traffic")
|
|
|
|
CURSOR_ID = 1
|
|
_MAX_UA = 512
|
|
|
|
|
|
@dataclass
|
|
class Chunk:
|
|
"""한 회차에 읽은 완전한 줄들과, 다음 회차가 이어 읽을 위치."""
|
|
|
|
lines: list[bytes] = field(default_factory=list)
|
|
inode: int = 0
|
|
offset: int = 0
|
|
rotated: bool = False
|
|
|
|
|
|
@dataclass
|
|
class IngestResult:
|
|
lines_read: int = 0
|
|
inserted: int = 0
|
|
#: 정적 자원·API 등 통계 대상이 아니라 버린 줄
|
|
skipped: int = 0
|
|
#: JSON 이 깨졌거나 필드가 틀린 줄
|
|
bad: int = 0
|
|
rotated: bool = False
|
|
#: 다른 프로세스가 이 회차를 잡고 있어 건너뜀
|
|
locked: bool = False
|
|
|
|
def as_dict(self) -> dict:
|
|
return asdict(self)
|
|
|
|
|
|
def _read_lines(path: str, offset: int, max_lines: int) -> tuple[list[bytes], int]:
|
|
"""offset 부터 개행으로 끝나는 줄만 max_lines 까지 읽는다. 쓰다 만 마지막 줄은 다음 회차로 남긴다."""
|
|
lines: list[bytes] = []
|
|
with open(path, "rb") as f:
|
|
f.seek(offset)
|
|
while len(lines) < max_lines:
|
|
line = f.readline()
|
|
if not line.endswith(b"\n"):
|
|
break
|
|
offset += len(line)
|
|
lines.append(line)
|
|
return lines, offset
|
|
|
|
|
|
def read_new_lines(path: str, inode: int, offset: int, max_lines: int) -> Chunk:
|
|
st = os.stat(path)
|
|
if st.st_ino == inode and st.st_size >= offset:
|
|
lines, new_offset = _read_lines(path, offset, max_lines)
|
|
return Chunk(lines, inode, new_offset)
|
|
|
|
first_run = inode == 0 and offset == 0
|
|
if not first_run and st.st_ino != inode:
|
|
# logrotate 가 이름을 바꿨다 — 이전 파일에 남은 줄부터 마저 읽는다
|
|
old = f"{path}.1"
|
|
try:
|
|
old_st = os.stat(old)
|
|
except FileNotFoundError:
|
|
old_st = None
|
|
if old_st is not None and old_st.st_ino == inode and old_st.st_size > offset:
|
|
lines, new_offset = _read_lines(old, offset, max_lines)
|
|
if lines:
|
|
return Chunk(lines, inode, new_offset)
|
|
|
|
lines, new_offset = _read_lines(path, 0, max_lines)
|
|
return Chunk(lines, st.st_ino, new_offset, rotated=not first_run)
|
|
|
|
|
|
def _kst_naive(value: str) -> datetime:
|
|
t = datetime.fromisoformat(value)
|
|
if t.tzinfo is not None:
|
|
t = t.astimezone(TIMEZONE)
|
|
return t.replace(tzinfo=None)
|
|
|
|
|
|
def build_request(entry: dict, secret: str) -> SiteRequest | None:
|
|
"""로그 한 줄(JSON) → 저장할 행. 통계 대상이 아니면 None. 필드가 틀리면 KeyError/ValueError/TypeError."""
|
|
uri = entry["uri"]
|
|
if not isinstance(uri, str):
|
|
raise TypeError("uri")
|
|
info = request_of(uri)
|
|
if info is None:
|
|
return None
|
|
|
|
created_at = _kst_naive(entry["time"])
|
|
ip = str(entry.get("ip") or "")
|
|
ua = str(entry.get("ua") or "")[:_MAX_UA]
|
|
ref = entry.get("ref")
|
|
bot = classify(ua)
|
|
return SiteRequest(
|
|
created_at=created_at,
|
|
method=str(entry.get("method") or "")[:8],
|
|
path=info.path,
|
|
status=int(entry["status"]),
|
|
bytes_sent=int(entry.get("bytes") or 0),
|
|
request_time_ms=round(float(entry.get("rt") or 0) * 1000),
|
|
kind=info.kind,
|
|
content_type=info.content_type,
|
|
content_id=info.content_id,
|
|
ip_hash=visitor_hash(secret, ip, ua, created_at),
|
|
# IP 는 목록에 있는 봇만 남긴다 — 사람·기타 봇은 해시만
|
|
ip=ip[:45] if bot is not None and bot.bot is not None else None,
|
|
is_bot=bot is not None,
|
|
bot_name=bot.bot if bot else None,
|
|
bot_company=bot.company if bot else None,
|
|
bot_purpose=bot.purpose if bot else None,
|
|
user_agent=ua,
|
|
referrer_host=referrer_host(ref if isinstance(ref, str) and ref != "-" else None),
|
|
)
|
|
|
|
|
|
def process_lines(lines: list[bytes], secret: str) -> tuple[list[SiteRequest], int, int]:
|
|
"""→ (저장할 행, 버린 줄 수, 깨진 줄 수)."""
|
|
rows: list[SiteRequest] = []
|
|
skipped = bad = 0
|
|
for raw in lines:
|
|
try:
|
|
entry = json.loads(raw.decode("utf-8", errors="replace"))
|
|
if not isinstance(entry, dict):
|
|
raise TypeError("line is not an object")
|
|
row = build_request(entry, secret)
|
|
except (KeyError, ValueError, TypeError):
|
|
bad += 1
|
|
continue
|
|
if row is None:
|
|
skipped += 1
|
|
else:
|
|
rows.append(row)
|
|
if bad:
|
|
logger.warning(f"[traffic] 접근 로그 깨진 줄 {bad}건 건너뜀")
|
|
return rows, skipped, bad
|
|
|
|
|
|
def lock_cursor_stmt():
|
|
"""다른 프로세스가 잡은 행은 기다리지 않고 건너뛴다(MySQL 8 SKIP LOCKED)."""
|
|
return select(SiteLogCursor).where(SiteLogCursor.id == CURSOR_ID).with_for_update(skip_locked=True)
|
|
|
|
|
|
async def _lock_cursor(session: AsyncSession) -> SiteLogCursor | None:
|
|
"""커서 행을 잠근다. 다른 프로세스가 잡고 있으면 None. 행이 없으면 만든다(DEBUG 자동 생성 대비)."""
|
|
cursor = (await session.execute(lock_cursor_stmt())).scalar_one_or_none()
|
|
if cursor is not None:
|
|
return cursor
|
|
|
|
count = await session.scalar(select(func.count()).select_from(SiteLogCursor).where(SiteLogCursor.id == CURSOR_ID))
|
|
if count:
|
|
await session.rollback()
|
|
return None
|
|
cursor = SiteLogCursor(id=CURSOR_ID, inode=0, file_offset=0)
|
|
session.add(cursor)
|
|
try:
|
|
await session.flush()
|
|
except IntegrityError:
|
|
# 다른 프로세스가 같은 순간에 만들었다 — 이번 회차는 그쪽이 읽는다
|
|
await session.rollback()
|
|
return None
|
|
return cursor
|
|
|
|
|
|
async def _insert_rows(session: AsyncSession, rows: list[SiteRequest]) -> None:
|
|
session.add_all(rows)
|
|
await session.flush()
|
|
|
|
|
|
async def ingest_once(session: AsyncSession, path: str, max_lines: int, secret: str) -> IngestResult:
|
|
cursor = await _lock_cursor(session)
|
|
if cursor is None:
|
|
return IngestResult(locked=True)
|
|
|
|
chunk = await asyncio.to_thread(read_new_lines, path, cursor.inode, cursor.file_offset, max_lines)
|
|
rows, skipped, bad = process_lines(chunk.lines, secret)
|
|
if rows:
|
|
await _insert_rows(session, rows)
|
|
cursor.inode = chunk.inode
|
|
cursor.file_offset = chunk.offset
|
|
cursor.updated_at = kst_now().replace(tzinfo=None)
|
|
await session.commit()
|
|
return IngestResult(
|
|
lines_read=len(chunk.lines), inserted=len(rows), skipped=skipped, bad=bad, rotated=chunk.rotated
|
|
)
|
|
|
|
|
|
async def ingest_configured(session: AsyncSession) -> IngestResult:
|
|
"""설정값으로 한 회차 수집."""
|
|
return await ingest_once(
|
|
session,
|
|
traffic_settings.TRAFFIC_ACCESS_LOG_PATH,
|
|
traffic_settings.TRAFFIC_INGEST_MAX_LINES,
|
|
internal_settings.INTERNAL_SECRET_KEY,
|
|
)
|
|
|
|
|
|
async def run_forever(stop: asyncio.Event) -> None:
|
|
"""lifespan 에서 띄우는 수집 루프. 상한까지 읽은 회차 뒤에는 쉬지 않고 이어 읽는다."""
|
|
interval = traffic_settings.TRAFFIC_INGEST_INTERVAL_SECONDS
|
|
max_lines = traffic_settings.TRAFFIC_INGEST_MAX_LINES
|
|
logger.info(f"[traffic] 접근 로그 수집 시작 - path: {traffic_settings.TRAFFIC_ACCESS_LOG_PATH}, 주기: {interval}s")
|
|
while not stop.is_set():
|
|
backlog = False
|
|
try:
|
|
async with BackgroundSessionLocal() as session:
|
|
result = await ingest_configured(session)
|
|
backlog = result.lines_read >= max_lines
|
|
if result.lines_read:
|
|
logger.info(f"[traffic] 접근 로그 수집 - {result.as_dict()}")
|
|
except FileNotFoundError:
|
|
logger.warning(f"[traffic] 접근 로그 파일 없음 - path: {traffic_settings.TRAFFIC_ACCESS_LOG_PATH}")
|
|
except Exception as e:
|
|
logger.warning(f"[traffic] 접근 로그 수집 실패 - error: {e}")
|
|
if backlog:
|
|
await asyncio.sleep(0)
|
|
continue
|
|
try:
|
|
await asyncio.wait_for(stop.wait(), timeout=interval)
|
|
except TimeoutError:
|
|
# 주기가 끝났다는 뜻일 뿐이다(오류 아님) — 다음 회차로
|
|
continue
|
|
logger.info("[traffic] 접근 로그 수집 중단")
|