From d8ff9209529c82d4b89e94f96aa0938db5b03dca Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:04 +0100 Subject: [PATCH] fault_manager, gateway: list each rosbag recording's retention priority * feat(fault_manager,gateway): list each rosbag recording's retention priority * fix(gateway): read every attached fault before a rosbag scope check gives up * fix(gateway): download a recording where the list or a fault route shows it * docs(gateway): name the fault manager's App in the rosbag download rule --- docs/api/rest.rst | 50 ++- docs/config/fault-manager.rst | 4 + docs/requirements/specs/bulkdata.rst | 4 +- scripts/check_cores_without_ros/main.cpp | 5 +- src/ros2_medkit_fault_manager/README.md | 1 + .../design/index.rst | 2 + .../core/rosbag_retention.hpp | 5 + .../src/core/rosbag_retention.cpp | 30 ++ .../src/fault_manager_node.cpp | 27 +- .../test/integration/rosbag_fm_harness.py | 3 +- .../integration/test_rosbag_quota.test.py | 4 + .../test/test_rosbag_retention.cpp | 111 ++++++ src/ros2_medkit_gateway/README.md | 10 + .../core/faults/fault_scope.hpp | 5 + .../core/faults/rosbag_recording.hpp | 27 +- .../core/managers/fault_manager.hpp | 8 +- .../transports/fault_service_transport.hpp | 7 +- .../ros2_medkit_gateway/dto/bulkdata.hpp | 3 +- .../ros2_fault_service_transport.hpp | 4 +- .../src/core/faults/fault_scope.cpp | 12 + .../src/core/faults/rosbag_recording.cpp | 86 +++-- .../src/core/managers/fault_manager.cpp | 8 +- .../src/http/handlers/bulkdata_handlers.cpp | 57 ++- .../ros2_fault_service_transport.cpp | 11 +- .../test/test_fault_manager_routing.cpp | 8 +- .../test/test_plugin_context_aggregation.cpp | 5 +- .../test/test_rosbag_recording.cpp | 29 +- .../test/features/test_bulk_data_api.test.py | 3 + .../test_rosbag_priority_list.test.py | 347 ++++++++++++++++++ src/ros2_medkit_msgs/srv/ListRosbags.srv | 15 +- 30 files changed, 805 insertions(+), 86 deletions(-) create mode 100644 src/ros2_medkit_integration_tests/test/features/test_rosbag_priority_list.test.py diff --git a/docs/api/rest.rst b/docs/api/rest.rst index e1a8a7129..b0d4fffe7 100644 --- a/docs/api/rest.rst +++ b/docs/api/rest.rst @@ -1968,6 +1968,7 @@ List all bulk-data items in a category for the entity. "fault_codes": ["MOTOR_OVERHEAT", "MOTOR_STALL"], "duration_sec": 6.0, "format": "mcap", + "priority": 900, "recording_id": "fault_MOTOR_OVERHEAT_1738664999000", "storage_files": 1 } @@ -1978,10 +1979,42 @@ List all bulk-data items in a category for the entity. For ``rosbags``, the descriptor ``id`` is the recording id - the bag directory name - and it is what the download URL takes. There is **one descriptor per recording**, not one per fault: faults confirmed in one burst share a single -recording, and ``x-medkit.fault_codes`` lists every fault attached to it. A -recording therefore reports its size once. One fault code can appear on several -descriptors, one per occurrence it kept, told apart by ``creation_date``, which -is the time that recording was made. +recording, and ``x-medkit.fault_codes`` lists the attached faults this +entity's list includes. A recording therefore reports its size once. One fault +code can appear on several descriptors, one per occurrence it kept, told apart +by ``creation_date``, which is the time that recording was made. + +``x-medkit.priority`` is the recording's retention priority: the highest +``priority`` of every fault attached to the recording, also the faults this +entity's list leaves out, from each fault's current severity (see Rosbag +Retention Rules in :doc:`/config/fault-manager`). It is ``0`` when the fault +manager runs without a valid retention configuration. A client that fetches the +most important recordings first sorts by ``priority``, then by +``creation_date``. + +**Which entity lists a recording.** An entity lists a recording when one of its +fault sources is exactly a reporting source of one of the recording's faults. A +recording shared by faults of two apps is listed under both, and each list names +its own faults in ``x-medkit.fault_codes``. The fault manager's own App lists +every recording: its source is the fault manager's FQN, ``/fault_manager``, or +``/fault_manager``. A Component or Function whose +sources include that FQN, such as the host Component of runtime discovery, lists +every recording too. In runtime discovery the fault manager node is an App like +every other node. In hybrid discovery it is an App no manifest declares, unless +``unmanifested_nodes: ignore`` hides it. In manifest-only discovery it exists +only when the manifest declares it. + +**Which entity downloads a recording.** The download route and the +:ref:`manifest and file routes ` serve a recording +to an entity whose sources include the fault manager's FQN, or when one of the +recording's faults passes the list's rule above or the rule of the entity's +fault route: every reporting source is one of the entity's sources or lies below +one at a ``/`` boundary (``plc`` does not cover ``plc_line1``). So every +recording the list shows and every ``bulk_data_uri`` the entity's faults +advertise downloads, and nothing else: a fault reported by two apps downloads +under both, and a fault reported by a node below the entity and by an outside +app downloads under that node's App and the outside app, not under the entity. A +fault-code URL also needs the requested fault in that scope. ``x-medkit.storage_files`` is how many storage files the recording is held in, read from the recording's own metadata. A ``1`` is the normal case and says the @@ -2319,8 +2352,13 @@ the file, and that answer carries ``Content-Range: bytes */``. **The listing is complete or refused.** ``GET /api/v1/{entity-path}/bulk-data/rosbags`` answers ``503`` when the fault manager -cannot be read for any of the sources the entity covers. A ``200`` is a -complete list, so an empty ``items`` means there are no recordings. +cannot be read for any of the sources the entity covers, or for every recording +on the fault manager's own App. A ``200`` is a complete list, so an empty +``items`` means there are no recordings. A recording downloads under an entity, +also through the manifest and file routes, when the entity's sources include the +fault manager's node, which lists and downloads every recording, or when one of +its faults has a reporting source equal to one of the entity's sources, or has +every reporting source at or below the entity's sources at a ``/`` boundary. Software Updates ---------------- diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index fd07f1d43..5534e5c8c 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -864,6 +864,10 @@ quota and logs a warning; ``keep`` also deletes the recordings it was allowed to the new recording alone and deletes nothing. The log line of a drop names the path, the size, the quota and the reason. +**The priority in the list.** ``~/list_rosbags`` and the gateway's ``GET .../bulk-data/rosbags`` +show each recording's priority (``priorities``, ``x-medkit.priority``): the rank above, read when the +list is served. It is ``0`` without rules and while the configuration is invalid. + **Open-time check.** When a fault whose rule says ``over_quota: drop`` confirms, and the recording is predicted not to fit, the recording is not started. The prediction is the stored bytes, less what the per-fault cap frees for that fault and what the fault's priority allows to evict, plus the bytes of diff --git a/docs/requirements/specs/bulkdata.rst b/docs/requirements/specs/bulkdata.rst index d0796d36a..755837a1c 100644 --- a/docs/requirements/specs/bulkdata.rst +++ b/docs/requirements/specs/bulkdata.rst @@ -19,7 +19,8 @@ BulkData The endpoint shall list all bulk-data items available in the addressed bulk-data category on the entity. Returns BulkDataDescriptor array with id, name, mimetype, size, creation_date fields. - Includes ``x-medkit`` extensions with fault_code, duration_sec, format. + For ``rosbags``, includes ``x-medkit`` extensions with fault_codes, duration_sec, format, + recording_id and priority, the recording's retention priority. .. req:: GET /{entity}/bulk-data/{category}/{bulk-data-id} :id: REQ_INTEROP_073 @@ -54,4 +55,3 @@ BulkData Returns 204 No Content on success. Supported for components and apps. The ``rosbags`` category is managed by the fault manager and cannot be deleted. - diff --git a/scripts/check_cores_without_ros/main.cpp b/scripts/check_cores_without_ros/main.cpp index 9d6a6efda..9fed3f89d 100644 --- a/scripts/check_cores_without_ros/main.cpp +++ b/scripts/check_cores_without_ros/main.cpp @@ -201,9 +201,12 @@ class NoFaultTransport : public gw::FaultServiceTransport { gw::FaultResult get_rosbag(const std::string & /*fault_code*/) override { return none(); } - gw::FaultResult list_rosbags(const std::string & /*entity_fqn*/) override { + gw::FaultResult list_rosbags(const std::string & /*entity_fqn*/, bool /*all_recordings*/) override { return none(); } + std::string fault_manager_fqn() const override { + return "/fault_manager"; + } bool wait_for_services(std::chrono::duration /*timeout*/) override { return false; } diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 620b0d776..0a87df8da 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -43,6 +43,7 @@ ros2 service call /fault_manager/clear_fault ros2_medkit_msgs/srv/ClearFault \ | `~/list_faults` | `ros2_medkit_msgs/srv/ListFaults` | Query faults with filtering | | `~/clear_fault` | `ros2_medkit_msgs/srv/ClearFault` | Clear/acknowledge a fault | | `~/get_snapshots` | `ros2_medkit_msgs/srv/GetSnapshots` | Get topic snapshots for a fault | +| `~/list_rosbags` | `ros2_medkit_msgs/srv/ListRosbags` | Rosbag rows of the faults an entity reported (`entity_fqn`), or every row with `all_recordings`; each row with its recording's retention priority (`priorities`) | ## Features diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index d44f6f95e..8a35f6771 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -593,6 +593,8 @@ Rosbag retention ring buffer in place. The size is an estimate: a recording that grows past it in its post-roll is dropped at the store. - ``recording_priority``: the priority of a stored recording. +- ``recording_priorities``: the priority of each of several recordings, for ``ListRosbags``. One + read of the rosbag rows and one read per distinct fault code, however many recordings. - ``on_fault_cleared``: removes every row of a cleared fault. ``RosbagCapture`` decides whether a clear removes recordings at all. - ``forget_recording``: removes the rows of a recording whose directory is gone, for 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 7a3ea21c5..1e446451b 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 @@ -122,6 +122,11 @@ class RosbagRetention { /// @throws a storage failure int64_t recording_priority(const std::string & recording_id); + /// recording_priority() of each of @p recording_ids, keyed by id. One read of the rosbag rows and + /// one read per distinct fault code, however many recordings. + /// @throws a storage failure + std::unordered_map recording_priorities(const std::vector & recording_ids); + /// Whether a new recording for @p fault_code may start. Checked only in kDegraded and for a /// fault whose rule says over_quota: drop. Refused when the storage, less what the cap and the /// eviction would free, plus @p reserve_bytes is over the quota. A failed read admits it. 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 bc96f67c3..67c0c01ca 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -511,6 +511,36 @@ int64_t RosbagRetention::recording_priority(const std::string & recording_id) { return rank_of(*state, codes, cache).priority; } +std::unordered_map +RosbagRetention::recording_priorities(const std::vector & recording_ids) { + std::unordered_map priorities; + for (const auto & id : recording_ids) { + priorities.emplace(id, 0); + } + if (priorities.empty()) { + return priorities; + } + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + if (state->mode != RetentionMode::kConfigured) { + return priorities; + } + std::unordered_map> codes_by_recording; + for (const auto & row : storage_.get_all_rosbag_files()) { + if (priorities.count(row.recording_id) != 0) { + codes_by_recording[row.recording_id].push_back(row.fault_code); + } + } + FactsCache cache; + for (auto & entry : priorities) { + const auto codes = codes_by_recording.find(entry.first); + if (codes != codes_by_recording.end()) { + entry.second = rank_of(*state, codes->second, cache).priority; + } + } + return priorities; +} + bool RosbagRetention::admits_new_recording(const std::string & fault_code, size_t reserve_bytes, const std::vector> & pending) { const auto state = std::atomic_load(&state_); 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 7c12a40dd..afe013da2 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -1238,18 +1238,23 @@ void FaultManagerNode::handle_get_rosbag(const std::shared_ptr & request, const std::shared_ptr & response) { - RCLCPP_DEBUG(get_logger(), "ListRosbags request for entity: %s", request->entity_fqn.c_str()); + RCLCPP_DEBUG(get_logger(), "ListRosbags request for entity: %s (all recordings: %s)", request->entity_fqn.c_str(), + request->all_recordings ? "true" : "false"); - if (request->entity_fqn.empty()) { + if (!request->all_recordings && request->entity_fqn.empty()) { response->success = false; response->error_message = "entity_fqn cannot be empty"; return; } - // Use batch storage API to get all rosbags for this entity std::vector rosbags = {}; try { - rosbags = storage_->list_rosbags_for_entity(request->entity_fqn); + if (request->all_recordings) { + rosbags = storage_->get_all_rosbag_files(); + std::reverse(rosbags.begin(), rosbags.end()); // newest first, as the entity listing orders its rows + } else { + rosbags = storage_->list_rosbags_for_entity(request->entity_fqn); + } } catch (const FaultStorage::IgnorableConnectionException & e) { RCLCPP_WARN(get_logger(), "Failed to connect with the fault storage server: %s", e.what()); response->success = false; @@ -1293,6 +1298,20 @@ void FaultManagerNode::handle_list_rosbags( response->created_at_ns.push_back(info.created_at_ns); } + // One retention call for the whole response: a per-recording read costs one storage transaction each. + try { + const auto priorities = rosbag_retention_->recording_priorities(response->recording_ids); + response->priorities.reserve(response->recording_ids.size()); + for (const auto & recording_id : response->recording_ids) { + response->priorities.push_back(priorities.at(recording_id)); + } + } catch (const std::exception & e) { + RCLCPP_WARN(get_logger(), "Failed to read the rosbag priorities: %s", e.what()); + response->success = false; + response->error_message = storage_unavailable(e); + return; + } + response->success = true; RCLCPP_DEBUG(get_logger(), "ListRosbags returned %zu rosbags for entity '%s'", response->fault_codes.size(), request->entity_fqn.c_str()); diff --git a/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py b/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py index ecd92c054..2978c2838 100644 --- a/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py +++ b/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py @@ -350,9 +350,10 @@ def get_rosbag(self, code='', recording_id=''): request.recording_id = recording_id return self._call(GetRosbag, 'get_rosbag', request) - def list_rosbags(self, entity=SOURCE_ID): + def list_rosbags(self, entity=SOURCE_ID, all_recordings=False): request = ListRosbags.Request() request.entity_fqn = entity + request.all_recordings = all_recordings return self._call(ListRosbags, 'list_rosbags', request) def _wait_for_subscription_count(self, reached, what): diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py index fb3482a92..516c6642e 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py @@ -971,6 +971,10 @@ def test_degraded_quota_is_a_hard_stop(self): with self.fm_run(**base, **{'snapshots.rosbag.auto_cleanup': False}) as fm: self.assertIsNotNone(fm.wait_line(r'Invalid rosbag retention configuration')) stored = {code: self.record(fm, code, 2) for code in ('DEG_A', 'DEG_B', 'DEG_C')} + listed = self.client.list_rosbags('', all_recordings=True) + self.assertTrue(listed.success, listed.error_message) + self.assertEqual(sorted(listed.fault_codes), ['DEG_A', 'DEG_B', 'DEG_C']) + self.assertEqual(list(listed.priorities), [0] * len(listed.fault_codes)) path, kept = self.record_growing(fm, 'DEG_NEW', 2) self.assertFalse(kept) self.assertFalse(os.path.exists(path)) diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp index dcb4aa5b0..d1eb9c52f 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp @@ -194,6 +194,54 @@ class FailingPolicyReadStorage : public InMemoryFaultStorage { bool fail_apply{false}; }; +/// Counts every fault and rosbag read the retention can make. +class CountingReadStorage : public InMemoryFaultStorage { + public: + std::optional get_fault(const std::string & fault_code) const override { + ++reads; + return InMemoryFaultStorage::get_fault(fault_code); + } + bool contains(const std::string & fault_code) const override { + ++reads; + return InMemoryFaultStorage::contains(fault_code); + } + std::vector list_faults(bool filter_by_severity, uint8_t severity, + const std::vector & statuses) const override { + ++reads; + return InMemoryFaultStorage::list_faults(filter_by_severity, severity, statuses); + } + std::vector get_all_faults() const override { + ++reads; + return InMemoryFaultStorage::get_all_faults(); + } + std::optional get_rosbag_file(const std::string & fault_code) const override { + ++reads; + return InMemoryFaultStorage::get_rosbag_file(fault_code); + } + std::vector get_rosbag_files(const std::string & fault_code) const override { + ++reads; + return InMemoryFaultStorage::get_rosbag_files(fault_code); + } + std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override { + ++reads; + return InMemoryFaultStorage::get_rosbag_files_by_recording(recording_id); + } + size_t get_total_rosbag_storage_bytes() const override { + ++reads; + return InMemoryFaultStorage::get_total_rosbag_storage_bytes(); + } + std::vector get_all_rosbag_files() const override { + ++reads; + return InMemoryFaultStorage::get_all_rosbag_files(); + } + std::vector list_rosbags_for_entity(const std::string & entity_fqn) const override { + ++reads; + return InMemoryFaultStorage::list_rosbags_for_entity(entity_fqn); + } + + mutable size_t reads = 0; +}; + /// Keeps every line it is given. class CapturingLogSink : public ros2_medkit_fault_manager::core::LogSink { public: @@ -580,4 +628,67 @@ TEST_F(RosbagRetentionStore, PolicyReadFailureFallsBackToInsertAndCap) { } } +TEST(RosbagRetention, RecordingPrioritiesReadsDoNotGrowWithRecordings) { + // The read count is not observable outside the process: one list call must not cost one + // storage transaction per recording. + ros2_medkit_fault_manager::core::FlatParams params; + params["defaults.priority"] = int64_t{10}; + params["severity.ERROR.priority"] = int64_t{50}; + params["severity.CRITICAL.priority"] = int64_t{900}; + auto parsed = RetentionPolicy::parse(params); + ASSERT_TRUE(parsed.errors.empty()); + const auto policy = std::make_shared(std::move(*parsed.policy)); + const std::vector> faults = { + {"F_WARN", fd::severity::kWarn}, {"F_ERROR", fd::severity::kError}, {"F_CRITICAL", fd::severity::kCritical}}; + + // Every fault code is linked in both runs: recording 0 links all of them, the others one each. + const auto reads_for = [&](size_t recordings) { + CountingReadStorage storage; + for (const auto & fault : faults) { + storage.report_fault_event(fault.first, fd::ReportKind::kFailed, fault.second, "reads", "/node", 1000, + DebounceConfig{}); + } + std::vector rows; + std::vector ids; + for (size_t i = 0; i < recordings; ++i) { + const std::string id = "fault_rec_" + std::to_string(i); + ids.push_back(id); + for (size_t f = 0; f < faults.size(); ++f) { + if (i == 0 || i % faults.size() == f) { + RosbagFileInfo row; + row.fault_code = faults[f].first; + row.file_path = "/bags/" + id; + row.recording_id = id; + row.format = "mcap"; + row.size_bytes = 1024; + row.created_at_ns = static_cast(1000 + i); + rows.push_back(row); + } + } + } + seed_rosbag_rows(storage, rows); + RosbagRetention retention(storage, RosbagRetentionLimits{}, test_log_sink(), kLogger); + retention.set_policy(RetentionMode::kConfigured, policy); + + storage.reads = 0; + const auto priorities = retention.recording_priorities(ids); + const size_t reads = storage.reads; + + EXPECT_EQ(priorities.size(), ids.size()); + for (const auto & id : ids) { + const auto found = priorities.find(id); + EXPECT_NE(found, priorities.end()) << id; + if (found != priorities.end()) { + EXPECT_EQ(found->second, retention.recording_priority(id)) << id; + } + } + return reads; + }; + + const size_t one = reads_for(1); + const size_t fifty = reads_for(50); + EXPECT_EQ(one, fifty) << "reads grow with the number of recordings"; + EXPECT_GT(one, 0u); +} + } // namespace diff --git a/src/ros2_medkit_gateway/README.md b/src/ros2_medkit_gateway/README.md index 1c705f6f5..d1b286da6 100644 --- a/src/ros2_medkit_gateway/README.md +++ b/src/ros2_medkit_gateway/README.md @@ -1223,6 +1223,16 @@ download serves one storage file, verbatim, named `.` (`.mcap` or `.sqlite3`). It is not an archive and it does not include the bag's `metadata.yaml`. +Each descriptor carries `x-medkit.priority`, the recording's retention priority: +the highest priority of every fault attached to it, from each fault's current +severity, and `0` without a valid retention configuration. A client sorts by +`priority`, then by `creation_date`. The fault manager's own App, and an entity +that hosts it, lists every recording. A recording downloads under an entity whose +sources include the fault manager's node, or when one of its faults has a +reporting source equal to one of the entity's sources (the list's rule) or has +every reporting source at or below the entity's sources at a `/` boundary (the +rule of the entity's fault route, which advertises the URL). + For a recording held in a single storage file, which is the normal case, the descriptor `size` is that file's length and therefore the length of the download. A recording that grew past `snapshots.rosbag.max_bag_size_mb` is split diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_scope.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_scope.hpp index 4353fa032..08f2529ff 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_scope.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_scope.hpp @@ -58,6 +58,11 @@ std::vector hosted_entities_of(const ThreadSafeEntityCache & cache, /// An empty scope set or an empty/absent source list returns false. bool fault_in_source_scope(const nlohmann::json & fault, const std::set & source_fqns); +/// True when at least one reporting source of `fault` equals one of `source_fqns` +/// exactly: the rule by which the rosbag list matches a fault to an entity. +/// An empty scope set or an empty/absent source list returns false. +bool fault_reported_by_any(const nlohmann::json & fault, const std::set & source_fqns); + /// Subset of `faults_array` whose faults satisfy `fault_in_source_scope`. nlohmann::json filter_faults_by_sources(const nlohmann::json & faults_array, const std::set & source_fqns); diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/rosbag_recording.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/rosbag_recording.hpp index 422a4f8d7..f9b839302 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/rosbag_recording.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/rosbag_recording.hpp @@ -17,9 +17,12 @@ #include #include #include +#include #include #include +#include "ros2_medkit_gateway/core/faults/fault_types.hpp" + namespace ros2_medkit_gateway { class FaultManager; @@ -47,8 +50,30 @@ std::optional parse_recording_file_index(const std::string & text); std::optional recording_file_path(const std::string & recording_path, const std::string & manifest_text, std::size_t index); +/// Whether @p scope holds the fault manager's own FQN. That entity lists and downloads every recording. +bool scope_holds_fault_manager(const FaultManager & fault_manager, const std::set & scope); + +enum class RecordingScope { + kInScope, + kNotInScope, + /// No attached fault matched, and at least one fault read got no answer. + kUnavailable, +}; + +/// Whether a recording attached to @p fault_codes downloads under an entity whose fault sources are +/// @p scope. In scope when the scope holds the fault manager's FQN, or when an attached fault passes the +/// list's rule (fault_reported_by_any()) or the fault route's rule (fault_in_source_scope()): every URL +/// the list or a fault route shows downloads, and nothing else. Every rosbag download route uses it. +RecordingScope recording_scope(FaultManager & fault_manager, const std::vector & fault_codes, + const std::set & scope); + +/// The rosbag rows of an entity whose fault sources are @p source_filters, as `{"rosbags": [...]}`. +/// One list call with all_recordings when the filters hold the fault manager's FQN, else one call per +/// filter. The first failed call is returned as it is. +FaultResult list_entity_rosbags(FaultManager & fault_manager, const std::vector & source_filters); + enum class RecordingLookupStatus { - /// The recording exists and one of its faults is in the entity's scope. + /// The recording exists and recording_scope() puts it in the entity's scope. kFound, /// The fault manager answered and holds no recording with this id. kNotFound, diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/managers/fault_manager.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/managers/fault_manager.hpp index 1386d1daf..58b89260c 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/managers/fault_manager.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/managers/fault_manager.hpp @@ -90,8 +90,12 @@ class FaultManager { /// Get rosbag file info for a fault. FaultResult get_rosbag(const std::string & fault_code); - /// Get all rosbag files for an entity (batch operation). - FaultResult list_rosbags(const std::string & entity_fqn); + /// Get all rosbag files for an entity (batch operation). With @p all_recordings, every + /// stored recording; @p entity_fqn is then ignored. + FaultResult list_rosbags(const std::string & entity_fqn, bool all_recordings); + + /// FQN of the fault manager node (forwards to transport). + std::string fault_manager_fqn() const; /// Check if fault manager services are available. bool is_available() const; diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/transports/fault_service_transport.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/transports/fault_service_transport.hpp index 97f908424..e1f5c7047 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/transports/fault_service_transport.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/transports/fault_service_transport.hpp @@ -58,7 +58,12 @@ class FaultServiceTransport { virtual FaultResult get_rosbag(const std::string & fault_code) = 0; - virtual FaultResult list_rosbags(const std::string & entity_fqn) = 0; + /// The rosbag rows of faults that @p entity_fqn reported, each with its recording's `priority`. + /// With @p all_recordings, every stored row; @p entity_fqn is then ignored. + virtual FaultResult list_rosbags(const std::string & entity_fqn, bool all_recordings) = 0; + + /// FQN of the fault manager node these services belong to, for example `/fault_manager`. + virtual std::string fault_manager_fqn() const = 0; virtual bool wait_for_services(std::chrono::duration timeout) = 0; diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/dto/bulkdata.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/dto/bulkdata.hpp index 17b8c30c3..1b5fc9799 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/dto/bulkdata.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/dto/bulkdata.hpp @@ -61,7 +61,8 @@ inline constexpr std::string_view dto_name = "BulkDataCate // creation_date - ISO 8601 timestamp string (required) // description - optional human-readable description // x-medkit - optional open vendor extension object. For rosbags: -// {fault_codes, duration_sec, format, recording_id}, plus +// {fault_codes, duration_sec, format, priority, +// recording_id}, plus // manifest: true when the recording has a manifest, and // storage_files, how many storage files the recording's // metadata names, omitted when that metadata cannot be read diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/ros2/transports/ros2_fault_service_transport.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/ros2/transports/ros2_fault_service_transport.hpp index 6c408ca5e..7613a1ce6 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/ros2/transports/ros2_fault_service_transport.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/ros2/transports/ros2_fault_service_transport.hpp @@ -80,7 +80,9 @@ class Ros2FaultServiceTransport : public FaultServiceTransport { FaultResult get_rosbag(const std::string & fault_code) override; - FaultResult list_rosbags(const std::string & entity_fqn) override; + FaultResult list_rosbags(const std::string & entity_fqn, bool all_recordings) override; + + std::string fault_manager_fqn() const override; bool wait_for_services(std::chrono::duration timeout) override; diff --git a/src/ros2_medkit_gateway/src/core/faults/fault_scope.cpp b/src/ros2_medkit_gateway/src/core/faults/fault_scope.cpp index d44265372..9805bd604 100644 --- a/src/ros2_medkit_gateway/src/core/faults/fault_scope.cpp +++ b/src/ros2_medkit_gateway/src/core/faults/fault_scope.cpp @@ -176,6 +176,18 @@ bool fault_in_source_scope(const nlohmann::json & fault, const std::set & source_fqns) { + if (!fault.contains("reporting_sources") || !fault["reporting_sources"].is_array()) { + return false; + } + for (const auto & src : fault["reporting_sources"]) { + if (src.is_string() && source_fqns.count(src.get()) != 0) { + return true; + } + } + return false; +} + nlohmann::json filter_faults_by_sources(const nlohmann::json & faults_array, const std::set & source_fqns) { nlohmann::json filtered = nlohmann::json::array(); diff --git a/src/ros2_medkit_gateway/src/core/faults/rosbag_recording.cpp b/src/ros2_medkit_gateway/src/core/faults/rosbag_recording.cpp index 5630085c0..e6f41534b 100644 --- a/src/ros2_medkit_gateway/src/core/faults/rosbag_recording.cpp +++ b/src/ros2_medkit_gateway/src/core/faults/rosbag_recording.cpp @@ -54,6 +54,53 @@ bool is_plain_file(const std::filesystem::path & path) { } // namespace +bool scope_holds_fault_manager(const FaultManager & fault_manager, const std::set & scope) { + const std::string fqn = fault_manager.fault_manager_fqn(); + return !fqn.empty() && scope.count(fqn) != 0; +} + +RecordingScope recording_scope(FaultManager & fault_manager, const std::vector & fault_codes, + const std::set & scope) { + if (scope_holds_fault_manager(fault_manager, scope)) { + return RecordingScope::kInScope; + } + bool unanswered = false; + for (const auto & code : fault_codes) { + const auto fault = fault_manager.get_fault(code, ""); + // The list's rule, or the rule by which GET {entity}/faults/{code} advertises the download. + if (fault.success && (fault_reported_by_any(fault.data, scope) || fault_in_source_scope(fault.data, scope))) { + return RecordingScope::kInScope; + } + if (!fault.success && fault.failure == FaultFailure::Unavailable) { + unanswered = true; // a later fault can still put the recording in scope + } + } + return unanswered ? RecordingScope::kUnavailable : RecordingScope::kNotInScope; +} + +FaultResult list_entity_rosbags(FaultManager & fault_manager, const std::vector & source_filters) { + const std::set scope(source_filters.begin(), source_filters.end()); + if (scope_holds_fault_manager(fault_manager, scope)) { + return fault_manager.list_rosbags("", true); + } + nlohmann::json rows = nlohmann::json::array(); + for (const auto & source_filter : source_filters) { + auto listed = fault_manager.list_rosbags(source_filter, false); + if (!listed.success) { + return listed; + } + if (listed.data.contains("rosbags") && listed.data["rosbags"].is_array()) { + for (auto & row : listed.data["rosbags"]) { + rows.push_back(std::move(row)); + } + } + } + FaultResult merged; + merged.success = true; + merged.data = {{"rosbags", std::move(rows)}}; + return merged; +} + bool recording_has_manifest(const std::string & recording_path) { return is_plain_file(std::filesystem::path(recording_path) / kRecordingManifestFile); } @@ -141,25 +188,23 @@ RecordingLookup find_recording(FaultManager & fault_manager, const std::string & } const std::set scope(source_filters.begin(), source_filters.end()); - bool in_scope = false; + std::vector codes; if (rosbag.data.contains("fault_codes") && rosbag.data["fault_codes"].is_array()) { for (const auto & code : rosbag.data["fault_codes"]) { - if (!code.is_string()) { - continue; - } - const auto fault = fault_manager.get_fault(code.get(), ""); - if (!fault.success && fault.failure == FaultFailure::Unavailable) { - return lookup; - } - if (fault.success && fault_in_source_scope(fault.data, scope)) { - in_scope = true; - break; + if (code.is_string()) { + codes.push_back(code.get()); } } } - if (!in_scope) { - lookup.status = RecordingLookupStatus::kNotInEntity; - return lookup; + switch (recording_scope(fault_manager, codes, scope)) { + case RecordingScope::kInScope: + break; + case RecordingScope::kNotInScope: + lookup.status = RecordingLookupStatus::kNotInEntity; + return lookup; + case RecordingScope::kUnavailable: + default: + return lookup; } lookup.status = RecordingLookupStatus::kFound; lookup.path = rosbag.data["file_path"].get(); @@ -174,14 +219,11 @@ RecordingLookup find_recording(FaultManager & fault_manager, const std::string & lookup.status = RecordingLookupStatus::kNotInEntity; return lookup; } - for (const auto & source_filter : source_filters) { - const auto listed = fault_manager.list_rosbags(source_filter); - if (!listed.success) { - return lookup; - } - if (!listed.data.contains("rosbags") || !listed.data["rosbags"].is_array()) { - continue; - } + const auto listed = list_entity_rosbags(fault_manager, source_filters); + if (!listed.success) { + return lookup; + } + if (listed.data.contains("rosbags") && listed.data["rosbags"].is_array()) { for (const auto & row : listed.data["rosbags"]) { if (row.is_object() && row.value("recording_id", std::string{}) == recording_id) { return lookup; diff --git a/src/ros2_medkit_gateway/src/core/managers/fault_manager.cpp b/src/ros2_medkit_gateway/src/core/managers/fault_manager.cpp index c406cbac6..4d88a2bf5 100644 --- a/src/ros2_medkit_gateway/src/core/managers/fault_manager.cpp +++ b/src/ros2_medkit_gateway/src/core/managers/fault_manager.cpp @@ -53,8 +53,12 @@ FaultResult FaultManager::get_rosbag(const std::string & fault_code) { return transport_->get_rosbag(fault_code); } -FaultResult FaultManager::list_rosbags(const std::string & entity_fqn) { - return transport_->list_rosbags(entity_fqn); +FaultResult FaultManager::list_rosbags(const std::string & entity_fqn, bool all_recordings) { + return transport_->list_rosbags(entity_fqn, all_recordings); +} + +std::string FaultManager::fault_manager_fqn() const { + return transport_->fault_manager_fqn(); } bool FaultManager::is_available() const { diff --git a/src/ros2_medkit_gateway/src/http/handlers/bulkdata_handlers.cpp b/src/ros2_medkit_gateway/src/http/handlers/bulkdata_handlers.cpp index f48e611b2..07da359ac 100644 --- a/src/ros2_medkit_gateway/src/http/handlers/bulkdata_handlers.cpp +++ b/src/ros2_medkit_gateway/src/http/handlers/bulkdata_handlers.cpp @@ -14,7 +14,6 @@ #include "ros2_medkit_gateway/core/http/handlers/bulkdata_handlers.hpp" -#include "ros2_medkit_gateway/core/faults/fault_scope.hpp" #include "ros2_medkit_gateway/core/faults/rosbag_recording.hpp" #include @@ -294,6 +293,7 @@ fold_rosbag_rows_into_descriptors(const std::vector & rows, std::optional storage_files; double duration_sec{0.0}; int64_t created_at_ns{0}; + int64_t priority{0}; bool manifest{false}; std::vector fault_codes; }; @@ -349,6 +349,8 @@ fold_rosbag_rows_into_descriptors(const std::vector & rows, entry.storage_files = storage.file_count; entry.duration_sec = row.value("duration_sec", 0.0); entry.created_at_ns = created_at_ns; + // The fault manager repeats the recording's priority on each of its rows. + entry.priority = row.value("priority", int64_t{0}); entry.manifest = row.value("manifest", false); entry.fault_codes.push_back(fault_code); index_by_recording.emplace(recording_id, recordings.size()); @@ -370,6 +372,7 @@ fold_rosbag_rows_into_descriptors(const std::vector & rows, descriptor.x_medkit = nlohmann::json{{"fault_codes", entry.fault_codes}, {"duration_sec", entry.duration_sec}, {"format", entry.format}, + {"priority", entry.priority}, // Redundant with the descriptor id, kept because // clients already group on it. {"recording_id", entry.recording_id}}; @@ -509,20 +512,19 @@ BulkDataHandlers::list_descriptors(const http::TypedRequest & req) { } } - // Collect rosbags across all source filters. A listing that could not read every - // one of them is refused rather than served short: a 200 here is a complete list. + // Collect rosbags across all source filters, or every recording for the fault manager's own + // entity. A listing that could not read every one of them is refused rather than served + // short: a 200 here is a complete list. std::vector all_rosbags; - for (const auto & source_filter : source_filters) { - auto rosbags_result = fault_mgr->list_rosbags(source_filter); - if (!rosbags_result.success) { - return tl::unexpected(make_error(503, ERR_SERVICE_UNAVAILABLE, "Recordings could not be listed", - json{{"details", rosbags_result.error_message}})); - } - if (rosbags_result.data.contains("rosbags")) { - for (auto rosbag : rosbags_result.data["rosbags"]) { - rosbag["manifest"] = faults::recording_has_manifest(rosbag.value("file_path", std::string{})); - all_rosbags.push_back(std::move(rosbag)); - } + auto rosbags_result = faults::list_entity_rosbags(*fault_mgr, source_filters); + if (!rosbags_result.success) { + return tl::unexpected(make_error(503, ERR_SERVICE_UNAVAILABLE, "Recordings could not be listed", + json{{"details", rosbags_result.error_message}})); + } + if (rosbags_result.data.contains("rosbags")) { + for (auto rosbag : rosbags_result.data["rosbags"]) { + rosbag["manifest"] = faults::recording_has_manifest(rosbag.value("file_path", std::string{})); + all_rosbags.push_back(std::move(rosbag)); } } @@ -612,13 +614,9 @@ http::Result BulkDataHandlers::download(const http::TypedR make_error(404, ERR_RESOURCE_NOT_FOUND, "Bulk-data not found", json{{"bulk_data_id", bulk_data_id}})); } - // Security check: the bag belongs to this entity when ANY fault it was captured - // for is within the entity's source scope. Union rather than a single code - // because a burst shares one recording, and each of those faults already had its - // own downloadable copy of it before - so this grants nothing new, it only - // renames the door. Tested with the shared boundary-aware matcher: the - // transport's get_fault(code, source) check is a raw prefix match, so app id - // "plc" would otherwise claim the assets of "plc_line1". + // Security check: faults::recording_scope(), the rule of every rosbag download route. What + // the list or a fault route shows downloads, and nothing else. Not the transport's + // get_fault(code, source) check: a raw prefix match lets app id "plc" claim "plc_line1". auto source_filters = get_source_filters(entity); std::set scope(source_filters.begin(), source_filters.end()); @@ -629,21 +627,14 @@ http::Result BulkDataHandlers::download(const http::TypedR // the caller that another fault shares its recording. build_sovd_fault_response // refuses to mix sources for the same reason. When the id really was a recording // id there is no requested code and the union is the whole answer. - if (detail::rosbag_resolved_by_fault_code(rosbag_result.data, bulk_data_id)) { - auto requested = fault_mgr->get_fault(bulk_data_id, ""); - if (!requested.success || !faults::fault_in_source_scope(requested.data, scope)) { - return tl::unexpected(make_error(404, ERR_RESOURCE_NOT_FOUND, "Bulk-data not found for this entity", - json{{"entity_id", path_info->entity_id}})); - } + if (detail::rosbag_resolved_by_fault_code(rosbag_result.data, bulk_data_id) && + faults::recording_scope(*fault_mgr, {bulk_data_id}, scope) != faults::RecordingScope::kInScope) { + return tl::unexpected(make_error(404, ERR_RESOURCE_NOT_FOUND, "Bulk-data not found for this entity", + json{{"entity_id", path_info->entity_id}})); } const auto attached_codes = detail::rosbag_attached_fault_codes(rosbag_result.data, bulk_data_id); - - const bool authorized = std::any_of(attached_codes.begin(), attached_codes.end(), [&](const std::string & code) { - auto fault_result = fault_mgr->get_fault(code, ""); - return fault_result.success && faults::fault_in_source_scope(fault_result.data, scope); - }); - if (!authorized) { + if (faults::recording_scope(*fault_mgr, attached_codes, scope) != faults::RecordingScope::kInScope) { return tl::unexpected(make_error(404, ERR_RESOURCE_NOT_FOUND, "Bulk-data not found for this entity", json{{"entity_id", path_info->entity_id}})); } diff --git a/src/ros2_medkit_gateway/src/ros2/transports/ros2_fault_service_transport.cpp b/src/ros2_medkit_gateway/src/ros2/transports/ros2_fault_service_transport.cpp index f097ec7e6..f0b64dff3 100644 --- a/src/ros2_medkit_gateway/src/ros2/transports/ros2_fault_service_transport.cpp +++ b/src/ros2_medkit_gateway/src/ros2/transports/ros2_fault_service_transport.cpp @@ -167,6 +167,10 @@ bool Ros2FaultServiceTransport::is_available() const { list_faults_client_->service_is_ready() && clear_fault_client_->service_is_ready(); } +std::string Ros2FaultServiceTransport::fault_manager_fqn() const { + return fault_manager_base_path_; +} + FaultResult Ros2FaultServiceTransport::report_fault(const std::string & fault_code, uint8_t severity, const std::string & description, const std::string & source_id) { FaultResult result; @@ -447,11 +451,12 @@ FaultResult Ros2FaultServiceTransport::get_rosbag(const std::string & fault_code return result; } -FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_fqn) { +FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_fqn, bool all_recordings) { FaultResult result; auto request = std::make_shared(); request->entity_fqn = entity_fqn; + request->all_recordings = all_recordings; auto response = invoke_fault_service( list_rosbags_client_, request, executor_, executor_mutex_, std::chrono::duration(service_timeout_sec_), @@ -471,7 +476,7 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f // match fault_codes is reported as a mismatch rather than silently truncated. const size_t n = response->fault_codes.size(); if (response->recording_ids.size() != n || response->file_paths.size() != n || response->formats.size() != n || - response->durations_sec.size() != n || response->sizes_bytes.size() != n || + response->durations_sec.size() != n || response->sizes_bytes.size() != n || response->priorities.size() != n || response->created_at_ns.size() != n) { result.success = false; result.error_message = "ListRosbags response has mismatched array sizes (fault_codes=" + std::to_string(n) + @@ -480,6 +485,7 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f ", formats=" + std::to_string(response->formats.size()) + ", durations_sec=" + std::to_string(response->durations_sec.size()) + ", sizes_bytes=" + std::to_string(response->sizes_bytes.size()) + + ", priorities=" + std::to_string(response->priorities.size()) + ", created_at_ns=" + std::to_string(response->created_at_ns.size()) + ")"; return result; } @@ -491,6 +497,7 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f {"format", response->formats[i]}, {"duration_sec", response->durations_sec[i]}, {"size_bytes", response->sizes_bytes[i]}, + {"priority", response->priorities[i]}, {"created_at_ns", response->created_at_ns[i]}}); } result.data = {{"rosbags", rosbags}}; diff --git a/src/ros2_medkit_gateway/test/test_fault_manager_routing.cpp b/src/ros2_medkit_gateway/test/test_fault_manager_routing.cpp index ff001a933..b0d8a4de9 100644 --- a/src/ros2_medkit_gateway/test/test_fault_manager_routing.cpp +++ b/src/ros2_medkit_gateway/test/test_fault_manager_routing.cpp @@ -120,7 +120,11 @@ class MockFaultServiceTransport : public FaultServiceTransport { return r; } - FaultResult list_rosbags(const std::string & entity_fqn) override { + std::string fault_manager_fqn() const override { + return "/fault_manager"; + } + + FaultResult list_rosbags(const std::string & entity_fqn, bool /*all_recordings*/) override { last_list_rosbags_entity_ = entity_fqn; ++list_rosbags_calls_; FaultResult r; @@ -407,7 +411,7 @@ TEST(FaultManagerRoutingTest, ListRosbagsForwardsEntityFqn) { auto mock = std::make_shared(); FaultManager mgr(mock); - auto r = mgr.list_rosbags("/sensors/lidar"); + auto r = mgr.list_rosbags("/sensors/lidar", false); EXPECT_TRUE(r.success); EXPECT_EQ(mock->last_list_rosbags_entity_, "/sensors/lidar"); diff --git a/src/ros2_medkit_gateway/test/test_plugin_context_aggregation.cpp b/src/ros2_medkit_gateway/test/test_plugin_context_aggregation.cpp index b7ba6ee3b..32920a6f2 100644 --- a/src/ros2_medkit_gateway/test/test_plugin_context_aggregation.cpp +++ b/src/ros2_medkit_gateway/test/test_plugin_context_aggregation.cpp @@ -208,9 +208,12 @@ class FakeFaultTransport : public ros2_medkit_gateway::FaultServiceTransport { ros2_medkit_gateway::FaultResult get_rosbag(const std::string & /*fault_code*/) override { return {false, json::object(), "not implemented"}; } - ros2_medkit_gateway::FaultResult list_rosbags(const std::string & /*entity_fqn*/) override { + ros2_medkit_gateway::FaultResult list_rosbags(const std::string & /*entity_fqn*/, bool /*all_recordings*/) override { return {false, json::object(), "not implemented"}; } + std::string fault_manager_fqn() const override { + return "/fault_manager"; + } bool wait_for_services(std::chrono::duration /*timeout*/) override { return true; } diff --git a/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp b/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp index 6f80efc06..5a9df1460 100644 --- a/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp +++ b/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp @@ -61,6 +61,8 @@ class FakeFaultTransport : public FaultServiceTransport { /// Stands for a store that could not be read: an answer, but not about the recording. bool get_rosbag_declines_everything{false}; bool get_fault_unavailable{false}; + /// Fault codes whose read gets no answer while the others answer. + std::set get_fault_unavailable_for; bool list_rosbags_fails{false}; /// Filters whose listing fails while the others answer. std::set list_rosbags_fails_for; @@ -97,7 +99,11 @@ class FakeFaultTransport : public FaultServiceTransport { return r; } - FaultResult list_rosbags(const std::string & entity_fqn) override { + std::string fault_manager_fqn() const override { + return "/fault_manager"; + } + + FaultResult list_rosbags(const std::string & entity_fqn, bool /*all_recordings*/) override { ++list_rosbags_calls; FaultResult r; r.success = !list_rosbags_fails && list_rosbags_fails_for.count(entity_fqn) == 0; @@ -123,7 +129,7 @@ class FakeFaultTransport : public FaultServiceTransport { FaultResult get_fault(const std::string & fault_code, const std::string & /*source_id*/) override { FaultResult r; r.success = false; - if (get_fault_unavailable) { + if (get_fault_unavailable || get_fault_unavailable_for.count(fault_code) != 0) { r.failure = FaultFailure::Unavailable; return r; } @@ -266,6 +272,25 @@ TEST_F(FindRecordingTest, ABurstRecordingIsFoundThroughAnyOfItsFaults) { EXPECT_EQ(find("fault_LIDAR_1000", {"/chassis"}).status, RecordingLookupStatus::kNotInEntity); } +// @verifies REQ_INTEROP_073 +TEST(RecordingScopeTest, AnUnansweredFaultReadDoesNotEndTheScopeCheck) { + // One fault read that times out cannot be forced from outside the process. + auto transport = std::make_shared(); + FaultManager manager(transport); + transport->faults["A"] = {"/sensors/lidar"}; + transport->faults["B"] = {"/sensors/lidar"}; + transport->faults["MOTOR"] = {"/powertrain/motor"}; + transport->get_fault_unavailable_for = {"A"}; + const std::set scope = {"/sensors/lidar"}; + + EXPECT_EQ(faults::recording_scope(manager, {"A", "B"}, scope), faults::RecordingScope::kInScope); + EXPECT_EQ(faults::recording_scope(manager, {"B", "A"}, scope), faults::RecordingScope::kInScope); + // No attached fault matched and one read got no answer: nothing settles it. + EXPECT_EQ(faults::recording_scope(manager, {"A", "MOTOR"}, scope), faults::RecordingScope::kUnavailable); + EXPECT_EQ(faults::recording_scope(manager, {"MOTOR", "A"}, scope), faults::RecordingScope::kUnavailable); + EXPECT_EQ(faults::recording_scope(manager, {"MOTOR"}, scope), faults::RecordingScope::kNotInScope); +} + // === Byte ranges === // @verifies REQ_INTEROP_073 diff --git a/src/ros2_medkit_integration_tests/test/features/test_bulk_data_api.test.py b/src/ros2_medkit_integration_tests/test/features/test_bulk_data_api.test.py index 6c8cc58cc..74603dc27 100644 --- a/src/ros2_medkit_integration_tests/test/features/test_bulk_data_api.test.py +++ b/src/ros2_medkit_integration_tests/test/features/test_bulk_data_api.test.py @@ -157,6 +157,9 @@ def test_bulk_data_list_descriptors_structure(self): f'recording_id should be the bag directory name, ' f'got: {x_medkit["recording_id"]}', ) + # This fault manager runs without retention rules, so every recording ranks 0. + for item in data['items']: + self.assertEqual(item['x-medkit'].get('priority'), 0, item) def test_bulk_data_list_descriptors_empty_result(self): """Bulk-data returns empty or non-empty array for component rosbags. diff --git a/src/ros2_medkit_integration_tests/test/features/test_rosbag_priority_list.test.py b/src/ros2_medkit_integration_tests/test/features/test_rosbag_priority_list.test.py new file mode 100644 index 000000000..b88e1bd00 --- /dev/null +++ b/src/ros2_medkit_integration_tests/test/features/test_rosbag_priority_list.test.py @@ -0,0 +1,347 @@ +#!/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. + +"""The retention priority on the rosbag list, and which entity lists and downloads a recording. + +The fault manager runs with the rules ``severity.CRITICAL.priority: 900`` and +``defaults.priority: 10``. Faults are reported for two demo apps, A (``temp_sensor``) and B +(``rpm_sensor``); the lidar demo node only feeds the recorded topic. Two nodes of this test have +names that share a prefix with A. The result is read from ``GET .../bulk-data/rosbags``, the +downloads, and the fault manager's own ``list_rosbags`` service. +""" + +import shutil +import tempfile +import unittest + +import launch_testing +import rclpy +from rclpy.node import Node +import requests +from ros2_medkit_msgs.msg import Fault +from ros2_medkit_msgs.srv import ListRosbags, ReportFault + +from ros2_medkit_test_utils.constants import ALLOWED_EXIT_CODES +from ros2_medkit_test_utils.gateway_test_case import GatewayTestCase +from ros2_medkit_test_utils.launch_helpers import create_test_launch + +APP_A = 'temp_sensor' +APP_B = 'rpm_sensor' +FQN_A = '/powertrain/engine/temp_sensor' +FQN_B = '/powertrain/engine/rpm_sensor' +NAMESPACE = '/powertrain/engine' +# A's FQN starts with this one's, and this one's starts with A's. +PREFIX_APP = 'temp' +SUFFIX_APP = 'temp_sensor_x' +# A node one namespace level below A. +CHILD_APP = 'child' +CHILD_FQN = FQN_A + '/' + CHILD_APP +FM_APP = 'fault_manager' +LIDAR_APP = 'lidar_sensor' +LIDAR_OWN_FAULT = 'LIDAR_CALIBRATION_REQUIRED' +CRITICAL_PRIORITY = 900 +DEFAULT_PRIORITY = 10 +LIST_TIMEOUT_SEC = 30.0 +LOG_TIMEOUT_SEC = 30.0 + +ROSBAG_STORAGE_PATH = tempfile.mkdtemp(prefix='rosbag_e2e_priority_list_') + + +def generate_test_description(): + return create_test_launch( + demo_nodes=[LIDAR_APP, APP_A, APP_B], + # Healthy lidar: its scan is the recorded topic, the test reports the faults. + lidar_faulty=False, + fault_manager=True, + fault_manager_params={ + 'confirmation_threshold': -1, + 'snapshots.rosbag.duration_sec': 5.0, + # Long enough for a second fault to join a running recording. + 'snapshots.rosbag.duration_after_sec': 2.0, + 'snapshots.rosbag.format': 'mcap', + 'snapshots.rosbag.storage_path': ROSBAG_STORAGE_PATH, + 'snapshots.rosbag.retention.severity.CRITICAL.priority': CRITICAL_PRIORITY, + 'snapshots.rosbag.retention.defaults.priority': DEFAULT_PRIORITY, + }, + ) + + +def _items(listing): + return listing.get('items', []) + + +def _bulk_data_uris(value): + """Yield every bulk_data_uri in a fault response.""" + if isinstance(value, dict): + for key, item in value.items(): + if key == 'bulk_data_uri': + yield item + else: + yield from _bulk_data_uris(item) + elif isinstance(value, list): + for item in value: + yield from _bulk_data_uris(item) + + +def _codes(item): + return item.get('x-medkit', {}).get('fault_codes', []) + + +class TestRosbagPriorityList(GatewayTestCase): + """Priority per recording, the fault manager's App, and the download scope.""" + + MIN_EXPECTED_APPS = 7 + REQUIRED_APPS = {LIDAR_APP, APP_A, APP_B, FM_APP, PREFIX_APP, SUFFIX_APP, CHILD_APP} + + warn_id = None + + @classmethod + def setUpClass(cls): + # The prefix nodes exist before the discovery wait, so the gateway serves them as Apps. + rclpy.init() + cls.driver = Node('_priority_list_driver') + cls.prefix_node = Node(PREFIX_APP, namespace=NAMESPACE) + cls.suffix_node = Node(SUFFIX_APP, namespace=NAMESPACE) + cls.child_node = Node(CHILD_APP, namespace=FQN_A) + cls.report_client = cls.driver.create_client(ReportFault, '/fault_manager/report_fault') + cls.list_client = cls.driver.create_client(ListRosbags, '/fault_manager/list_rosbags') + super().setUpClass() + assert cls.report_client.wait_for_service(timeout_sec=20.0), \ + 'report_fault service not available' + assert cls.list_client.wait_for_service(timeout_sec=20.0), \ + 'list_rosbags service not available' + + @classmethod + def tearDownClass(cls): + cls.child_node.destroy_node() + cls.suffix_node.destroy_node() + cls.prefix_node.destroy_node() + cls.driver.destroy_node() + rclpy.shutdown() + super().tearDownClass() + + def _call(self, client, request): + future = client.call_async(request) + rclpy.spin_until_future_complete(self.driver, future, timeout_sec=10.0) + self.assertIsNotNone(future.result(), 'the service call timed out') + return future.result() + + def _report(self, fault_code, severity, source): + request = ReportFault.Request() + request.fault_code = fault_code + request.event_type = ReportFault.Request.EVENT_FAILED + request.severity = severity + request.description = 'priority list e2e' + request.source_id = source + self.assertTrue(self._call(self.report_client, request).accepted) + + def _listing(self, app): + return _items(self.get_json(f'/apps/{app}/bulk-data/rosbags')) + + def _ids(self, app): + return {item['id'] for item in self._listing(app)} + + def _wait_descriptor(self, endpoint, fault_code, predicate=None): + """Return the first descriptor of `endpoint` with `fault_code` that meets `predicate`.""" + def find(listing): + for item in _items(listing): + if fault_code in _codes(item) and (predicate is None or predicate(item)): + return item + return None + return self.poll_endpoint_until(f'{endpoint}/bulk-data/rosbags', find, + timeout=LIST_TIMEOUT_SEC) + + def _status(self, path): + return requests.get(f'{self.BASE_URL}{path}', timeout=30).status_code + + def test_01_each_recording_carries_its_priority(self): + """A CRITICAL and a WARN recording of one app list 900 and 10. + + @verifies REQ_INTEROP_072 + """ + # The lidar's own fault records at startup. Its listing means the faults below meet an + # idle capture. + self._wait_descriptor(f'/apps/{LIDAR_APP}', LIDAR_OWN_FAULT) + self._report('E2E_CRIT', Fault.SEVERITY_CRITICAL, FQN_A) + critical = self._wait_descriptor(f'/apps/{APP_A}', 'E2E_CRIT') + self._report('E2E_WARN', Fault.SEVERITY_WARN, FQN_A) + warn = self._wait_descriptor(f'/apps/{APP_A}', 'E2E_WARN') + type(self).warn_id = warn['id'] + + self.assertNotEqual(critical['id'], warn['id']) + self.assertEqual(critical['x-medkit'].get('priority'), CRITICAL_PRIORITY, critical) + self.assertEqual(warn['x-medkit'].get('priority'), DEFAULT_PRIORITY, warn) + + def test_02_the_priority_follows_the_current_severity(self): + """The WARN fault reported again as CRITICAL: the same recording now lists 900. + + @verifies REQ_INTEROP_072 + """ + self.assertIsNotNone(self.warn_id, 'the WARN recording of test_01 is missing') + before = self._ids(APP_A) + self._report('E2E_WARN', Fault.SEVERITY_CRITICAL, FQN_A) + self._wait_descriptor( + f'/apps/{APP_A}', 'E2E_WARN', + lambda item: item['id'] == self.warn_id + and item['x-medkit'].get('priority') == CRITICAL_PRIORITY) + + # A recording the re-report started would be listed by the time a later one is: the + # capture records one window at a time. + self._report('E2E_PROBE', Fault.SEVERITY_WARN, FQN_A) + probe = self._wait_descriptor(f'/apps/{APP_A}', 'E2E_PROBE') + self.assertNotIn('E2E_WARN', _codes(probe)) + self.assertEqual(self._ids(APP_A), before | {probe['id']}) + holding = [item['id'] for item in self._listing(APP_A) if 'E2E_WARN' in _codes(item)] + self.assertEqual(holding, [self.warn_id]) + + def test_03_a_shared_recording_lists_under_both_apps(self, proc_output): + """A WARN fault of A and a CRITICAL fault of B share one recording, 900 under both. + + @verifies REQ_INTEROP_072 + @verifies REQ_INTEROP_073 + """ + self._report('A_LOW', Fault.SEVERITY_WARN, FQN_A) + proc_output.assertWaitFor("fault 'A_LOW' confirmed, flushing buffer to bag", + timeout=LOG_TIMEOUT_SEC) + self._report('Z_HIGH', Fault.SEVERITY_CRITICAL, FQN_B) + proc_output.assertWaitFor("Fault 'Z_HIGH' confirmed during post-fault recording", + timeout=LOG_TIMEOUT_SEC) + + under_a = self._wait_descriptor(f'/apps/{APP_A}', 'A_LOW') + under_b = self._wait_descriptor(f'/apps/{APP_B}', 'Z_HIGH') + self.assertEqual(under_a['id'], under_b['id']) + self.assertEqual(under_a['x-medkit'].get('priority'), CRITICAL_PRIORITY, under_a) + self.assertEqual(under_b['x-medkit'].get('priority'), CRITICAL_PRIORITY, under_b) + for app in (APP_A, APP_B): + self.assertEqual(self._status(f'/apps/{app}/bulk-data/rosbags/{under_a["id"]}'), 200, + app) + + def test_04_a_fault_of_two_apps_downloads_under_both(self): + """One fault reported by A and B lists and downloads under both, not under a prefix name. + + @verifies REQ_INTEROP_073 + """ + self._report('E2E_TWO', Fault.SEVERITY_ERROR, FQN_A) + self._report('E2E_TWO', Fault.SEVERITY_ERROR, FQN_B) + + def with_manifest(item): + return item['x-medkit'].get('manifest') is True + + under_a = self._wait_descriptor(f'/apps/{APP_A}', 'E2E_TWO', with_manifest) + under_b = self._wait_descriptor(f'/apps/{APP_B}', 'E2E_TWO', with_manifest) + recording_id = under_a['id'] + self.assertEqual(under_b['id'], recording_id) + + for app in (APP_A, APP_B): + base = f'/apps/{app}/bulk-data/rosbags/{recording_id}' + self.assertEqual(self._status(base), 200, app) + self.assertEqual(self._status(f'{base}/manifest'), 200, app) + for app in (PREFIX_APP, SUFFIX_APP): + self.assertNotIn(recording_id, self._ids(app), app) + base = f'/apps/{app}/bulk-data/rosbags/{recording_id}' + self.assertEqual(self._status(base), 404, app) + self.assertEqual(self._status(f'{base}/manifest'), 404, app) + + def test_05_the_fault_manager_app_lists_every_recording(self): + """The fault manager's App lists the other apps' recordings and downloads them. + + @verifies REQ_INTEROP_072 + @verifies REQ_INTEROP_073 + """ + others = set() + for app in (LIDAR_APP, APP_A, APP_B): + others |= self._ids(app) + listing = self._listing(FM_APP) + self.assertTrue(others, 'the other apps list no recording') + self.assertEqual({item['id'] for item in listing}, others) + + shared = next(item for item in listing if 'A_LOW' in _codes(item)) + self.assertEqual(sorted(_codes(shared)), ['A_LOW', 'Z_HIGH']) + self.assertEqual(shared['x-medkit'].get('priority'), CRITICAL_PRIORITY) + self.assertEqual(shared['x-medkit'].get('storage_files'), 1, shared) + base = f'/apps/{FM_APP}/bulk-data/rosbags/{shared["id"]}' + response = requests.get(f'{self.BASE_URL}{base}', timeout=30) + self.assertEqual(response.status_code, 200) + self.assertEqual(len(response.content), shared['size']) + self.assertEqual(self._status(f'{base}/manifest'), 200) + + host = None + for component in _items(self.get_json('/components')): + hosts = _items(self.get_json(f'/components/{component["id"]}/hosts')) + if any(app.get('id') == FM_APP for app in hosts): + host = component['id'] + break + self.assertIsNotNone(host, 'no component hosts the fault manager') + hosted = _items(self.get_json(f'/components/{host}/bulk-data/rosbags')) + self.assertEqual({item['id'] for item in hosted}, others) + + def test_06_the_service_lists_every_recording_for_an_empty_entity(self): + """list_rosbags with all_recordings and no entity returns every recording. + + @verifies REQ_INTEROP_072 + """ + request = ListRosbags.Request() + request.entity_fqn = '' + request.all_recordings = True + response = self._call(self.list_client, request) + self.assertTrue(response.success, response.error_message) + self.assertEqual(len(response.priorities), len(response.fault_codes)) + listed = {item['id']: item for item in self._listing(FM_APP)} + self.assertEqual(set(response.recording_ids), set(listed)) + for recording_id, priority in zip(response.recording_ids, response.priorities): + self.assertEqual(priority, listed[recording_id]['x-medkit']['priority'], recording_id) + + def test_07_the_parent_downloads_what_its_fault_route_advertises(self): + """A fault of A's child alone: A's fault route advertises the recording; it downloads. + + @verifies REQ_INTEROP_073 + """ + self._report('CHILD_ONLY', Fault.SEVERITY_ERROR, CHILD_FQN) + recording_id = self._wait_descriptor(f'/apps/{CHILD_APP}', 'CHILD_ONLY')['id'] + + fault = self.get_json(f'/apps/{APP_A}/faults/CHILD_ONLY') + advertised = f'/apps/{APP_A}/bulk-data/rosbags/{recording_id}' + self.assertIn(advertised, [uri.replace('/api/v1', '') for uri in _bulk_data_uris(fault)]) + self.assertEqual(self._status(advertised), 200) + + def test_08_a_fault_of_the_child_and_another_app_is_not_the_parents(self): + """A fault of A's child and of B: A neither shows it nor downloads it; B downloads it. + + @verifies REQ_INTEROP_073 + """ + self._report('CHILD_AND_B', Fault.SEVERITY_ERROR, CHILD_FQN) + self._report('CHILD_AND_B', Fault.SEVERITY_ERROR, FQN_B) + recording_id = self._wait_descriptor(f'/apps/{APP_B}', 'CHILD_AND_B')['id'] + + self.assertNotIn(recording_id, self._ids(APP_A)) + self.assertEqual(self._status(f'/apps/{APP_A}/faults/CHILD_AND_B'), 404) + base = f'/apps/{APP_A}/bulk-data/rosbags/{recording_id}' + self.assertEqual(self._status(base), 404) + self.assertEqual(self._status(f'{base}/manifest'), 404) + self.assertEqual(self._status(f'/apps/{APP_B}/bulk-data/rosbags/{recording_id}'), 200) + + +@launch_testing.post_shutdown_test() +class TestShutdown(unittest.TestCase): + """Post-shutdown checks.""" + + def test_exit_codes(self, proc_info): + """Gateway and fault manager exit cleanly.""" + launch_testing.asserts.assertExitCodes( + proc_info, allowable_exit_codes=ALLOWED_EXIT_CODES) + + def test_cleanup_temp_directory(self): + """Remove this run's bag storage.""" + shutil.rmtree(ROSBAG_STORAGE_PATH, ignore_errors=True) diff --git a/src/ros2_medkit_msgs/srv/ListRosbags.srv b/src/ros2_medkit_msgs/srv/ListRosbags.srv index 5595816d0..4b408da5a 100644 --- a/src/ros2_medkit_msgs/srv/ListRosbags.srv +++ b/src/ros2_medkit_msgs/srv/ListRosbags.srv @@ -20,12 +20,17 @@ # Request fields # Entity FQN (fully qualified name) to filter rosbags by. -# Matches against fault reporting_sources using prefix matching. +# A row is returned when one of its fault's reporting_sources equals it exactly. string entity_fqn + +# True: every stored recording, whatever reported its faults. entity_fqn is then +# ignored and may be empty. +bool all_recordings --- # Response fields -# True if the request was processed successfully. +# True if the request was processed successfully. The arrays below are meaningful +# only when it is true: a failed request may leave them partly filled. bool success # Fault codes for each rosbag (parallel array with other fields). @@ -48,6 +53,12 @@ float64[] durations_sec # Per recording, the same figure as GetRosbag size_bytes. uint64[] sizes_bytes +# Retention priority of each recording, parallel to fault_codes. Rows of one +# recording repeat the same value. The highest priority of every fault linked to +# the recording, also faults this entity did not report, from each fault's current +# severity. 0 unless the retention configuration is valid. +int64[] priorities + # When each recording was made, nanoseconds since the epoch. # One fault keeps several recordings, so this is what separates one occurrence from # another; the fault's own first_occurred dates them all the same, and dates them