From 6d60e85ea4eb2ec3baf6661c8f75dee1cc069c30 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sat, 28 Nov 2026 15:36:30 -0600 Subject: [PATCH] athenad: run each connection in its own process for instant network changes (#39500) --- .../tests/test_companion_data_guards.py | 7 +- openpilot/system/athena/athenad.py | 319 ++++++++++-------- openpilot/system/athena/tests/test_athenad.py | 84 +++-- .../system/athena/tests/test_athenad_ping.py | 16 +- .../athena/tests/test_upload_preferences.py | 4 +- prebuilt.json | 2 +- 6 files changed, 262 insertions(+), 170 deletions(-) diff --git a/openpilot/starpilot/galaxy/tests/test_companion_data_guards.py b/openpilot/starpilot/galaxy/tests/test_companion_data_guards.py index 0595f23a32..64fe7eb754 100644 --- a/openpilot/starpilot/galaxy/tests/test_companion_data_guards.py +++ b/openpilot/starpilot/galaxy/tests/test_companion_data_guards.py @@ -1,3 +1,4 @@ +import queue import threading from types import SimpleNamespace from unittest.mock import Mock, patch @@ -25,11 +26,11 @@ def test_athena_allow_cellular_is_still_deferred(): stop = threading.Event() item = athenad.UploadItem(path='/unused', url='https://upload.test', headers={}, created_at=int(athenad.datetime.now().timestamp() * 1000), id='phone-test', allow_cellular=True) - queue = Mock() - queue.get.return_value = item + pending = queue.PriorityQueue() + pending.put(item) sm = Mock() sm.__getitem__ = Mock(return_value=SimpleNamespace(networkMetered=False, networkType=SimpleNamespace(raw=1))) - with patch.object(athenad, 'upload_queue', queue), patch.object(athenad.messaging, 'SubMaster', return_value=sm), \ + with patch.object(athenad, 'upload_queue', pending), patch.object(athenad.messaging, 'SubMaster', return_value=sm), \ patch.object(athenad, 'phone_uplink_active', return_value=True), \ patch.object(athenad, 'retry_upload', side_effect=lambda *_: stop.set()) as retry, \ patch.object(athenad, '_do_upload') as upload: diff --git a/openpilot/system/athena/athenad.py b/openpilot/system/athena/athenad.py index f552de7078..a099c76257 100755 --- a/openpilot/system/athena/athenad.py +++ b/openpilot/system/athena/athenad.py @@ -4,21 +4,25 @@ from __future__ import annotations from openpilot.starpilot.galaxy.companion import phone_uplink_active import base64 +import ctypes +import fcntl import hashlib import itertools import json import math +import multiprocessing import os import queue import random import re import select +import signal import socket import subprocess import sys import threading import time -from contextlib import suppress +from contextlib import contextmanager, suppress from dataclasses import asdict, dataclass, replace from datetime import datetime from functools import partial, total_ordering @@ -52,7 +56,7 @@ from openpilot.system.athena.rpc import (boolean, dict_of, dispatcher, dumps_cal list_of, loads, number, one_of, regex, struct) -from openpilot.starpilot.connect.provider import active_provider, owns_recording, cloudlog_root, mark_recording +from openpilot.starpilot.connect.provider import ROUTE_MARKER, active_provider, owns_recording, cloudlog_root, mark_recording CLOUD_PROVIDER = active_provider() ATHENA_HOST = os.getenv('ATHENA_HOST', CLOUD_PROVIDER.athena) if CLOUD_PROVIDER.name == 'comma' else CLOUD_PROVIDER.athena @@ -175,6 +179,7 @@ class AbortTransferException(Exception): class UploadQueueCache: + lock = threading.Lock() @staticmethod def initialize(upload_queue: Queue[UploadItem]) -> None: @@ -189,16 +194,51 @@ class UploadQueueCache: @staticmethod def cache(upload_queue: Queue[UploadItem]) -> None: try: - queue: list[UploadItem | None] = list(upload_queue.queue) - items = [asdict(i) for i in queue if i is not None and (i.id not in cancelled_uploads)] - Params().put("AthenadUploadQueue", items, block=True) + with UploadQueueCache.lock: # so an older snapshot can't overwrite a newer one + # in-flight uploads too, the session can be killed at any time + items = [{**item, "current": False, "progress": 0} for item in listUploadQueue()] + Params().put("AthenadUploadQueue", items, block=True) except Exception: cloudlog.exception("athena.UploadQueueCache.cache.exception") -def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None: - end_event = threading.Event() +def get_route_source() -> str | None: + # local address of the default route. connecting a UDP socket does the route lookup without sending anything + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + sock.connect(("8.8.8.8", 443)) + return sock.getsockname()[0] + except OSError: + return None + +def die_with_parent() -> None: + if sys.platform == "linux": + ctypes.CDLL(None).prctl(1, signal.SIGKILL) # PR_SET_PDEATHSIG + + +def fork(target: Callable, *args) -> multiprocessing.process.BaseProcess: + process = multiprocessing.get_context("fork").Process(target=target, args=args, daemon=True) + process.start() + return process + + +def run_session(ws_uri: str, dongle_id: str, retries: int) -> None: + # each connection gets a fresh process. killing it, like on a network change, drops all of its sockets and threads at once + die_with_parent() + start = time.monotonic() + cloudlog.event("athenad.main.connecting_ws", ws_uri=ws_uri, retries=retries) + try: + ws = create_connection(ws_uri, cookie="jwt=" + Api(dongle_id).get_token(), enable_multithread=True, timeout=30.0) + except (ConnectionError, TimeoutError, WebSocketException): + sys.exit(1) + except Exception: + cloudlog.exception("athenad.main.exception") + sys.exit(1) + cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri, retries=retries, duration=time.monotonic() - start) + UploadQueueCache.initialize(upload_queue) + + end_event = threading.Event() threads = [ threading.Thread(target=ws_manage, args=(ws, end_event), name='ws_manage'), threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'), @@ -214,23 +254,12 @@ def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None: ] for thread in threads: + thread.daemon = True thread.start() - try: - while not end_event.wait(0.1): - if exit_event is not None and exit_event.is_set(): - end_event.set() - except (KeyboardInterrupt, SystemExit): - end_event.set() - raise - finally: - for thread in threads: - cloudlog.debug(f"athena.joining {thread.name}") - thread.join() + end_event.wait() # any thread ending the session ends the process def jsonrpc_handler(end_event: threading.Event) -> None: - dispatcher.add_method(partial(startLocalProxy, end_event), name="startLocalProxy", - remote_ws_uri=regex(r'wss://ssh\.comma\.ai(:(443|8443))?/[0-9a-f]{16}'), local_port=one_of(8022, *LOCAL_PORT_WHITELIST)) while not end_event.is_set(): try: data = recv_queue.get(timeout=1) @@ -249,39 +278,39 @@ def jsonrpc_handler(end_event: threading.Event) -> None: send_queue_push(json.dumps({"error": str(e)}), SEND_PRIORITY_HIGH) +def finish_upload(tid: int) -> None: + cur_upload_items[tid] = None + UploadQueueCache.cache(upload_queue) + + def retry_upload(tid: int, end_event: threading.Event, increase_count: bool = True) -> None: item = cur_upload_items[tid] - if item is not None and item.retry_count < MAX_RETRY_COUNT: - new_retry_count = item.retry_count + 1 if increase_count else item.retry_count - - item = replace( - item, - retry_count=new_retry_count, - progress=0, - current=False - ) - upload_queue.put_nowait(item) - UploadQueueCache.cache(upload_queue) - + retry = item is not None and item.retry_count < MAX_RETRY_COUNT + with UploadQueueCache.lock: # move it back atomically + if retry: + upload_queue.put_nowait(replace(item, retry_count=item.retry_count + increase_count, progress=0, current=False)) cur_upload_items[tid] = None - + UploadQueueCache.cache(upload_queue) + if retry: end_event.wait(RETRY_DELAY) +def network_metered() -> bool: + # not deviceState, it lags a network change by up to 10 s. unknown might be a modem that hasn't reported in yet + network_type = HARDWARE.get_network_type() + return network_type == NetworkType.none or HARDWARE.get_network_metered(network_type) + + def cb(sm, item, tid, end_event: threading.Event, sz: int, cur: int) -> None: # Abort transfer if connection changed to metered after starting upload - # or if athenad is shutting down to re-connect the websocket - if phone_uplink_active(): + if phone_uplink_active() or end_event.is_set(): raise AbortTransferException if not item.allow_cellular: if (time.monotonic() - sm.recv_time['deviceState']) > DEVICE_STATE_UPDATE_INTERVAL: sm.update(0) - if sm['deviceState'].networkMetered and not Params().get_bool("AlwaysAllowUploads"): + if sm['deviceState'].networkMetered and network_metered() and not Params().get_bool("AlwaysAllowUploads"): raise AbortTransferException - if end_event.is_set(): - raise AbortTransferException - cur_upload_items[tid] = replace(item, progress=cur / sz if sz else 1) @@ -293,21 +322,27 @@ def upload_handler(end_event: threading.Event) -> None: cur_upload_items[tid] = None try: - cur_upload_items[tid] = item = replace(upload_queue.get(timeout=1), current=True) + with upload_queue.not_empty: # wait for work without taking it + upload_queue.not_empty.wait_for(lambda: upload_queue.queue, timeout=1) + with UploadQueueCache.lock: # so a cache snapshot sees the item either queued or in flight + cur_upload_items[tid] = item = replace(upload_queue.get_nowait(), current=True) if item.id in cancelled_uploads: - cancelled_uploads.remove(item.id) + with UploadQueueCache.lock: # so a cache snapshot never saves it + cur_upload_items[tid] = None + cancelled_uploads.remove(item.id) continue # Remove item if too old age = datetime.now() - datetime.fromtimestamp(item.created_at / 1000) if age.total_seconds() > MAX_AGE: cloudlog.event("athena.upload_handler.expired", item=item, error=True) + finish_upload(tid) continue # Check if uploading over metered connection is allowed sm.update(0) - metered = sm['deviceState'].networkMetered + metered = network_metered() network_type = sm['deviceState'].networkType.raw if phone_uplink_active() or (metered and not item.allow_cellular and not Params().get_bool("AlwaysAllowUploads")): retry_upload(tid, end_event, False) @@ -328,8 +363,7 @@ def upload_handler(end_event: threading.Event) -> None: retry_upload(tid, end_event) else: cloudlog.event("athena.upload_handler.success", fn=fn, sz=sz, network_type=network_type, metered=metered) - - UploadQueueCache.cache(upload_queue) + finish_upload(tid) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.SSLError): cloudlog.event("athena.upload_handler.timeout", fn=fn, sz=sz, network_type=network_type, metered=metered) retry_upload(tid, end_event) @@ -341,6 +375,7 @@ def upload_handler(end_event: threading.Event) -> None: pass except Exception: cloudlog.exception("athena.upload_handler.exception") + finish_upload(tid) def _do_upload(upload_item: UploadItem, callback: Callable | None = None) -> requests.Response: @@ -422,6 +457,7 @@ def listDataDirectory(prefix='') -> list[str]: class VideoClips: + """Clip requests are files in clips/.queue, so they outlive the session process. A worker process encodes them oldest first.""" @dataclass class Clip: route: str @@ -436,10 +472,32 @@ class VideoClips: def __init__(self): self.clip_provider = CLOUD_PROVIDER.name self.clip_path = os.path.join(Paths.log_root(), "clips" if self.clip_provider == "comma" else "clips-" + self.clip_provider) - self.lock = threading.Condition() - self.clips: dict[str, VideoClips.Clip] = {} - self.transcode_proc: tuple[str, subprocess.Popen] | None = None - threading.Thread(target=self._worker, name="video_clip", daemon=True).start() + self.queue_path = os.path.join(self.clip_path, ".queue") + + @contextmanager + def _locked(self): + # requests are created and deleted by the session process, finished by the worker process + os.makedirs(self.queue_path, exist_ok=True) + fd = os.open(self.queue_path, os.O_RDONLY) # the directory itself, no request name can collide with it + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + def _request_path(self, filename: str) -> str: + return os.path.join(self.queue_path, filename) + + def _requests(self) -> list[Clip]: + with suppress(FileNotFoundError): + clips = [clip for name in os.listdir(self.queue_path) if not name.startswith(".") and (clip := self._request(name))] + return sorted(clips, key=lambda clip: clip.requested_at) + return [] + + def _request(self, filename: str) -> Clip | None: + with suppress(OSError, TypeError, ValueError), open(self._request_path(filename)) as f: + return self.Clip(**json.load(f)) + return None def _encode(self, clip: Clip, inputs: Iterable[str], output_path: str, start_time: float, duration: float) -> None: inputs = list(inputs) @@ -458,12 +516,8 @@ class VideoClips: str(start_time), str(duration), "--bitrate", str(clip.bitrate * 1_000_000), "--speedup", str(clip.speedup), "--metadata", metadata, "--", *inputs] - with self.lock: - if self.clips.get(clip.filename) is not clip: - return - process = subprocess.Popen(command, stdin=subprocess.PIPE if PC else subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True) - self.transcode_proc = (clip.filename, process) + process = subprocess.Popen(command, stdin=subprocess.PIPE if PC else subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True, preexec_fn=die_with_parent) try: if PC: if process.stdin is None: @@ -473,7 +527,10 @@ class VideoClips: escaped_path = path.replace("'", "'\\''") process.stdin.write(f"file 'file:{escaped_path}'\noption framerate {CAMERA_FPS}\nduration {SEGMENT_LENGTH}\n") process.stdin.close() - process.wait() + while process.poll() is None: + if self._request(clip.filename) != clip: # deleted or replaced + process.kill() # encoderd ignores SIGTERM + time.sleep(0.5) if process.returncode != 0: raise RuntimeError(f"clip encoder exited with code {process.returncode}") finally: @@ -481,47 +538,43 @@ class VideoClips: if process.stdin is not None: process.stdin.close() if process.poll() is None: - process.terminate() + process.kill() process.wait() - with self.lock: - if self.transcode_proc is not None and self.transcode_proc[0] == clip.filename: - self.transcode_proc = None - def _worker(self) -> None: + def worker(self) -> None: + die_with_parent() + with suppress(FileNotFoundError), os.scandir(self.clip_path) as entries: + for entry in entries: + if entry.name.startswith(".") and not entry.name.startswith(".cloud-") and entry.name != ROUTE_MARKER and entry.is_file(): + os.unlink(entry.path) # left over from a killed encode, including encoderd's lock that blocks the deleter while True: - with self.lock: - while not self.clips: - self.lock.wait() - clip = next(iter(self.clips.values())) - temporary_path = "" + if not (queued := self._requests()): + time.sleep(1) + continue + clip = queued[0] + temporary_path = os.path.join(self.clip_path, f".{clip.filename}") + output_path = os.path.join(self.clip_path, clip.filename) try: - with self.lock: - if self.clips.get(clip.filename) is not clip: - continue first_segment = math.floor(clip.source_start_time / SEGMENT_LENGTH) inputs = self._source_inputs(clip.route, clip.camera, clip.source_start_time, clip.source_end_time) os.makedirs(self.clip_path, exist_ok=True) if self.clip_provider != "comma": mark_recording(self.clip_path, self.clip_provider) - temporary_path = os.path.join(self.clip_path, f".{clip.filename}") - output_path = os.path.join(self.clip_path, clip.filename) self._encode(clip, inputs, temporary_path, clip.source_start_time - first_segment * SEGMENT_LENGTH, clip.source_end_time - clip.source_start_time) - with self.lock: - if self.clips.get(clip.filename) is clip: + with self._locked(): + if self._request(clip.filename) == clip: os.replace(temporary_path, output_path) - del self.clips[clip.filename] + os.unlink(self._request_path(clip.filename)) except Exception: - with self.lock: - failed = self.clips.get(clip.filename) is clip - if failed: - del self.clips[clip.filename] - if failed: - cloudlog.exception("athena.video_clip.failed") + with self._locked(): + if self._request(clip.filename) == clip: + os.unlink(self._request_path(clip.filename)) + cloudlog.exception("athena.video_clip.failed") finally: - with suppress(OSError): - if temporary_path: - os.unlink(temporary_path) + for path in (temporary_path, f"{temporary_path}.lock"): # encoderd leaves its lock when killed + with suppress(OSError): + os.unlink(path) def _on_disk(self) -> dict[str, dict]: clips = {} @@ -596,19 +649,21 @@ class VideoClips: assert camera == os.path.basename(camera) and camera.endswith("camera.hevc"), "invalid camera filename" assert filename == os.path.basename(filename), "invalid filename" self._source_inputs(route_name, camera, source_start_time, source_end_time) - with self.lock: - self.clips[filename] = self.Clip(route_name, camera, source_start_time, source_end_time, clip["bitrate"], clip["speedup"], - filename, datetime.now().timestamp()) - self.lock.notify() + request = self.Clip(route_name, camera, source_start_time, source_end_time, clip["bitrate"], clip["speedup"], + filename, datetime.now().timestamp()) + temporary_path = self._request_path(f".{filename}") + with self._locked(): + with open(temporary_path, "w") as f: + json.dump(asdict(request), f) + os.replace(temporary_path, self._request_path(filename)) def getClipState(self, route: str | None = None) -> dict: route_match = re.search(RE.ROUTE_NAME, route or "") - with self.lock: - transcode_filename = self.transcode_proc[0] if self.transcode_proc is not None else None - active_clips = {clip.filename: {**asdict(clip), "status": "encoding" if clip.filename == transcode_filename else "queued"} - for clip in self.clips.values()} + requests = self._requests() # before the disk, so a clip finishing in between isn't missed clips = self._on_disk() - clips.update(active_clips) + for request in requests: + encoding = os.path.exists(os.path.join(self.clip_path, f".{request.filename}")) + clips[request.filename] = {**asdict(request), "status": "encoding" if encoding else "queued"} state = {"clips": sorted(clips.values(), key=lambda clip: clip["requested_at"], reverse=True)} if route_match is not None: route_name = route_match.group("log_id") @@ -617,13 +672,10 @@ class VideoClips: def deleteClip(self, filename: str) -> None: assert filename == os.path.basename(filename), "invalid filename" - with self.lock: - self.clips.pop(filename, None) - output_path = os.path.join(self.clip_path, filename) - if self.transcode_proc is not None and self.transcode_proc[0] == filename: - self.transcode_proc[1].terminate() - if os.path.exists(output_path): - os.unlink(output_path) + with self._locked(): + for path in (self._request_path(filename), os.path.join(self.clip_path, filename)): + with suppress(FileNotFoundError): + os.unlink(path) # the worker stops encoding it def getClipChunk(self, filename: str, offset: int) -> dict: assert filename == os.path.basename(filename) and not filename.startswith("."), "invalid filename" @@ -722,6 +774,7 @@ def cancelUpload(upload_id: str | list[str]) -> dict[str, int | str]: return {"success": 0, "error": "not found"} cancelled_uploads.update(cancelled_ids) + UploadQueueCache.cache(upload_queue) return {"success": 1} @dispatcher.add_method(latitude=number(-90, 90), longitude=number(-180, 180)) @@ -754,7 +807,8 @@ def setRouteViewed(route: str) -> dict[str, int | str]: return {"success": 1} -def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local_port: int) -> dict[str, int]: +@dispatcher.add_method(remote_ws_uri=regex(r'wss://ssh\.comma\.ai(:(443|8443))?/[0-9a-f]{16}'), local_port=one_of(8022, *LOCAL_PORT_WHITELIST)) +def startLocalProxy(remote_ws_uri: str, local_port: int) -> dict[str, int]: try: # migration, can be removed once 0.9.8 is out for a while if local_port == 8022: @@ -782,7 +836,7 @@ def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local proxy_end_event = threading.Event() threads = [ - threading.Thread(target=ws_proxy_recv, args=(ws, local_sock, ssock, proxy_end_event, global_end_event)), + threading.Thread(target=ws_proxy_recv, args=(ws, local_sock, ssock, proxy_end_event)), threading.Thread(target=ws_proxy_send, args=(ws, local_sock, csock, proxy_end_event)) ] for thread in threads: @@ -939,8 +993,8 @@ def log_handler(end_event: threading.Event) -> None: cloudlog.exception("athena.log_handler.exception") -def ws_proxy_recv(ws: WebSocket, local_sock: socket.socket, ssock: socket.socket, end_event: threading.Event, global_end_event: threading.Event) -> None: - while not (end_event.is_set() or global_end_event.is_set()): +def ws_proxy_recv(ws: WebSocket, local_sock: socket.socket, ssock: socket.socket, end_event: threading.Event) -> None: + while not end_event.is_set(): try: sock = ws.sock if sock is None: @@ -1060,6 +1114,7 @@ def backoff(retries: int) -> int: def main(exit_event: threading.Event | None = None): + exit_event = exit_event or threading.Event() try: set_core_affinity([0, 1, 2, 3]) except Exception: @@ -1067,45 +1122,35 @@ def main(exit_event: threading.Event | None = None): params = Params() dongle_id = params.get("DongleId") - UploadQueueCache.initialize(upload_queue) - ws_uri = ATHENA_HOST + "/ws/v2/" + dongle_id - api = Api(dongle_id) - conn_start = None + # this process only supervises, it has no threads so forking is safe + session = route_source = None conn_retries = 0 - while exit_event is None or not exit_event.is_set(): - try: - if conn_start is None: - conn_start = time.monotonic() + clip_worker = fork(video_clips.worker) + try: + while not exit_event.is_set(): + if (new_source := get_route_source()) != route_source: + route_source, conn_retries = new_source, 0 # a new network starts over without backoff - cloudlog.event("athenad.main.connecting_ws", ws_uri=ws_uri, retries=conn_retries) - ws = create_connection(ws_uri, - cookie="jwt=" + api.get_token(), - enable_multithread=True, - timeout=30.0) - cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri, retries=conn_retries, - duration=time.monotonic() - conn_start) - conn_start = None - - conn_retries = 0 - cur_upload_items.clear() - - handle_long_poll(ws, exit_event) - - ws.close() - except (KeyboardInterrupt, SystemExit): - break - except (ConnectionError, TimeoutError, WebSocketException): - conn_retries += 1 - params.remove("LastAthenaPingTime") - except Exception: - cloudlog.exception("athenad.main.exception") - - conn_retries += 1 - params.remove("LastAthenaPingTime") - - time.sleep(backoff(conn_retries)) + session, started = fork(run_session, ws_uri, dongle_id, conn_retries), time.monotonic() + retry_at = math.inf + # back off once the session ends, but reconnect right away when the network changes + while time.monotonic() < retry_at and get_route_source() == route_source and not exit_event.wait(0.1): + if not clip_worker.is_alive(): + clip_worker = fork(video_clips.worker) + if retry_at == math.inf and not session.is_alive(): + # a connection that ends right away, like the server closing it, still backs off + conn_retries = 0 if session.exitcode == 0 and time.monotonic() - started > 10 else conn_retries + 1 + if conn_retries: + params.remove("LastAthenaPingTime") + retry_at = time.monotonic() + backoff(conn_retries) + session.kill() + session.join() + finally: + for process in (session, clip_worker): + if process is not None: + process.kill() if __name__ == "__main__": diff --git a/openpilot/system/athena/tests/test_athenad.py b/openpilot/system/athena/tests/test_athenad.py index 7ada9ccfca..bfb31d53de 100644 --- a/openpilot/system/athena/tests/test_athenad.py +++ b/openpilot/system/athena/tests/test_athenad.py @@ -103,14 +103,6 @@ class TestAthenadMethods(OpenpilotTestCase): f.write(data) return fn - @staticmethod - def _video_clips(clip): - clips = object.__new__(athenad.VideoClips) - clips.lock = threading.Condition() - clips.clips = {clip.filename: clip} - clips.transcode_proc = None - return clips - # *** test cases *** @@ -196,7 +188,7 @@ class TestAthenadMethods(OpenpilotTestCase): def test_video_clip_hardware_encoder(self, mocker): clip = athenad.VideoClips.Clip("route", "fcamera.hevc", 10, 130, 2, 4, "clip.mp4", 123) - clips = self._video_clips(clip) + clips = athenad.VideoClips() process = mocker.Mock(stdin=None, returncode=0) process.poll.return_value = 0 popen = mocker.patch("openpilot.system.athena.athenad.subprocess.Popen", return_value=process) @@ -210,11 +202,10 @@ class TestAthenadMethods(OpenpilotTestCase): "--bitrate", "2000000", "--speedup", "4", "--metadata", metadata, "--", "segment0", "segment1", ] assert popen.call_args.kwargs["stdin"] == athenad.subprocess.DEVNULL - assert clips.transcode_proc is None def test_video_clip_hardware_encoder_failure(self, mocker): clip = athenad.VideoClips.Clip("route", "fcamera.hevc", 0, 60, 1, 1, "clip.mp4", 123) - clips = self._video_clips(clip) + clips = athenad.VideoClips() process = mocker.Mock(stdin=None, returncode=1) process.poll.return_value = 1 mocker.patch("openpilot.system.athena.athenad.subprocess.Popen", return_value=process) @@ -222,11 +213,10 @@ class TestAthenadMethods(OpenpilotTestCase): with self.assertRaisesRegex(RuntimeError, "clip encoder exited with code 1"): clips._encode(clip, ["segment"], "output.mp4", 0, 60) - assert clips.transcode_proc is None def test_video_clip_software_fallback(self, mocker): clip = athenad.VideoClips.Clip("route", "fcamera.hevc", 10, 30, 3, 2, "clip.mp4", 123) - clips = self._video_clips(clip) + clips = athenad.VideoClips() stdin = mocker.Mock() process = mocker.Mock(stdin=stdin, returncode=0) process.poll.return_value = 0 @@ -244,6 +234,61 @@ class TestAthenadMethods(OpenpilotTestCase): assert "file 'file:segment'\\''0'\n" in writes[1] assert writes[-1].startswith("file 'file:segment1'") + def test_video_clip_queue(self, mocker): + def encode(self, clip, inputs, output_path, start_time, duration): + with open(output_path, "w") as f: + f.write(clip.filename) + mocker.patch.object(athenad.VideoClips, "_encode", encode) + clips = athenad.VideoClips() + self._create_file("2021-03-29--13-32-47--0/fcamera.hevc") + for filename in ("a.mp4", "b.mp4"): + clips.createClip("0000000000000000|2021-03-29--13-32-47", 0, 60, {"camera": "fcamera.hevc", "filename": filename, "bitrate": 1, "speedup": 1}) + clips.deleteClip("b.mp4") + assert [clip.filename for clip in clips._requests()] == ["a.mp4"] + + # requests survive the process that made them + worker = athenad.fork(clips.worker) + try: + with Timeout(5, "clip not encoded"): + while clips._requests(): + time.sleep(0.01) + finally: + worker.kill() + worker.join() + assert sorted(os.listdir(clips.clip_path)) == [".queue", "a.mp4"] + + def test_video_clip_replaced_while_encoding(self, mocker): + class Done(BaseException): + pass + clips = athenad.VideoClips() + route = "0000000000000000|2021-03-29--13-32-47" + for segment in (0, 1): + self._create_file(f"2021-03-29--13-32-47--{segment}/fcamera.hevc") + def encode(self, clip, inputs, output_path, start_time, duration): + if clip.source_end_time == 120: + raise Done # the worker moved on to the replacement + clips.createClip(route, 0, 120, {"camera": "fcamera.hevc", "filename": "a.mp4", "bitrate": 1, "speedup": 1}) + with open(output_path, "w") as f: + f.write("stale") + mocker.patch.object(athenad.VideoClips, "_encode", encode) + mocker.patch.object(athenad, "die_with_parent") + mocker.patch.object(athenad.time, "sleep", side_effect=Done) # or the queue went idle + clips.createClip(route, 0, 60, {"camera": "fcamera.hevc", "filename": "a.mp4", "bitrate": 1, "speedup": 1}) + with self.assertRaises(Done): + clips.worker() + assert not os.path.exists(os.path.join(clips.clip_path, "a.mp4")) + assert [clip.source_end_time for clip in clips._requests()] == [120] + + def test_upload_cb_rechecks_stale_metered(self, mocker): + sm = mocker.MagicMock(recv_time={'deviceState': 0}) + sm['deviceState'].networkMetered = True # lags a switch to wifi + item = athenad.UploadItem(path="qlog", url="http://localhost", headers={}, created_at=0, id='0' * 40) + mocker.patch.object(athenad, "network_metered", return_value=False) + athenad.cb(sm, item, 0, threading.Event(), 10, 5) + mocker.patch.object(athenad, "network_metered", return_value=True) + with self.assertRaises(athenad.AbortTransferException): + athenad.cb(sm, item, 0, threading.Event(), 10, 5) + def test_strip_extension(self): # any requested log file with an invalid extension won't return as existing fn = self._create_file('qlog.bz2') @@ -334,7 +379,7 @@ class TestAthenadMethods(OpenpilotTestCase): time.sleep(0.1) # TODO: verify that upload actually succeeded - # TODO: also check that end_event and metered network raises AbortTransferException + # TODO: also check that metered network raises AbortTransferException assert athenad.upload_queue.qsize() == 0 @parameterized.expand([(500,True), (412,False)], names=("status", "retry")) @@ -381,9 +426,8 @@ class TestAthenadMethods(OpenpilotTestCase): item = athenad.UploadItem(path="qlog.zst", url="http://localhost:44444/qlog.zst", headers={}, created_at=int(time.time()*1000), id='0' * 40, allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) - dispatcher["cancelUpload"](item.id) - - assert item.id in athenad.cancelled_uploads + assert dispatcher["cancelUpload"](item.id) == {"success": 1} + assert self.params.get("AthenadUploadQueue") == [] self._wait_for_upload() time.sleep(0.1) @@ -401,10 +445,12 @@ class TestAthenadMethods(OpenpilotTestCase): item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.zst", headers={}, created_at=ts, id='', allow_cellular=True) athenad.upload_queue.put_nowait(item) + athenad.UploadQueueCache.cache(athenad.upload_queue) self._wait_for_upload() time.sleep(0.1) assert athenad.upload_queue.qsize() == 0 + assert self.params.get("AthenadUploadQueue") == [] # not restored by the next session def test_list_upload_queue_empty(self): items = dispatcher["listUploadQueue"]() @@ -479,8 +525,6 @@ class TestAthenadMethods(OpenpilotTestCase): assert asdict(athenad.upload_queue.queue[-1]) == asdict(item1) def test_start_local_proxy(self, mock_create_connection, mocker): - end_event = threading.Event() - ws_recv = queue.Queue() ws_send = queue.Queue() mock_ws = MockWebsocket(ws_recv, ws_send) @@ -492,7 +536,7 @@ class TestAthenadMethods(OpenpilotTestCase): socket_thread = threading.Thread(target=echo_socket.run) socket_thread.start() - athenad.startLocalProxy(end_event, 'ws://localhost:1234', port) + athenad.startLocalProxy('ws://localhost:1234', port) ws_recv.put_nowait(b'ping') try: diff --git a/openpilot/system/athena/tests/test_athenad_ping.py b/openpilot/system/athena/tests/test_athenad_ping.py index 33876a6235..aee3041c9a 100644 --- a/openpilot/system/athena/tests/test_athenad_ping.py +++ b/openpilot/system/athena/tests/test_athenad_ping.py @@ -56,14 +56,14 @@ class TestAthenadPing(OpenpilotTestCase): self.athenad.join() def assertTimeout(self, reconnect_time: float, subtests, mocker) -> None: + # each connection attempt is a forked session process + mock_fork = mocker.patch.object(athenad, "fork", wraps=athenad.fork) + def sessions() -> int: + return sum(call.args[0] is athenad.run_session for call in mock_fork.call_args_list) + self.athenad.start() - - mock_create_connection = mocker.patch('openpilot.system.athena.athenad.create_connection', - new_callable=lambda: mocker.MagicMock(wraps=athenad.create_connection)) - time.sleep(1) - mock_create_connection.assert_called_once() - mock_create_connection.reset_mock() + assert sessions() == 1 # check normal behavior, server pings on connection with subtests.test("Wi-Fi: receives ping"), Timeout(70, "no ping received"): @@ -71,7 +71,7 @@ class TestAthenadPing(OpenpilotTestCase): time.sleep(0.1) print("ping received") - mock_create_connection.assert_not_called() + assert sessions() == 1 # websocket should attempt reconnect after short time with subtests.test("LTE: attempt reconnect"): @@ -79,7 +79,7 @@ class TestAthenadPing(OpenpilotTestCase): print("waiting for reconnect attempt") start_time = time.monotonic() with Timeout(reconnect_time, "no reconnect attempt"): - while not mock_create_connection.called: + while sessions() == 1: time.sleep(0.1) print(f"reconnect attempt after {time.monotonic() - start_time:.2f}s") diff --git a/openpilot/system/athena/tests/test_upload_preferences.py b/openpilot/system/athena/tests/test_upload_preferences.py index 4dbc62b69d..8fcb21d7d3 100644 --- a/openpilot/system/athena/tests/test_upload_preferences.py +++ b/openpilot/system/athena/tests/test_upload_preferences.py @@ -53,6 +53,7 @@ class UploadPreferencesTest(unittest.TestCase): with patch.object(athenad, 'Params', return_value=self.params), \ patch.object(athenad.messaging, 'SubMaster', return_value=self.master(metered)), \ + patch.object(athenad, 'network_metered', return_value=metered), \ patch.object(athenad, 'upload_queue', pending), patch.object(athenad, 'cur_upload_items', {}), \ patch.object(athenad, 'cancelled_uploads', set()), patch.object(athenad, '_do_upload', side_effect=upload), \ patch.object(athenad.UploadQueueCache, 'cache'), \ @@ -64,7 +65,8 @@ class UploadPreferencesTest(unittest.TestCase): def test_callback_rechecks_live_override_and_still_aborts_shutdown(self): master = self.master(True) item, end = self.item(), threading.Event() - with patch.object(athenad, 'Params', return_value=self.params), patch.object(athenad, 'cur_upload_items', {}): + with patch.object(athenad, 'Params', return_value=self.params), patch.object(athenad, 'cur_upload_items', {}), \ + patch.object(athenad, 'network_metered', return_value=True): self.params.put_bool('AlwaysAllowUploads', True, block=True) athenad.cb(master, item, 1, end, 10, 1) self.assertEqual(athenad.cur_upload_items[1].progress, .1) diff --git a/prebuilt.json b/prebuilt.json index 888f9c82ae..de11dbd76e 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "bea9179bb12067359eac18b986c1390459c38020f7252d93460620b81a00876c", "schema_version": 1} +{"protected_inventory_sha256": "3329f1db438b49f1f8fb4efb5b64c5ddb17f654d2f2951004d2edafb12ef177a", "schema_version": 1}