From 2db2e6814a032c51aa36948a24f26093751954ce Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:04 +0100 Subject: [PATCH] fault_manager: keep a recording when the PostgreSQL commit outcome is unknown * fix(fault_manager): keep a recording whose PostgreSQL commit outcome is unknown * fix(fault_manager): keep the node up when a forget's PostgreSQL commit is in doubt * test(fault_manager): pin a known store failure on PostgreSQL as a discard * docs(fault_manager): name the exceptions to unchanged rows and to bags without a row --- docs/config/fault-manager.rst | 10 +- src/ros2_medkit_fault_manager/CMakeLists.txt | 4 + src/ros2_medkit_fault_manager/README.md | 2 + .../design/index.rst | 12 +- .../core/rosbag_retention.hpp | 12 +- .../fault_storage.hpp | 13 +- .../postgres_fault_storage.hpp | 13 +- .../rosbag_capture.hpp | 8 +- .../src/core/rosbag_retention.cpp | 5 + .../src/fault_manager_node.cpp | 10 + .../src/postgres_fault_storage.cpp | 32 +- .../src/rosbag_capture.cpp | 9 + .../test_rosbag_commit_in_doubt_pg.test.py | 442 ++++++++++++++++++ 13 files changed, 549 insertions(+), 23 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_commit_in_doubt_pg.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 70119d4de..fd07f1d43 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -118,6 +118,12 @@ reclassification of HEALED faults run only at startup, so they are skipped when be reached then. Snapshot capture starts with the first answer of the server. The bags of a fault cleared while the server cannot be reached are not deleted then. +A connection lost during the commit of a recording's metadata keeps the recording, because its row +may be stored. If the row was not stored, the directory stays on disk, not listed and not counted +against ``snapshots.rosbag.max_total_storage_mb``, until it is removed by hand. When the connection +is lost while ``GetRosbag`` or ``ListRosbags`` removes the rows of a recording whose directory is +gone, the request fails and the node keeps running; the next request removes what is left. + Report Queue ~~~~~~~~~~~~ @@ -730,7 +736,9 @@ written (unwritable ``storage_path``, missing storage backend), no recording is opened and no metadata entry is stored. A capture never leaves a row pointing at a bag that is not there, and never leaves a -bag that no row points at. If the metadata cannot be stored, the recording is +bag that no row points at, except after a connection lost during the commit with PostgreSQL +(see `PostgreSQL Storage`_) and when the removal of a discarded bag fails (logged with the +path). If the metadata cannot be stored, the recording is discarded with it: nothing could reach that bag anyway, since retrieval is keyed by fault code and the quota is computed from rows, so it would sit on disk unreachable and uncounted. If the quota sweep that follows fails instead, the bag and its rows diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index 0f65d2bd1..9adc62548 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -303,6 +303,10 @@ endif() # was unreachable at start answers. medkit_add_launch_test(test_retention_config_pg test/integration/test_retention_config_pg.test.py TIMEOUT 300 LABELS "integration") + + # A connection lost during the rosbag store transaction, cut by a protocol-aware proxy. + medkit_add_launch_test(test_rosbag_commit_in_doubt_pg test/integration/test_rosbag_commit_in_doubt_pg.test.py + TIMEOUT 300 LABELS "integration") endif() # Launches without snapshots.rosbag.format, so the parameter default (mcap) diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index ba018bb92..620b0d776 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -166,6 +166,8 @@ The build downloads libpqxx 7.10.7 from GitHub at configure time and links it st A wrong configuration stops the node at startup with exit code 1: a connection string libpq cannot parse, or a server that accepts the connection but does not allow creating the schema, or a table that lacks a column the node uses. A server that cannot be reached (including a wrong password or a missing database) does not stop it: the node runs without storage, services with an error field answer `Fault storage unavailable`, and `ReportFault` answers `accepted=false`. After a failed connection attempt, requests fail at once for 5 s and the next request tries again. An attempt waits at most 2 s per host address unless `connect_timeout` or `PGCONNECT_TIMEOUT` says otherwise, and a request on an open connection to a server that went off the network fails after `tcp_user_timeout` (5 s). With a libpq service, these values come from the service file. See `docs/config/fault-manager.rst` for the full table. +A connection lost during the commit of a recording's metadata keeps the recording, because its row may be stored. If the row was not stored, the directory stays on disk, not listed and not counted against `snapshots.rosbag.max_total_storage_mb`, until it is removed by hand. When the connection is lost while `GetRosbag` or `ListRosbags` removes the rows of a recording whose directory is gone, the request fails and the node keeps running; the next request removes what is left. + ## Near-Miss Series A **near miss** is a FAILED report that moved the debounce counter without the fault ending up diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 0537622cc..d44f6f95e 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -528,7 +528,8 @@ span can also legitimately exceed ``duration_sec + duration_after_sec``. If the metadata row cannot be stored, the bag is discarded rather than kept: retrieval is keyed by fault code and quota accounting enumerates rows, so a bag with no row would -occupy disk that nothing can find and nothing can evict. +occupy disk that nothing can find and nothing can evict. When the outcome of the commit is +unknown (``kInDoubt``, PostgreSQL only), the bag is kept: its row may be stored. Known interval: between the empty-buffer flush and the moment the recording guard is published, the writer is being created - directory creation plus a storage-backend open. @@ -545,7 +546,11 @@ in one transaction: ``insert`` upserts on ``(fault_code, file_path)``, ``remove` unlinks a file. ``RosbagApplyResult::orphaned_paths`` lists each path whose last link the call removed, once, so the caller decides what happens to the directory. A throw leaves every row as it was: ``BEGIN IMMEDIATE`` in SQLite, one ``run_in_transaction`` in PostgreSQL, a copy swapped in -under the mutex in memory. +under the mutex in memory. One exception: PostgreSQL throws ``RosbagCommitInDoubt`` when libpqxx +does not know the outcome of the commit (``pqxx::in_doubt_error``, for example a connection lost +during ``COMMIT``). The rows may then be either way, and the call is not retried. SQLite and memory +never throw it. A store in doubt returns ``StoreResult::kInDoubt``, and ``RosbagCapture`` keeps the +bag and logs one warning. A set must not insert and remove the same link, directly or through ``remove_recordings`` of an inserted row's recording id. The call throws ``std::invalid_argument`` before it changes a row. @@ -649,7 +654,8 @@ depends on the path: own thread removes the cap victims, a new recording that lost the cap and the quota evictions, once the retention mutex is released and before "Bag file created" or "Bag file completed" is logged. The executor never runs a store. A bag that never got a row is discarded on the same - thread. + thread. A store in doubt (``kInDoubt``) returns no paths: the new directory stays, and a cap + victim's directory can stay with no row when the commit was applied. - Clear and stale rows (the executor): the rows go inside the service call. The node's ``RetentionWorker``, one thread with a FIFO queue, removes the directories, so the clear service returns before a large bag is removed. diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp index 71a700ef4..7a3ea21c5 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp @@ -69,6 +69,7 @@ enum class StoreResult { kAllFaultsCleared, ///< Every fault of the recording is cleared. Nothing was stored. kStoreFailed, ///< The cap read or the insert failed. Nothing was stored. kDroppedOverQuota, ///< The recording does not fit the quota. Nothing was stored; the caller removes the bag. + kInDoubt, ///< The rows may or may not be stored (RosbagCommitInDoubt); the caller keeps the bag. }; struct StoreOutcome { @@ -86,7 +87,8 @@ struct StoreOutcome { bool quota_failed{false}; std::string error; ///< Exception text of the store failure or of the quota failure /// Directories no row names any more, each path once. Never the path of a recording that - /// kAllFaultsCleared or kStoreFailed left without rows: the caller discards that one. + /// kAllFaultsCleared or kStoreFailed left without rows: the caller discards that one. Empty with + /// kInDoubt. std::vector unlink_paths; }; @@ -143,11 +145,13 @@ class RosbagRetention { std::vector evict_over_quota(size_t max_bytes, const std::string & keep_recording_id = {}); /// Remove every row of @p fault_code. The caller decides whether a clear removes recordings. - /// @throws the storage failure; no row changed then + /// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows + /// may be gone RemovalOutcome on_fault_cleared(const std::string & fault_code); /// Remove every row of a recording whose directory is gone. - /// @throws the storage failure; no row changed then + /// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows + /// may be gone RemovalOutcome forget_recording(const std::string & recording_id); private: @@ -172,7 +176,7 @@ class RosbagRetention { const RetentionPolicyState & state); /// Apply @p changes of a store. Lists the directories no row names any more in @p outcome. - /// False, with kStoreFailed in @p outcome, when the apply throws. + /// False when the apply throws: kInDoubt in @p outcome for RosbagCommitInDoubt, else kStoreFailed. bool apply_store(const std::vector & rows, const RosbagChangeSet & changes, const std::unordered_map & recording_ids, StoreOutcome & outcome); diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp index 84d32fcc6..4f978dad4 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -214,6 +215,15 @@ struct RosbagApplyResult { std::vector orphaned_paths; }; +/// Thrown by FaultStorage::apply_rosbag_changes() when the outcome of its commit is unknown: the +/// rows may or may not have changed. Only PostgreSQL throws it. +class RosbagCommitInDoubt : public std::runtime_error { + public: + explicit RosbagCommitInDoubt(const std::string & detail) + : std::runtime_error("the commit outcome is unknown: " + detail) { + } +}; + /// Check the precondition of FaultStorage::apply_rosbag_changes() the same way in every backend. /// @throws std::invalid_argument when @p changes inserts and removes the same link, directly or /// through remove_recordings of an inserted row's recording id @@ -387,7 +397,8 @@ class FaultStorage { /// Apply a set of rosbag row changes in one transaction. The only write of the rosbag rows; /// core::RosbagRetention makes every retention decision on top of it. /// - /// - All or nothing: when anything throws, no row has changed. + /// - All or nothing: when anything throws, no row has changed. Except RosbagCommitInDoubt, which + /// only PostgreSQL throws: the rows may then be either way. SQLite and memory never throw it. /// - Applies no per-fault cap. /// - Never unlinks a file or a directory. orphaned_paths names the paths the caller may unlink. /// - Precondition: the set never inserts and removes the same link, directly or through diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp index 05037154c..94271e154 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp @@ -124,9 +124,20 @@ class PgFaultStorage : public FaultStorage { /// Open a new connection unless the current one is open. Caller holds mutex_. void ensure_connection() const; + /// How run_in_transaction() reports a commit whose outcome libpqxx does not know (pqxx::in_doubt_error). + enum class InDoubt { + kAsFailure, ///< Like any other failure + kReport, ///< As RosbagCommitInDoubt, without a retry + }; + /// Run @p fn in one transaction and commit. On a broken connection, reconnect and run it again. Caller holds mutex_. template - auto run_in_transaction(const char * what, Fn && fn) const -> decltype(fn(std::declval())); + auto run_in_transaction(const char * what, Fn && fn, + InDoubt in_doubt = InDoubt::kAsFailure) const -> decltype(fn(std::declval())); + + /// Throw the failure of a transaction: IgnorableConnectionException after fail_round() when the + /// connection is closed, std::runtime_error otherwise. Caller holds mutex_. + [[noreturn]] void throw_transaction_failure(const char * what, const std::string & error) const; /// Create the tables and indexes that do not exist yet, in @p tx, and check the columns of existing ones. void create_schema(pqxx::work & tx) const; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp index 3c8bbe3a8..568dd125e 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp @@ -327,7 +327,8 @@ class RosbagCapture { /// Both finalisation paths end here, so a bag that cannot be looked up never /// survives on disk: retrieval is keyed by fault code and the quota enumerates /// rows, so a directory with no row is unreachable, uncounted, and can never be - /// evicted to make room. + /// evicted to make room. Except a store in doubt: it returns no paths, the new + /// directory stays, and a cap victim's directory can stay when the commit was applied. /// /// The decisions are core::RosbagRetention::store(). The bag is discarded here when /// every fault of it is cleared or the store failed, and nothing else. A failed quota @@ -341,9 +342,10 @@ class RosbagCapture { /// into a log with the bag already orphaned. /// /// A recording the quota refused (core::StoreResult::kDroppedOverQuota) is removed here too, - /// and logged once the directory is gone. + /// and logged once the directory is gone. A store in doubt (core::StoreResult::kInDoubt) keeps + /// the bag and logs one warning: its rows may be committed. /// - /// @return True when the rows are durable. + /// @return True when the rows are known to be durable. bool store_rows_or_discard_bag(std::vector rows, const std::string & bag_path); /// Whether the operator asked this fault code to keep a recording history. diff --git a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp index 890458b1f..bc96f67c3 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -253,6 +253,11 @@ bool RosbagRetention::apply_store(const std::vector & rows, cons outcome.unlink_paths = freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_ids, RemovalReason::kCap); } + } catch (const RosbagCommitInDoubt & e) { + // The caller logs it: the bag stays, and no eviction runs on rows that may not exist. + outcome.result = StoreResult::kInDoubt; + outcome.error = e.what(); + return false; } catch (const std::exception & e) { outcome.result = StoreResult::kStoreFailed; outcome.error = e.what(); diff --git a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp index 20d0d3f10..7c12a40dd 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -1216,6 +1216,10 @@ void FaultManagerNode::handle_get_rosbag(const std::shared_ptrrecording_id.c_str(), e.what()); + return; } return; } @@ -1269,6 +1273,12 @@ void FaultManagerNode::handle_list_rosbags( response->success = false; response->error_message = storage_unavailable(e); return; + } catch (const RosbagCommitInDoubt & e) { + RCLCPP_WARN(get_logger(), "Stale rows of recording '%s' may still be stored: %s", info.recording_id.c_str(), + e.what()); + response->success = false; + response->error_message = storage_unavailable(e); + return; } } continue; diff --git a/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp b/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp index 081683414..6f431780d 100644 --- a/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp @@ -246,9 +246,18 @@ void PgFaultStorage::ensure_connection() const { throw IgnorableConnectionException("Failed to connect to PostgreSQL: " + last_error); } +void PgFaultStorage::throw_transaction_failure(const char * what, const std::string & error) const { + // Some errors hide a lost connection: a closed connection counts as unreachable. + if (!db_conn_ || !db_conn_->is_open()) { + fail_round(error); + throw FaultStorage::IgnorableConnectionException(std::string(what) + " failed to connect to PostgreSQL: " + error); + } + throw std::runtime_error(std::string(what) + " PostgreSQL error: " + error); +} + template -auto PgFaultStorage::run_in_transaction(const char * what, - Fn && fn) const -> decltype(fn(std::declval())) { +auto PgFaultStorage::run_in_transaction(const char * what, Fn && fn, + InDoubt in_doubt) const -> decltype(fn(std::declval())) { using Result = decltype(fn(std::declval())); for (int attempt = 0;; ++attempt) { @@ -281,16 +290,18 @@ auto PgFaultStorage::run_in_transaction(const char * what, core::logf(log_sink_, core::LogLevel::kWarn, "postgres_fault_storage", "%s lost the connection (%s); retrying transaction %d/%d", what, error.c_str(), attempt + 1, max_retries_); - } catch (const std::exception & e) { - // There are other types of error that "hide" connection issues - // Before throwing a runtime_error, check if the connection is open + } catch (const pqxx::in_doubt_error & e) { + // The commit may have been applied: a retry could apply it twice. const std::string error = redact(e.what()); + if (in_doubt == InDoubt::kAsFailure) { + throw_transaction_failure(what, error); + } if (!db_conn_ || !db_conn_->is_open()) { fail_round(error); - throw FaultStorage::IgnorableConnectionException(std::string(what) + - " failed to connect to PostgreSQL: " + error); } - throw std::runtime_error(std::string(what) + " PostgreSQL error: " + error); + throw RosbagCommitInDoubt(std::string(what) + ": " + error); + } catch (const std::exception & e) { + throw_transaction_failure(what, redact(e.what())); } } } @@ -1111,7 +1122,7 @@ RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & c std::lock_guard lock(mutex_); RosbagApplyResult result; - result.orphaned_paths = run_in_transaction("apply_rosbag_changes", [&](pqxx::work & tx) { + const auto apply = [&](pqxx::work & tx) { std::set candidates; for (const auto & link : changes.remove) { auto res = execute(tx, "DELETE FROM rosbag_files WHERE fault_code = $1 AND file_path = $2 RETURNING file_path", @@ -1149,7 +1160,8 @@ RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & c } } return orphaned; - }); + }; + result.orphaned_paths = run_in_transaction("apply_rosbag_changes", apply, InDoubt::kReport); return result; } diff --git a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp index 41a7d7971..3f8b2f324 100644 --- a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp @@ -1602,6 +1602,15 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, return false; } + if (outcome.result == core::StoreResult::kInDoubt) { + // The row may be committed: removing the directory could lose a stored recording. + RCLCPP_WARN(node_->get_logger(), + "Recording '%s' kept: the commit outcome of its rosbag metadata is unknown (%s). If its row was not " + "stored, the directory is not listed and not counted against the quota", + bag_path.c_str(), outcome.error.c_str()); + return false; + } + if (outcome.result == core::StoreResult::kStoreFailed) { // Without a row nothing can ever reach this bag: retrieval is keyed by fault // code, and quota accounting enumerates rows, so a kept directory would sit diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_commit_in_doubt_pg.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_commit_in_doubt_pg.test.py new file mode 100644 index 000000000..4e748ed7a --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_commit_in_doubt_pg.test.py @@ -0,0 +1,442 @@ +#!/usr/bin/env python3 +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +A connection lost during the rosbag store transaction, on a real fault_manager_node and PostgreSQL. + +A TCP proxy owned by the test sits between the fault manager and the server. It reads the +PostgreSQL protocol 3 messages and cuts the store transaction at a chosen point. +ROS2_MEDKIT_TEST_PG_CONN names the server, as `postgresql://user:password@host:port/database`. +Each test creates its own database on it. +""" + +import os +import pathlib +import re +import select +import shutil +import socket +import struct +import sys +import threading +import urllib.parse +import uuid + +from launch import LaunchDescription +import launch_testing +import launch_testing.actions +import launch_testing.util +import psycopg2 + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rosbag_fm_harness import ( # noqa: E402 + EVENT_TIMEOUT_SEC, MESSAGE_SIZE, MIB, poll, RetentionCase, +) + +# The store transaction is the one that sends this statement, as a Parse or a Query message. +STORE_STATEMENT = b'INSERT INTO rosbag_files' +# The transaction that forgets a recording whose directory is gone. +FORGET_STATEMENT = b'DELETE FROM rosbag_files WHERE recording_id' +IN_DOUBT_WARN = r"Recording '{path}' kept: the commit outcome of its rosbag metadata is unknown" + + +def generate_test_description(): + return LaunchDescription([launch_testing.util.KeepAliveProc(), + launch_testing.actions.ReadyToTest()]), {} + + +def _close(sock): + for call in (lambda: sock.shutdown(socket.SHUT_RDWR), sock.close): + try: + call() + except OSError: + pass + + +class _Link: + """One proxied connection: both sockets and the bytes not yet framed in each direction.""" + + def __init__(self, client, server): + self.client = client + self.server = server + self.from_client = bytearray() + self.from_server = bytearray() + self.startup_done = False + self.backend_pid = None + self.withhold = False + + def close(self): + _close(self.server) + _close(self.client) + + def frontend_messages(self): + """Yield (type, body, raw) of each complete client message; the startup has no type.""" + while True: + header = 0 if not self.startup_done else 1 + if len(self.from_client) < header + 4: + return + length = struct.unpack('!I', self.from_client[header:header + 4])[0] + if len(self.from_client) < header + length: + return + raw = bytes(self.from_client[:header + length]) + del self.from_client[:header + length] + self.startup_done = True + yield raw[:header], raw[header + 4:], raw + + def backend_messages(self): + """Yield (type, body, raw) of each complete server message.""" + while len(self.from_server) >= 5: + length = struct.unpack('!I', self.from_server[1:5])[0] + if len(self.from_server) < 1 + length: + return + raw = bytes(self.from_server[:1 + length]) + del self.from_server[:1 + length] + yield raw[:1], raw[5:], raw + + +class PgCutProxy: + """ + Forward PostgreSQL connections; once armed, cut the rosbag store transaction. + + The proxy picks the first transaction that sends the armed statement after arm(), then: + COMMITTED forwards its COMMIT, withholds the server's CommandComplete and closes both sides; + ABORTED closes the server side instead of forwarding COMMIT, then the client side; + STATEMENT closes both sides instead of forwarding the statement. Later connections pass. + """ + + COMMITTED = 'committed' + ABORTED = 'aborted' + STATEMENT = 'statement' + + def __init__(self, target_host, target_port): + self._target = (target_host, target_port) + self._lock = threading.Lock() + self._mode = None + self._statement = STORE_STATEMENT + self._picked = None + self._links = [] + self.cut = threading.Event() + self.cut_backend_pid = None + self._listener = socket.socket() + self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._listener.bind(('127.0.0.1', 0)) + self._listener.listen() + self.port = self._listener.getsockname()[1] + threading.Thread(target=self._accept, daemon=True).start() + + def arm(self, mode, statement=STORE_STATEMENT): + with self._lock: + self._mode = mode + self._statement = statement + self._picked = None + self.cut_backend_pid = None + self.cut.clear() + + def close(self): + with self._lock: + links, self._links = self._links, [] + # A shutdown wakes the thread blocked in accept(); a close alone keeps listening. + _close(self._listener) + for link in links: + link.close() + + def _accept(self): + while True: + try: + client, _ = self._listener.accept() + server = socket.create_connection(self._target) + except OSError: + return + link = _Link(client, server) + with self._lock: + self._links.append(link) + threading.Thread(target=self._serve, args=(link,), daemon=True).start() + + def _serve(self, link): + """Move whole messages both ways on one thread, so a cut sees both directions in order.""" + try: + while True: + readable, _, _ = select.select([link.client, link.server], [], []) + for sock in readable: + data = sock.recv(65536) + if not data: + return + if sock is link.client: + link.from_client += data + for kind, body, raw in link.frontend_messages(): + if not self._from_client(link, kind, body, raw): + return + else: + link.from_server += data + for kind, body, raw in link.backend_messages(): + if not self._from_server(link, kind, body, raw): + return + except (OSError, ValueError): + pass + finally: + link.close() + + def _act(self, link): + """Record the cut connection's backend and end the arming. Caller holds the lock.""" + self.cut_backend_pid = link.backend_pid + self._mode = None + self.cut.set() + + def _from_client(self, link, kind, body, raw): + with self._lock: + if (self._mode is not None and self._picked is None and kind in (b'P', b'Q') + and self._statement in body): + self._picked = link + if self._mode == self.STATEMENT: + link.close() + self._act(link) + return False + is_commit = kind == b'Q' and body.rstrip(b'\0').strip().upper() == b'COMMIT' + if self._mode is not None and self._picked is link and is_commit: + if self._mode == self.ABORTED: + _close(link.server) + _close(link.client) + self._act(link) + return False + link.withhold = True + link.server.sendall(raw) + return True + + def _from_server(self, link, kind, body, raw): + if kind == b'K' and len(body) >= 4: + link.backend_pid = struct.unpack('!i', body[:4])[0] + if link.withhold: + if kind == b'C' and body.startswith(b'COMMIT'): + with self._lock: + link.close() + self._act(link) + return False + return True + link.client.sendall(raw) + return True + + +class TestRosbagCommitInDoubtPostgres(RetentionCase): + + def setUp(self): + super().setUp() + base = os.environ.get('ROS2_MEDKIT_TEST_PG_CONN') + self.assertTrue(base, 'ROS2_MEDKIT_TEST_PG_CONN is not set') + self.admin_url = base + self.database = 'rosbag_doubt_' + uuid.uuid4().hex[:12] + self._admin('CREATE DATABASE ' + self.database) + self.addCleanup(self._admin, f'DROP DATABASE IF EXISTS {self.database} WITH (FORCE)') + parts = urllib.parse.urlsplit(base) + self.direct_url = urllib.parse.urlunsplit(parts._replace(path='/' + self.database)) + self.proxy = PgCutProxy(parts.hostname, parts.port or 5432) + self.addCleanup(self.proxy.close) + # No SSL or GSS negotiation: the proxy reads plain protocol 3. + netloc = f'{parts.username}:{parts.password}@127.0.0.1:{self.proxy.port}' + self.url = urllib.parse.urlunsplit(parts._replace( + netloc=netloc, path='/' + self.database, query='sslmode=disable&gssencmode=disable')) + + def _admin(self, statement): + conn = psycopg2.connect(self.admin_url) + try: + conn.autocommit = True + with conn.cursor() as cur: + cur.execute(statement) + finally: + conn.close() + + def _query(self, statement, *args): + conn = psycopg2.connect(self.direct_url) + try: + with conn.cursor() as cur: + cur.execute(statement, args) + return cur.fetchall() + finally: + conn.close() + + def _execute(self, statement): + conn = psycopg2.connect(self.direct_url) + try: + conn.autocommit = True + with conn.cursor() as cur: + cur.execute(statement) + finally: + conn.close() + + def storage_params(self): + return {'storage_type': 'postgres', 'database_url': self.url} + + def stored_rows(self): + return self._query('SELECT fault_code, file_path FROM rosbag_files ORDER BY id') + + def store(self, fm, code): + """Confirm `code` over 1 MiB of payload and return (bag path, mark) of its store.""" + mark = fm.mark() + self.client.publish_bytes(MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report(code).accepted) + # Any outcome line of the store, so a wrong outcome fails on its assertion, not a timeout. + bag = rf'(\S*fault_{code}_\d+)' + outcome = fm.wait_line( + rf"Bag file created: {bag}|Recording '{bag}' kept: |" + rf"Failed to store rosbag metadata for '{bag}'", since=mark) + self.assertIsNotNone(outcome, f'no store outcome for {code}:\n' + fm.output()[-3000:]) + return next(group for group in outcome.groups() if group), mark + + def cut_store(self, fm, code, mode): + """Arm the proxy, store a recording of `code`, and return (bag path, mark).""" + self.proxy.arm(mode) + stored = self.store(fm, code) + self.assertTrue(self.proxy.cut.wait(EVENT_TIMEOUT_SEC), 'the proxy never cut the store:\n' + + fm.output()[-3000:]) + return stored + + def check_recovers(self, fm, code): + """Check that the next fault's recording is stored normally after the reconnect.""" + self.assertTrue(poll(lambda: self.client.get_fault(code).success), + 'the fault manager never reached the server again') + path = self.record(fm, 'DOUBT_NEXT', 1) + self.assertIn(('DOUBT_NEXT', path), self.stored_rows()) + + def check_kept_once(self, fm, path, mark): + """Check that one WARN names the kept recording and that it never counted as created.""" + self.assertTrue(os.path.isdir(path), f'{path} was removed:\n' + fm.output()[-3000:]) + escaped = re.escape(path) + self.assertEqual(fm.count_lines(IN_DOUBT_WARN.format(path=escaped), since=mark), 1, + fm.output()[-3000:]) + self.assertEqual(fm.count_lines(rf'\[WARN\].*{escaped}', since=mark), 1, + fm.output()[-3000:]) + self.assertEqual(fm.count_lines(rf'Bag file created: {escaped}', since=mark), 0, + fm.output()[-3000:]) + + def test_commit_cut_after_the_server_committed_keeps_the_recording(self): + with self.fm_run() as fm: + path, mark = self.cut_store(fm, 'DOUBT_COMMITTED', PgCutProxy.COMMITTED) + self.assertTrue(os.path.isdir(path), f'{path} was removed:\n' + fm.output()[-3000:]) + self.assertIsNone(fm.proc.poll(), 'the fault manager exited') + self.assertIn(('DOUBT_COMMITTED', path), self.stored_rows()) + self.check_recovers(fm, 'DOUBT_COMMITTED') + self.assertTrue(self.client.get_rosbag('DOUBT_COMMITTED').success) + # Checked after the next store: a line for the cut store would have come before it. + self.check_kept_once(fm, path, mark) + + def test_commit_cut_before_the_server_got_it_keeps_the_recording(self): + with self.fm_run() as fm: + path, mark = self.cut_store(fm, 'DOUBT_ABORTED', PgCutProxy.ABORTED) + self.assertTrue(os.path.isdir(path), f'{path} was removed:\n' + fm.output()[-3000:]) + self.assertIsNone(fm.proc.poll(), 'the fault manager exited') + pid = self.proxy.cut_backend_pid + self.assertIsNotNone(pid, 'the proxy saw no backend key data') + # The open transaction ends with its backend. + backend = 'SELECT 1 FROM pg_stat_activity WHERE pid = %s' + self.assertTrue(poll(lambda: not self._query(backend, pid)), + f'backend {pid} of the cut connection never ended') + self.assertEqual( + self._query('SELECT fault_code FROM rosbag_files WHERE file_path = %s', path), []) + self.check_recovers(fm, 'DOUBT_ABORTED') + self.check_kept_once(fm, path, mark) + + def test_statement_failure_before_commit_is_retried(self): + with self.fm_run() as fm: + path, mark = self.cut_store(fm, 'DOUBT_RETRIED', PgCutProxy.STATEMENT) + self.assertTrue(os.path.isdir(path), f'{path} was removed:\n' + fm.output()[-3000:]) + retried = r'apply_rosbag_changes lost the connection .*; retrying transaction 1/' + self.assertEqual(fm.count_lines(retried, since=mark), 1, fm.output()[-3000:]) + self.assertIn(('DOUBT_RETRIED', path), self.stored_rows()) + created = rf'Bag file created: {re.escape(path)}' + self.assertEqual(fm.count_lines(created, since=mark), 1, fm.output()[-3000:]) + self.check_recovers(fm, 'DOUBT_RETRIED') + self.assertEqual(fm.count_lines(r'kept: the commit outcome', since=mark), 0, + fm.output()[-3000:]) + + def reject_rows_of(self, code): + """Make the server reject every rosbag row of `code` with an error, until cleanup.""" + self._execute( + 'CREATE FUNCTION reject_rosbag_row() RETURNS trigger LANGUAGE plpgsql AS ' + "$$ BEGIN RAISE EXCEPTION 'rosbag row rejected by the test'; END $$") + self._execute( + 'CREATE TRIGGER reject_rosbag_row BEFORE INSERT ON rosbag_files FOR EACH ROW ' + f"WHEN (NEW.fault_code = '{code}') EXECUTE FUNCTION reject_rosbag_row()") + self.addCleanup(self._execute, 'DROP FUNCTION IF EXISTS reject_rosbag_row() CASCADE') + + def test_known_statement_failure_discards_the_recording(self): + with self.fm_run() as fm: + self.reject_rows_of('KNOWN_FAILURE') + path, mark = self.store(fm, 'KNOWN_FAILURE') + self.assertFalse(os.path.exists(path), f'{path} was kept:\n' + fm.output()[-3000:]) + # The server's message spans lines, so the WARN's start and end are matched apart. + failed = (rf"Failed to store rosbag metadata for '{re.escape(path)}' " + r'\(.*rosbag row rejected by the test') + self.assertEqual(fm.count_lines(failed, since=mark), 1, fm.output()[-3000:]) + discarded = r'; discarded the bag, nothing could reference it' + self.assertEqual(fm.count_lines(discarded, since=mark), 1, fm.output()[-3000:]) + self.assertEqual(self.rows_of(path), []) + self.assertIsNone(fm.proc.poll(), 'the fault manager exited') + self.check_recovers(fm, 'KNOWN_FAILURE') + # Checked after the next store: a line for the failed store would have come before it. + self.assertEqual(fm.count_lines(r'kept: the commit outcome', since=mark), 0, + fm.output()[-3000:]) + + def arm_forget(self, fm, code, mode): + """Store a recording of `code`, remove its directory and arm the proxy on its forget.""" + path = self.record(fm, code, 1) + shutil.rmtree(path) + self.proxy.arm(mode, FORGET_STATEMENT) + return path, fm.mark() + + def rows_of(self, path): + return self._query('SELECT fault_code FROM rosbag_files WHERE file_path = %s', path) + + def answer(self, fm, call): + """Return the answer of a service call, or fail with the fault manager's output.""" + try: + return call() + except AssertionError as error: + self.fail(f'{error}:\n' + fm.output()[-3000:]) + + def check_up_after_forget(self, fm, code, mark): + """Check that the cut forget logged one WARN and that the fault manager still answers.""" + self.assertTrue(self.proxy.cut.wait(EVENT_TIMEOUT_SEC), 'the proxy never cut the forget') + warn = r'\[WARN\].*the commit outcome is unknown' + self.assertIsNotNone(fm.wait_line(warn, since=mark), fm.output()[-3000:]) + self.assertTrue(poll(lambda: self.answer(fm, lambda: self.client.get_fault(code)).success), + 'the fault manager never reached the server again') + self.assertIsNone(fm.proc.poll(), 'the fault manager exited') + self.assertEqual(fm.count_lines(warn, since=mark), 1, fm.output()[-3000:]) + + def test_get_rosbag_forget_cut_at_commit_keeps_the_node_up(self): + with self.fm_run() as fm: + path, mark = self.arm_forget(fm, 'FORGET_GET', PgCutProxy.COMMITTED) + served = self.answer(fm, lambda: self.client.get_rosbag('FORGET_GET')) + self.assertFalse(served.success) + self.assertEqual(served.error_message, 'Rosbag file not found on disk: ' + path) + self.check_up_after_forget(fm, 'FORGET_GET', mark) + self.assertEqual(self.rows_of(path), []) + + def test_list_rosbags_forget_cut_at_commit_keeps_the_node_up(self): + with self.fm_run() as fm: + path, mark = self.arm_forget(fm, 'FORGET_LIST', PgCutProxy.ABORTED) + listed = self.answer(fm, self.client.list_rosbags) + self.assertFalse(listed.success) + self.assertTrue(listed.error_message.startswith('Fault storage unavailable: '), + listed.error_message) + self.check_up_after_forget(fm, 'FORGET_LIST', mark) + # The cut forget was never committed; the next request removes the rows. + pid = self.proxy.cut_backend_pid + backend = 'SELECT 1 FROM pg_stat_activity WHERE pid = %s' + self.assertTrue(poll(lambda: not self._query(backend, pid)), + f'backend {pid} of the cut connection never ended') + self.assertEqual(self.rows_of(path), [('FORGET_LIST',)]) + self.assertTrue(self.answer(fm, self.client.list_rosbags).success) + self.assertEqual(self.rows_of(path), [])