From 32c25b4fd7c90264e3b76e9fc878ddab3edbd367 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:09 +0100 Subject: [PATCH] Delete one rosbag recording through the bulk-data API * feat: delete one rosbag recording through the bulk-data API * fix: exact delete status rule, 409 without locking, protected-recording docs * docs: recording-not-found code on unavailable storage, deletable field * test: protected-recording delete 404 carries x-medkit-recording-not-found --- docs/api/rest.rst | 75 ++- docs/config/fault-manager.rst | 8 +- docs/config/server.rst | 5 +- docs/requirements/specs/bulkdata.rst | 10 +- src/ros2_medkit_fault_manager/README.md | 35 +- .../design/index.rst | 48 +- .../core/fault_manager_core.hpp | 11 + .../core/rosbag_retention.hpp | 68 +- .../fault_audit_log.hpp | 9 + .../fault_manager_node.hpp | 13 + .../retention_worker.hpp | 2 +- .../src/core/fault_manager_core.cpp | 50 +- .../src/core/rosbag_retention.cpp | 151 +++++ .../src/fault_audit_log.cpp | 81 ++- .../src/fault_manager_node.cpp | 77 ++- .../src/retention_worker.cpp | 3 + .../test/integration/rosbag_fm_harness.py | 12 +- .../test_retention_config_pg.test.py | 24 + .../test_rosbag_commit_in_doubt_pg.test.py | 42 ++ .../integration/test_rosbag_quota_pg.test.py | 22 + .../test_rosbag_status_actions.test.py | 31 +- .../test_rosbag_storage_availability.test.py | 24 + src/ros2_medkit_gateway/README.md | 18 +- .../core/faults/fault_types.hpp | 16 + .../core/faults/rosbag_recording.hpp | 14 +- .../core/http/handlers/bulkdata_handlers.hpp | 7 +- .../core/managers/fault_manager.hpp | 6 + .../transports/fault_service_transport.hpp | 11 + .../ros2_medkit_gateway/dto/bulkdata.hpp | 2 +- .../ros2_fault_service_transport.hpp | 6 + .../src/core/faults/rosbag_recording.cpp | 20 +- .../src/core/managers/fault_manager.cpp | 5 + .../src/http/handlers/bulkdata_handlers.cpp | 62 +- .../src/http/rest_server.cpp | 9 +- .../ros2_fault_service_transport.cpp | 36 +- .../test/test_rosbag_recording.cpp | 76 +++ .../test_locking_disabled_contract.test.py | 8 + .../test/features/test_rosbag_delete.test.py | 583 ++++++++++++++++++ ..._rosbag_delete_storage_unavailable.test.py | 246 ++++++++ .../test_scenario_bulk_data_upload.test.py | 25 +- src/ros2_medkit_msgs/CMakeLists.txt | 1 + src/ros2_medkit_msgs/design/index.rst | 2 + src/ros2_medkit_msgs/srv/DeleteRosbag.srv | 46 ++ src/ros2_medkit_msgs/srv/ListRosbags.srv | 5 + 44 files changed, 1907 insertions(+), 98 deletions(-) create mode 100644 src/ros2_medkit_integration_tests/test/features/test_rosbag_delete.test.py create mode 100644 src/ros2_medkit_integration_tests/test/features/test_rosbag_delete_storage_unavailable.test.py create mode 100644 src/ros2_medkit_msgs/srv/DeleteRosbag.srv diff --git a/docs/api/rest.rst b/docs/api/rest.rst index 66e60460c..ca2cd3477 100644 --- a/docs/api/rest.rst +++ b/docs/api/rest.rst @@ -1982,6 +1982,7 @@ List all bulk-data items in a category for the entity. "duration_sec": 6.0, "format": "mcap", "priority": 900, + "deletable": false, "recording_id": "fault_MOTOR_OVERHEAT_1738664999000", "storage_files": 1 } @@ -2005,6 +2006,12 @@ manager runs without a valid retention configuration. A client that fetches the most important recordings first sorts by ``priority``, then by ``creation_date``. +``x-medkit.deletable`` is ``true`` when every fault linked to the recording, +also the faults this entity's list leaves out, is CLEARED or HEALED at the time +of the listing: the status the :ref:`rosbag delete ` needs. +It says nothing else: a delete can still answer ``503`` when the fault manager's +store or audit log cannot answer. + **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 @@ -2181,8 +2188,8 @@ Upload Bulk Data ``POST /api/v1/{entity-path}/bulk-data/{category}`` Upload a new bulk-data file to the specified category. Files are sent as -``multipart/form-data``. The ``rosbags`` category is read-only and cannot be -used for uploads. +``multipart/form-data``. The ``rosbags`` category does not accept uploads: its +recordings are made by the fault manager. **Supported entity types:** components, apps only. Areas and functions return 405. @@ -2246,8 +2253,8 @@ Delete Bulk Data ``DELETE /api/v1/{entity-path}/bulk-data/{category}/{id}`` -Delete a specific bulk-data item. The ``rosbags`` category is managed by the -fault manager and cannot be deleted via this endpoint. +Delete a specific bulk-data item. In the ``rosbags`` category it deletes one +recording, see :ref:`rest-rosbag-delete`. **Supported entity types:** components, apps only. Areas and functions return 405. @@ -2260,9 +2267,67 @@ fault manager and cannot be deleted via this endpoint. **Response Codes:** - **204 No Content**: Item deleted successfully -- **400 Bad Request**: ``rosbags`` category (managed by fault manager) - **404 Not Found**: Entity, category, or bulk-data ID not found - **405 Method Not Allowed**: Delete attempted on areas or functions +- **409 Conflict**: Another client holds the entity's ``bulk-data`` lock + (``lock-broken``), or a fault linked to a rosbag recording is neither CLEARED + nor HEALED +- **503 Service Unavailable**: The fault manager did not answer a rosbag delete + +.. _rest-rosbag-delete: + +Delete a Rosbag Recording +~~~~~~~~~~~~~~~~~~~~~~~~~ + +``DELETE /api/v1/{apps|components}/{id}/bulk-data/rosbags/{recording_id}`` + +Deletes one recording: every storage file of it (a split recording goes whole), +its directory, and every row that links a fault to it, also the faults of other +entities. A client that keeps copies downloads them first, then deletes the +recording once its faults are CLEARED or HEALED. The delete does not depend on +the retention configuration. It needs the OPERATOR role, and a lock another +client holds on the entity's ``bulk-data`` refuses it with ``409`` +``lock-broken``. + +.. code-block:: bash + + curl -X DELETE http://localhost:8080/api/v1/apps/motor_controller/bulk-data/rosbags/fault_MOTOR_OVERHEAT_1738664999000 + +- **204 No Content**: every fault linked to the recording is CLEARED or HEALED. + The rows are gone, so the recording is no longer listed or downloadable, and + the fault manager removes the directory right after, on its retention worker, + as for every other removal. A directory that cannot be removed is logged by + the fault manager. +- **404 Not Found**: the id is not a recording, or the recording is outside + the entity's scope (the rule of the download route), or it was deleted + already. Only an id the fault manager holds no recording for, or a recording + it does not find on an unavailable storage path (below), carries + ``vendor_code`` ``x-medkit-recording-not-found``. A fault code is not a + recording id here. While the fault manager's storage path is unavailable (see + ``ROSBAG_STORAGE_UNAVAILABLE`` in :doc:`/config/fault-manager`), a recording + whose directory it does not find is not listed and not downloadable, and its + delete answers ``404`` with ``x-medkit-recording-not-found``, although its rows + are kept. Nothing is deleted. Once a listing or a download finds a recorded + directory again, the delete answers as described here. +- **409 Conflict** with ``error_code`` ``precondition-not-fulfilled``: a linked + fault is neither CLEARED nor HEALED: PREFAILED, PREPASSED, CONFIRMED or any + other stored status. ``parameters.fault_codes`` names those faults. Nothing is + deleted. Clear them, or wait until they heal. +- **503 Service Unavailable**: the fault manager, its store or its audit log + could not answer, or the outcome of removing the rows is unknown (a + PostgreSQL connection lost at the commit). The directory then stays. A + ``503`` after the gateway's call to the fault manager timed out + (``fault_manager.service_timeout_sec``) leaves the outcome unknown: the fault + manager can still finish the delete. List the recordings again to see whether + the recording is gone. + +With the audit log on, the fault manager writes one ``rosbag_deleted`` event per +linked fault before it removes the rows, in every audit mode. The event records +the decision: when the removal then fails (``503``), the event stays and so does +the recording (after a commit of unknown outcome, at least its directory), and a +later delete writes a new event. With +``audit_log.fail_closed: true`` an event that cannot be written stops the +delete: ``503``, nothing deleted. .. _rest-rosbag-recording-files: diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 99995b547..cc24981af 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -1286,7 +1286,9 @@ by default: with it off there is no table, no file and no write cost. * - ``audit_log.transitions`` - ``"all"`` - Which transitions are recorded: ``all`` (occurred, confirmed, healed, cleared) or - ``confirmed_only``. Any other value falls back to ``all`` with a warning. + ``confirmed_only``. Any other value falls back to ``all`` with a warning. Both modes + also record ``rosbag_deleted``: one event per linked fault when a client deletes a + recording (see :ref:`rest-rosbag-delete`), with the fault's status at the delete. * - ``audit_log.retention_max_records`` - ``0`` - Seal and prune the oldest segment once the log passes this many records. @@ -1305,7 +1307,9 @@ by default: with it off there is no table, no file and no write cost. actions that follow it (``on_healed``, ``on_cleared``; for the symptom also the root cause's ``on_cleared``): the stored recordings stay until a space limit or a later status change removes them, and a recording stored after - the failed append follows the fault's status like any store. + the failed append follows the fault's status like any store. A client + delete of a recording whose ``rosbag_deleted`` events cannot be appended + is refused (``503``) and deletes nothing. * - ``audit_log.database_path`` - ``""`` - Where the audit database lives. Empty puts it beside the fault database, diff --git a/docs/config/server.rst b/docs/config/server.rst index bbebc38d1..9dac7d8b7 100644 --- a/docs/config/server.rst +++ b/docs/config/server.rst @@ -845,8 +845,9 @@ Example: .. note:: The ``rosbags`` category is available through the Fault Manager and cannot be - used for uploads or deletes. It is included in the category list whenever the Fault - Manager serves rosbags, which is always the case on the ROS 2 node. + used for uploads. A delete removes one recording once its faults are cleared or + healed (see :ref:`rest-rosbag-delete`). It is included in the category list whenever + the Fault Manager serves rosbags, which is always the case on the ROS 2 node. .. note:: diff --git a/docs/requirements/specs/bulkdata.rst b/docs/requirements/specs/bulkdata.rst index 755837a1c..4c29e9be0 100644 --- a/docs/requirements/specs/bulkdata.rst +++ b/docs/requirements/specs/bulkdata.rst @@ -20,7 +20,8 @@ BulkData Returns BulkDataDescriptor array with id, name, mimetype, size, creation_date fields. For ``rosbags``, includes ``x-medkit`` extensions with fault_codes, duration_sec, format, - recording_id and priority, the recording's retention priority. + recording_id, priority, the recording's retention priority, and deletable, true when every + fault linked to the recording is CLEARED or HEALED. .. req:: GET /{entity}/bulk-data/{category}/{bulk-data-id} :id: REQ_INTEROP_073 @@ -43,7 +44,7 @@ BulkData Accepts multipart/form-data with a required ``file`` field and optional ``description`` and ``metadata`` fields. Returns 201 Created with a Location header pointing to the new - resource. Supported for components and apps. The ``rosbags`` category is read-only. + resource. Supported for components and apps. The ``rosbags`` category does not accept uploads. .. req:: DELETE /{entity}/bulk-data/{category}/{bulk-data-id} :id: REQ_INTEROP_075 @@ -54,4 +55,7 @@ BulkData The endpoint shall delete the addressed bulk-data item from the entity, if permitted. Returns 204 No Content on success. Supported for components and apps. - The ``rosbags`` category is managed by the fault manager and cannot be deleted. + In the ``rosbags`` category the item is one recording: every file of it, its directory and + every row linking a fault to it go once every linked fault is CLEARED or HEALED (204), 409 + while a linked fault is active, 404 for an id that is not a recording in the entity's scope, + 503 when the fault manager cannot answer. diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index e8925dbe6..63ee9b67d 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -43,7 +43,8 @@ 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`) | +| `~/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`) and whether every fault linked to the recording is CLEARED or HEALED (`deletable`) | +| `~/delete_rosbag` | `ros2_medkit_msgs/srv/DeleteRosbag` | Delete one recording once every linked fault is CLEARED or HEALED; see [Deleting a recording](#deleting-a-recording) | ## Features @@ -288,9 +289,37 @@ API (`FaultStorage::get_near_misses`). A database written by an earlier build ga first open. **There is no service or REST surface for it yet** - reading it means going through the storage API or the database file. +## Deleting a recording + +`~/delete_rosbag` deletes one recording: every row that links a fault to it and, once those are +gone, its directory with every storage file. The gateway calls it for +`DELETE /api/v1/{apps|components}/{id}/bulk-data/rosbags/{recording_id}`. The request names the +recording and `scope_fault_codes`, the linked codes that put the recording in the caller's scope; the +answer is `not_found` when none of them is still linked, so a clear or a sweep that removed the only +link the caller could see does not let it delete the recording. The other answers: + +- success: every linked fault was CLEARED or HEALED. The rows are gone, and the directory is queued to + the retention worker, logged `Recording removed: (DELETE)` once removed. The call does + not wait for it: it runs on the node's only executor. +- `fault_active`: a linked fault is neither CLEARED nor HEALED: PREFAILED, PREPASSED, CONFIRMED or any + other stored status. `active_fault_codes` names them; nothing is deleted. +- `storage_unavailable`: the store could not be read, a linked fault is not stored, the recording is on + a storage path the startup check found unavailable, the audit append failed with + `audit_log.fail_closed`, or the removal failed. With a PostgreSQL commit of unknown outcome the rows + may be gone; the directory stays, as on every other removal path. + +Over HTTP a recording on an unavailable storage path answers 404, not 503: `~/list_rosbags` leaves it +out and `~/get_rosbag` declines it, so the gateway does not find it and does not call +`~/delete_rosbag`. Nothing is deleted either way. + +With the audit log on, the delete appends one `rosbag_deleted` event per linked fault, in one +transaction and in every audit mode, before it removes the rows: the event records the decision. When +the removal then fails, the event stays, and a later delete writes a new one. The delete does not +depend on the retention configuration. + ## Advanced: Tamper-Evident Audit Log -An optional append-only, hash-chained audit log records every fault state transition (`occurred`, `confirmed`, `healed`, `cleared`) so the fault history is independently verifiable. Auto-recovery (a fault reaching the healing threshold via PASSED events) is recorded as a distinct `healed` row with source `auto_heal`, so the fault's END is in the timeline and is not confused with a manual `cleared`. The manager has no acknowledge action separate from clearing, so `~/clear_fault` is recorded as `cleared` (clear == ack); there is no `ack` kind. The log also records its own lifecycle with `logging_activated` / `logging_deactivated` markers at start and stop. It is **off by default** because it adds a write and storage cost per transition. +An optional append-only, hash-chained audit log records every fault state transition (`occurred`, `confirmed`, `healed`, `cleared`) so the fault history is independently verifiable. Auto-recovery (a fault reaching the healing threshold via PASSED events) is recorded as a distinct `healed` row with source `auto_heal`, so the fault's END is in the timeline and is not confused with a manual `cleared`. The manager has no acknowledge action separate from clearing, so `~/clear_fault` is recorded as `cleared` (clear == ack); there is no `ack` kind. The log also records its own lifecycle with `logging_activated` / `logging_deactivated` markers at start and stop, and a client delete of a recording as one `rosbag_deleted` row per linked fault, with the fault's status at the delete, source `delete_rosbag` and description `rosbag deleted`. It is **off by default** because it adds a write and storage cost per transition. Each transition appends one immutable row holding `record_hash = sha256(prev_hash + canonical(event))` (OpenSSL EVP SHA-256), the `prev_hash` it links to, and a monotonic `seq`. The hash is computed once at insert and never recomputed. A persisted chain head lets the chain resume across restarts. The log is stored in its own SQLite database (separate from the fault store) and is treated as append-only: the manager only ever inserts rows, and `BEFORE UPDATE` / `BEFORE DELETE` triggers reject out-of-band edits (the guarded rotation prune excepted). @@ -305,7 +334,7 @@ Each transition appends one immutable row holding `record_hash = sha256(prev_has | Parameter | Type | Default | Description | | --------------------------------- | ------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `audit_log.enabled` | bool | `false` | Enable the tamper-evident audit log | -| `audit_log.transitions` | string | `"all"` | Which transitions to record: `"all"` (occurred/confirmed/healed/cleared) or `"confirmed_only"`. Lifecycle markers are always recorded. | +| `audit_log.transitions` | string | `"all"` | Which transitions to record: `"all"` (occurred/confirmed/healed/cleared) or `"confirmed_only"`. Lifecycle markers and `rosbag_deleted` are always recorded. | | `audit_log.database_path` | string | `""` | SQLite path. Empty => sibling `fault_audit.db` next to the fault DB (or `:memory:` for in-memory fault stores) | | `audit_log.retention_max_records` | int | `0` | Seal + prune the oldest segment beyond this many retained records (0 = unlimited) | | `audit_log.fail_closed` | bool | `false` | When `true`, an audit append failure is re-raised as a fail-FAST error signalling the audit chain is broken and needs operator action. It does **not** roll back the already-committed fault-state change (the fault store is a separate DB - no cross-DB atomicity). When `false`, the failure is logged and counted and fault processing continues. Either way the gap is recorded via the in-process dropped-writes / audit-healthy signals (not operator-observable at runtime yet). | diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 88cd29f21..9e4f180fc 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -234,7 +234,7 @@ Main Components 7. **ROS adapter** - what stays in ``FaultManagerNode`` and ``ros2/`` - - The eight services and the ``FaultEvent`` publisher + - The nine services and the ``FaultEvent`` publisher - Wall timers that call ``tick`` with the wall clock - ``CaptureThreadPool``, ``SnapshotCapture`` and ``RosbagCapture``, reached from the core through ``ros2::RosCaptureHooks`` @@ -621,8 +621,14 @@ except ``capture_priorities``: dropped at the store. What the cap frees is computed with the triggering fault code's ``max_bags`` and ``keep_first``: the codes that join the recording later are not known when it opens. - ``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. +- ``recording_priorities``: the priority of each of several recordings. One read of the rosbag rows + and one read per distinct fault code, however many recordings. +- ``recording_list_facts``: for ``ListRosbags``, the priority and ``deletable`` of each of several + recordings, from the same reads: one read of the rosbag rows, one read per distinct fault code. + ``deletable`` is the status rule of ``decide_delete``: every linked fault stored and CLEARED or + HEALED. It leaves out the scope and the protection. +- ``decide_delete(recording_id, scope_fault_codes)`` and ``delete_recording(rows)``: the two halves + of ``DeleteRosbag``, see below. - ``on_fault_cleared``, ``on_fault_healed`` and ``on_startup_reclassified``: one status change of a fault, in one hold of the mutex, and the only decision of it. Each decides with the private ``clear_deletes`` (the ``on_cleared`` of the fault's rule in ``kConfigured`` when the rule sets it, @@ -801,9 +807,38 @@ bytes, its WARN names those bytes instead of saying the new recording alone exce the rows it counts; ``decide_quota`` and ``space_candidates`` take it for the eviction order from ``first_paths``, which skips them too), the status actions (``on_status_change``: heal, clear, startup reclassification; the delete generation still -advances) and ``forget_recording``. A decision skips their rows and, while a set is held, logs +advances) and ``forget_recording``. ``decide_delete`` refuses a protected recording with +``kStorageUnavailable``: its directory is on a disk that is not mounted and would stay with no row. +A decision skips their rows and, while a set is held, logs ``: skipped protected rosbag row(s)`` once at DEBUG. +**A client delete.** ``FaultManagerNode::handle_delete_rosbag`` (``~/delete_rosbag``, +``DeleteRosbag.srv``) runs three steps on the executor: + +1. ``decide_delete`` under the retention mutex reads the recording's rows and each linked fault once: + ``kNotFound`` when no row has the id or none of ``scope_fault_codes`` is still linked (a clear or + a sweep may have removed the only link the gateway's scope rests on), ``kStorageUnavailable`` when + a read fails, a linked fault is not stored (no path deletes a fault record, so only a failed read + gets there) or the recording is protected, ``kFaultActive`` with those codes when a linked + fault is neither CLEARED nor HEALED, else ``kDelete`` with the rows and the linked codes. +2. ``FaultManagerCore::record_rosbag_deleted`` under the core mutex reads each linked fault and + appends one ``rosbag_deleted`` event per code with ``FaultAuditLog::append_all``, in one + transaction. The event is written before the rows go: it records the decision. A failed fault + read, or with ``audit_log.fail_closed`` a failed append, answers ``storage_unavailable`` and + nothing is deleted. Without ``fail_closed`` a failed append is logged and counted as a dropped + write, and the delete goes on. +3. ``delete_recording`` under the retention mutex removes, in one change set, the decided rows still + stored (``kNotFound`` when none is left), and the node posts the freed directory to the retention + worker with ``RemovalReason::kClientDelete``, logged ``Recording removed: + (DELETE)``. ``RosbagCommitInDoubt`` answers ``storage_unavailable`` and posts nothing, so the + directory stays, as on every other removal path. + +The audit cannot run inside a hold of the retention mutex: the lock order is core mutex, retention +mutex, storage. No linked fault changes status between steps 1 and 3, because every status change +runs on the same single-threaded executor. The retention worker may remove rows meanwhile, which +step 3 handles. The callback does not wait for the directory: the removal runs on the worker after +the answer. ``ListRosbags`` fills ``deletable`` per row from ``recording_list_facts``. + The node publishes the mode and the policy once, with ``RosbagRetention::set_policy``, after it builds the retention and before capture starts. Each decision loads that snapshot once with ``std::atomic_load`` and uses it throughout. @@ -841,8 +876,8 @@ depends on the path: logged. The executor never runs a store. A bag that never got a row is discarded on the same 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, heal, startup reclassification and stale rows (the executor; stale rows also in the startup - storage check): the rows go inside the service call or the constructor. The node's +- Clear, heal, startup reclassification, stale rows and a client delete (the executor; stale rows + also in the startup storage check): the rows go inside the service call or the constructor. The node's ``RetentionWorker``, one thread with a FIFO queue, removes the directories, so the clear and report services return before a large bag is removed. - Age sweep (the retention worker): the periodic job calls ``sweep_expired`` with the system clock, @@ -904,6 +939,7 @@ removal after it succeeded. No line announces a removal that has not happened ye ``(max_age_sec.healed)`` or ``(max_age_sec.cleared)``; - a recording the free-space floor deleted: ``Recording removed: (min_free_disk_mb)``; the new recording of a post-store pass gets the drop line instead; +- a recording a client deleted (``DeleteRosbag``): ``Recording removed: (DELETE)``; - a quota eviction: ``Deleted old bag '' to enforce storage limit``; - a stale row: no line, because its directory was already missing; - a removal that failed: a WARN with the path, the reason and the error. diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp index 8c4a6f32c..b14131cb8 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp @@ -224,6 +224,14 @@ class FaultManagerCore { void record_transition(const char * transition, const fd::FaultRecord & fault, const std::string & source_id, int64_t occurred_at_ns); + /// Appends one rosbag_deleted event per code of @p fault_codes, all in one transaction: the fault's + /// severity and current status, source `delete_rosbag`, description `rosbag deleted`. + /// Recorded in every audit mode; no-op when the log is off. + /// @throws a storage failure of a fault read, or a missing fault; nothing is appended then + /// @throws the append failure when audit_log.fail_closed is set; nothing is appended then + void record_rosbag_deleted(const std::string & recording_id, const std::vector & fault_codes, + int64_t occurred_at_ns); + /// Runs the periodic jobs that are due at @p wall_now_ns (ns since the epoch): time-based /// auto-confirmation every kAutoConfirmPeriodSec and correlation cleanup every /// correlation_cleanup_interval_sec. A job runs from half a period before its due time, because the @@ -293,6 +301,9 @@ class FaultManagerCore { const DebounceConfig & resolved); void audit_transition(const char * transition, const fd::FaultRecord & fault, const std::string & source_id, int64_t occurred_at_ns); + /// Whether the audit mode records @p transition: every kind, or with confirmed_only the confirmations and + /// the rosbag deletes. + bool audit_records(const std::string & transition) const; void publish_event(const char * event_type, const fd::FaultRecord & fault, const std::vector & auto_cleared_codes = {}); 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 bf52d68ec..f2934749a 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 @@ -54,15 +54,16 @@ struct RetentionPolicyState { /// Why a recording's directory is no longer named by any row. enum class RemovalReason { - kCap, ///< The per-fault cap (max_bags) - kQuota, ///< The quota (max_total_storage_mb) - kCleared, ///< The fault was cleared: its on_cleared, else auto_cleanup with a max_bags of 1 - kHealed, ///< The fault healed and its on_healed is delete - kStale, ///< The directory was already missing - kAgeActive, ///< max_age_sec.active: the fault is active and its last FAILED is too old - kAgeHealed, ///< max_age_sec.healed - kAgeCleared, ///< max_age_sec.cleared - kFreeSpace, ///< min_free_disk_mb: the free space under the storage path is below the floor + kCap, ///< The per-fault cap (max_bags) + kQuota, ///< The quota (max_total_storage_mb) + kCleared, ///< The fault was cleared: its on_cleared, else auto_cleanup with a max_bags of 1 + kHealed, ///< The fault healed and its on_healed is delete + kStale, ///< The directory was already missing + kAgeActive, ///< max_age_sec.active: the fault is active and its last FAILED is too old + kAgeHealed, ///< max_age_sec.healed + kAgeCleared, ///< max_age_sec.cleared + kFreeSpace, ///< min_free_disk_mb: the free space under the storage path is below the floor + kClientDelete, ///< A client deleted the recording (DeleteRosbag) }; /// Whether the age at @p now_ns of a fault whose last FAILED report was at @p last_failed_ns is @@ -118,6 +119,37 @@ struct RemovalOutcome { bool deletes{false}; ///< A status change decided to delete the fault's recordings }; +/// What a delete of one recording does, decided before anything is removed (RosbagRetention::decide_delete). +struct DeleteDecision { + enum class Result { + kDelete, ///< Every linked fault is CLEARED or HEALED + kNotFound, ///< No row has the id, or none of the scope codes is linked to it + kFaultActive, ///< A linked fault is stored with a status other than CLEARED or HEALED + kStorageUnavailable, ///< A read failed, a linked fault is not stored, or the recording is protected + } result{Result::kNotFound}; + std::vector rows; ///< With kDelete: every row of the recording + std::vector fault_codes; ///< With kDelete and kFaultActive: the linked codes, each once + std::vector active_fault_codes; ///< With kFaultActive: the linked codes neither CLEARED nor HEALED +}; + +/// The removal of a decided delete (RosbagRetention::delete_recording). +struct DeleteOutcome { + enum class Result { + kDeleted, ///< The rows still stored were removed + kNotFound, ///< No row of the decision is stored any more + kStorageUnavailable, ///< The read or the removal failed: no row changed + kInDoubt, ///< RosbagCommitInDoubt: the rows may be gone, the directory stays + } result{Result::kNotFound}; + /// With kDeleted: the directory when no row names it any more, with RemovalReason::kClientDelete. + std::vector unlink_paths; +}; + +/// Retention priority and delete eligibility of a listed recording. +struct RecordingListFacts { + int64_t priority{0}; ///< As RosbagRetention::recording_priority() + bool deletable{false}; ///< Every linked fault is stored and CLEARED or HEALED +}; + /// One removal step of the free-space floor. struct SpaceStep { enum class Result { @@ -192,6 +224,24 @@ class RosbagRetention { /// @throws a storage failure std::unordered_map recording_priorities(const std::vector & recording_ids); + /// The priority and the delete eligibility of each of @p recording_ids, keyed by id: the status rule of + /// decide_delete(), without its scope and protection checks. One read of the rosbag rows and one read per + /// distinct fault code, however many recordings. An id with no row is not deletable. + /// @throws a storage failure + std::unordered_map + recording_list_facts(const std::vector & recording_ids); + + /// The first step of a delete of @p recording_id: in one hold of the mutex, read its rows and each linked + /// fault. kNotFound when no row has the id or none of @p scope_fault_codes is linked to it; kStorageUnavailable + /// when a read fails, a linked fault is not stored, or the recording is protected (protect_recordings()); then + /// kFaultActive when a linked fault is neither CLEARED nor HEALED. Logs a WARN for each kStorageUnavailable. + /// Removes nothing. Never throws. + DeleteDecision decide_delete(const std::string & recording_id, const std::vector & scope_fault_codes); + + /// The last step of a delete: in one hold of the mutex, remove the rows of @p rows (a kDelete decision) that + /// are still stored, in one change set. Logs a WARN for kStorageUnavailable and kInDoubt. Never throws. + DeleteOutcome delete_recording(const std::vector & rows); + /// 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/include/ros2_medkit_fault_manager/fault_audit_log.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_audit_log.hpp index 967090690..fff813c39 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_audit_log.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_audit_log.hpp @@ -67,6 +67,9 @@ constexpr const char * kTransitionHealed = "healed"; /// its own start and stop. constexpr const char * kTransitionLoggingActivated = "logging_activated"; constexpr const char * kTransitionLoggingDeactivated = "logging_deactivated"; +/// A client deleted a recording the fault is linked to. Recorded in every audit mode; its status is +/// the fault's status at the delete. +constexpr const char * kTransitionRosbagDeleted = "rosbag_deleted"; // NOTE: there is deliberately no "ack" kind. The open fault_manager has no // acknowledge action separate from clearing: ~/clear_fault IS the acknowledge, // and it is recorded as kTransitionCleared (clear == ack). A separate "ack" kind @@ -143,6 +146,10 @@ class FaultAuditLog { /// @return the monotonic seq assigned to the new record. int64_t append(const AuditEvent & event); + /// Append @p events in one transaction, the hash chain advanced per event: all or none. + /// @throws std::runtime_error when the transaction fails; no event is then stored. + void append_all(const std::vector & events); + /// Walk the persisted chain oldest-first and validate every link. AuditVerifyResult verify() const; @@ -185,6 +192,8 @@ class FaultAuditLog { std::optional read_head_row_locked() const; ChainHead load_head_locked() const; void store_head_locked(const ChainHead & head_record); + /// Insert @p event as the record after @p prev, inside the caller's transaction. Returns the new head. + ChainHead insert_record_locked(const ChainHead & prev, const AuditEvent & event); /// Seal + prune the oldest segment if the retained count exceeds the limit. void rotate_if_needed_locked(); diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp index 655d5c014..c33d81ac9 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp @@ -43,6 +43,7 @@ #include "ros2_medkit_fault_manager/threshold_resolver.hpp" #include "ros2_medkit_msgs/msg/fault_event.hpp" #include "ros2_medkit_msgs/srv/clear_fault.hpp" +#include "ros2_medkit_msgs/srv/delete_rosbag.hpp" #include "ros2_medkit_msgs/srv/get_fault.hpp" #include "ros2_medkit_msgs/srv/get_rosbag.hpp" #include "ros2_medkit_msgs/srv/get_snapshots.hpp" @@ -162,6 +163,17 @@ class FaultManagerNode : public rclcpp::Node { void handle_list_rosbags(const std::shared_ptr & request, const std::shared_ptr & response); + /// Handle DeleteRosbag: delete one recording once every linked fault is CLEARED or HEALED. + /// + /// Three steps: RosbagRetention::decide_delete() under the retention mutex, the audit events under the core + /// mutex, then RosbagRetention::delete_recording() under the retention mutex and the directory posted to the + /// retention worker. The audit cannot run inside a hold of the retention mutex: the lock order is core mutex, + /// retention mutex, storage. Precondition: every status change runs on this node's only executor, the + /// executor that runs this callback, so no linked fault changes status between the decision and the removal. + /// The retention worker may remove rows meanwhile; delete_recording() removes only the rows still stored. + void handle_delete_rosbag(const std::shared_ptr & request, + const std::shared_ptr & response); + /// Handle ListFaultsForEntity service request void handle_list_faults_for_entity(const std::shared_ptr & request, @@ -316,6 +328,7 @@ class FaultManagerNode : public rclcpp::Node { rclcpp::Service::SharedPtr get_snapshots_srv_; rclcpp::Service::SharedPtr get_rosbag_srv_; rclcpp::Service::SharedPtr list_rosbags_srv_; + rclcpp::Service::SharedPtr delete_rosbag_srv_; rclcpp::Service::SharedPtr list_faults_for_entity_srv_; rclcpp::TimerBase::SharedPtr auto_confirm_timer_; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp index 02f85e275..cc7049911 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp @@ -68,7 +68,7 @@ class RetentionWorker { /// Remove the directory of @p recording on the calling thread, then log the removal with its /// reason: `Recording removed: (its max_bags)`, `(fault cleared)`, `(fault healed)`, - /// `(max_age_sec.active)`, `.healed`, `.cleared` or `(min_free_disk_mb)`, or main's + /// `(max_age_sec.active)`, `.healed`, `.cleared`, `(min_free_disk_mb)` or `(DELETE)`, or main's /// `Deleted old bag '' to enforce storage limit` for the quota. No line when nothing was /// removed, and none for a stale row. A failure logs a WARN with the path, the reason and the /// error. diff --git a/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp b/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp index 1474a5673..8c5ad6621 100644 --- a/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp +++ b/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp @@ -21,8 +21,11 @@ #include #include #include +#include +#include #include #include +#include namespace ros2_medkit_fault_manager::core { @@ -167,6 +170,44 @@ void FaultManagerCore::record_transition(const char * transition, const fd::Faul audit_transition(transition, fault, source_id, occurred_at_ns); } +void FaultManagerCore::record_rosbag_deleted(const std::string & recording_id, + const std::vector & fault_codes, int64_t occurred_at_ns) { + std::lock_guard lock(mutex_); + if (!audit_ || !audit_records(kTransitionRosbagDeleted)) { + return; + } + std::vector events; + events.reserve(fault_codes.size()); + for (const auto & code : fault_codes) { + const auto fault = storage_->get_fault(code); + if (!fault) { + throw std::runtime_error("fault '" + code + "' is not stored"); + } + AuditEvent event; + event.fault_code = code; + event.transition = kTransitionRosbagDeleted; + event.severity = fault->severity; + event.status = fault->status; + event.source_id = "delete_rosbag"; + event.description = "rosbag " + recording_id + " deleted"; + event.occurred_at_ns = occurred_at_ns; + events.push_back(std::move(event)); + } + + try { + audit_->append_all(events); + } catch (const std::exception & e) { + audit_dropped_writes_.fetch_add(events.size(), std::memory_order_relaxed); + audit_healthy_.store(false, std::memory_order_relaxed); + logf(log_, LogLevel::kError, config_.logger_name, + "Failed to append the rosbag_deleted audit records of recording '%s': %s [audit dropped_writes=%" PRIu64 "]", + recording_id.c_str(), e.what(), audit_dropped_writes_.load(std::memory_order_relaxed)); + if (audit_fail_closed_) { + throw; + } + } +} + void FaultManagerCore::run_locked(const std::function & fn) { std::lock_guard lock(mutex_); fn(); @@ -809,10 +850,7 @@ void FaultManagerCore::warn_on_conflicting_debounce_policy(const std::string & f void FaultManagerCore::audit_transition(const char * transition, const fd::FaultRecord & fault, const std::string & source_id, int64_t occurred_at_ns) { - if (!audit_) { - return; - } - if (audit_confirmed_only_ && std::string(transition) != kTransitionConfirmed) { + if (!audit_ || !audit_records(transition)) { return; } @@ -856,6 +894,10 @@ void FaultManagerCore::audit_transition(const char * transition, const fd::Fault } } +bool FaultManagerCore::audit_records(const std::string & transition) const { + return !audit_confirmed_only_ || transition == kTransitionConfirmed || transition == kTransitionRosbagDeleted; +} + void FaultManagerCore::publish_event(const char * event_type, const fd::FaultRecord & fault, const std::vector & auto_cleared_codes) { fd::FaultEventRecord event; 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 6c9d8e89d..d34ee91c2 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -172,7 +172,9 @@ struct RosbagRetention::FaultFacts { StatusAction on_healed{StatusAction::kKeep}; std::optional on_cleared; ///< Unset: the clear default applies int status{kStatusCleared}; + bool stored{false}; ///< The storage holds the fault bool cleared{false}; ///< The storage holds the fault as CLEARED + bool closed{false}; ///< The storage holds the fault as CLEARED or HEALED, the states a delete accepts std::string read_error; ///< Set when the read failed: the facts are not known bool warned{false}; ///< The store has logged the failed read }; @@ -656,7 +658,9 @@ RosbagRetention::FaultFacts RosbagRetention::fault_facts(const RetentionPolicySt facts.on_healed = rule.on_healed; facts.on_cleared = rule.on_cleared; facts.status = status_rank(fault); + facts.stored = fault.has_value(); facts.cleared = fault.has_value() && fault->status == fd::fault_status::kCleared; + facts.closed = facts.cleared || (fault.has_value() && fault->status == fd::fault_status::kHealed); cache.emplace(fault_code, facts); return facts; } @@ -746,6 +750,153 @@ RosbagRetention::recording_priorities(const std::vector & recording return priorities; } +std::unordered_map +RosbagRetention::recording_list_facts(const std::vector & recording_ids) { + std::unordered_map facts; + for (const auto & id : recording_ids) { + facts.emplace(id, RecordingListFacts{}); + } + if (facts.empty()) { + return facts; + } + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + std::unordered_map> codes_by_recording; + for (const auto & row : storage_.get_all_rosbag_files()) { + if (facts.count(row.recording_id) != 0) { + codes_by_recording[row.recording_id].push_back(row.fault_code); + } + } + FactsCache cache; + for (auto & entry : facts) { + const auto codes = codes_by_recording.find(entry.first); + if (codes == codes_by_recording.end()) { + continue; + } + if (state->mode == RetentionMode::kConfigured) { + entry.second.priority = rank_of(*state, codes->second, cache).priority; + } + entry.second.deletable = + std::all_of(codes->second.begin(), codes->second.end(), [this, &state, &cache](const std::string & code) { + return fault_facts(*state, code, cache).closed; + }); + } + return facts; +} + +DeleteDecision RosbagRetention::decide_delete(const std::string & recording_id, + const std::vector & scope_fault_codes) { + DeleteDecision decision; + // An empty id names rows whose backfill did not finish, not one recording. + if (recording_id.empty()) { + return decision; + } + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + const auto refuse = [&decision]() { + decision = DeleteDecision{}; + decision.result = DeleteDecision::Result::kStorageUnavailable; + }; + try { + auto rows = storage_.get_rosbag_files_by_recording(recording_id); + std::vector codes; + for (const auto & row : rows) { + if (std::find(codes.begin(), codes.end(), row.fault_code) == codes.end()) { + codes.push_back(row.fault_code); + } + } + // The scope the caller resolved: a link that went since does not count. + const bool in_scope = + std::any_of(scope_fault_codes.begin(), scope_fault_codes.end(), [&codes](const std::string & code) { + return std::find(codes.begin(), codes.end(), code) != codes.end(); + }); + if (!in_scope) { + return decision; + } + // Its directory is on a disk that is not mounted and would stay with no row. + if (is_protected(recording_id)) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Not deleting recording '%s': it is a recording of the unavailable storage path", recording_id.c_str()); + refuse(); + return decision; + } + FactsCache cache; + for (const auto & code : codes) { + const FaultFacts fault = fault_facts(*state, code, cache); + if (!fault.stored) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Not deleting recording '%s': its linked fault '%s' is not stored", recording_id.c_str(), code.c_str()); + refuse(); + return decision; + } + if (!fault.closed) { + decision.active_fault_codes.push_back(code); + } + } + decision.fault_codes = std::move(codes); + if (!decision.active_fault_codes.empty()) { + decision.result = DeleteDecision::Result::kFaultActive; + return decision; + } + decision.rows = std::move(rows); + decision.result = DeleteDecision::Result::kDelete; + } catch (const std::exception & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, "Could not read recording '%s' for its delete: %s", + recording_id.c_str(), e.what()); + refuse(); + } catch (...) { + logf(log_sink_, LogLevel::kWarn, logger_name_, "Could not read recording '%s' for its delete: unknown exception", + recording_id.c_str()); + refuse(); + } + return decision; +} + +DeleteOutcome RosbagRetention::delete_recording(const std::vector & rows) { + DeleteOutcome outcome; + if (rows.empty()) { + return outcome; + } + const std::string & recording_id = rows.front().recording_id; + std::lock_guard lock(mutex_); + // The decided rows that are still stored: a sweep or a status change may have removed some since. + std::vector stored; + RosbagChangeSet changes; + try { + for (const auto & row : storage_.get_rosbag_files_by_recording(recording_id)) { + const bool decided = std::any_of(rows.begin(), rows.end(), [&row](const RosbagFileInfo & known) { + return known.fault_code == row.fault_code && known.file_path == row.file_path; + }); + if (decided) { + changes.remove.push_back({row.fault_code, row.file_path}); + stored.push_back(row); + } + } + if (stored.empty()) { + return outcome; + } + outcome.unlink_paths = remove(stored, changes, RemovalReason::kClientDelete).unlink_paths; + } catch (const RosbagCommitInDoubt & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Delete of recording '%s': the outcome of removing its rows is unknown; its directory stays: %s", + recording_id.c_str(), e.what()); + outcome.result = DeleteOutcome::Result::kInDoubt; + return outcome; + } catch (const std::exception & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, "Delete of recording '%s' failed; its rows stay: %s", + recording_id.c_str(), e.what()); + outcome.result = DeleteOutcome::Result::kStorageUnavailable; + return outcome; + } catch (...) { + logf(log_sink_, LogLevel::kWarn, logger_name_, "Delete of recording '%s' failed; its rows stay: unknown exception", + recording_id.c_str()); + outcome.result = DeleteOutcome::Result::kStorageUnavailable; + return outcome; + } + outcome.result = DeleteOutcome::Result::kDeleted; + return outcome; +} + 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_audit_log.cpp b/src/ros2_medkit_fault_manager/src/fault_audit_log.cpp index fa7d45e27..88153172c 100644 --- a/src/ros2_medkit_fault_manager/src/fault_audit_log.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_audit_log.cpp @@ -372,41 +372,44 @@ void FaultAuditLog::store_head_locked(const ChainHead & head_record) { } } +ChainHead FaultAuditLog::insert_record_locked(const ChainHead & prev, const AuditEvent & event) { + const int64_t new_seq = prev.seq + 1; + const std::string record_hash = sha256_hex(prev.record_hash + canonicalize(new_seq, event)); + + Stmt insert(db_.get(), + "INSERT INTO audit_log (seq, occurred_at_ns, fault_code, transition, severity, status, " + "source_id, description, prev_hash, record_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + insert.bind_int64(1, new_seq); + insert.bind_int64(2, event.occurred_at_ns); + insert.bind_text(3, event.fault_code); + insert.bind_text(4, event.transition); + insert.bind_int64(5, static_cast(event.severity)); + insert.bind_text(6, event.status); + insert.bind_text(7, event.source_id); + insert.bind_text(8, event.description); + insert.bind_text(9, prev.record_hash); + insert.bind_text(10, record_hash); + if (insert.step() != SQLITE_DONE) { + throw std::runtime_error(std::string("audit: failed to insert record: ") + sqlite3_errmsg(db_.get())); + } + return ChainHead{new_seq, record_hash}; +} + int64_t FaultAuditLog::append(const AuditEvent & event) { std::lock_guard lock(mutex_); - const int64_t new_seq = head_.seq + 1; - const std::string prev_hash = head_.record_hash; - const std::string canonical = canonicalize(new_seq, event); - const std::string record_hash = sha256_hex(prev_hash + canonical); - + ChainHead next; exec_or_throw(db_.get(), "BEGIN IMMEDIATE", "begin append"); try { - Stmt insert(db_.get(), - "INSERT INTO audit_log (seq, occurred_at_ns, fault_code, transition, severity, status, " - "source_id, description, prev_hash, record_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - insert.bind_int64(1, new_seq); - insert.bind_int64(2, event.occurred_at_ns); - insert.bind_text(3, event.fault_code); - insert.bind_text(4, event.transition); - insert.bind_int64(5, static_cast(event.severity)); - insert.bind_text(6, event.status); - insert.bind_text(7, event.source_id); - insert.bind_text(8, event.description); - insert.bind_text(9, prev_hash); - insert.bind_text(10, record_hash); - if (insert.step() != SQLITE_DONE) { - throw std::runtime_error(std::string("audit: failed to insert record: ") + sqlite3_errmsg(db_.get())); - } - - store_head_locked(ChainHead{new_seq, record_hash}); + next = insert_record_locked(head_, event); + store_head_locked(next); exec_or_throw(db_.get(), "COMMIT", "commit append"); } catch (...) { exec_or_throw(db_.get(), "ROLLBACK", "rollback append"); throw; } - head_ = ChainHead{new_seq, record_hash}; + head_ = next; // The append is durable now that COMMIT succeeded. Retention rotation is // best-effort maintenance (seal + prune of the oldest segment); a rotation @@ -419,7 +422,35 @@ int64_t FaultAuditLog::append(const AuditEvent & event) { } catch (const std::exception &) { ++rotation_failures_; } - return new_seq; + return next.seq; +} + +void FaultAuditLog::append_all(const std::vector & events) { + if (events.empty()) { + return; + } + std::lock_guard lock(mutex_); + + ChainHead next = head_; + exec_or_throw(db_.get(), "BEGIN IMMEDIATE", "begin append"); + try { + for (const auto & event : events) { + next = insert_record_locked(next, event); + } + store_head_locked(next); + exec_or_throw(db_.get(), "COMMIT", "commit append"); + } catch (...) { + exec_or_throw(db_.get(), "ROLLBACK", "rollback append"); + throw; + } + + head_ = next; + // Best-effort, as for append(): the events are durable. + try { + rotate_if_needed_locked(); + } catch (const std::exception &) { + ++rotation_failures_; + } } void FaultAuditLog::rotate_if_needed_locked() { 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 05d818ec4..ec48de399 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -355,6 +355,12 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" handle_list_rosbags(request, response); }); + delete_rosbag_srv_ = create_service( + "~/delete_rosbag", [this](const std::shared_ptr & request, + const std::shared_ptr & response) { + handle_delete_rosbag(request, response); + }); + list_faults_for_entity_srv_ = create_service( "~/list_faults_for_entity", [this](const std::shared_ptr & request, @@ -1796,13 +1802,16 @@ void FaultManagerNode::handle_list_rosbags( // 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); + const auto facts = rosbag_retention_->recording_list_facts(response->recording_ids); response->priorities.reserve(response->recording_ids.size()); + response->deletable.reserve(response->recording_ids.size()); for (const auto & recording_id : response->recording_ids) { - response->priorities.push_back(priorities.at(recording_id)); + const auto & fact = facts.at(recording_id); + response->priorities.push_back(fact.priority); + response->deletable.push_back(fact.deletable); } } catch (const std::exception & e) { - RCLCPP_WARN(get_logger(), "Failed to read the rosbag priorities: %s", e.what()); + RCLCPP_WARN(get_logger(), "Failed to read the rosbag priorities and statuses: %s", e.what()); response->success = false; response->error_message = storage_unavailable(e); return; @@ -1813,6 +1822,68 @@ void FaultManagerNode::handle_list_rosbags( request->entity_fqn.c_str()); } +void FaultManagerNode::handle_delete_rosbag( + const std::shared_ptr & request, + const std::shared_ptr & response) { + const std::string & recording_id = request->recording_id; + const auto refuse = [&response](const char * error_code, std::string message) { + response->success = false; + response->error_code = error_code; + response->error_message = std::move(message); + }; + if (!validate_recording_id(recording_id).empty()) { + refuse("not_found", "No recording: " + recording_id); + return; + } + + const auto decision = rosbag_retention_->decide_delete(recording_id, request->scope_fault_codes); + switch (decision.result) { + case core::DeleteDecision::Result::kDelete: + break; + case core::DeleteDecision::Result::kNotFound: + refuse("not_found", "No recording: " + recording_id); + return; + case core::DeleteDecision::Result::kFaultActive: + refuse("fault_active", "A fault linked to recording " + recording_id + " is active"); + response->active_fault_codes = decision.active_fault_codes; + return; + case core::DeleteDecision::Result::kStorageUnavailable: + refuse("storage_unavailable", "Recording " + recording_id + + " cannot be deleted now: its rows or faults could not be read, or its " + "storage path is unavailable"); + return; + } + + // Written before the rows go: the event records the decision. + try { + core_->record_rosbag_deleted(recording_id, decision.fault_codes, wall_clock_.now_ns()); + } catch (const std::exception & e) { + refuse("storage_unavailable", "The audit log could not record the delete of " + recording_id + ": " + e.what()); + return; + } + + auto outcome = rosbag_retention_->delete_recording(decision.rows); + switch (outcome.result) { + case core::DeleteOutcome::Result::kDeleted: + break; + case core::DeleteOutcome::Result::kNotFound: + refuse("not_found", "No recording: " + recording_id); + return; + case core::DeleteOutcome::Result::kStorageUnavailable: + refuse("storage_unavailable", "The rows of recording " + recording_id + " could not be removed"); + return; + case core::DeleteOutcome::Result::kInDoubt: + refuse("storage_unavailable", + "Recording " + recording_id + " kept: the commit outcome is unknown for the removal of its rows"); + return; + } + // The callback does not wait for the removal: this is the node's only executor. + retention_worker_->post_removals("delete", std::move(outcome.unlink_paths)); + response->success = true; + RCLCPP_INFO(get_logger(), "Recording '%s' deleted on request, %zu linked fault(s)", recording_id.c_str(), + decision.fault_codes.size()); +} + void FaultManagerNode::handle_list_faults_for_entity( const std::shared_ptr & request, const std::shared_ptr & response) { diff --git a/src/ros2_medkit_fault_manager/src/retention_worker.cpp b/src/ros2_medkit_fault_manager/src/retention_worker.cpp index ed23422d7..bc5f0af0a 100644 --- a/src/ros2_medkit_fault_manager/src/retention_worker.cpp +++ b/src/ros2_medkit_fault_manager/src/retention_worker.cpp @@ -43,6 +43,8 @@ const char * removal_reason_name(core::RemovalReason reason) { return "max_age_sec.cleared"; case core::RemovalReason::kFreeSpace: return "min_free_disk_mb"; + case core::RemovalReason::kClientDelete: + return "DELETE"; } return "unknown"; } @@ -210,6 +212,7 @@ bool RetentionWorker::remove_recording(const core::FreedRecording & recording) { case core::RemovalReason::kAgeHealed: case core::RemovalReason::kAgeCleared: case core::RemovalReason::kFreeSpace: + case core::RemovalReason::kClientDelete: core::logf(log_sink_, core::LogLevel::kInfo, logger_name_, "Recording removed: %s (%s)", recording.recording_id.c_str(), removal_reason_name(recording.reason)); break; 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 46a2061ff..a8eb05352 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 @@ -42,7 +42,8 @@ from rclpy.node import Node from rclpy.qos import HistoryPolicy, QoSProfile, ReliabilityPolicy from ros2_medkit_msgs.srv import ( - ClearFault, GetFault, GetRosbag, ListFaults, ListFaultsForEntity, ListRosbags, ReportFault, + ClearFault, DeleteRosbag, GetFault, GetRosbag, ListFaults, ListFaultsForEntity, ListRosbags, + ReportFault, ) from std_msgs.msg import UInt8MultiArray @@ -271,7 +272,8 @@ def wait_for_services(self): """ for srv_type, name in ((ReportFault, 'report_fault'), (ClearFault, 'clear_fault'), (GetRosbag, 'get_rosbag'), (ListRosbags, 'list_rosbags'), - (GetFault, 'get_fault'), (ListFaults, 'list_faults'), + (GetFault, 'get_fault'), (DeleteRosbag, 'delete_rosbag'), + (ListFaults, 'list_faults'), (GetParameters, 'get_parameters'), (DescribeParameters, 'describe_parameters'), (SetParameters, 'set_parameters'), @@ -375,6 +377,12 @@ def list_rosbags(self, entity=SOURCE_ID, all_recordings=False): request.all_recordings = all_recordings return self._call(ListRosbags, 'list_rosbags', request) + def delete_rosbag(self, recording_id, scope_fault_codes): + request = DeleteRosbag.Request() + request.recording_id = recording_id + request.scope_fault_codes = list(scope_fault_codes) + return self._call(DeleteRosbag, 'delete_rosbag', request) + def _wait_for_subscription_count(self, reached, what): deadline = time.monotonic() + STARTUP_TIMEOUT_SEC while not reached(self.publisher.get_subscription_count()): diff --git a/src/ros2_medkit_fault_manager/test/integration/test_retention_config_pg.test.py b/src/ros2_medkit_fault_manager/test/integration/test_retention_config_pg.test.py index 60ccce8f0..a953b016f 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_retention_config_pg.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_retention_config_pg.test.py @@ -231,3 +231,27 @@ def listed(): self.assertIn('KEPT', codes) self.assertNotIn(STORAGE_CODE, codes) self.assertEqual(fm.count_lines(r'\[ERROR\]'), 0, fm.output()[-3000:]) + + def test_delete_refused_while_the_server_is_unreachable(self): + self.proxy.accept_connections() + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + path = self.record(fm, 'UNREACHABLE', 0.25) + self.assertTrue(self.client.clear('UNREACHABLE').success) + self.assertEqual(self.client.get_fault('UNREACHABLE').fault.status, 'CLEARED') + rows = self.stored_rows() + self.assertEqual(rows, [('UNREACHABLE', path)]) + recording_id = os.path.basename(path) + self.proxy.refuse_connections() + refused = self.client.delete_rosbag(recording_id, ['UNREACHABLE']) + self.assertFalse(refused.success) + self.assertEqual(refused.error_code, 'storage_unavailable', refused.error_message) + self.proxy.accept_connections() + listings = [] + + def listed(): + listings[:] = [self.client.list_rosbags(all_recordings=True)] + return listings[0].success + self.assertTrue(poll(listed, interval=0.5), listings[0].error_message) + self.assertEqual(list(listings[0].recording_ids), [recording_id]) + self.assertEqual(self.stored_rows(), rows) + self.assertTrue(os.path.isdir(path), f'{path} was removed:\n' + fm.output()[-3000:]) 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 index 4e748ed7a..9a2f5e057 100644 --- 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 @@ -50,6 +50,9 @@ 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' +# The transaction that removes links one by one, as DeleteRosbag does. +LINK_DELETE_STATEMENT = b'DELETE FROM rosbag_files WHERE fault_code' +DELETE_REMOVAL = r'Recording removed: {} \(DELETE\)' IN_DOUBT_WARN = r"Recording '{path}' kept: the commit outcome of its rosbag metadata is unknown" @@ -440,3 +443,42 @@ def test_list_rosbags_forget_cut_at_commit_keeps_the_node_up(self): self.assertEqual(self.rows_of(path), [('FORGET_LIST',)]) self.assertTrue(self.answer(fm, self.client.list_rosbags).success) self.assertEqual(self.rows_of(path), []) + + def record_cleared(self, fm, code): + """Record `code`, clear it, and return the bag path of the recording it alone links.""" + path = self.record(fm, code, 1) + self.assertTrue(self.client.clear(code).success) + self.assertEqual(self.client.get_fault(code).fault.status, 'CLEARED') + self.assertEqual(self.rows_of(path), [(code,)]) + return path + + def test_delete_cut_at_commit_keeps_the_directory(self): + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + path = self.record_cleared(fm, 'DOUBT_DELETE') + other = self.record_cleared(fm, 'DOUBT_DELETE_OTHER') + self.proxy.arm(PgCutProxy.COMMITTED, LINK_DELETE_STATEMENT) + mark = fm.mark() + answer = self.answer(fm, lambda: self.client.delete_rosbag( + os.path.basename(path), ['DOUBT_DELETE'])) + self.assertTrue(self.proxy.cut.wait(EVENT_TIMEOUT_SEC), + 'the proxy never cut the delete') + self.assertFalse(answer.success) + self.assertEqual(answer.error_code, 'storage_unavailable', answer.error_message) + self.assertIn('the commit outcome is unknown', answer.error_message) + self.assertIsNone(fm.proc.poll(), 'the fault manager exited') + # The server committed: the rows are gone, the directory stays with no row. + self.assertEqual(self.rows_of(path), []) + self.assertTrue(poll(lambda: self.answer( + fm, lambda: self.client.get_fault('DOUBT_DELETE')).success), + 'the fault manager never reached the server again') + # A later removal runs on the same worker, after anything the cut delete queued. + deleted = self.answer(fm, lambda: self.client.delete_rosbag( + os.path.basename(other), ['DOUBT_DELETE_OTHER'])) + self.assertTrue(deleted.success, deleted.error_message) + self.assertIsNotNone( + fm.wait_line(DELETE_REMOVAL.format(re.escape(os.path.basename(other))), + since=mark), fm.output()[-3000:]) + self.assertTrue(os.path.isdir(path), f'{path} was removed:\n' + fm.output()[-3000:]) + self.assertEqual( + fm.count_lines(DELETE_REMOVAL.format(re.escape(os.path.basename(path))), + since=mark), 0, fm.output()[-3000:]) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py index a68e889b4..3eb8e5f2b 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py @@ -22,6 +22,7 @@ import os import pathlib +import re import sys import urllib.parse import uuid @@ -107,3 +108,24 @@ def test_clear_removes_the_row_and_the_directory(self): fm.output()[-3000:]) self.assert_recording_gone('PG_A', bag) self.assertEqual(bag_dirs(self.storage), []) + + def test_delete_of_a_cleared_recording(self): + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + bag = self.record(fm, 'PG_DELETE', 1) + self.assertTrue(self.client.clear('PG_DELETE').success) + self.assertEqual(self.client.get_fault('PG_DELETE').fault.status, 'CLEARED') + self.assertEqual(self.stored_rows(), [('PG_DELETE', bag)]) + recording_id = os.path.basename(bag) + mark = fm.mark() + deleted = self.client.delete_rosbag(recording_id, ['PG_DELETE']) + self.assertTrue(deleted.success, deleted.error_message) + self.assertEqual(deleted.error_code, '') + self.assertEqual(self.stored_rows(), []) + # The worker logs the line once the directory is removed. + removed = rf'Recording removed: {re.escape(recording_id)} \(DELETE\)' + self.assertIsNotNone(fm.wait_line(removed, since=mark), fm.output()[-3000:]) + self.assertFalse(os.path.exists(bag), f'{bag} is still on disk') + self.assertEqual(bag_dirs(self.storage), []) + again = self.client.delete_rosbag(recording_id, ['PG_DELETE']) + self.assertFalse(again.success) + self.assertEqual(again.error_code, 'not_found', again.error_message) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_status_actions.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_status_actions.test.py index dee2f3b2a..f95279690 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_status_actions.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_status_actions.test.py @@ -35,7 +35,7 @@ from rosbag_fm_harness import ( # noqa: E402 bag_dirs, EVENT_TIMEOUT_SEC, HEAL_CLEANUP, HEALED_REMOVAL, HEALING, MESSAGE_SIZE, poll, - RetentionCase, rules, SEVERITY_WARN, + RetentionCase, rules, SEVERITY_WARN, sqlite_exec, ) from std_msgs.msg import UInt8MultiArray # noqa: E402 import yaml # noqa: E402 @@ -469,3 +469,32 @@ def test_invalid_values_degrade(self): fm.wait_line(CLEAR_CLEANUP.format('DEGRADED'), since=mark), fm.output()[-3000:]) self.assertFalse(os.path.exists(path), f'{path} is still on disk') + + def test_delete_needs_cleared_or_healed(self): + """A linked fault stored with a status other than CLEARED or HEALED blocks DeleteRosbag.""" + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + path = self.record(fm, 'ODD', 0.25) + recording_id = os.path.basename(path) + self.assertTrue(self.client.clear('ODD').success) + self.assertEqual(self.row_paths('ODD'), [path]) + # A status the fault manager never writes. + sqlite_exec(self.db, 'UPDATE faults SET status = ? WHERE fault_code = ?', + 'SUSPENDED', 'ODD') + listing = self.client.list_rosbags(all_recordings=True) + self.assertTrue(listing.success, listing.error_message) + self.assertEqual(list(listing.recording_ids), [recording_id]) + self.assertEqual(list(listing.deletable), [False]) + refused = self.client.delete_rosbag(recording_id, ['ODD']) + self.assertFalse(refused.success) + self.assertEqual(refused.error_code, 'fault_active', refused.error_message) + self.assertEqual(list(refused.active_fault_codes), ['ODD']) + self.assertEqual(self.row_paths('ODD'), [path]) + self.assertTrue(os.path.isdir(path), f'{path} is gone') + + sqlite_exec(self.db, 'UPDATE faults SET status = ? WHERE fault_code = ?', + 'CLEARED', 'ODD') + listing = self.client.list_rosbags(all_recordings=True) + self.assertEqual(list(listing.deletable), [True]) + deleted = self.client.delete_rosbag(recording_id, ['ODD']) + self.assertTrue(deleted.success, deleted.error_message) + self.assertEqual(self.row_paths('ODD'), []) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_storage_availability.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_storage_availability.test.py index 4cf420647..f419fa0dc 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_storage_availability.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_storage_availability.test.py @@ -23,6 +23,7 @@ import errno import os import pathlib +import re import shutil import sys import time @@ -378,3 +379,26 @@ def test_zero_rows_is_available(self): self.assertEqual(check.groups(), ('0', '0', '0', 'true'), check.string) self.assertEqual(fm.count_lines(r'\[ERROR\]'), 0, fm.output()[-3000:]) self.assertEqual(self.storage_fault_statuses(), []) + + def test_delete_refused_while_unavailable(self): + (path,), rows = self.start_unavailable(('PROTECTED',)) + recording_id = os.path.basename(path) + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + self.assert_started_unavailable(fm, rows) + self.assertTrue(self.client.clear('PROTECTED').success) + self.assertEqual(self.client.get_fault('PROTECTED').fault.status, 'CLEARED') + refused = self.client.delete_rosbag(recording_id, ['PROTECTED']) + self.assertFalse(refused.success) + self.assertEqual(refused.error_code, 'storage_unavailable', refused.error_message) + self.assertEqual(self.stored_rows(), rows) + self.mount() + self.assertEqual(self.recording_ids(self.client.list_rosbags(all_recordings=True)), + [recording_id]) + self.wait_storage_fault('CLEARED') + mark = fm.mark() + deleted = self.client.delete_rosbag(recording_id, ['PROTECTED']) + self.assertTrue(deleted.success, deleted.error_message) + self.assertEqual(self.stored_rows(), []) + removed = rf'Recording removed: {re.escape(recording_id)} \(DELETE\)' + self.assertIsNotNone(fm.wait_line(removed, since=mark), fm.output()[-3000:]) + self.assertFalse(os.path.exists(path), f'{path} is still on disk') diff --git a/src/ros2_medkit_gateway/README.md b/src/ros2_medkit_gateway/README.md index 29d8da07a..7672e757b 100644 --- a/src/ros2_medkit_gateway/README.md +++ b/src/ros2_medkit_gateway/README.md @@ -78,7 +78,7 @@ readable descriptor a reason that says "read-only" answers 403. The same holds f - `GET /api/v1/{entity}/{id}/bulk-data/rosbags/{recording_id}/manifest` - Manifest of a rosbag recording: its storage files in order, with size and sha256 - `GET /api/v1/{entity}/{id}/bulk-data/rosbags/{recording_id}/files/{index}` - Download one storage file of a rosbag recording (supports `Range`) - `POST /api/v1/{entity}/{id}/bulk-data/{category}` - Upload bulk data (components/apps only) -- `DELETE /api/v1/{entity}/{id}/bulk-data/{category}/{item_id}` - Delete bulk data (components/apps only) +- `DELETE /api/v1/{entity}/{id}/bulk-data/{category}/{item_id}` - Delete bulk data (components/apps only); in `rosbags`, one recording once its faults are cleared or healed ### Logging Endpoints @@ -1239,6 +1239,20 @@ 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). +`DELETE /api/v1/{entity-path}/bulk-data/rosbags/{recording_id}` deletes a +recording: every storage file of it, its directory, and every row that links a +fault to it, also faults of other entities. It answers `204` when every linked +fault is CLEARED or HEALED, and `409` (`precondition-not-fulfilled`, the active +codes in `parameters.fault_codes`) while one is PREFAILED, PREPASSED or +CONFIRMED; nothing is deleted then. `404` when the id is not a recording or the +entity may not download it, `503` when the fault manager, its store or its +audit log cannot answer. A `204` means the rows are gone; the fault manager +removes the directory right after, on its retention worker. The route needs the +OPERATOR role and answers `409` (`lock-broken`) while another client holds the +entity's `bulk-data` lock. `x-medkit.deletable` on each +descriptor says whether every linked fault is CLEARED or HEALED at the time of +the listing. The delete does not depend on the retention configuration. + 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 @@ -1787,7 +1801,7 @@ The file takes a target the including build already defines, else `find_package` A program that hosts the core gets the cyclic-subscription samplers and the bulk-data store from the core, and passes the following: - **Samplers.** `register_builtin_samplers(services)` (`core/builtin_samplers.hpp`) registers `data`, `faults`, `configurations` and `logs` on `services.sampler_registry()`, plus `updates` when `services.update_manager()` is set. Each sampler reads through the same managers and helpers as its GET route. A `data` subscription on an entity a plugin owns reads through that plugin's `DataProvider` (or its `x-plc-data` route), and on any other entity through `services.data_access_manager()` and its `TopicDataProvider`. A collection with no manager behind it answers with the error text of its GET route, not a crash. The host passes `GatewayServices` (it must outlive the samplers) and registers a subscription transport itself, for example `SseTransportProvider`. `GET /` reports `cyclic_subscriptions` true only when a transport and at least one sampler are registered. -- **Bulk data.** `BulkDataConfig` (`core/config.hpp`: `storage_dir`, `max_upload_size`, `categories`, with the defaults of the `bulk_data.*` parameters) and `make_bulk_data_store(config)` (`core/managers/bulk_data_store.hpp`) build the store. The host returns it from `GatewayServices::bulk_data_store()` before it starts `RESTServer`, which sizes the upload limit from it. The `rosbags` category is listed only when `FaultServiceTransport::serves_rosbags()` is true; otherwise a request for it answers 404 like any unknown category. The default is true; a host whose fault manager records no rosbags overrides it. `GET /` reports `bulk_data` true only when a store exists or rosbags are served. +- **Bulk data.** `BulkDataConfig` (`core/config.hpp`: `storage_dir`, `max_upload_size`, `categories`, with the defaults of the `bulk_data.*` parameters) and `make_bulk_data_store(config)` (`core/managers/bulk_data_store.hpp`) build the store. The host returns it from `GatewayServices::bulk_data_store()` before it starts `RESTServer`, which sizes the upload limit from it. The `rosbags` category is listed only when `FaultServiceTransport::serves_rosbags()` is true; otherwise a request for it answers 404 like any unknown category. The default is true; a host whose fault manager records no rosbags overrides it. `FaultServiceTransport::delete_rosbag()` has a default that answers unavailable, so a transport without it builds and its rosbag DELETE answers 503. `GET /` reports `bulk_data` true only when a store exists or rosbags are served. - **Freeze frames.** `make_freeze_frame_capture(config, events, plugins)` (`core/faults/freeze_frame_capture.hpp`) builds a `FreezeFrameCapture`. On a `fault_confirmed` event it reads the data of each reporting source through the same path as `GET /{entity}/data` (`plugin_data_readers()` in `core/data/data_item_reader.hpp`: the plugin's `DataProvider`, else its `x-plc-data` route) and keeps the frames, so the fault detail's `environment_data` carries a `freeze_frame` with the values from the confirmation. The host passes a `FreezeFrameCaptureConfig` (`enabled` = `entity_freeze_frame.enabled`, default true; `max_faults`, default 256, the frames of the fault captured longest ago are evicted past it; `list_retry_interval`, default 5 s, the wait between two startup fault-list attempts), a `FaultEventSource` (the capture subscribes on construction and its subscription ends on destruction; a source serves several subscribers, so this can be the source the host returns from `GatewayServices::fault_events()`, which the fault SSE stream subscribes to), and the `PluginManager` that owns the entities. The factory returns null when the configuration is disabled or no plugin is loaded. The host returns the capture from `GatewayServices::freeze_frames()` and keeps it alive as long as the services. Optional: a `StandingFaultLister` that lists every fault at start (any status, muted ones flagged; nullopt or a throw when the list could not be read), an `EventsReadyWaiter` that holds the lister until the event feed delivers, and an `EntityFreezeFrameStore` (`core/faults/entity_freeze_frame_store.hpp`; `SqliteEntityFreezeFrameStore` writes a file). With a store, each capture is written through with the fault's occurrence (`occurrence_count` and `first_occurred`), and the stored frames load on construction and count against the bound. With a lister, no reloaded frame is served before a list has succeeded: another occurrence, or a fault the list does not hold, drops the frame, and an empty list keeps every reloaded frame. A list that could not be read is retried every `list_retry_interval`, with one warning, and live confirms are captured in between; a live capture replaces the reloaded frame of its code. With no lister, every reloaded frame is kept and served at once. The catch-up then frames each confirmed, unmuted fault that has no frame, while the bound has room. An entity no plugin serves gets no frame. The ROS 2 node feeds the same class from the fault manager's events topic (`EntityFreezeFrameCapture`) and opens the store from `entity_freeze_frame.storage.path`, or next to `triggers.storage.path` when that is empty. - **Lock expiry.** `LockReaper(locks, subscriptions, interval_sec, logger)` (`core/managers/lock_reaper.hpp`) calls `LockManager::cleanup_expired()` every `interval_sec` (`LockConfig::cleanup_interval`, default 30, raised to 1 when lower) on a thread it owns. For each expired lock whose scope is empty or includes `cyclic-subscriptions` it removes the cyclic subscriptions of the locked entity. `subscriptions` may be null. The destructor and `stop()` join the thread. Without a reaper a host keeps expired locks until it calls `cleanup_expired()` itself. The ROS 2 node runs the same class. - **Scripts.** `make_script_host(config, plugin_backend)` (`core/managers/script_manager.hpp`) returns a `ScriptManager` and, when no plugin backend is given and `ScriptsConfig::scripts_dir` is not empty, the `DefaultScriptProvider` (fork/execvp) behind it. `ScriptsConfig` (`core/script_types.hpp`) has the defaults of the `scripts.*` parameters, and `entries` carries predefined scripts. The host returns `host.manager` from `GatewayServices::script_manager()` and keeps the `ScriptHost` alive as long as the services. With neither a backend nor a directory the script routes answer 501. diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_types.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_types.hpp index 695f77ecb..625b53e0c 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_types.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/faults/fault_types.hpp @@ -17,6 +17,7 @@ #include #include #include +#include namespace ros2_medkit_gateway { @@ -68,4 +69,19 @@ struct FaultWithEnvJsonResult { FaultFailure failure = FaultFailure::Declined; }; +/// Outcome of a delete of one rosbag recording (`delete_rosbag`). +struct RosbagDeleteResult { + enum class Status : uint8_t { + kDeleted, ///< The rows are gone and the directory is queued for removal + kNotFound, ///< No recording has the id, or none of the scope codes is linked to it + kFaultActive, ///< A linked fault is PREFAILED, PREPASSED or CONFIRMED: nothing was deleted + /// No answer, or the fault manager's store or audit log could not answer: nothing was deleted, or the + /// outcome of the removal is unknown + kUnavailable, + }; + Status status{Status::kUnavailable}; + std::vector active_fault_codes; ///< With kFaultActive + std::string error_message; +}; + } // namespace ros2_medkit_gateway 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 f9b839302..47e814876 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 @@ -63,9 +63,12 @@ enum class RecordingScope { /// 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. +/// the list or a fault route shows downloads, and nothing else. Every rosbag route uses it. +/// With @p in_scope_codes, every code is checked and each one that puts the recording in scope is appended +/// there: every code when the scope holds the fault manager's FQN. RecordingScope recording_scope(FaultManager & fault_manager, const std::vector & fault_codes, - const std::set & scope); + const std::set & scope, + std::vector * in_scope_codes = nullptr); /// 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 @@ -87,6 +90,8 @@ struct RecordingLookup { RecordingLookupStatus status{RecordingLookupStatus::kUnavailable}; /// Recording directory. Set when status is kFound. std::string path; + /// With kFound and all_scope_codes: the attached fault codes that put the recording in the entity's scope. + std::vector scope_fault_codes; }; /// Resolve @p recording_id for an entity whose fault sources are @p source_filters. @@ -94,9 +99,10 @@ struct RecordingLookup { /// The id names a recording only, never a fault code. kNotFound is returned only on /// positive evidence: the fault manager resolved the id to no recording, or it /// declined the id and a complete listing of the entity's recordings does not carry -/// it. Anything short of that is kUnavailable. +/// it. Anything short of that is kUnavailable. With @p all_scope_codes, a found recording carries every +/// attached code that puts it in scope (recording_scope() with in_scope_codes). RecordingLookup find_recording(FaultManager & fault_manager, const std::string & recording_id, - const std::vector & source_filters); + const std::vector & source_filters, bool all_scope_codes = false); } // namespace faults } // namespace ros2_medkit_gateway diff --git a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/http/handlers/bulkdata_handlers.hpp b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/http/handlers/bulkdata_handlers.hpp index 7e7809b4d..c44b95abd 100644 --- a/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/http/handlers/bulkdata_handlers.hpp +++ b/src/ros2_medkit_gateway/include/ros2_medkit_gateway/core/http/handlers/bulkdata_handlers.hpp @@ -72,7 +72,8 @@ class BulkDataHandlers { http::Result, http::ResponseAttachments>> upload(const http::TypedRequest & req, const http::MultipartBody & body); - /// DELETE /{entity}/bulk-data/{category_id}/{file_id} - 204 No Content. + /// DELETE /{entity}/bulk-data/{category_id}/{file_id} - 204 No Content. For `rosbags`, one recording + /// through the fault manager: 409 while a linked fault is active, 503 when the fault manager cannot answer. http::Result remove(const http::TypedRequest & req); /// GET /{entity}/bulk-data/rosbags/{recording_id}/manifest - the recording's @@ -139,6 +140,10 @@ class BulkDataHandlers { * to keep the handler's public surface unchanged. */ std::vector get_source_filters(const EntityInfo & entity) const; + + /// The rosbags branch of remove(): resolve @p recording_id in the entity's scope, then delete it. + http::Result remove_recording(const EntityInfo & entity, const std::string & entity_id, + const std::string & recording_id); }; namespace detail { 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 58b89260c..2bb7c7010 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 @@ -19,6 +19,7 @@ #include #include #include +#include #include "ros2_medkit_gateway/core/faults/fault_types.hpp" #include "ros2_medkit_gateway/core/transports/fault_service_transport.hpp" @@ -94,6 +95,11 @@ class FaultManager { /// stored recording; @p entity_fqn is then ignored. FaultResult list_rosbags(const std::string & entity_fqn, bool all_recordings); + /// Delete one recording (forwards to transport). @p scope_fault_codes are the linked codes that put the + /// recording in the caller's scope. + RosbagDeleteResult delete_rosbag(const std::string & recording_id, + const std::vector & scope_fault_codes); + /// FQN of the fault manager node (forwards to transport). std::string fault_manager_fqn() 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 e1f5c7047..9b8e9f320 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 @@ -18,6 +18,7 @@ #include #include #include +#include #include "ros2_medkit_gateway/core/faults/fault_types.hpp" @@ -62,6 +63,16 @@ class FaultServiceTransport { /// 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; + /// Delete one recording once every linked fault is CLEARED or HEALED. @p scope_fault_codes are the + /// recording's linked codes that put it in the caller's scope; none of them still linked answers kNotFound. + /// The default answers kUnavailable, so a transport without the service builds and its DELETE answers 503. + virtual RosbagDeleteResult delete_rosbag(const std::string & /*recording_id*/, + const std::vector & /*scope_fault_codes*/) { + RosbagDeleteResult result; + result.error_message = "This fault manager transport does not delete recordings"; + return result; + } + /// FQN of the fault manager node these services belong to, for example `/fault_manager`. virtual std::string fault_manager_fqn() const = 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 1b5fc9799..01e3d9bdb 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 @@ -62,7 +62,7 @@ inline constexpr std::string_view dto_name = "BulkDataCate // description - optional human-readable description // x-medkit - optional open vendor extension object. For rosbags: // {fault_codes, duration_sec, format, priority, -// recording_id}, plus +// deletable, 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 7613a1ce6..9224016ae 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 @@ -20,9 +20,11 @@ #include #include #include +#include #include "ros2_medkit_gateway/core/transports/fault_service_transport.hpp" #include "ros2_medkit_msgs/srv/clear_fault.hpp" +#include "ros2_medkit_msgs/srv/delete_rosbag.hpp" #include "ros2_medkit_msgs/srv/get_fault.hpp" #include "ros2_medkit_msgs/srv/get_rosbag.hpp" #include "ros2_medkit_msgs/srv/get_snapshots.hpp" @@ -82,6 +84,9 @@ class Ros2FaultServiceTransport : public FaultServiceTransport { FaultResult list_rosbags(const std::string & entity_fqn, bool all_recordings) override; + RosbagDeleteResult delete_rosbag(const std::string & recording_id, + const std::vector & scope_fault_codes) override; + std::string fault_manager_fqn() const override; bool wait_for_services(std::chrono::duration timeout) override; @@ -107,6 +112,7 @@ class Ros2FaultServiceTransport : public FaultServiceTransport { rclcpp::Client::SharedPtr get_snapshots_client_; rclcpp::Client::SharedPtr get_rosbag_client_; rclcpp::Client::SharedPtr list_rosbags_client_; + rclcpp::Client::SharedPtr delete_rosbag_client_; double service_timeout_sec_{5.0}; std::string fault_manager_base_path_{"/fault_manager"}; 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 e6f41534b..5f9a0c0a7 100644 --- a/src/ros2_medkit_gateway/src/core/faults/rosbag_recording.cpp +++ b/src/ros2_medkit_gateway/src/core/faults/rosbag_recording.cpp @@ -60,21 +60,33 @@ bool scope_holds_fault_manager(const FaultManager & fault_manager, const std::se } RecordingScope recording_scope(FaultManager & fault_manager, const std::vector & fault_codes, - const std::set & scope) { + const std::set & scope, std::vector * in_scope_codes) { if (scope_holds_fault_manager(fault_manager, scope)) { + if (in_scope_codes != nullptr) { + in_scope_codes->insert(in_scope_codes->end(), fault_codes.begin(), fault_codes.end()); + } return RecordingScope::kInScope; } bool unanswered = false; + bool in_scope = 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 (in_scope_codes == nullptr) { + return RecordingScope::kInScope; + } + in_scope_codes->push_back(code); + in_scope = true; + continue; } if (!fault.success && fault.failure == FaultFailure::Unavailable) { unanswered = true; // a later fault can still put the recording in scope } } + if (in_scope) { + return RecordingScope::kInScope; + } return unanswered ? RecordingScope::kUnavailable : RecordingScope::kNotInScope; } @@ -166,7 +178,7 @@ std::optional recording_file_path(const std::string & recording_pat } RecordingLookup find_recording(FaultManager & fault_manager, const std::string & recording_id, - const std::vector & source_filters) { + const std::vector & source_filters, bool all_scope_codes) { RecordingLookup lookup; const auto rosbag = fault_manager.get_rosbag(recording_id); @@ -196,7 +208,7 @@ RecordingLookup find_recording(FaultManager & fault_manager, const std::string & } } } - switch (recording_scope(fault_manager, codes, scope)) { + switch (recording_scope(fault_manager, codes, scope, all_scope_codes ? &lookup.scope_fault_codes : nullptr)) { case RecordingScope::kInScope: break; case RecordingScope::kNotInScope: 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 4d88a2bf5..374eef611 100644 --- a/src/ros2_medkit_gateway/src/core/managers/fault_manager.cpp +++ b/src/ros2_medkit_gateway/src/core/managers/fault_manager.cpp @@ -57,6 +57,11 @@ FaultResult FaultManager::list_rosbags(const std::string & entity_fqn, bool all_ return transport_->list_rosbags(entity_fqn, all_recordings); } +RosbagDeleteResult FaultManager::delete_rosbag(const std::string & recording_id, + const std::vector & scope_fault_codes) { + return transport_->delete_rosbag(recording_id, scope_fault_codes); +} + std::string FaultManager::fault_manager_fqn() const { return transport_->fault_manager_fqn(); } 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 07da359ac..6e629a11d 100644 --- a/src/ros2_medkit_gateway/src/http/handlers/bulkdata_handlers.cpp +++ b/src/ros2_medkit_gateway/src/http/handlers/bulkdata_handlers.cpp @@ -294,6 +294,7 @@ fold_rosbag_rows_into_descriptors(const std::vector & rows, double duration_sec{0.0}; int64_t created_at_ns{0}; int64_t priority{0}; + bool deletable{false}; bool manifest{false}; std::vector fault_codes; }; @@ -349,8 +350,9 @@ 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. + // The fault manager repeats the recording's priority and delete eligibility on each of its rows. entry.priority = row.value("priority", int64_t{0}); + entry.deletable = row.value("deletable", false); entry.manifest = row.value("manifest", false); entry.fault_codes.push_back(fault_code); index_by_recording.emplace(recording_id, recordings.size()); @@ -373,6 +375,7 @@ fold_rosbag_rows_into_descriptors(const std::vector & rows, {"duration_sec", entry.duration_sec}, {"format", entry.format}, {"priority", entry.priority}, + {"deletable", entry.deletable}, // Redundant with the descriptor id, kept because // clients already group on it. {"recording_id", entry.recording_id}}; @@ -851,6 +854,49 @@ BulkDataHandlers::upload(const http::TypedRequest & req, const http::MultipartBo return std::make_pair(http::Created{std::move(descriptor)}, std::move(att)); } +// --------------------------------------------------------------------------- +// DELETE /{entity}/bulk-data/rosbags/{recording_id} - one recording, through the fault manager +// --------------------------------------------------------------------------- + +http::Result BulkDataHandlers::remove_recording(const EntityInfo & entity, + const std::string & entity_id, + const std::string & recording_id) { + auto * fault_mgr = ctx_.services().fault_manager(); + // The download's scope rule; the fault manager deletes only while one of these codes is still linked. + const auto lookup = faults::find_recording(*fault_mgr, recording_id, get_source_filters(entity), true); + switch (lookup.status) { + case faults::RecordingLookupStatus::kFound: + break; + case faults::RecordingLookupStatus::kNotFound: + return tl::unexpected(make_error(404, ERR_X_MEDKIT_RECORDING_NOT_FOUND, "No recording with this id", + json{{"recording_id", recording_id}})); + case faults::RecordingLookupStatus::kNotInEntity: + return tl::unexpected(make_error(404, ERR_RESOURCE_NOT_FOUND, "Recording not found for this entity", + json{{"entity_id", entity_id}})); + case faults::RecordingLookupStatus::kUnavailable: + default: + return tl::unexpected(make_error(503, ERR_SERVICE_UNAVAILABLE, "Fault manager did not answer", + json{{"recording_id", recording_id}})); + } + + const auto deleted = fault_mgr->delete_rosbag(recording_id, lookup.scope_fault_codes); + switch (deleted.status) { + case RosbagDeleteResult::Status::kDeleted: + return http::NoContent{}; + case RosbagDeleteResult::Status::kNotFound: + return tl::unexpected(make_error(404, ERR_RESOURCE_NOT_FOUND, "Recording not found for this entity", + json{{"entity_id", entity_id}})); + case RosbagDeleteResult::Status::kFaultActive: + return tl::unexpected( + make_error(409, ERR_PRECONDITION_NOT_FULFILLED, "A fault linked to the recording is active; clear it first", + json{{"recording_id", recording_id}, {"fault_codes", deleted.active_fault_codes}})); + case RosbagDeleteResult::Status::kUnavailable: + default: + return tl::unexpected(make_error(503, ERR_SERVICE_UNAVAILABLE, "The recording could not be deleted", + json{{"recording_id", recording_id}, {"details", deleted.error_message}})); + } +} + // --------------------------------------------------------------------------- // DELETE /{entity}/bulk-data/{category_id}/{file_id} - 204 No Content // --------------------------------------------------------------------------- @@ -880,18 +926,18 @@ http::Result BulkDataHandlers::remove(const http::TypedRequest return tl::unexpected(make_error(400, ERR_INVALID_REQUEST, "Missing category")); } - // Rosbags are managed by the fault system, not user-deletable. - if (category == "rosbags") { - return tl::unexpected(make_error(400, ERR_INVALID_PARAMETER, - "Category 'rosbags' does not support deletion. " - "Rosbags are managed by the fault system.")); - } - auto item_id = extract_bulk_data_id(req.path()); if (item_id.empty()) { return tl::unexpected(make_error(400, ERR_INVALID_REQUEST, "Missing bulk-data ID")); } + if (category == "rosbags") { + if (!rosbags_served(ctx_)) { + return tl::unexpected(make_error(404, ERR_RESOURCE_NOT_FOUND, "Unknown category: rosbags")); + } + return remove_recording(entity, path_info->entity_id, item_id); + } + auto * store = ctx_.bulk_data_store(); if (store == nullptr) { return tl::unexpected(make_error(500, ERR_INTERNAL_ERROR, "Bulk data storage not configured")); diff --git a/src/ros2_medkit_gateway/src/http/rest_server.cpp b/src/ros2_medkit_gateway/src/http/rest_server.cpp index 4cc314625..f0c097b87 100644 --- a/src/ros2_medkit_gateway/src/http/rest_server.cpp +++ b/src/ros2_medkit_gateway/src/http/rest_server.cpp @@ -1486,9 +1486,16 @@ void RESTServer::setup_routes() { .tag("Bulk Data") .requires_role(UserRole::OPERATOR) .summary(std::string("Delete bulk-data file for ") + et.singular) - .description(std::string("Deletes a bulk-data file for this ") + et.singular + ".") + .description(std::string("Deletes a bulk-data file for this ") + et.singular + + ". In the `rosbags` category it deletes one recording, every file of it, once every " + "fault linked to it is CLEARED or HEALED: 409 `precondition-not-fulfilled` with the " + "active codes in `parameters.fault_codes` otherwise, 503 when the fault manager cannot " + "answer.") // BulkDataHandlers::remove -> validate_lock_access("bulk-data"). .lock_guarded() + // 409: a linked fault is not CLEARED or HEALED; declared here too, since the registry drops the + // lock 409 when locking is off. 503: the fault manager or its store did not answer a rosbag delete. + .errors({409, 503}) .operation_id(std::string("delete") + capitalize(et.singular) + "BulkData"); } else { // 405 stub routes for entity types that cannot host uploaded bulk-data 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 f0b64dff3..924dfe9cd 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 @@ -124,6 +124,8 @@ Ros2FaultServiceTransport::Ros2FaultServiceTransport(rclcpp::Node * node) : node client_node_->create_client(fault_manager_base_path_ + "/get_rosbag"); list_rosbags_client_ = client_node_->create_client(fault_manager_base_path_ + "/list_rosbags"); + delete_rosbag_client_ = + client_node_->create_client(fault_manager_base_path_ + "/delete_rosbag"); RCLCPP_INFO(node_->get_logger(), "Ros2FaultServiceTransport initialized (base_path=%s, timeout=%.1fs)", fault_manager_base_path_.c_str(), service_timeout_sec_); @@ -142,6 +144,7 @@ Ros2FaultServiceTransport::~Ros2FaultServiceTransport() { get_snapshots_client_.reset(); get_rosbag_client_.reset(); list_rosbags_client_.reset(); + delete_rosbag_client_.reset(); executor_.reset(); client_node_.reset(); @@ -477,7 +480,7 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f 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->priorities.size() != n || - response->created_at_ns.size() != n) { + response->deletable.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) + ", recording_ids=" + std::to_string(response->recording_ids.size()) + @@ -486,6 +489,7 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f ", 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()) + + ", deletable=" + std::to_string(response->deletable.size()) + ", created_at_ns=" + std::to_string(response->created_at_ns.size()) + ")"; return result; } @@ -498,6 +502,7 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f {"duration_sec", response->durations_sec[i]}, {"size_bytes", response->sizes_bytes[i]}, {"priority", response->priorities[i]}, + {"deletable", static_cast(response->deletable[i])}, {"created_at_ns", response->created_at_ns[i]}}); } result.data = {{"rosbags", rosbags}}; @@ -508,4 +513,33 @@ FaultResult Ros2FaultServiceTransport::list_rosbags(const std::string & entity_f return result; } +RosbagDeleteResult Ros2FaultServiceTransport::delete_rosbag(const std::string & recording_id, + const std::vector & scope_fault_codes) { + RosbagDeleteResult result; + + auto request = std::make_shared(); + request->recording_id = recording_id; + request->scope_fault_codes = scope_fault_codes; + + auto response = invoke_fault_service( + delete_rosbag_client_, request, executor_, executor_mutex_, std::chrono::duration(service_timeout_sec_), + "DeleteRosbag", result.error_message); + if (!response) { + return result; + } + if (response->success) { + result.status = RosbagDeleteResult::Status::kDeleted; + return result; + } + result.error_message = response->error_message; + if (response->error_code == "not_found") { + result.status = RosbagDeleteResult::Status::kNotFound; + } else if (response->error_code == "fault_active") { + result.status = RosbagDeleteResult::Status::kFaultActive; + result.active_fault_codes = response->active_fault_codes; + } + // storage_unavailable, and a code this gateway does not know, stay kUnavailable: nothing says it was deleted. + return result; +} + } // namespace ros2_medkit_gateway::ros2 diff --git a/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp b/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp index 5a9df1460..7770bc799 100644 --- a/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp +++ b/src/ros2_medkit_gateway/test/test_rosbag_recording.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -777,4 +778,79 @@ TEST_F(RecordingHandlersTest, AListingThatCouldNotReadEverySourceIs503) { EXPECT_EQ(down.error().http_status, 503); } +/// A fault manager that deletes, and remembers every delete it was asked for. +class DeletingFaultTransport : public FakeFaultTransport { + public: + std::vector>> delete_calls; + + RosbagDeleteResult delete_rosbag(const std::string & recording_id, + const std::vector & scope_fault_codes) override { + delete_calls.emplace_back(recording_id, scope_fault_codes); + RosbagDeleteResult result; + result.status = RosbagDeleteResult::Status::kDeleted; + return result; + } +}; + +/// RecordingHandlersTest on a fault manager that deletes. +class BulkDataRosbagDelete : public RecordingHandlersTest { + protected: + void SetUp() override { + RecordingHandlersTest::SetUp(); + deleting_ = std::make_shared(); + deleting_->recordings = transport_->recordings; + deleting_->faults = transport_->faults; + transport_ = deleting_; + manager_ = std::make_unique(deleting_); + services_.faults = manager_.get(); + } + + std::shared_ptr deleting_; +}; + +// In-process: the interleaving this guards against (a link removed between the gateway's scope check and +// the fault manager's delete) cannot be forced between two processes. +// @verifies REQ_INTEROP_075 +TEST_F(BulkDataRosbagDelete, SendsTheInScopeCodes) { + // A burst of the lidar's and the motor's fault; the lidar's App sees only its own. + deleting_->recordings["fault_SHARED_3000"] = {(root_ / "fault_SHARED_3000").string(), {"LIDAR", "MOTOR"}}; + const auto req = request("/apps/lidar/bulk-data/rosbags/fault_SHARED_3000"); + const auto response = handlers_.remove(http::TypedRequest(req)); + ASSERT_TRUE(response.has_value()) << response.error().message; + ASSERT_EQ(deleting_->delete_calls.size(), 1u); + EXPECT_EQ(deleting_->delete_calls[0].first, "fault_SHARED_3000"); + EXPECT_EQ(deleting_->delete_calls[0].second, std::vector{"LIDAR"}); +} + +// In-process: every real gateway uses the ROS transport, so no real process reaches the default. +// @verifies REQ_INTEROP_075 +TEST(FaultManager, DeleteRosbagDefaultAnswersUnavailable) { + auto transport = std::make_shared(); + transport->recordings["fault_LIDAR_1000"] = {"/var/bags/fault_LIDAR_1000", {"LIDAR"}}; + transport->faults["LIDAR"] = {"lidar"}; + ros2_medkit_gateway::FaultManager manager(transport); + EXPECT_EQ(manager.delete_rosbag("fault_LIDAR_1000", {"LIDAR"}).status, RosbagDeleteResult::Status::kUnavailable); + + RecordingServices services; + App lidar; + lidar.id = "lidar"; + lidar.external = true; + lidar.component_id = "machine"; + Component machine; + machine.id = "machine"; + services.cache.update_all({}, {machine}, {lidar}, {}); + services.faults = &manager; + CorsConfig cors{}; + AuthConfig auth{}; + TlsConfig tls{}; + handlers::HandlerContext ctx{services, cors, auth, tls, nullptr}; + handlers::BulkDataHandlers handlers{ctx}; + httplib::Request req; + req.path = "/api/v1/apps/lidar/bulk-data/rosbags/fault_LIDAR_1000"; + const auto response = handlers.remove(http::TypedRequest(req)); + ASSERT_FALSE(response.has_value()); + EXPECT_EQ(response.error().http_status, 503); + EXPECT_EQ(response.error().code, ERR_SERVICE_UNAVAILABLE); +} + } // namespace diff --git a/src/ros2_medkit_integration_tests/test/features/test_locking_disabled_contract.test.py b/src/ros2_medkit_integration_tests/test/features/test_locking_disabled_contract.test.py index e0790c56a..531df20e6 100644 --- a/src/ros2_medkit_integration_tests/test/features/test_locking_disabled_contract.test.py +++ b/src/ros2_medkit_integration_tests/test/features/test_locking_disabled_contract.test.py @@ -212,6 +212,14 @@ def test_no_operation_declares_a_lock_conflict(self): f'{len(offenders)} operations declare a lock conflict: ' f'{offenders[:20]}') + def test_bulk_data_delete_keeps_its_fault_conflict(self): + """Declare the 409 of a rosbag delete with an active fault, a 409 that needs no lock.""" + by_id = {op.get('operationId'): op for _, _, op in self.operations()} + for operation_id in ('deleteAppBulkData', 'deleteComponentBulkData'): + with self.subTest(operation_id): + self.assertIn(operation_id, by_id) + self.assertIn('409', by_id[operation_id].get('responses', {})) + def test_the_lock_crud_is_still_documented_and_still_served(self): """Anti-vacuous, and the boundary of the change. diff --git a/src/ros2_medkit_integration_tests/test/features/test_rosbag_delete.test.py b/src/ros2_medkit_integration_tests/test/features/test_rosbag_delete.test.py new file mode 100644 index 000000000..e27acead8 --- /dev/null +++ b/src/ros2_medkit_integration_tests/test/features/test_rosbag_delete.test.py @@ -0,0 +1,583 @@ +#!/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. + +"""DELETE of one rosbag recording through the bulk-data API. + +A real gateway and a real fault manager, with no retention parameters. A clear keeps the +recording (``auto_cleanup`` off), so a client deletes it once every linked fault is CLEARED or +HEALED. The audit log records confirmations only and fails closed. Two fault codes have their own +thresholds: DEL_HEALS heals on one PASSED report; DEL_PENDING confirms on the second FAILED report +and heals at a counter of 2, so it can rest PREFAILED and PREPASSED. A recording past 1 MB is +split; the split case publishes a blob topic for that. +""" + +import os +import signal +import sqlite3 +import tempfile +import threading +import time +import unittest + +import launch_testing +import rclpy +from rclpy.duration import Duration +from rclpy.node import Node +from rclpy.qos import HistoryPolicy, QoSProfile, ReliabilityPolicy +import requests +from ros2_medkit_msgs.srv import ClearFault, DeleteRosbag, GetFault, ListRosbags, ReportFault + +from ros2_medkit_test_utils.constants import ALLOWED_EXIT_CODES, get_time_scale +from ros2_medkit_test_utils.gateway_test_case import GatewayTestCase +from ros2_medkit_test_utils.launch_helpers import create_test_launch + +from std_msgs.msg import String + +APP_A = 'temp_sensor' +APP_B = 'rpm_sensor' +FQN_A = '/powertrain/engine/temp_sensor' +FQN_B = '/powertrain/engine/rpm_sensor' +FM_APP = 'fault_manager' +LIDAR_APP = 'lidar_sensor' +LIDAR_OWN_FAULT = 'LIDAR_CALIBRATION_REQUIRED' +SCAN_TOPIC = '/perception/lidar/scan' +SEVERITY_ERROR = 2 + +SCALE = get_time_scale() +WAIT_SEC = 60.0 * SCALE +SERVICE_SEC = 30.0 * SCALE +HTTP_SEC = 30.0 * SCALE + +# 200 KB each, about 4 MB together: several storage files of the 1 MB split. +BLOB_TOPIC = '/rosbag_delete_probe/blob' +BLOB_BYTES = 200 * 1024 +BLOB_COUNT = 20 + +ROOT = tempfile.mkdtemp(prefix='rosbag_e2e_delete_') +STORAGE = os.path.join(ROOT, 'bags') +AUDIT_DB = os.path.join(ROOT, 'audit.db') +THRESHOLDS = os.path.join(ROOT, 'fault_codes.yaml') +with open(THRESHOLDS, 'w') as _file: + _file.write('DEL_HEALS:\n' + ' confirmation_threshold: -1\n' + ' healing_enabled: true\n' + ' healing_threshold: 0\n' + 'DEL_PENDING:\n' + ' confirmation_threshold: -2\n' + ' healing_enabled: true\n' + ' healing_threshold: 2\n') + +AUDIT_FAILURE = "Failed to append the rosbag_deleted audit records of recording '{}'" + + +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, + # A fault confirmed again records again, so a newer recording can take its cap. + 'snapshots.recapture_cooldown_sec': 0.0, + 'snapshots.rosbag.duration_sec': 3.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': STORAGE, + 'snapshots.rosbag.max_bag_size_mb': 1, + 'snapshots.rosbag.auto_cleanup': False, + 'snapshots.rosbag.include_topics': [SCAN_TOPIC, BLOB_TOPIC], + 'fault_thresholds.config_file': THRESHOLDS, + 'audit_log.enabled': True, + 'audit_log.transitions': 'confirmed_only', + 'audit_log.fail_closed': True, + 'audit_log.database_path': AUDIT_DB, + }, + ) + + +def _items(listing): + return listing.get('items', []) + + +def _codes(item): + return item.get('x-medkit', {}).get('fault_codes', []) + + +def _poll(predicate, timeout=WAIT_SEC, interval=0.1): + """Return True once `predicate()` is true, False at the deadline.""" + deadline = time.monotonic() + timeout + waiter = threading.Event() + while True: + if predicate(): + return True + if time.monotonic() >= deadline: + return False + waiter.wait(interval) + + +class TestRosbagDelete(GatewayTestCase): + """Delete one recording: status, scope, lock, audit and the fault manager's answers.""" + + MIN_EXPECTED_APPS = 4 + REQUIRED_APPS = {LIDAR_APP, APP_A, APP_B, FM_APP} + + active_id = None + pending_id = None + + @classmethod + def setUpClass(cls): + rclpy.init() + cls.node = Node('_rosbag_delete_driver') + # Before the fault manager starts: an explicit topic is subscribed when it is found then. + qos = QoSProfile(reliability=ReliabilityPolicy.RELIABLE, + history=HistoryPolicy.KEEP_LAST, depth=BLOB_COUNT) + cls.blob_pub = cls.node.create_publisher(String, BLOB_TOPIC, qos) + cls.report_client = cls.node.create_client(ReportFault, '/fault_manager/report_fault') + cls.clear_client = cls.node.create_client(ClearFault, '/fault_manager/clear_fault') + cls.get_client = cls.node.create_client(GetFault, '/fault_manager/get_fault') + cls.list_client = cls.node.create_client(ListRosbags, '/fault_manager/list_rosbags') + cls.delete_client = cls.node.create_client(DeleteRosbag, '/fault_manager/delete_rosbag') + super().setUpClass() + for client in (cls.report_client, cls.clear_client, cls.get_client, cls.list_client): + assert client.wait_for_service(timeout_sec=SERVICE_SEC), client.srv_name + cls._wait_idle_capture() + + @classmethod + def tearDownClass(cls): + cls.node.destroy_node() + rclpy.shutdown() + super().tearDownClass() + + @classmethod + def _wait_idle_capture(cls): + """Wait for the lidar's own startup recording, so each fault below starts its own.""" + url = f'{cls.BASE_URL}/apps/{LIDAR_APP}/bulk-data/rosbags' + + def listed(): + try: + response = requests.get(url, timeout=5) + except requests.exceptions.RequestException: + return False + return response.status_code == 200 and any( + LIDAR_OWN_FAULT in _codes(item) for item in _items(response.json())) + assert _poll(listed), f'{LIDAR_OWN_FAULT} was never recorded' + + # ------------------------------------------------------------------ + # The fault manager's services + # ------------------------------------------------------------------ + + def _call(self, client, request, timeout=SERVICE_SEC): + future = client.call_async(request) + rclpy.spin_until_future_complete(self.node, future, timeout_sec=timeout) + self.assertIsNotNone(future.result(), f'{client.srv_name} did not answer') + return future.result() + + def _report(self, code, source=FQN_A, passed=False): + request = ReportFault.Request() + request.fault_code = code + request.event_type = (ReportFault.Request.EVENT_PASSED if passed + else ReportFault.Request.EVENT_FAILED) + request.severity = SEVERITY_ERROR + request.description = 'rosbag delete e2e' + request.source_id = source + self.assertTrue(self._call(self.report_client, request).accepted, code) + + def _clear(self, code): + request = ClearFault.Request() + request.fault_code = code + self.assertTrue(self._call(self.clear_client, request).success, code) + + def _status(self, code): + request = GetFault.Request() + request.fault_code = code + response = self._call(self.get_client, request) + self.assertTrue(response.success, response.error_message) + return response.fault.status + + def _assert_status(self, code, status): + self.assertEqual(self._status(code), status, code) + + def _rows(self, recording_id): + """Return the sorted fault codes of every row of the recording.""" + request = ListRosbags.Request() + request.all_recordings = True + response = self._call(self.list_client, request) + self.assertTrue(response.success, response.error_message) + return sorted(code for code, rid in zip(response.fault_codes, response.recording_ids) + if rid == recording_id) + + def _delete_request(self, recording_id, scope): + self.assertTrue(self.delete_client.wait_for_service(timeout_sec=SERVICE_SEC), + 'the delete_rosbag service never appeared') + request = DeleteRosbag.Request() + request.recording_id = recording_id + request.scope_fault_codes = list(scope) + return request + + # ------------------------------------------------------------------ + # HTTP and disk + # ------------------------------------------------------------------ + + def _listing(self, app): + return _items(self.get_json(f'/apps/{app}/bulk-data/rosbags', timeout=HTTP_SEC)) + + def _descriptor(self, app, recording_id): + return next((item for item in self._listing(app) if item['id'] == recording_id), None) + + def _wait_recording(self, code, app=APP_A, exclude=()): + """Return the first descriptor of `code` the app lists, skipping the ids in `exclude`.""" + def find(listing): + return next((item for item in _items(listing) + if code in _codes(item) and item['id'] not in exclude), None) + return self.poll_endpoint_until(f'/apps/{app}/bulk-data/rosbags', find, + timeout=WAIT_SEC, interval=0.2) + + def _record(self, code, source=FQN_A, app=APP_A, reports=1): + """Confirm `code` and return the id of its recording, listed under `app`.""" + for _ in range(reports): + self._report(code, source) + recording_id = self._wait_recording(code, app)['id'] + self._assert_status(code, 'CONFIRMED') + self.assertTrue(os.path.isdir(self._dir(recording_id)), recording_id) + return recording_id + + def _record_cleared(self, code): + """Record `code` and clear it: a recording that only its CLEARED fault links.""" + recording_id = self._record(code) + self._clear(code) + self._assert_status(code, 'CLEARED') + self.assertEqual(self._rows(recording_id), [code]) + return recording_id + + def _delete(self, app, recording_id, headers=None): + return requests.delete(f'{self.BASE_URL}/apps/{app}/bulk-data/rosbags/{recording_id}', + headers=headers or {}, timeout=HTTP_SEC) + + def _dir(self, recording_id): + return os.path.join(STORAGE, recording_id) + + def _assert_gone(self, recording_id, apps=(APP_A,)): + """Check the rows, the listings, the download, then within a deadline the directory.""" + self.assertEqual(self._rows(recording_id), []) + for app in apps + (FM_APP,): + self.assertIsNone(self._descriptor(app, recording_id), app) + download = requests.get(f'{self.BASE_URL}/apps/{FM_APP}/bulk-data/rosbags/{recording_id}', + timeout=HTTP_SEC) + self.assertEqual(download.status_code, 404, download.text) + self.assertTrue(_poll(lambda: not os.path.exists(self._dir(recording_id))), + f'{self._dir(recording_id)} is still on disk') + + def _assert_kept(self, recording_id, rows, app=APP_A): + self.assertEqual(self._rows(recording_id), sorted(rows)) + self.assertIsNotNone(self._descriptor(app, recording_id), recording_id) + self.assertTrue(os.path.isdir(self._dir(recording_id)), recording_id) + + def _assert_refused_active(self, response, codes): + self.assertEqual(response.status_code, 409, response.text) + body = response.json() + self.assertEqual(body.get('error_code'), 'precondition-not-fulfilled', body) + self.assertEqual(sorted(body.get('parameters', {}).get('fault_codes', [])), sorted(codes), + body) + + def _audit_events(self, recording_id): + """Return (fault_code, status, source_id) of the rosbag_deleted events of the recording.""" + conn = sqlite3.connect(AUDIT_DB, timeout=30) + try: + rows = conn.execute( + 'SELECT fault_code, status, source_id, description FROM audit_log ' + "WHERE transition = 'rosbag_deleted' ORDER BY seq").fetchall() + finally: + conn.close() + return [(code, status, source) for code, status, source, description in rows + if description == f'rosbag {recording_id} deleted'] + + # ------------------------------------------------------------------ + # Tests + # ------------------------------------------------------------------ + + def test_01_an_active_fault_keeps_its_recording(self): + """A CONFIRMED fault: 409 naming it, not deletable; the recording stays. + + @verifies REQ_INTEROP_072 + @verifies REQ_INTEROP_075 + """ + recording_id = self._record('DEL_ACTIVE') + type(self).active_id = recording_id + descriptor = self._descriptor(APP_A, recording_id) + self.assertIs(descriptor['x-medkit'].get('deletable'), False, descriptor) + + self._assert_refused_active(self._delete(APP_A, recording_id), ['DEL_ACTIVE']) + self._assert_kept(recording_id, ['DEL_ACTIVE']) + self.assertEqual(self._audit_events(recording_id), []) + + def test_02_a_cleared_faults_recording_is_deleted(self): + """The same fault cleared: deletable, 204, then gone from every view and from disk. + + @verifies REQ_INTEROP_072 + @verifies REQ_INTEROP_075 + """ + recording_id = self.active_id + self.assertIsNotNone(recording_id, 'the recording of test_01 is missing') + self.assertEqual(self._rows(recording_id), ['DEL_ACTIVE']) + self._clear('DEL_ACTIVE') + self._assert_status('DEL_ACTIVE', 'CLEARED') + descriptor = self._descriptor(APP_A, recording_id) + self.assertIs(descriptor['x-medkit'].get('deletable'), True, descriptor) + + response = self._delete(APP_A, recording_id) + self.assertEqual(response.status_code, 204, response.text) + self._assert_gone(recording_id) + self.assertEqual(self._audit_events(recording_id), + [('DEL_ACTIVE', 'CLEARED', 'delete_rosbag')]) + + def test_03_a_deleted_recording_and_a_fault_code_are_not_found(self): + """A second DELETE and a fault code as the id: 404. + + @verifies REQ_INTEROP_075 + """ + self.assertIsNotNone(self.active_id, 'the recording of test_01 is missing') + self.assertEqual(self._rows(self.active_id), []) + response = self._delete(APP_A, self.active_id) + self.assertEqual(response.status_code, 404, response.text) + + recording_id = self._record_cleared('DEL_BY_CODE') + response = self._delete(APP_A, 'DEL_BY_CODE') + self.assertEqual(response.status_code, 404, response.text) + self._assert_kept(recording_id, ['DEL_BY_CODE']) + + def test_04_a_healed_faults_recording_is_deleted(self): + """A fault that healed: 204. + + @verifies REQ_INTEROP_075 + """ + recording_id = self._record('DEL_HEALS') + self._report('DEL_HEALS', passed=True) + self._assert_status('DEL_HEALS', 'HEALED') + self.assertIs(self._descriptor(APP_A, recording_id)['x-medkit'].get('deletable'), True) + + response = self._delete(APP_A, recording_id) + self.assertEqual(response.status_code, 204, response.text) + self._assert_gone(recording_id) + + def test_05_a_shared_recording_waits_for_every_fault(self, proc_output, fault_manager_node): + """A burst of a cleared and a CONFIRMED fault: 409 naming the CONFIRMED one, then 204. + + @verifies REQ_INTEROP_075 + """ + self._report('SHARED_A', FQN_A) + proc_output.assertWaitFor("fault 'SHARED_A' confirmed, flushing buffer to bag", + process=fault_manager_node, timeout=WAIT_SEC) + self._report('SHARED_B', FQN_B) + proc_output.assertWaitFor("Fault 'SHARED_B' confirmed during post-fault recording", + process=fault_manager_node, timeout=WAIT_SEC) + recording_id = self._wait_recording('SHARED_A')['id'] + self.assertEqual(self._wait_recording('SHARED_B', APP_B)['id'], recording_id) + self._clear('SHARED_A') + self._assert_status('SHARED_A', 'CLEARED') + self._assert_status('SHARED_B', 'CONFIRMED') + self.assertEqual(self._rows(recording_id), ['SHARED_A', 'SHARED_B']) + self.assertIs(self._descriptor(APP_A, recording_id)['x-medkit'].get('deletable'), False) + + self._assert_refused_active(self._delete(APP_A, recording_id), ['SHARED_B']) + self._assert_kept(recording_id, ['SHARED_A', 'SHARED_B']) + + self._clear('SHARED_B') + self.assertIs(self._descriptor(APP_B, recording_id)['x-medkit'].get('deletable'), True) + response = self._delete(APP_A, recording_id) + self.assertEqual(response.status_code, 204, response.text) + self._assert_gone(recording_id, apps=(APP_A, APP_B)) + # confirmed_only mode: one event per linked fault all the same. + self.assertEqual(sorted(self._audit_events(recording_id)), + [('SHARED_A', 'CLEARED', 'delete_rosbag'), + ('SHARED_B', 'CLEARED', 'delete_rosbag')]) + + def test_06_a_prefailed_fault_keeps_its_recording(self): + """A cleared fault reported FAILED once more rests PREFAILED: 409 naming it. + + @verifies REQ_INTEROP_075 + """ + recording_id = self._record('DEL_PENDING', reports=2) + type(self).pending_id = recording_id + self._clear('DEL_PENDING') + self._report('DEL_PENDING') + self._assert_status('DEL_PENDING', 'PREFAILED') + + self._assert_refused_active(self._delete(APP_A, recording_id), ['DEL_PENDING']) + self._assert_kept(recording_id, ['DEL_PENDING']) + + def test_07_a_prepassed_fault_keeps_its_recording(self): + """The PREFAILED fault reported PASSED until it rests PREPASSED: 409 naming it. + + @verifies REQ_INTEROP_075 + """ + recording_id = self.pending_id + self.assertIsNotNone(recording_id, 'the recording of test_06 is missing') + self._assert_status('DEL_PENDING', 'PREFAILED') + # The counter goes -1, 0, 1; the fault heals only at 2. + for _ in range(2): + self._report('DEL_PENDING', passed=True) + self._assert_status('DEL_PENDING', 'PREPASSED') + + self._assert_refused_active(self._delete(APP_A, recording_id), ['DEL_PENDING']) + self._assert_kept(recording_id, ['DEL_PENDING']) + + def test_08_a_split_recording_goes_whole(self): + """A recording of several storage files: 204, every file and the directory gone. + + @verifies REQ_INTEROP_075 + """ + self.assertTrue(_poll(lambda: self.blob_pub.get_subscription_count() > 0), + f'the capture never subscribed to {BLOB_TOPIC}') + message = String() + message.data = 'x' * BLOB_BYTES + for _ in range(BLOB_COUNT): + self.blob_pub.publish(message) + self.assertTrue(self.blob_pub.wait_for_all_acked(Duration(seconds=SERVICE_SEC)), + 'the capture did not take a blob') + recording_id = self._record('DEL_SPLIT') + storage_files = [name for name in os.listdir(self._dir(recording_id)) + if name.endswith('.mcap')] + self.assertGreater(len(storage_files), 1, storage_files) + self.assertEqual(self._descriptor(APP_A, recording_id)['x-medkit'].get('storage_files'), + len(storage_files)) + self._clear('DEL_SPLIT') + self._assert_status('DEL_SPLIT', 'CLEARED') + + response = self._delete(APP_A, recording_id) + self.assertEqual(response.status_code, 204, response.text) + self._assert_gone(recording_id) + + def test_09_an_app_outside_the_scope_gets_404(self): + """A deletable recording of A, deleted under B: 404, and it stays. + + @verifies REQ_INTEROP_075 + """ + recording_id = self._record_cleared('DEL_SCOPE') + self.assertIsNone(self._descriptor(APP_B, recording_id)) + + response = self._delete(APP_B, recording_id) + self.assertEqual(response.status_code, 404, response.text) + self._assert_kept(recording_id, ['DEL_SCOPE']) + + def test_10_the_fault_manager_app_deletes_any_recording(self): + """DELETE on the fault manager's App: 204. + + @verifies REQ_INTEROP_075 + """ + recording_id = self._record_cleared('DEL_VIA_FM') + self.assertIsNotNone(self._descriptor(FM_APP, recording_id)) + + response = self._delete(FM_APP, recording_id) + self.assertEqual(response.status_code, 204, response.text) + self._assert_gone(recording_id) + + def test_11_a_lock_of_another_client_refuses(self): + """Another client holds the App's lock: the lock error, nothing deleted. + + @verifies REQ_INTEROP_075 + """ + recording_id = self._record_cleared('DEL_LOCKED') + lock = requests.post(f'{self.BASE_URL}/apps/{APP_A}/locks', json={'lock_expiration': 300}, + headers={'X-Client-Id': 'holder'}, timeout=HTTP_SEC) + self.assertEqual(lock.status_code, 201, lock.text) + lock_id = lock.json()['id'] + try: + response = self._delete(APP_A, recording_id, headers={'X-Client-Id': 'other'}) + self.assertEqual(response.status_code, 409, response.text) + self.assertEqual(response.json().get('error_code'), 'lock-broken', response.text) + self._assert_kept(recording_id, ['DEL_LOCKED']) + finally: + released = requests.delete(f'{self.BASE_URL}/apps/{APP_A}/locks/{lock_id}', + headers={'X-Client-Id': 'holder'}, timeout=HTTP_SEC) + self.assertEqual(released.status_code, 204, released.text) + + def test_12_a_link_gone_from_the_scope_is_not_found(self, proc_output, fault_manager_node): + """The only in-scope link went after the scope was read: not_found, nothing removed.""" + self._report('RELINK_X', FQN_A) + proc_output.assertWaitFor("fault 'RELINK_X' confirmed, flushing buffer to bag", + process=fault_manager_node, timeout=WAIT_SEC) + self._report('RELINK_Y', FQN_B) + proc_output.assertWaitFor("Fault 'RELINK_Y' confirmed during post-fault recording", + process=fault_manager_node, timeout=WAIT_SEC) + shared = self._wait_recording('RELINK_Y', APP_B)['id'] + self.assertEqual(self._rows(shared), ['RELINK_X', 'RELINK_Y']) + # A newer recording of X takes X's only slot (max_bags_per_fault 1): its link goes. + self._clear('RELINK_X') + self._report('RELINK_X', FQN_A) + newer = self._wait_recording('RELINK_X', exclude=(shared,))['id'] + self.assertNotEqual(newer, shared) + self.assertEqual(self._rows(shared), ['RELINK_Y']) + self._clear('RELINK_Y') + self._assert_status('RELINK_X', 'CONFIRMED') + self._assert_status('RELINK_Y', 'CLEARED') + + response = self._call(self.delete_client, self._delete_request(shared, ['RELINK_X'])) + self.assertFalse(response.success) + self.assertEqual(response.error_code, 'not_found', response.error_message) + self._assert_kept(shared, ['RELINK_Y'], app=APP_B) + + def test_13_a_failed_audit_append_stops_the_delete(self, proc_output, fault_manager_node): + """Another writer holds the audit database: storage_unavailable, nothing deleted.""" + recording_id = self._record_cleared('DEL_AUDIT_LOCKED') + request = self._delete_request(recording_id, ['DEL_AUDIT_LOCKED']) + # The log's busy timeout is 5 s; the writer holds the lock until the answer is in. + holder = sqlite3.connect(AUDIT_DB, timeout=30, isolation_level=None) + try: + holder.execute('BEGIN IMMEDIATE') + future = self.delete_client.call_async(request) + proc_output.assertWaitFor(AUDIT_FAILURE.format(recording_id), + process=fault_manager_node, timeout=WAIT_SEC) + rclpy.spin_until_future_complete(self.node, future, timeout_sec=SERVICE_SEC) + response = future.result() + self.assertIsNotNone(response, 'delete_rosbag did not answer') + self.assertFalse(response.success) + self.assertEqual(response.error_code, 'storage_unavailable', response.error_message) + finally: + holder.execute('ROLLBACK') + holder.close() + self._assert_kept(recording_id, ['DEL_AUDIT_LOCKED']) + self.assertEqual(self._audit_events(recording_id), []) + + response = self._delete(APP_A, recording_id) + self.assertEqual(response.status_code, 204, response.text) + self._assert_gone(recording_id) + self.assertEqual(self._audit_events(recording_id), + [('DEL_AUDIT_LOCKED', 'CLEARED', 'delete_rosbag')]) + + def test_99_a_stopped_fault_manager_answers_503(self, proc_info, fault_manager_node): + """The fault manager process stopped: 503. + + @verifies REQ_INTEROP_075 + """ + recording_id = self._record_cleared('DEL_FM_DOWN') + os.kill(fault_manager_node.process_details['pid'], signal.SIGTERM) + proc_info.assertWaitForShutdown(process=fault_manager_node, timeout=WAIT_SEC) + + response = self._delete(APP_A, recording_id) + self.assertEqual(response.status_code, 503, response.text) + self.assertEqual(response.json().get('error_code'), 'service-unavailable', response.text) + self.assertTrue(os.path.isdir(self._dir(recording_id)), recording_id) + + +@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; the fault manager stopped on SIGTERM.""" + launch_testing.asserts.assertExitCodes( + proc_info, allowable_exit_codes=ALLOWED_EXIT_CODES) diff --git a/src/ros2_medkit_integration_tests/test/features/test_rosbag_delete_storage_unavailable.test.py b/src/ros2_medkit_integration_tests/test/features/test_rosbag_delete_storage_unavailable.test.py new file mode 100644 index 000000000..9d0a49925 --- /dev/null +++ b/src/ros2_medkit_integration_tests/test/features/test_rosbag_delete_storage_unavailable.test.py @@ -0,0 +1,246 @@ +#!/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. + +"""DELETE of a recording whose storage path is unavailable. + +A real gateway and two runs of a real fault manager on one SQLite file. The first run records +and clears a fault. The storage directory is renamed away before the second run, so the second +run starts with the storage path unavailable. The gateway does not see the recording then and +answers 404. Once the directory is back and a listing finds it, the same DELETE answers 204. +""" + +import ctypes +import os +import signal +import sqlite3 +import subprocess +import tempfile +import threading +import time +import unittest + +from ament_index_python.packages import get_package_prefix +import launch_testing +import rclpy +from rclpy.node import Node +import requests +from ros2_medkit_msgs.srv import ClearFault, ReportFault + +from ros2_medkit_test_utils.constants import ALLOWED_EXIT_CODES, get_time_scale +from ros2_medkit_test_utils.coverage import get_coverage_env +from ros2_medkit_test_utils.gateway_test_case import GatewayTestCase +from ros2_medkit_test_utils.launch_helpers import create_test_launch + +APP = 'temp_sensor' +FQN = '/powertrain/engine/temp_sensor' +TOPIC = '/powertrain/engine/temperature' +CODE = 'DEL_UNMOUNTED' +SEVERITY_ERROR = 2 + +SCALE = get_time_scale() +WAIT_SEC = 60.0 * SCALE +SERVICE_SEC = 30.0 * SCALE +HTTP_SEC = 30.0 * SCALE + +ROOT = tempfile.mkdtemp(prefix='rosbag_e2e_delete_unmounted_') +STORAGE = os.path.join(ROOT, 'bags') +UNMOUNTED = STORAGE + '.unmounted' +DB = os.path.join(ROOT, 'faults.db') + +FM_PARAMS = { + 'storage_type': 'sqlite', + 'database_path': DB, + 'confirmation_threshold': -1, + 'snapshots.rosbag.enabled': True, + 'snapshots.rosbag.topics': TOPIC, + 'snapshots.rosbag.format': 'mcap', + 'snapshots.rosbag.storage_path': STORAGE, + 'snapshots.rosbag.duration_sec': 3.0, + # The sensor publishes at 2 Hz: the window holds messages whatever the buffer had. + 'snapshots.rosbag.duration_after_sec': 1.0, + 'snapshots.rosbag.lazy_start': False, + 'snapshots.rosbag.auto_cleanup': False, +} +STARTED = 'FaultManager node started' +SUBSCRIBED = f"Subscribed to '{TOPIC}'" +UNAVAILABLE = f"Rosbag storage path '{STORAGE}' is unavailable" + +# prctl option: the kernel sends the child this signal when the test process dies. +PR_SET_PDEATHSIG = 1 + + +def generate_test_description(): + return create_test_launch(demo_nodes=[APP], fault_manager=False, lidar_faulty=False) + + +def _die_with_parent(): + ctypes.CDLL('libc.so.6', use_errno=True).prctl(PR_SET_PDEATHSIG, signal.SIGKILL) + + +def _poll(predicate, timeout=WAIT_SEC, interval=0.1): + """Return True once `predicate()` is true, False at the deadline.""" + deadline = time.monotonic() + timeout + waiter = threading.Event() + while True: + if predicate(): + return True + if time.monotonic() >= deadline: + return False + waiter.wait(interval) + + +def _stored_recordings(): + """Return (fault_code, recording_id) of every stored rosbag row.""" + conn = sqlite3.connect(DB, timeout=30) + try: + return conn.execute( + 'SELECT fault_code, recording_id FROM rosbag_files ORDER BY id').fetchall() + finally: + conn.close() + + +class FaultManagerRun: + """One fault_manager_node process on the shared database; its output goes to a file.""" + + def __init__(self, log_path): + self.log_path = log_path + env = os.environ.copy() + env.update(get_coverage_env('ros2_medkit_fault_manager')) + env['RCUTILS_LOGGING_BUFFERED_STREAM'] = '0' + args = [os.path.join(get_package_prefix('ros2_medkit_fault_manager'), 'lib', + 'ros2_medkit_fault_manager', 'fault_manager_node'), '--ros-args'] + for key, value in FM_PARAMS.items(): + text = ('true' if value else 'false') if isinstance(value, bool) else str(value) + args += ['-p', f'{key}:={text}'] + self._log = open(log_path, 'w') + self.proc = subprocess.Popen(args, stdout=self._log, stderr=subprocess.STDOUT, env=env, + preexec_fn=_die_with_parent) + + def output(self): + with open(self.log_path) as handle: + return handle.read() + + def wait_text(self, text): + return _poll(lambda: text in self.output()) + + def stop(self): + """SIGTERM the process and return its exit code.""" + if self.proc.poll() is None: + self.proc.send_signal(signal.SIGTERM) + try: + return self.proc.wait(timeout=WAIT_SEC) + finally: + self._log.close() + + +class TestRosbagDeleteStorageUnavailable(GatewayTestCase): + """A protected recording answers 404 over HTTP until a listing finds its directory again.""" + + MIN_EXPECTED_APPS = 1 + REQUIRED_APPS = {APP} + + @classmethod + def setUpClass(cls): + rclpy.init() + cls.node = Node('_rosbag_delete_unmounted_driver') + cls.report_client = cls.node.create_client(ReportFault, '/fault_manager/report_fault') + cls.clear_client = cls.node.create_client(ClearFault, '/fault_manager/clear_fault') + super().setUpClass() + + @classmethod + def tearDownClass(cls): + cls.node.destroy_node() + rclpy.shutdown() + super().tearDownClass() + + def _start(self, name): + run = FaultManagerRun(os.path.join(ROOT, f'{name}.log')) + self.addCleanup(lambda: run.proc.poll() is None and run.proc.kill()) + self.assertTrue(run.wait_text(STARTED), run.output()[-3000:]) + return run + + def _stop(self, run): + self.assertEqual(run.stop(), 0, run.output()[-3000:]) + + def _call(self, client, request): + self.assertTrue(client.wait_for_service(timeout_sec=SERVICE_SEC), client.srv_name) + future = client.call_async(request) + rclpy.spin_until_future_complete(self.node, future, timeout_sec=SERVICE_SEC) + self.assertIsNotNone(future.result(), f'{client.srv_name} did not answer') + return future.result() + + def _listing(self): + """Return the recording ids of the app's first complete listing (a 200).""" + listing = self.poll_endpoint(f'/apps/{APP}/bulk-data/rosbags', timeout=WAIT_SEC) + return [item['id'] for item in listing.get('items', [])] + + def _delete(self, recording_id): + return requests.delete(f'{self.BASE_URL}/apps/{APP}/bulk-data/rosbags/{recording_id}', + timeout=HTTP_SEC) + + def test_protected_recording_is_not_found_until_a_listing_finds_it(self): + """404 while the storage path is unavailable, the row kept; 204 once it is back. + + @verifies REQ_INTEROP_075 + """ + first = self._start('first') + self.assertTrue(first.wait_text(SUBSCRIBED), first.output()[-3000:]) + report = ReportFault.Request() + report.fault_code = CODE + report.event_type = ReportFault.Request.EVENT_FAILED + report.severity = SEVERITY_ERROR + report.description = 'rosbag delete with the storage path unavailable' + report.source_id = FQN + self.assertTrue(self._call(self.report_client, report).accepted) + recording_id = self.poll_endpoint_until( + f'/apps/{APP}/bulk-data/rosbags', + lambda listing: next((item['id'] for item in listing.get('items', []) + if CODE in item.get('x-medkit', {}).get('fault_codes', [])), + None), + timeout=WAIT_SEC) + clear = ClearFault.Request() + clear.fault_code = CODE + self.assertTrue(self._call(self.clear_client, clear).success) + self._stop(first) + rows = [(CODE, recording_id)] + self.assertEqual(_stored_recordings(), rows) + + os.rename(STORAGE, UNMOUNTED) + second = self._start('second') + self.assertIn(UNAVAILABLE, second.output()) + self.assertNotIn(recording_id, self._listing()) + response = self._delete(recording_id) + self.assertEqual(response.status_code, 404, response.text) + self.assertEqual(response.json().get('vendor_code'), 'x-medkit-recording-not-found', + response.text) + self.assertEqual(_stored_recordings(), rows) + self.assertTrue(os.path.isdir(os.path.join(UNMOUNTED, recording_id))) + + os.rename(UNMOUNTED, STORAGE) + self.assertIn(recording_id, self._listing()) + response = self._delete(recording_id) + self.assertEqual(response.status_code, 204, response.text) + self.assertEqual(_stored_recordings(), []) + path = os.path.join(STORAGE, recording_id) + self.assertTrue(_poll(lambda: not os.path.exists(path)), f'{path} is still on disk') + self._stop(second) + + +@launch_testing.post_shutdown_test() +class TestRosbagDeleteStorageUnavailableShutdown(unittest.TestCase): + + def test_exit_codes(self, proc_info): + """Check that the launched processes exited cleanly.""" + launch_testing.asserts.assertExitCodes(proc_info, allowable_exit_codes=ALLOWED_EXIT_CODES) diff --git a/src/ros2_medkit_integration_tests/test/scenarios/test_scenario_bulk_data_upload.test.py b/src/ros2_medkit_integration_tests/test/scenarios/test_scenario_bulk_data_upload.test.py index 4ac24a0d7..bde2307e0 100644 --- a/src/ros2_medkit_integration_tests/test/scenarios/test_scenario_bulk_data_upload.test.py +++ b/src/ros2_medkit_integration_tests/test/scenarios/test_scenario_bulk_data_upload.test.py @@ -16,7 +16,8 @@ """Scenario: Bulk data upload — full CRUD lifecycle for file uploads. Launches the gateway with bulk_data categories configured (calibration, -firmware) on a unique port, plus a single demo node for entity targets. +firmware) on a unique port, plus a single demo node for entity targets and a +fault manager that answers for the rosbags category. Tests upload (POST), list, download, delete, and error handling. """ @@ -33,7 +34,9 @@ from ros2_medkit_test_utils.constants import ALLOWED_EXIT_CODES, API_BASE_PATH, get_test_port from ros2_medkit_test_utils.gateway_test_case import GatewayTestCase -from ros2_medkit_test_utils.launch_helpers import create_demo_nodes, create_gateway_node +from ros2_medkit_test_utils.launch_helpers import ( + create_demo_nodes, create_fault_manager_node, create_gateway_node, +) TEST_PORT = get_test_port() BULK_DATA_BASE_URL = f'http://localhost:{TEST_PORT}{API_BASE_PATH}' @@ -55,6 +58,8 @@ def generate_test_description(): # A single demo node so we have at least one app entity to test with demo_nodes = create_demo_nodes(['temp_sensor']) + # Answers that a rosbag id names no recording. + demo_nodes.append(create_fault_manager_node()) delayed = TimerAction(period=2.0, actions=demo_nodes) @@ -88,7 +93,7 @@ class TestScenarioBulkDataUpload(GatewayTestCase): 10. Upload to functions — 405 11. Delete uploaded item — 204 12. Delete nonexistent item — 404 - 13. Delete rosbags category — 400 + 13. Delete an unknown rosbag recording — 404 14. Delete on areas — 405 15. List categories includes configured ones 16. List descriptors after upload @@ -99,8 +104,8 @@ class TestScenarioBulkDataUpload(GatewayTestCase): """ BASE_URL = BULK_DATA_BASE_URL - MIN_EXPECTED_APPS = 1 - REQUIRED_APPS = {'temp_sensor'} + MIN_EXPECTED_APPS = 2 + REQUIRED_APPS = {'temp_sensor', 'fault_manager'} test_app_id = 'temp_sensor' test_component_id = None @@ -282,14 +287,14 @@ def test_12_delete_nonexistent_item(self): r = requests.delete(url, timeout=10) self.assertEqual(r.status_code, 404) - def test_13_delete_rosbags_rejected(self): - """DELETE rosbags category returns 400. + def test_13_delete_unknown_rosbag_not_found(self): + """DELETE of an id that names no recording returns 404. - @verifies REQ_INTEROP_074 + @verifies REQ_INTEROP_075 """ url = f'{self.BASE_URL}/apps/{self.test_app_id}/bulk-data/rosbags/some_id' - r = requests.delete(url, timeout=10) - self.assertEqual(r.status_code, 400) + r = requests.delete(url, timeout=30) + self.assertEqual(r.status_code, 404, r.text) def test_14_delete_to_areas_405(self): """DELETE on areas returns 405. diff --git a/src/ros2_medkit_msgs/CMakeLists.txt b/src/ros2_medkit_msgs/CMakeLists.txt index 71ab7039c..9bfde8b23 100644 --- a/src/ros2_medkit_msgs/CMakeLists.txt +++ b/src/ros2_medkit_msgs/CMakeLists.txt @@ -39,6 +39,7 @@ rosidl_generate_interfaces(${PROJECT_NAME} "srv/GetSnapshots.srv" "srv/GetRosbag.srv" "srv/ListRosbags.srv" + "srv/DeleteRosbag.srv" "srv/ListFaultsForEntity.srv" "srv/ListEntities.srv" "srv/GetEntityData.srv" diff --git a/src/ros2_medkit_msgs/design/index.rst b/src/ros2_medkit_msgs/design/index.rst index c416f2425..a2a20ea68 100644 --- a/src/ros2_medkit_msgs/design/index.rst +++ b/src/ros2_medkit_msgs/design/index.rst @@ -63,6 +63,8 @@ Service Definitions - Retrieve rosbag file path for download * - ``ListRosbags.srv`` - List all available rosbag snapshots + * - ``DeleteRosbag.srv`` + - Delete one rosbag recording once every linked fault is cleared or healed * - ``ListEntities.srv`` - List entities with optional type filtering (for SOVD service interface) * - ``GetEntityData.srv`` diff --git a/src/ros2_medkit_msgs/srv/DeleteRosbag.srv b/src/ros2_medkit_msgs/srv/DeleteRosbag.srv new file mode 100644 index 000000000..84b8129e4 --- /dev/null +++ b/src/ros2_medkit_msgs/srv/DeleteRosbag.srv @@ -0,0 +1,46 @@ +# 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. +# +# DeleteRosbag.srv - Delete one rosbag recording. +# +# Removes every row that links a fault to the recording and queues its directory, every +# storage file of it, for removal. Refused while a linked fault is neither CLEARED nor +# HEALED (PREFAILED, PREPASSED, CONFIRMED or any other stored status). + +# Request fields + +# The recording to delete: its id, the basename of its directory. +string recording_id + +# The linked fault codes that put the recording in the caller's scope. The answer is +# not_found when none of them is still linked to the recording. A caller that may see +# every recording names every linked code. +string[] scope_fault_codes +--- +# Response fields + +# True when the rows are removed and the directory is queued for removal. +bool success + +# Set when success is false: "not_found" (no recording with this id, or none of +# scope_fault_codes is linked to it), "fault_active" (nothing is deleted) or +# "storage_unavailable" (the store or the audit log could not answer, or the outcome of +# the removal is unknown; the directory stays). Empty on success. +string error_code + +# Human-readable reason when success is false. +string error_message + +# With fault_active: the linked faults that are neither CLEARED nor HEALED. +string[] active_fault_codes diff --git a/src/ros2_medkit_msgs/srv/ListRosbags.srv b/src/ros2_medkit_msgs/srv/ListRosbags.srv index 4b408da5a..8b69fb639 100644 --- a/src/ros2_medkit_msgs/srv/ListRosbags.srv +++ b/src/ros2_medkit_msgs/srv/ListRosbags.srv @@ -59,6 +59,11 @@ uint64[] sizes_bytes # severity. 0 unless the retention configuration is valid. int64[] priorities +# Per row, whether every fault linked to the recording is CLEARED or HEALED, also the +# faults this entity did not report: the status a DeleteRosbag of the recording needs. +# Parallel to fault_codes; rows of one recording repeat the same value. +bool[] deletable + # 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