diff --git a/gui/app.py b/gui/app.py index e12ab92..f1b9757 100644 --- a/gui/app.py +++ b/gui/app.py @@ -2712,7 +2712,7 @@ def reports_trips_import(): -@app.route("/access-points/auto-verification") +@app.route("/reports/access-points/auto-verification") def auto_verification_map(): interfaces, interface_error = ( diff --git a/reports/access_points.py b/reports/access_points.py index 7b9f271..1896a9f 100644 --- a/reports/access_points.py +++ b/reports/access_points.py @@ -1224,6 +1224,22 @@ Time interval: — {esc(format_datetime(last_time))} + +""" + + html += """ +
""" diff --git a/reports/dashboard.py b/reports/dashboard.py index 34ede71..7e7f0f6 100644 --- a/reports/dashboard.py +++ b/reports/dashboard.py @@ -64,6 +64,8 @@ from .sessions import ( ) +from .recovery import recovery_block + # ============================================================ # Helpers # ============================================================ @@ -793,6 +795,14 @@ def generate_dashboard( context, ) + # -------------------------------------------------------- + # Recovery + # -------------------------------------------------------- + + html += recovery_block( + conn + ) + # -------------------------------------------------------- # Footer # -------------------------------------------------------- diff --git a/reports/recovery.py b/reports/recovery.py new file mode 100644 index 0000000..2d9d650 --- /dev/null +++ b/reports/recovery.py @@ -0,0 +1,366 @@ +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( + "+ Дата начала: + {esc(candidate["start_time"])} +
+ ++ Обнаружено: + {esc(candidate["kind"])} +
+ +Состояние данных в БД:
+Найденные файлы:
+Причины обнаружения:
++ Возможное дальнейшее действие: + {esc(candidate["actions"])} +
+