Files
wifi-gps-mapper-releases/reports/recovery.py
T

367 lines
8.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from datetime import datetime, timedelta, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
from .config import CAPTURES_DIR, get_timezone
from .template import card
from .utils import esc
MIN_STALE_AGE = timedelta(minutes=15)
MAX_STALE_AGE = timedelta(hours=24)
SESSION_FILES = (
"capture.pcapng",
"gps_track.nmea",
"access_points.csv",
"handshakes.22000",
"essid.txt",
"identities.txt",
"parser.log",
)
def _utc_now(value=None):
if value is None:
return datetime.now(timezone.utc)
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _file_is_stale(path, now):
try:
modified = datetime.fromtimestamp(
path.stat().st_mtime,
timezone.utc,
)
except OSError:
return False
age = now - modified
return (
MIN_STALE_AGE <= age <= MAX_STALE_AGE
)
def _capture_is_interrupted(path, end_time, now):
if end_time is not None:
return False
try:
if not path.is_file():
return False
if path.stat().st_size <= 0:
return False
except OSError:
return False
return _file_is_stale(path, now)
def _resolve_session_directory(capture_file, captures_dir):
if not capture_file:
return None
root = Path(captures_dir).resolve()
path = Path(capture_file)
if not path.is_absolute():
path = root.parent / path
try:
resolved = path.resolve()
resolved.relative_to(root)
except (OSError, ValueError):
return None
return resolved.parent
def _parser_was_interrupted(parser_log):
last_started = -1
last_finished = -1
try:
with parser_log.open(
"r",
encoding="utf-8",
errors="replace",
) as file:
for index, line in enumerate(file):
if "Parser started" in line:
last_started = index
if "Parser finished" in line:
last_finished = index
except OSError:
return False
return last_started >= 0 and last_started > last_finished
def _session_counts(conn, session_id):
counts = {}
for name, table in (
("gps", "gps_track"),
("access_points", "access_point_observations"),
("handshakes", "handshakes"),
):
row = conn.execute(
f"""
SELECT COUNT(*)
FROM {table}
WHERE session_id = ?
""",
(session_id,),
).fetchone()
counts[name] = int(row[0])
return counts
def _parse_datetime(value):
if not value:
return None
try:
result = datetime.fromisoformat(
str(value).replace("Z", "+00:00")
)
except ValueError:
return None
if result.tzinfo is None:
return result.replace(tzinfo=timezone.utc)
return result.astimezone(timezone.utc)
def _format_datetime(value, display_timezone):
parsed = _parse_datetime(value)
if parsed is None:
return "Неизвестно"
return parsed.astimezone(
display_timezone
).strftime("%Y-%m-%d %H:%M:%S")
def _collect_files(session_dir):
result = []
for filename in SESSION_FILES:
path = session_dir / filename
try:
if not path.is_file():
continue
size = path.stat().st_size
except OSError:
continue
result.append({
"name": filename,
"size": size,
})
return result
def find_recovery_candidates(
conn,
captures_dir=None,
now=None,
timezone_name=None,
):
now = _utc_now(now)
if captures_dir is None:
captures_dir = CAPTURES_DIR
if timezone_name is None:
timezone_name = get_timezone()
try:
display_timezone = ZoneInfo(timezone_name)
except (TypeError, ValueError):
display_timezone = timezone.utc
rows = conn.execute("""
SELECT
id,
start_time,
end_time,
capture_file
FROM capture_sessions
ORDER BY id DESC
""").fetchall()
candidates = []
for row in rows:
session_id = row[0]
start_time = row[1]
end_time = row[2]
capture_file = row[3]
session_dir = _resolve_session_directory(
capture_file,
captures_dir,
)
if session_dir is None or not session_dir.is_dir():
continue
capture_path = session_dir / "capture.pcapng"
parser_log = session_dir / "parser.log"
capture_interrupted = _capture_is_interrupted(
capture_path,
end_time,
now,
)
parser_interrupted = (
parser_log.is_file()
and _file_is_stale(parser_log, now)
and _parser_was_interrupted(parser_log)
)
if not capture_interrupted and not parser_interrupted:
continue
counts = _session_counts(
conn,
session_id,
)
reasons = []
if capture_interrupted:
reasons.append(
"Запись capture.pcapng не обновлялась более "
"15 минут, а сессия в БД остаётся открытой."
)
if parser_interrupted:
reasons.append(
"В parser.log обнаружен запуск парсера без "
"последующего сообщения Parser finished; "
"лог не обновлялся более 15 минут."
)
files = _collect_files(session_dir)
candidates.append({
"id": session_id,
"start_time": _format_datetime(
start_time,
display_timezone,
),
"kind": (
"capture_and_parser"
if capture_interrupted and parser_interrupted
else "capture"
if capture_interrupted
else "parser"
),
"counts": counts,
"files": files,
"reasons": reasons,
"actions": (
"Проверить целостность файлов захвата и "
"оценить возможность завершения обработки поездки."
if capture_interrupted
else
"В БД уже присутствуют результаты обработки. "
"Сначала сверить их с исходными файлами; "
"не запускать повторный парсинг без проверки."
if any(counts.values())
else
"Проверить исходные файлы и оценить возможность "
"повторного выполнения парсинга."
),
})
return candidates
def recovery_block(conn):
candidates = find_recovery_candidates(conn)
if not candidates:
return ""
html = []
for candidate in candidates:
counts = candidate["counts"]
files_html = "".join(
"<li>{} — {} байт</li>".format(
esc(item["name"]),
item["size"],
)
for item in candidate["files"]
)
reasons_html = "".join(
"<li>{}</li>".format(esc(reason))
for reason in candidate["reasons"]
)
html.append(f"""
<div class="card">
<h3>Поездка #{candidate["id"]}</h3>
<p>
<strong>Дата начала:</strong>
{esc(candidate["start_time"])}
</p>
<p>
<strong>Обнаружено:</strong>
{esc(candidate["kind"])}
</p>
<p><strong>Состояние данных в БД:</strong></p>
<ul>
<li>GPS: {counts["gps"]}</li>
<li>Наблюдения точек доступа: {counts["access_points"]}</li>
<li>Handshake: {counts["handshakes"]}</li>
</ul>
<p><strong>Найденные файлы:</strong></p>
<ul>
{files_html}
</ul>
<p><strong>Причины обнаружения:</strong></p>
<ul>
{reasons_html}
</ul>
<p>
<strong>Возможное дальнейшее действие:</strong>
{esc(candidate["actions"])}
</p>
</div>
""")
return card(
"⚠️ Восстановление поездок",
"\n".join(html),
)