From 68ec80b8cc50d043aac30c2ba24694374d903ad1 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:08 +0100 Subject: [PATCH] fault_manager: change rosbag retention parameters while the node runs * feat(fault_manager): change rosbag retention parameters while the node runs * fix(fault_manager): refuse mixed parameter sets; PostgreSQL case in the fault manager * fix(fault_manager): run retention passes only for age, floor or interval changes * fix: decide each floor step and open-time check with one retention policy --- docs/api/rest.rst | 13 + docs/config/fault-manager.rst | 84 ++- docs/tutorials/snapshots.rst | 15 +- src/ros2_medkit_fault_manager/CMakeLists.txt | 5 + src/ros2_medkit_fault_manager/README.md | 18 +- .../config/rosbag_retention.example.yaml | 4 +- .../design/index.rst | 82 +- .../core/fault_manager_core.hpp | 5 + .../core/retention_policy.hpp | 4 + .../core/rosbag_retention.hpp | 86 ++- .../fault_manager_node.hpp | 41 +- .../rosbag_capture.hpp | 23 +- .../snapshot_capture.hpp | 4 - .../src/core/fault_manager_core.cpp | 5 + .../src/core/retention_policy.cpp | 51 ++ .../src/core/rosbag_retention.cpp | 165 +++- .../src/fault_manager_node.cpp | 301 +++++++- .../src/rosbag_capture.cpp | 74 +- .../test/integration/rosbag_fm_harness.py | 5 +- .../integration/test_retention_config.test.py | 59 +- .../test_retention_runtime_pg.test.py | 224 ++++++ .../test_rosbag_storage_availability.test.py | 34 + .../test/test_rosbag_capture.cpp | 9 +- .../test/test_rosbag_retention.cpp | 126 ++++ src/ros2_medkit_gateway/README.md | 6 + .../transports/ros2_parameter_transport.cpp | 59 +- .../CMakeLists.txt | 4 +- src/ros2_medkit_integration_tests/package.xml | 1 + .../fault_manager_process.py | 212 ++++++ .../features/test_configuration_api.test.py | 32 + .../features/test_retention_runtime.test.py | 711 ++++++++++++++++++ 31 files changed, 2273 insertions(+), 189 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_retention_runtime_pg.test.py create mode 100644 src/ros2_medkit_integration_tests/ros2_medkit_test_utils/fault_manager_process.py create mode 100644 src/ros2_medkit_integration_tests/test/features/test_retention_runtime.test.py diff --git a/docs/api/rest.rst b/docs/api/rest.rst index b0d4fffe7..66e60460c 100644 --- a/docs/api/rest.rst +++ b/docs/api/rest.rst @@ -1481,8 +1481,21 @@ Manage ROS 2 node parameters. - **400:** Invalid value - the node rejected it, or it cannot be converted to the parameter's type at all (e.g. a mixed-type array). Both are the caller's body, so both are ``400``, never ``500``. + - **403:** The parameter is read-only - **404:** Parameter not found + The gateway reads the parameter's current value and its descriptor before the + write. The JSON value is converted to the current value's type (``1.5`` to the + integer ``1``, a string other than ``"true"`` or ``"1"`` to ``false``, any value + to a string when the current value is one), except for a parameter whose + descriptor allows dynamic typing: that one is sent with the JSON's own type + (``1.5`` as a double, a ``null`` as the string ``"null"``), so the node checks + what the client sent. A rejection answers ``403`` when the descriptor says the + parameter is read-only, and ``400`` otherwise, whatever the node's reason says. + When the descriptor cannot be read, a reason that contains "read-only" or + "read only" answers ``403``. The gateway's own parameters follow the same + rule, for example the read-only ``plugins..path``. + **Example:** .. code-block:: bash diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 3951fc3b5..99995b547 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -649,10 +649,13 @@ Capture continuous rosbag recordings around fault events. - ``500`` - Maximum total storage for all rosbags (MB). A recording shared by a burst of faults counts once towards the total, and eviction removes a - whole burst's bag at a time (oldest first). The recording that was just - stored is never evicted by its own sweep. If it alone is larger than the - limit it is kept, a warning is logged, and the storage stays over the - limit until a newer recording replaces it. + whole burst's bag at a time. Without retention rules eviction goes + oldest first and the recording that was just stored is never evicted by + its own sweep: if it alone is larger than the limit it is kept, a + warning is logged, and the storage stays over the limit until a newer + recording replaces it. With retention rules eviction follows their + ranked order and ``over_quota: drop`` can drop the new recording, see + :ref:`rosbag-retention-rules`. * - ``rosbag.max_bags_per_fault`` - ``1`` - How many recordings one fault code keeps. Past the cap the oldest is @@ -827,6 +830,8 @@ messages before everything stopped. Note the condition: a single captured topic goes quiet while others keep publishing is pruned like anything else, because each arrival prunes the whole buffer by age. +.. _rosbag-retention-rules: + Rosbag Retention Rules ~~~~~~~~~~~~~~~~~~~~~~ @@ -834,8 +839,8 @@ The parameters under ``snapshots.rosbag.retention.`` set a rule per fault: a ``p ``over_quota`` choice, a ``max_bags`` cap, ``keep_first``, what happens to the fault's recordings when it heals (``on_healed``) or is cleared (``on_cleared``), how long they are kept in each status (``max_age_sec``), and how much free space stays on the disk (``min_free_disk_mb``). They are read at -startup, validated and -logged. They are read only while +startup, validated and logged, and each one given at startup can be changed while the node runs (see +Changes While the Node Runs below). They are used only while rosbag capture is on (``snapshots.rosbag.enabled: true``); with it off, the fault manager warns once and ignores them. Without any ``snapshots.rosbag.retention.*`` parameter the fault manager behaves as before. An example file is ``config/rosbag_retention.example.yaml``. @@ -1050,7 +1055,7 @@ deletion frees. Each removed recording is logged as ``Recording removed: (m Every pass ends with one DEBUG line ``floor pass: removed= free= floor= met= source=``. -A pass runs at two moments, and one pass runs at a time, on the retention worker thread: +A pass runs at three moments, and one pass runs at a time, on the retention worker thread: - after each store that kept the new recording, at its priority. A store whose per-fault cap removed every new row kept nothing and runs no pass. It never deletes a recording @@ -1059,6 +1064,8 @@ A pass runs at two moments, and one pass runs at a time, on the retention worker ``over_quota: keep`` does not keep a recording that leaves the free space below the floor. - in the periodic job, after the age sweep, with no priority limit: other data that fills the disk can then delete any recording, the highest priority last. +- once in the job of a change of ``min_free_disk_mb``, ``sweep_interval_sec`` or a max age while the + node runs, also with no priority limit (see Changes While the Node Runs below). The floor is a target, not a reservation: other writers can change the free space between two measurements. When PostgreSQL shares the disk (``storage_type: postgres``), ``min_free_disk_mb`` is @@ -1183,9 +1190,66 @@ the configuration: the next fault that confirms reports it again. A start with a (or none) clears it. If the fault storage is unreachable at start, the report or the clear is retried every second until the storage accepts it. -The retention parameters are read only: a ``SetParameters`` request for one is refused. At startup the -fault manager also warns once, listing every parameter override that no declaration consumed, so a -misspelled key does not pass unnoticed. +At startup the fault manager also warns once, listing every parameter override that no declaration +consumed, so a misspelled key does not pass unnoticed. + +**Changes While the Node Runs.** Each retention parameter given at startup can be changed while the +fault manager runs, for example through the gateway: + +.. code-block:: bash + + curl -X PUT \ + http://localhost:8080/api/v1/apps/fault_manager/configurations/snapshots.rosbag.retention.fault_codes.MOTOR_OVERHEAT.priority \ + -H 'Content-Type: application/json' -d '{"data": 900}' + +- Only the parameters given at startup exist. ``min_free_disk_mb`` (``0``) and ``sweep_interval_sec`` + (``60``) always exist, so they can be changed also when not given; that declaration alone does not + configure the retention, the rules follow the parameters given at startup or changed since. A first + change on a fault manager started without retention parameters makes the retention configured + (every priority ``0``). Adding or removing a rule needs a restart: a key not given at startup answers + HTTP 400 with ``parameter '' cannot be set because it was not declared``. +- A change is validated as the whole configuration with the change applied, by the same parser as at + startup. It is refused when it adds an error the current configuration does not have: HTTP 400, the + reason names each new error with its full parameter name, and nothing changes. A retention parameter + cannot be unset: a ``PARAMETER_NOT_SET`` value is refused (the gateway sends a JSON ``null`` as the + string ``"null"``, which the parser refuses as the wrong type). A set that holds retention + parameters and other parameters at once (``set_parameters_atomically``) is refused: set the retention + parameters on their own. The gateway sets one parameter per request. +- An accepted change of a valid configuration becomes the rules at once and logs one INFO line + ``Rosbag retention rules changed (configured): ``. A job on the retention worker then applies + it to the stored recordings and ends with one INFO line ``Rosbag retention change applied: ...``: + + - ``priority`` and ``over_quota``: the next decision and the next listing use them; nothing is + removed, and no age or floor pass runs. + - A lower ``max_bags`` for a fault code with stored recordings, also when a changed ``match`` or + ``pattern_order`` moves the code to another rule: the cap applies to its recordings at once, each + removal logged as ``Recording removed: (its max_bags)``. + - ``on_cleared`` or ``on_healed`` becoming ``delete`` (also through the clear default): the + recordings of faults already CLEARED or HEALED go, logged with ``(fault cleared)`` or + ``(fault healed)``. A fault that failed again before the job reached it keeps them. + - ``max_age_sec``, ``min_free_disk_mb`` and ``sweep_interval_sec``, and a ``match`` or + ``pattern_order`` change when a pattern sets a max age: the periodic job takes the new interval (its + next pass one interval after the change), and the age pass (when a max age is set) and the floor + pass (when the floor is above 0) run at once. With no max age and the floor at 0 the periodic job is + off and no pass runs. Only these changes run a pass. The INFO line ends with + ``passes run: ; periodic job s, off, or unchanged>``. + +- A failure in the job logs WARN lines: a failing age or floor pass logs its own WARN, as in the + periodic job, and the change then logs one summary WARN ``Rosbag retention change not applied: + failed: ``, the error of a failed storage read for the + caps and the status actions. The PostgreSQL storage logs its reconnection attempts under its own + logger, ``postgres_fault_storage``. The parameter keeps its new value. A set of any retention + parameter, the same value included, runs the job again: it compares the rules with the rules it last + applied in full. +- In degrade each invalid value can be repaired on its own: a change that leaves only errors the + configuration already had is accepted, the node stays degraded and logs + ``Rosbag retention rules changed (degraded): ...``. The change that leaves no error ends degrade: the + rules apply as above and ``ROSBAG_RETENTION_CONFIG_INVALID`` is cleared. +- With rosbag capture off a change is validated the same way and logs that the rules are not used. +- A change is lost at restart: the parameters file wins. + +A refused change answers 400, not 403, also when the parameter name contains "read-only": the gateway +decides 403 from the parameter's descriptor (see :doc:`/api/rest`). .. seealso:: diff --git a/docs/tutorials/snapshots.rst b/docs/tutorials/snapshots.rst index b5e341db0..c511eef5f 100644 --- a/docs/tutorials/snapshots.rst +++ b/docs/tutorials/snapshots.rst @@ -675,12 +675,15 @@ Rosbag Configuration Options file, see :ref:`below `. * - ``snapshots.rosbag.max_total_storage_mb`` - ``500`` - - Total storage limit for all bag files. Oldest bags are automatically - deleted when this limit is exceeded. The recording that was just written - is never one of them: when it alone is over the limit it is kept, a - warning is logged, and every older bag is deleted. A recording shared by a burst of - faults counts once towards the total, and eviction removes a whole - burst's bag at a time. + - Total storage limit for all bag files. Without retention rules the + oldest bags are deleted when this limit is exceeded, and the recording + that was just written is never one of them: when it alone is over the + limit it is kept, a warning is logged, and every older bag is deleted. + With retention rules the bags go in their ranked order and + ``over_quota: drop`` can drop the new recording, see + :ref:`rosbag-retention-rules`. A recording shared by a burst of faults + counts once towards the total, and eviction removes a whole burst's bag + at a time. * - ``snapshots.rosbag.max_bags_per_fault`` - ``1`` - Recordings kept per fault code; ``0`` means unlimited. Past the cap the diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index c3f4011ff..337fa9280 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -337,6 +337,11 @@ endif() # A connection lost during the rosbag store transaction, cut by a protocol-aware proxy. medkit_add_launch_test(test_rosbag_commit_in_doubt_pg test/integration/test_rosbag_commit_in_doubt_pg.test.py TIMEOUT 300 LABELS "integration") + + # A runtime retention change whose apply fails while the server is unreachable, and the same value set + # again once it answers. + medkit_add_launch_test(test_retention_runtime_pg test/integration/test_retention_runtime_pg.test.py + TIMEOUT 300 LABELS "integration") endif() # Launches without snapshots.rosbag.format, so the parameter default (mcap) diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 69e53d057..e8925dbe6 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -149,7 +149,8 @@ There is no marker file: a disk that is not mounted while no recording is stored `snapshots.rosbag.retention.*` sets a `priority` (0-1000), an `over_quota` choice (`keep` or `drop`), a `max_bags` cap, `keep_first`, `on_healed` and `on_cleared` (`keep` or `delete`) and `max_age_sec` (`active`, `healed`, `cleared`) per fault, from four levels: fault code, the first matching pattern of -`pattern_order`, severity, defaults. They are read at startup and validated. Each fault code keeps at most its +`pattern_order`, severity, defaults. They are read at startup and validated, and each one given at startup can be +changed while the node runs (see below). Each fault code keeps at most its rule's `max_bags` recordings (`max_bags_per_fault` when no level sets it, `0` = no cap); with `keep_first` and a `max_bags` of 2 or more the first recording stays and the second oldest goes. "First" is the oldest recording of the fault code still stored. A heal deletes a fault's recordings with `on_healed: delete` (default `keep`; HEALED @@ -189,6 +190,21 @@ A parameter the ROS YAML loader moved (found by reading each parameters file a s running without the rules, with the quota as a hard stop for new recordings, and reports the fault `ROSBAG_RETENTION_CONFIG_INVALID`. See `config/rosbag_retention.example.yaml` and `docs/config/fault-manager.rst`. +A retention parameter given at startup can be set while the node runs, for example with +`PUT /api/v1/apps/fault_manager/configurations/snapshots.rosbag.retention.fault_codes.MOTOR_OVERHEAT.priority` on +the gateway. `min_free_disk_mb` and `sweep_interval_sec` always exist (defaults 0 and 60); the rules follow the +parameters given at startup or changed since. Adding or removing a rule needs a restart: another key is not +declared (400). A change is validated as the whole configuration with the same parser as at startup and refused +(400, the reason names each new error) when it adds an error; nothing changes then. An accepted valid change is used +at once and a job on the retention worker applies it to the stored recordings: a lower `max_bags` trims the code's +recordings, an `on_cleared` or `on_healed` that became `delete` removes the recordings of faults already CLEARED or +HEALED, and a changed max age, floor or interval sets the periodic job and runs the passes that are on: the age pass +when a max age is set, the floor pass when the floor is above 0; no other change runs a pass. The job ends with `Rosbag retention change applied` (INFO). After a failure a failing pass logs its +own WARN and the job one summary WARN naming what was not applied; the parameter keeps its value, and setting it again +retries. In degrade each invalid value can be repaired on its own; the change that leaves no error ends degrade and +clears `ROSBAG_RETENTION_CONFIG_INVALID`. With rosbag capture off a change is validated and not used. A value cannot +be unset, a set that also holds other parameters is refused, and a change is lost at restart. + ### Storage Backends This is the persisted fault store (`storage_type`), separate from the rosbag storage diff --git a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml index 9b7b9c927..6579d7690 100644 --- a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml +++ b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml @@ -34,7 +34,9 @@ # With drop, a recording predicted not to fit is not started. # Any other key under retention is an error: the fault manager keeps running without the rules, the # quota becomes a hard stop for new recordings (nothing is evicted for it) and it reports the fault -# ROSBAG_RETENTION_CONFIG_INVALID. Retention values are read-only at runtime. +# ROSBAG_RETENTION_CONFIG_INVALID. A value given here can be changed while the node runs (for example +# with a PUT on the gateway's configurations of the fault manager app) and applies at once; another +# key, or removing one, needs a restart. A change is lost at restart. # # Use with: ros2 run ros2_medkit_fault_manager fault_manager_node --ros-args --params-file # The rules are read only when snapshots.rosbag.enabled is true. diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 7ecd75e7b..88cd29f21 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -655,18 +655,20 @@ except ``capture_priorities``: the outcome is unknown and returns nothing, so a committed removal leaves the directory without a row, as in the store path. It does not advance a delete generation: the age of a fault whose recording is still in flight was just restarted by its FAILED report. -- ``evict_one_for_space(priority_limit, last_resort_recording_id)``: one removal step of the - free-space floor. It reads ``get_all_rosbag_files`` once, ranks every recording whose priority is at - most ``priority_limit`` in the eviction order below (``INT64_MAX`` for no limit), picks the first one - that is not ``last_resort_recording_id``, or that one when it is the only candidate, and removes - every link of it in one change set. It returns a ``SpaceStep``: ``kRemoved`` with the directory +- ``evict_one_for_space(new_recording_id)``: one removal step of the free-space floor. It loads the + policy snapshot once; from it come the limit and the order. The limit is the priority of + ``new_recording_id`` (``stored_recording_priority``, from its rows), or none when the id is empty (the + periodic pass); a new recording no row names any more ends the step with ``kNoCandidate``. It reads + ``get_all_rosbag_files`` once, ranks every recording whose priority is at most the limit in the + eviction order below, picks the first one that is not ``new_recording_id``, or that one when it is + the only candidate, and removes every link of it in one change set. It returns a ``SpaceStep``: ``kRemoved`` with the directory (``RemovalReason::kFreeSpace``), ``kNoCandidate`` when no candidate is left, or ``kFailed``. A read or apply failure logs one WARN and returns ``kFailed``; ``RosbagCommitInDoubt`` logs one WARN that the outcome is unknown and returns ``kFailed``, so the directory stays. It never reads the free space: that is a file system call. -- ``has_space_candidate(priority_limit)``: the same choice without the removal, for the open-time - floor check. A failed read answers true and logs nothing. -- ``fault_priority(fault_code)``: the priority of the fault's rule, 0 unless ``kConfigured``. +- ``has_space_candidate_for_fault(fault_code)``: the same choice without the removal, for the open-time + floor check, with the priority of the fault's rule (0 unless ``kConfigured``) as the limit, both from + one policy snapshot. A failed read answers true and logs one WARN. - ``capture_priorities(fault_codes)``: the priorities of captures in the capture queue, without the retention mutex, so a capture pick does not wait behind a store, a floor pass or a sweep that holds it during its storage calls. It loads the policy snapshot once with ``std::atomic_load``, @@ -709,8 +711,49 @@ alone. ``core::find_differences`` compares, per applying section, the loader's n sets, and counts a name the loader produced twice as moved. Any difference, or a shifted retention key, makes the constructor throw, so the process exits with code 1, also with rosbag capture off. -The node declares each retention override as a read-only parameter with its own value. An invalid -retention configuration degrades the node: the policy stays unset and the node reports +The node declares each retention override as a dynamically typed parameter with its own value, and +``min_free_disk_mb`` and ``sweep_interval_sec`` with the parser's defaults when they are not given. It +keeps the keys given at startup or changed since (``retention_given_``): only these reach the parser, so +the two default declarations do not configure the retention. + +**Runtime changes.** ``FaultManagerNode::on_retention_params_set`` is the node's one on-set parameter +callback (handle ``retention_params_handle_``), registered last in the constructor. It passes every name +outside ``snapshots.rosbag.retention.``. It refuses a ``PARAMETER_NOT_SET`` value: rclcpp would undeclare +the dynamically typed parameter. It refuses a set that holds retention names and other names: a callback +rclcpp runs after it (the ``use_sim_time`` check) could refuse the others after this one published. +Otherwise it builds the current values of the kept keys (``get_parameter``) +and the candidate with the change applied, parses both with ``RetentionPolicy::parse`` and refuses the set +when the candidate has an error the current values do not have, with those errors as the reason. rclcpp +calls it before it stores the value and Humble has no post-set callback, so the side effects run here +after every check passed: a valid candidate is published with ``RosbagRetention::set_policy`` and one +``retention change`` job is posted to the retention worker; a change that ends degrade arms the retention +timer, which clears ``ROSBAG_RETENTION_CONFIG_INVALID`` on the executor. The callback makes no storage and +no file system call. With rosbag capture off it validates and logs that the rules are not used. + +The job, ``apply_retention_change``, compares the new state with ``applied_retention_``, the state whose +caps and status actions it last applied in full (the startup state at first; read and written only on +the worker). It reads the rosbag rows and the faults once. For each stored fault code it compares +``RosbagRetention::cap_under`` under both states, with the fault's severity, and passes every code whose +cap went down to ``RosbagRetention::trim_to_caps`` (the store's cap path, ``cap_changes``, with the codes +and no new row, in one change set; reason ``kCap``). For each stored fault in CLEARED or HEALED whose +``deletes_under`` went from keep to delete it calls ``core.run_locked`` with +``RosbagRetention::apply_status_action_if_current``, which re-reads the fault under the core mutex and acts +as the status change, the delete generation advanced, only while the fault is still in that status. The +lock order is core -> retention -> storage, as for a clear from the service. Only when the periodic job +starts, or ``RetentionPolicy::same_passes`` finds a changed max age, floor or interval, it sets the +periodic job with the new interval and runs one sweep and one floor pass (``run_retention_passes``); when +the periodic job stops, it clears it. ``periodic_interval_sec_`` holds the interval set on the worker, so +a later change back to the applied rules still resets it after a failed job. A failing pass logs its own +WARN; a failed part (caps, status actions, sweep, floor) then makes the job log one summary WARN naming +the parts not applied and keep ``applied_retention_``, so a set of the same value retries. Only a job +with no failure sets ``applied_retention_`` and logs ``Rosbag retention change applied``. + +The capture queue (``capture_priorities``), the open-time checks (``admits_new_recording``, +``RosbagCapture::floor_admits_recording``), the floor pass (``RosbagCapture::floor_bytes()``, read once +per pass) and the periodic job (``run_retention_passes``) read the snapshot ``set_policy`` publishes, so a +change reaches them without a copy to refresh. + +An invalid retention configuration degrades the node: the policy stays unset and the node reports ``ROSBAG_RETENTION_CONFIG_INVALID`` through ``FaultManagerCore::report``. The core calls ``CaptureHooks::on_confirmed`` when a fault moved to CONFIRMED (a report after its re-read, or the tick), not gated by muting or the capture cooldown: the node records the request and arms a wall timer, which @@ -751,7 +794,7 @@ unavailable never ends that state. **Protected recordings.** ``protect_recordings`` and ``release_recordings`` set and drop, under the retention mutex, the recording ids no removal decision of ``RosbagRetention`` removes: the age sweep, -``evict_one_for_space`` and ``has_space_candidate`` (through ``space_candidates``), the quota eviction +``evict_one_for_space`` and ``has_space_candidate_for_fault`` (through ``space_candidates``), the quota eviction (``decide_quota`` and ``evict``; the total still counts their sizes, ``admits_new_recording`` does not count them as evictable, and when the oldest-first store stays over the quota with protected bytes, its WARN names those bytes instead of saying the new recording alone exceeds it), the cap (``cap_changes`` neither counts nor removes them, and takes ``keep_first``'s first recording from @@ -806,8 +849,7 @@ depends on the path: then removes the returned directories on the same thread once the retention mutex is released, and logs ``retention sweep: now= removed=`` at DEBUG. ``now`` is the time the pass decided with, read before ``sweep_expired``, not the time of the line. -- Free-space floor (the retention worker): ``RosbagCapture::run_floor_pass(priority_limit, - new_recording_id)``. It measures ``std::filesystem::space(path).available`` of the nearest existing +- Free-space floor (the retention worker): ``RosbagCapture::run_floor_pass(new_recording_id)``. It measures ``std::filesystem::space(path).available`` of the nearest existing directory of the effective storage path (``storage_path``, or the system temp directory), never under the retention mutex. While the free space is below the floor it calls ``evict_one_for_space``, removes the returned directory on this thread and measures again; it @@ -829,14 +871,14 @@ depends on the path: each pass. Two callers post or run it, both on the retention worker thread, so one pass runs at a time: after a store that inserted at least one row of its recording (``StoreOutcome::new_rows_stored``; a cap that removed every new row keeps - nothing), the store's thread reads the recording's priority and posts - ``run_floor_pass(priority, recording_id)``; the periodic job runs ``run_floor_pass(INT64_MAX, "")`` - after the age sweep. The floor exists only on the node's worker: a ``RosbagCapture`` built with its - own inline worker has no floor (``floor_bytes_`` 0), and in degrade the node passes no floor. + nothing), the store's thread posts ``run_floor_pass(recording_id)``, and each step reads the + recording's priority with the rules it ranks with, so a rules change while the job waits cannot pair + an old limit with new priorities; the periodic job runs ``run_floor_pass("")`` after the age sweep. The floor comes from the policy snapshot of the retention: a ``RosbagCapture`` + built with its own retention has no policy and no floor, and in degrade there is no policy. - Open-time floor check (the capture pool, under the node's rosbag mutex): when a recording is about to open, after the quota check, ``RosbagCapture::floor_admits_recording`` measures the free space. - Below the floor it asks ``fault_priority`` and ``has_space_candidate``; with no candidate the - recording does not start and one INFO line names the floor. A fault that joins an open burst is not + Below the floor it asks ``has_space_candidate_for_fault``; with no candidate the recording does not + start and one INFO line names the floor. A fault that joins an open burst is not checked. **The periodic job.** ``RetentionWorker::set_periodic(interval, job)`` gives the worker thread a @@ -848,7 +890,7 @@ the thread does not wake on its own; ``clear_periodic()`` returns it to that sta ``drain_and_stop()`` ends the wait at once, runs the queued jobs and never the periodic job. ``Mode::kInline`` stores no periodic job: it has no thread to wait. The node sets the job last in its constructor, only when the policy is valid and ``runs_periodic()`` (``sweeps()`` or a -``min_free_disk_mb`` above 0), with ``sweep_interval_sec``. The job runs the age sweep when +``min_free_disk_mb`` above 0), with ``sweep_interval_sec``; a runtime change sets it again or clears it. The job runs the age sweep when ``sweeps()``, then the floor pass. The startup policy line ends with ``sweep: off`` or ``sweep: every s`` from the same ``runs_periodic()``, then ``floor: off`` or ``floor: MB``. 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 92f2c6a5c..8c4a6f32c 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 @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -232,6 +233,10 @@ class FaultManagerCore { /// later than @p wall_now_ns plus one period back to that. void tick(int64_t wall_now_ns); + /// Run @p fn under the core mutex, so no report, clear or tick changes a fault status while it + /// runs. @p fn must not call back into the core. Lock order: core -> retention -> storage. + void run_locked(const std::function & fn); + /// Number of times each tick job has run. For tests and observability. uint64_t auto_confirm_runs() const { return auto_confirm_runs_.load(std::memory_order_relaxed); diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp index 64588d4eb..76ea624fc 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp @@ -97,6 +97,10 @@ class RetentionPolicy { /// True when the periodic job runs: sweeps(), or min_free_disk_mb above 0. bool runs_periodic() const; + /// True when the age sweep and the floor pass decide the same under @p other: the same max_age_sec keys at each + /// level that sets one, the same patterns and pattern_order when a pattern sets one, the same interval and floor. + bool same_passes(const RetentionPolicy & other) const; + /// `sweep_interval_sec`, 1 to 86400, default 60. int64_t sweep_interval_sec() const { return sweep_interval_sec_; 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 52b47d47d..bf52d68ec 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 @@ -134,13 +134,15 @@ struct SpaceStep { struct SweepOutcome { size_t removed_links{0}; ///< Rows the pass removed std::vector unlink_paths; ///< Directories no row names any more, each path once + bool failed{false}; ///< A storage failure or RosbagCommitInDoubt: nothing returned }; /// Every rosbag retention decision of the fault manager, on FaultStorage::apply_rosbag_changes(). /// /// Each public method holds one mutex for its whole decision, except set_policy(), which publishes -/// the policy snapshot with std::atomic_store, and capture_priorities(), which reads it: neither -/// takes the mutex. Lock order: the caller's outer locks -> this mutex -> the storage's own lock. +/// the policy snapshot with std::atomic_store, capture_priorities() and policy_state(), which read +/// it, and cap_under() and deletes_under(), which read a state the caller passes: none takes the +/// mutex. Lock order: the caller's outer locks -> this mutex -> the storage's own lock. /// Under it only storage calls and logging run: /// no other lock and no file system call. Nothing here unlinks a file or logs a removal. Each /// method returns the directories the caller removes, with the reason it logs after each removal. @@ -154,10 +156,25 @@ class RosbagRetention { RosbagRetention & operator=(RosbagRetention &&) = delete; ~RosbagRetention() = default; + /// A status change that may delete a fault's recordings. + enum class StatusChange { kCleared, kHealed, kReclassified }; + /// Publish the rules. @p policy is null unless @p mode is kConfigured. Safe to call while /// decisions run: each decision uses the snapshot it loaded. void set_policy(RetentionMode mode, std::shared_ptr policy); + /// The snapshot set_policy() published last. Takes no mutex. + std::shared_ptr policy_state() const; + + /// The cap of @p fault_code with @p severity under @p state: its rule's max_bags in kConfigured, + /// else max_bags_per_fault. 0 = no cap. No storage call. + size_t cap_under(const RetentionPolicyState & state, const std::string & fault_code, uint8_t severity) const; + + /// Whether @p change of @p fault_code with @p severity deletes its recordings under @p state, as + /// on_fault_cleared(), on_fault_healed() and on_startup_reclassified() decide it. No storage call. + bool deletes_under(const RetentionPolicyState & state, StatusChange change, const std::string & fault_code, + uint8_t severity) const; + /// Keep every row of @p recording_ids: each removal decision below skips them, and the quota still counts their /// sizes. Replaces the set held before. While a set is held, each decision logs the rows it skipped at DEBUG. void protect_recordings(std::unordered_set recording_ids); @@ -227,6 +244,21 @@ class RosbagRetention { /// @throws as on_fault_cleared() RemovalOutcome on_startup_reclassified(const std::string & fault_code); + /// The status action of @p change on @p fault_code, only while the storage holds the fault in the + /// status of @p change (CLEARED, or HEALED for kHealed). Re-reads the fault, then decides and + /// removes as on_fault_cleared() or on_fault_healed(), the delete generation advanced. Any other + /// status, or no such fault: nothing removed, the generation unchanged. The caller holds the core + /// mutex, so no status change runs between the read and the removal. + /// @throws a storage failure; no row changed then, except with RosbagCommitInDoubt + RemovalOutcome apply_status_action_if_current(StatusChange change, const std::string & fault_code); + + /// Apply each code's current cap (max_bags, keep_first) to its stored recordings, as a store + /// applies it, in one change set: a protected recording is neither counted nor removed. The freed + /// directories carry RemovalReason::kCap. + /// @throws a storage failure, a fault read included; no row changed then, except with + /// RosbagCommitInDoubt + RemovalOutcome trim_to_caps(const std::vector & fault_codes); + /// Remove every row of a recording whose directory is gone. /// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows /// may be gone @@ -237,26 +269,25 @@ class RosbagRetention { /// status. Only that fault's link goes: a shared recording keeps its other links. A link whose /// fault the storage does not hold is not aged. Returns at once with nothing unless kConfigured /// and a level sets a max age above 0. Two reads per pass: the rosbag rows and the faults. - /// A storage failure: one WARN, nothing returned. RosbagCommitInDoubt: one WARN, nothing returned. + /// A storage failure: one WARN, nothing returned, `failed` set. RosbagCommitInDoubt: the same. /// Never throws. SweepOutcome sweep_expired(int64_t now_ns); /// One removal step of the free-space floor. Picks the first recording in the quota's eviction /// order (lowest priority, then cleared, healed, active, then unprotected before keep_first, then - /// oldest) whose priority is at most @p priority_limit, never @p last_resort_recording_id while - /// another candidate is left, and removes every row of it in one change set. + /// oldest) whose priority is at most the limit, never @p new_recording_id while another candidate + /// is left, and removes every row of it in one change set. The limit is the priority of + /// @p new_recording_id, or none when it is empty (the periodic pass). One policy snapshot gives + /// the limit and the order. A new recording no row names any more leaves no candidate. /// @return kRemoved with its directory, kNoCandidate when no candidate is left, or kFailed after /// a storage failure or RosbagCommitInDoubt, logged with one WARN, no directory freed. /// Never throws. - SpaceStep evict_one_for_space(int64_t priority_limit, const std::string & last_resort_recording_id); - - /// Whether evict_one_for_space(@p priority_limit, ...) has a candidate, without removing it. - /// A failed read answers true and logs nothing. Never throws. - bool has_space_candidate(int64_t priority_limit); + SpaceStep evict_one_for_space(const std::string & new_recording_id); - /// Priority of the rule of @p fault_code as the storage holds the fault now, 0 unless kConfigured. - /// @throws a storage failure - int64_t fault_priority(const std::string & fault_code); + /// Whether a floor step for a new recording of @p fault_code would have a candidate, without removing + /// it: a recording at most at the priority of the fault's rule. One policy snapshot gives the priority + /// and the order. A failed read answers true with one WARN. Never throws. + bool has_space_candidate_for_fault(const std::string & fault_code); /// Priorities of captures of @p fault_codes in the capture queue, in order: the priority of the /// rule of each fault as the storage holds it now, all from one policy snapshot. 0 unless @@ -276,9 +307,6 @@ class RosbagRetention { struct SpaceCandidate; using FactsCache = std::unordered_map; - /// A status change that may delete a fault's recordings. - enum class StatusChange { kCleared, kHealed, kReclassified }; - /// The store without rules: quota eviction oldest first. StoreOutcome store_oldest_first(const std::vector & rows, const RetentionPolicyState & state, FactsCache & cache); @@ -314,6 +342,12 @@ class RosbagRetention { const std::vector & fault_codes, const std::map & first_path_by_code, FactsCache & cache); + /// The priority of a stored recording under @p state: the highest priority of the faults it is linked to. + /// Unset when no row names it. Expects mutex_ held. + /// @throws a failure of a read + std::optional stored_recording_priority(const RetentionPolicyState & state, + const std::string & recording_id); + /// The recordings the floor may delete at @p priority_limit, in eviction order. Counts the protected rows left out /// in @p skipped. Expects mutex_ held. /// @throws a failure of a read @@ -346,6 +380,13 @@ class RosbagRetention { /// on_fault_cleared(), on_fault_healed() and on_startup_reclassified(). RemovalOutcome on_status_change(StatusChange change, const std::string & fault_code); + /// Advance the delete generation of @p fault_code and remove every row of it. Expects mutex_ held. + /// @throws the storage failure of the removal, with the generation already advanced + RemovalOutcome delete_recordings_of(StatusChange change, const std::string & fault_code); + + /// Whether a clear deletes: @p on_cleared when set, else auto_cleanup with a cap of exactly 1. + bool clear_decision(const std::optional & on_cleared, size_t cap) const; + /// Expects mutex_ held. uint64_t generation_of(const std::string & fault_code) const; @@ -359,14 +400,17 @@ class RosbagRetention { /// keeps its row. bool row_still_wanted(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); - /// The insert and the per-fault cap removals of @p rows, as one change set. In kConfigured each - /// fault code takes the cap of its rule, a code whose fault cannot be read is not capped, and - /// with @p store_logs the store's warnings are logged. Fills @p recording_ids with the recording - /// id of every path it read or was given. + /// The insert and the per-fault cap removals of @p rows, as one change set. The codes of @p rows + /// and then @p trim_codes are capped, each once. In kConfigured each fault code takes the cap of + /// its rule, a code whose fault cannot be read is not capped, and with @p store_logs the store's + /// warnings are logged. A protected row is neither counted nor removed; a store or a trim logs the + /// skipped count at DEBUG. Fills @p recording_ids with the recording id of every path it read or + /// was given. /// @throws a failure of the cap read RosbagChangeSet cap_changes(const std::vector & rows, const RetentionPolicyState & state, FactsCache & cache, bool store_logs, - std::unordered_map & recording_ids); + std::unordered_map & recording_ids, + const std::vector & trim_codes = {}); /// Quota eviction. @p out holds what was applied, also when this throws. void evict(size_t max_bytes, const std::string & keep_recording_id, Eviction & out); 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 c5a013ca4..655d5c014 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 @@ -18,9 +18,11 @@ #include #include #include +#include #include #include #include +#include #include "rclcpp/rclcpp.hpp" #include "ros2_medkit_fault_manager/capture_thread_pool.hpp" @@ -168,10 +170,26 @@ class FaultManagerNode : public rclcpp::Node { /// Declare every startup parameter and read it into a config, unvalidated. core::FaultManagerConfig declare_config(); - /// Declare every \`snapshots.rosbag.retention.*\` override as a read-only parameter holding its own value. - /// Returns the values keyed relative to that prefix. + /// Declare every \`snapshots.rosbag.retention.*\` override as a dynamically typed parameter holding its own value, + /// and min_free_disk_mb and sweep_interval_sec with their defaults when not given. Returns the given values keyed + /// relative to that prefix. core::FlatParams declare_retention_params(); + /// The on-set callback of every parameter. Names outside the retention prefix pass; a set that mixes them with + /// retention names is refused. A set of retention names is validated as the whole candidate configuration and + /// refused when it adds an error; an accepted valid candidate is published at once and a job applies it to the + /// stored recordings. No storage or file system call. + rcl_interfaces::msg::SetParametersResult on_retention_params_set(const std::vector & parameters); + + /// The worker job of an accepted change: lowered caps, status actions that became delete and, when a max age, the + /// floor or the interval changed, the periodic job and one sweep and floor pass. Compares @p next with the state + /// last applied in full; a failure logs one summary WARN and keeps that state, so the same change set again + /// retries. + void apply_retention_change(const std::shared_ptr & next); + + /// One sweep pass and one floor pass on the policy snapshot. Returns the names of the passes that failed. + std::vector run_retention_passes(); + /// Validate the retention parameters and keep the policy, or degrade. Throws on a shifted key. void configure_retention(const core::FlatParams & params); @@ -218,8 +236,8 @@ class FaultManagerNode : public rclcpp::Node { /// One pass of the age sweep, on the retention worker: the rows go under the retention mutex, /// the directories after it is released. Logs `retention sweep: now= removed=`, with - /// the time the pass decided with. - void sweep_expired_recordings(); + /// the time the pass decided with. False when the storage failed. + bool sweep_expired_recordings(); /// Create snapshot configuration from the validated config SnapshotConfig create_snapshot_config(); @@ -248,12 +266,23 @@ class FaultManagerNode : public rclcpp::Node { core::FaultManagerConfig config_; ///< Validated startup configuration - /// Parsed retention rules. Null when none are configured, when rosbag is off or when degraded. + /// Parsed retention rules. Null when none are configured, when rosbag is off or when degraded. Executor only; the + /// worker reads the snapshot RosbagRetention publishes. std::shared_ptr retention_policy_; bool retention_degraded_{false}; ///< The retention parameters are invalid: the rules are not used. std::string retention_fault_description_; - /// The startup report (degraded) or clear (valid or no rules) of the own fault is not done yet. + /// The report (degraded) or clear (valid or no rules) of the own fault is not done yet: set at startup and by a + /// change that ends degrade. bool retention_startup_pending_{true}; + /// Retention keys, relative to the prefix, given at startup or changed since. Only these reach the parser. + std::set retention_given_; + /// The policy state the worker applied last in full: caps, status actions and passes. Read and written on the + /// worker. + std::shared_ptr applied_retention_; + /// The interval of the periodic job set on the worker, unset when it is off. Written before the change callback + /// is registered, then only on the worker. + std::optional periodic_interval_sec_; + rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr retention_params_handle_; /// Codes recorded under the core mutex by on_confirm_candidate; the timer reads their status and re-reports. std::set retention_candidates_; /// A confirmation happened (or a candidate read as CONFIRMED) and the own fault is not reported yet. diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp index 2e55748e2..2cbdf1bd2 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp @@ -91,7 +91,8 @@ class RosbagCapture { /// Create rosbag capture on a retention and a worker the caller owns, as the fault manager /// node does. The caller drains @p retention_worker after stop() and before it destroys this - /// capture: a floor pass posted to it runs on this capture. config.min_free_disk_mb sets the floor. + /// capture: a floor pass posted to it runs on this capture. The policy snapshot of @p retention + /// sets the floor (min_free_disk_mb), read at each check and pass. /// @param retention Retention decisions over @p storage /// @param retention_worker Removes the directories a clear frees, runs the floor passes RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const RosbagConfig & config, @@ -147,13 +148,15 @@ class RosbagCapture { /// One pass of the free-space floor (min_free_disk_mb). Runs only on the retention worker thread, /// so one pass runs at a time. While the measured free space is below the floor, it takes one - /// core::RosbagRetention::evict_one_for_space() step at @p priority_limit, removes the directory - /// and measures again. @p new_recording_id is the recording just stored, deleted only when nothing - /// else is left; its drop is logged with the drop line. Ends with one DEBUG line + /// core::RosbagRetention::evict_one_for_space() step, removes the directory and measures again. + /// @p new_recording_id is the recording just stored: each step takes its priority as the limit, and + /// deletes it only when nothing else is left; its drop is logged with the drop line. Empty for the + /// periodic pass, which has no limit. Ends with one DEBUG line /// `floor pass: removed= free= floor= met= source=`, /// and with one WARN when it stops below the floor because nothing is left to delete. Does nothing - /// when the floor is off. - void run_floor_pass(int64_t priority_limit, const std::string & new_recording_id); + /// when the floor is off. False when a step failed in the storage or the free space could not be + /// read. + bool run_floor_pass(const std::string & new_recording_id); /// Get current configuration const RosbagConfig & config() const { @@ -309,9 +312,13 @@ class RosbagCapture { /// nothing. std::optional measure_free_bytes() const; - /// After a stored recording: post a floor pass at its priority to the retention worker. + /// After a stored recording: post a floor pass for it to the retention worker. Each step reads its priority. void post_floor_pass(const std::string & recording_id); + /// The floor in bytes from the policy snapshot the retention publishes now. 0 = off, also without + /// valid rules. + uint64_t floor_bytes() const; + /// Open a fresh bag for @p fault_code: generate the path, create its parent /// directory and open active_writer_. Independent of the ring buffer, so a /// post-fault-only recording can use it with nothing buffered. @@ -467,8 +474,6 @@ class RosbagCapture { std::unique_ptr own_log_sink_; std::shared_ptr retention_; std::shared_ptr retention_worker_; - /// The free-space floor in bytes, 0 = off. Set only on a worker the caller owns. - uint64_t floor_bytes_{0}; /// ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE when this capture was built; empty = measure the filesystem. std::string capacity_file_; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/snapshot_capture.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/snapshot_capture.hpp index 41a2cc832..08db59608 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/snapshot_capture.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/snapshot_capture.hpp @@ -98,10 +98,6 @@ struct RosbagConfig { /// If true, delete bag file when fault is cleared bool auto_cleanup{true}; - - /// Free space in MiB kept on the filesystem of storage_path (retention.min_free_disk_mb), 0 = off. - /// Only a capture on a retention worker the caller owns enforces it. - uint64_t min_free_disk_mb{0}; }; /// Configuration for snapshot capture 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 ad1bf2df0..1474a5673 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 @@ -167,6 +167,11 @@ void FaultManagerCore::record_transition(const char * transition, const fd::Faul audit_transition(transition, fault, source_id, occurred_at_ns); } +void FaultManagerCore::run_locked(const std::function & fn) { + std::lock_guard lock(mutex_); + fn(); +} + void FaultManagerCore::tick(int64_t wall_now_ns) { std::lock_guard lock(mutex_); const int64_t auto_confirm_period_ns = seconds_to_ns(kAutoConfirmPeriodSec); diff --git a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp index 81bd11ebb..26b367986 100644 --- a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp +++ b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp @@ -197,6 +197,34 @@ bool sets_max_age(const RetentionRule & rule) { rule.max_age_cleared.value_or(0) > 0; } +bool sets_age_key(const RetentionRule & rule) { + return rule.max_age_active || rule.max_age_healed || rule.max_age_cleared; +} + +bool same_age_keys(const RetentionRule & a, const RetentionRule & b) { + return a.max_age_active == b.max_age_active && a.max_age_healed == b.max_age_healed && + a.max_age_cleared == b.max_age_cleared; +} + +/// The same keys with the same age keys, over the levels that set one: a level without one adds no age. +template +bool same_age_levels(const std::map & mine, const std::map & theirs) { + const auto aged = [](const std::map & levels) { + std::vector> out; + for (const auto & [key, rule] : levels) { + if (sets_age_key(rule)) { + out.emplace_back(key, &rule); + } + } + return out; + }; + const auto a = aged(mine); + const auto b = aged(theirs); + return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](const auto & x, const auto & y) { + return x.first == y.first && same_age_keys(*x.second, *y.second); + }); +} + /// The segment at @p index, null past the end. const std::string * segment(const std::vector & parts, size_t index) { return index < parts.size() ? &parts[index] : nullptr; @@ -480,6 +508,29 @@ bool RetentionPolicy::runs_periodic() const { return sweeps() || min_free_disk_mb_ > 0; } +bool RetentionPolicy::same_passes(const RetentionPolicy & other) const { + if (sweep_interval_sec_ != other.sweep_interval_sec_ || min_free_disk_mb_ != other.min_free_disk_mb_ || + !same_age_keys(defaults_, other.defaults_) || !same_age_levels(severities_, other.severities_) || + !same_age_levels(codes_, other.codes_)) { + return false; + } + // The first matching pattern hides the later ones, also when it sets no age key. + const auto pattern_ages = [](const std::map & patterns) { + return std::any_of(patterns.begin(), patterns.end(), [](const auto & entry) { + return sets_age_key(entry.second.rule); + }); + }; + if (!pattern_ages(patterns_) && !pattern_ages(other.patterns_)) { + return true; + } + return pattern_order_ == other.pattern_order_ && + std::equal(patterns_.begin(), patterns_.end(), other.patterns_.begin(), other.patterns_.end(), + [](const auto & a, const auto & b) { + return a.first == b.first && a.second.match == b.second.match && + same_age_keys(a.second.rule, b.second.rule); + }); +} + std::optional> RetentionPolicy::max_bags_other_than(int64_t value) const { const auto differs = [value](const RetentionRule & rule) { return rule.max_bags && *rule.max_bags != value; 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 b8e821bf0..6c9d8e89d 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -219,6 +219,43 @@ void RosbagRetention::set_policy(RetentionMode mode, std::shared_ptr RosbagRetention::policy_state() const { + return std::atomic_load(&state_); +} + +size_t RosbagRetention::cap_under(const RetentionPolicyState & state, const std::string & fault_code, + uint8_t severity) const { + if (state.mode != RetentionMode::kConfigured || !state.policy) { + return limits_.max_bags_per_fault; + } + return state.policy->resolve(fault_code, severity).max_bags.value_or(limits_.max_bags_per_fault); +} + +bool RosbagRetention::deletes_under(const RetentionPolicyState & state, StatusChange change, + const std::string & fault_code, uint8_t severity) const { + if (state.mode != RetentionMode::kConfigured || !state.policy) { + return change == StatusChange::kCleared && clear_decision(std::nullopt, limits_.max_bags_per_fault); + } + const ResolvedRule rule = state.policy->resolve(fault_code, severity); + switch (change) { + case StatusChange::kCleared: + return clear_decision(rule.on_cleared, rule.max_bags.value_or(limits_.max_bags_per_fault)); + case StatusChange::kHealed: + return rule.on_healed == StatusAction::kDelete; + case StatusChange::kReclassified: + return rule.on_cleared == StatusAction::kDelete; + } + return false; +} + +bool RosbagRetention::clear_decision(const std::optional & on_cleared, size_t cap) const { + if (on_cleared) { + return *on_cleared == StatusAction::kDelete; + } + // The default: only a cap of exactly 1 loses its recording on a clear, a longer history is kept. + return limits_.auto_cleanup && cap == 1; +} + void RosbagRetention::protect_recordings(std::unordered_set recording_ids) { std::lock_guard lock(mutex_); protected_ = std::move(recording_ids); @@ -663,12 +700,20 @@ int64_t RosbagRetention::recording_priority(const std::string & recording_id) { if (state->mode != RetentionMode::kConfigured) { return 0; } + return stored_recording_priority(*state, recording_id).value_or(0); +} + +std::optional RosbagRetention::stored_recording_priority(const RetentionPolicyState & state, + const std::string & recording_id) { std::vector codes; for (const auto & row : storage_.get_rosbag_files_by_recording(recording_id)) { codes.push_back(row.fault_code); } + if (codes.empty()) { + return std::nullopt; + } FactsCache cache; - return rank_of(*state, codes, cache).priority; + return rank_of(state, codes, cache).priority; } std::unordered_map @@ -836,6 +881,22 @@ RemovalOutcome RosbagRetention::on_status_change(StatusChange change, const std: if (!deletes) { return {}; } + return delete_recordings_of(change, fault_code); +} + +RemovalOutcome RosbagRetention::apply_status_action_if_current(StatusChange change, const std::string & fault_code) { + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + FactsCache cache; + const FaultFacts facts = fault_facts(*state, fault_code, cache); + const bool current = change == StatusChange::kHealed ? facts.status == kStatusHealed : facts.cleared; + if (!current || !change_deletes(*state, change, fault_code, cache)) { + return {}; + } + return delete_recordings_of(change, fault_code); +} + +RemovalOutcome RosbagRetention::delete_recordings_of(StatusChange change, const std::string & fault_code) { // Advanced before the removal: a recording the code joined earlier loses its row at its store, // also when this removal throws. ++delete_generations_[fault_code]; @@ -855,6 +916,28 @@ RemovalOutcome RosbagRetention::on_status_change(StatusChange change, const std: return outcome; } +RemovalOutcome RosbagRetention::trim_to_caps(const std::vector & fault_codes) { + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + FactsCache cache; + // Read first, so a failed read throws here: cap_changes leaves a code it cannot read uncapped. + if (state->mode == RetentionMode::kConfigured) { + for (const auto & code : fault_codes) { + fault_facts(*state, code, cache); + } + } + std::unordered_map recording_ids; + const RosbagChangeSet changes = cap_changes({}, *state, cache, false, recording_ids, fault_codes); + RemovalOutcome outcome; + if (changes.remove.empty()) { + return outcome; + } + outcome.unlink_paths = + freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_ids, RemovalReason::kCap); + outcome.removed_rows = changes.remove.size(); + return outcome; +} + RemovalOutcome RosbagRetention::forget_recording(const std::string & recording_id) { // An empty id names rows whose backfill did not finish, not one recording. if (recording_id.empty()) { @@ -877,6 +960,8 @@ SweepOutcome RosbagRetention::sweep_expired(int64_t now_ns) { if (state->mode != RetentionMode::kConfigured || !state->policy || !state->policy->sweeps()) { return {}; } + SweepOutcome failure; + failure.failed = true; RosbagChangeSet changes; // The first removed link of each path names the recording and the reason. std::unordered_map freed_by_path; @@ -922,11 +1007,11 @@ SweepOutcome RosbagRetention::sweep_expired(int64_t now_ns) { } catch (const std::exception & e) { logf(log_sink_, LogLevel::kWarn, logger_name_, "Rosbag age sweep could not read the storage; nothing is removed until the next pass: %s", e.what()); - return {}; + return failure; } catch (...) { logf(log_sink_, LogLevel::kWarn, logger_name_, "Rosbag age sweep could not read the storage; nothing is removed until the next pass: unknown exception"); - return {}; + return failure; } if (changes.remove.empty()) { return {}; @@ -939,17 +1024,17 @@ SweepOutcome RosbagRetention::sweep_expired(int64_t now_ns) { logf(log_sink_, LogLevel::kWarn, logger_name_, "Rosbag age sweep: the outcome of removing %zu link(s) is unknown; their directories stay: %s", changes.remove.size(), e.what()); - return {}; + return failure; } catch (const std::exception & e) { logf(log_sink_, LogLevel::kWarn, logger_name_, "Rosbag age sweep failed to remove %zu link(s); the next pass tries again: %s", changes.remove.size(), e.what()); - return {}; + return failure; } catch (...) { logf(log_sink_, LogLevel::kWarn, logger_name_, "Rosbag age sweep failed to remove %zu link(s); the next pass tries again: unknown exception", changes.remove.size()); - return {}; + return failure; } SweepOutcome outcome; outcome.removed_links = changes.remove.size(); @@ -1017,14 +1102,22 @@ RosbagRetention::space_candidates(const RetentionPolicyState & state, int64_t pr return candidates; } -SpaceStep RosbagRetention::evict_one_for_space(int64_t priority_limit, const std::string & last_resort_recording_id) { +SpaceStep RosbagRetention::evict_one_for_space(const std::string & new_recording_id) { std::lock_guard lock(mutex_); + // One snapshot: the limit and the order come from the same rules. const auto state = std::atomic_load(&state_); SpaceStep step; std::vector candidates; size_t skipped = 0; try { - candidates = space_candidates(*state, priority_limit, skipped); + std::optional limit = std::numeric_limits::max(); + if (!new_recording_id.empty()) { + limit = stored_recording_priority(*state, new_recording_id); + } + if (!limit) { + return step; + } + candidates = space_candidates(*state, *limit, skipped); } catch (const std::exception & e) { logf(log_sink_, LogLevel::kWarn, logger_name_, "Rosbag free-space pass could not read the storage; nothing is removed until the next pass: %s", e.what()); @@ -1041,8 +1134,8 @@ SpaceStep RosbagRetention::evict_one_for_space(int64_t priority_limit, const std if (candidates.empty()) { return step; } - auto chosen = std::find_if(candidates.begin(), candidates.end(), [&last_resort_recording_id](const auto & c) { - return c.recording_id != last_resort_recording_id; + auto chosen = std::find_if(candidates.begin(), candidates.end(), [&new_recording_id](const auto & c) { + return c.recording_id != new_recording_id; }); if (chosen == candidates.end()) { chosen = candidates.begin(); // the last resort is the only candidate left @@ -1080,25 +1173,28 @@ SpaceStep RosbagRetention::evict_one_for_space(int64_t priority_limit, const std return step; } -bool RosbagRetention::has_space_candidate(int64_t priority_limit) { +bool RosbagRetention::has_space_candidate_for_fault(const std::string & fault_code) { std::lock_guard lock(mutex_); + // One snapshot: the fault's priority and the order come from the same rules. const auto state = std::atomic_load(&state_); size_t skipped = 0; try { - return !space_candidates(*state, priority_limit, skipped).empty(); + int64_t limit = 0; + if (state->mode == RetentionMode::kConfigured) { + FactsCache cache; + limit = fault_facts(*state, fault_code, cache).priority; + } + return !space_candidates(*state, limit, skipped).empty(); + } catch (const std::exception & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Could not read the storage for the min_free_disk_mb check of fault '%s'; recording it: %s", + fault_code.c_str(), e.what()); } catch (...) { - return true; - } -} - -int64_t RosbagRetention::fault_priority(const std::string & fault_code) { - std::lock_guard lock(mutex_); - const auto state = std::atomic_load(&state_); - if (state->mode != RetentionMode::kConfigured) { - return 0; + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Could not read the storage for the min_free_disk_mb check of fault '%s'; recording it: unknown exception", + fault_code.c_str()); } - FactsCache cache; - return fault_facts(*state, fault_code, cache).priority; + return true; } std::vector RosbagRetention::capture_priorities(const std::vector & fault_codes) noexcept { @@ -1127,14 +1223,10 @@ std::vector RosbagRetention::capture_priorities(const std::vector & rows, const RetentionPolicyState & state, FactsCache & cache, bool store_logs, - std::unordered_map & recording_ids) { + std::unordered_map & recording_ids, + const std::vector & trim_codes) { for (const auto & row : rows) { recording_ids.emplace(row.file_path, row.recording_id); } @@ -1221,11 +1314,16 @@ RosbagChangeSet RosbagRetention::cap_changes(const std::vector & bool stored; bool incoming; }; + std::vector codes; + codes.reserve(rows.size() + trim_codes.size()); + for (const auto & row : rows) { + codes.push_back(row.fault_code); + } + codes.insert(codes.end(), trim_codes.begin(), trim_codes.end()); std::set> dropped; std::set done; size_t skipped = 0; - for (const auto & incoming : rows) { - const std::string & code = incoming.fault_code; + for (const auto & code : codes) { if (!done.insert(code).second) { continue; } @@ -1312,7 +1410,8 @@ RosbagChangeSet RosbagRetention::cap_changes(const std::vector & } } - if (store_logs) { + // A probe (admits_new_recording) removes nothing and logs nothing. + if (store_logs || !trim_codes.empty()) { log_protected("cap", skipped); } for (const auto & row : rows) { 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 e233c7182..05d818ec4 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -283,6 +282,7 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" : retention_policy_ != nullptr ? core::RetentionMode::kConfigured : core::RetentionMode::kUnconfigured, retention_policy_); + applied_retention_ = rosbag_retention_->policy_state(); // Before any rule removes a row: an unavailable storage protects every recorded row. check_rosbag_storage_at_startup(); @@ -467,15 +467,14 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" // valid policy with a max age or a floor runs it. if (retention_policy_ && retention_policy_->runs_periodic()) { retention_worker_->set_periodic(std::chrono::seconds(retention_policy_->sweep_interval_sec()), [this]() { - if (retention_policy_->sweeps()) { - sweep_expired_recordings(); - } - // No recording is stored by this pass: the floor has no priority limit. - if (rosbag_capture_) { - rosbag_capture_->run_floor_pass(std::numeric_limits::max(), ""); - } + run_retention_passes(); }); + periodic_interval_sec_ = retention_policy_->sweep_interval_sec(); } + // After the last declaration: a change applies to every member built above. + retention_params_handle_ = add_on_set_parameters_callback([this](const std::vector & parameters) { + return on_retention_params_set(parameters); + }); } FaultManagerNode::~FaultManagerNode() { @@ -756,8 +755,8 @@ core::FaultManagerConfig FaultManagerNode::declare_config() { core::FlatParams FaultManagerNode::declare_retention_params() { core::FlatParams flat; + // Any type: the parser checks it, so a wrong type is a reason, not an rclcpp type error. rcl_interfaces::msg::ParameterDescriptor descriptor; - descriptor.read_only = true; descriptor.dynamic_typing = true; const std::string prefix = kRetentionParamPrefix; for (const auto & [name, value] : get_node_parameters_interface()->get_parameter_overrides()) { @@ -766,10 +765,288 @@ core::FlatParams FaultManagerNode::declare_retention_params() { } declare_parameter(name, value, descriptor); flat[name.substr(prefix.size())] = to_param_value(value); + retention_given_.insert(name.substr(prefix.size())); + } + // Declared also when not given, so they can be set while the node runs. A default does not reach the parser. + const core::RetentionPolicy defaults; + const std::pair scalars[] = {{"min_free_disk_mb", defaults.min_free_disk_mb()}, + {"sweep_interval_sec", defaults.sweep_interval_sec()}}; + for (const auto & [key, value] : scalars) { + if (!has_parameter(prefix + key)) { + declare_parameter(prefix + key, rclcpp::ParameterValue(value), descriptor); + } } return flat; } +rcl_interfaces::msg::SetParametersResult +FaultManagerNode::on_retention_params_set(const std::vector & parameters) { + rcl_interfaces::msg::SetParametersResult result; + result.successful = true; + const std::string prefix = kRetentionParamPrefix; + core::FlatParams changed; + std::vector refused; + std::vector others; + for (const auto & parameter : parameters) { + const std::string & name = parameter.get_name(); + if (name.compare(0, prefix.size(), prefix) != 0) { + others.push_back(name); + continue; + } + // rclcpp undeclares a dynamically typed parameter set to PARAMETER_NOT_SET. + if (parameter.get_type() == rclcpp::PARAMETER_NOT_SET) { + refused.push_back(name + ": a retention parameter cannot be unset; set a value"); + continue; + } + changed[name.substr(prefix.size())] = to_param_value(parameter.get_parameter_value()); + } + if (!refused.empty()) { + result.successful = false; + result.reason = join(refused, "; "); + return result; + } + if (changed.empty()) { + return result; + } + // A later callback (rclcpp's use_sim_time check) can still refuse the other names after this one published. + if (!others.empty()) { + result.successful = false; + result.reason = "set the retention parameters on their own, not with " + join(others, ", "); + return result; + } + + // Only the errors the change adds refuse it: in degrade each invalid key can be repaired on its own. + core::FlatParams current; + for (const auto & key : retention_given_) { + current[key] = to_param_value(get_parameter(prefix + key).get_parameter_value()); + } + core::FlatParams candidate = current; + for (const auto & [key, value] : changed) { + candidate[key] = value; + } + const auto now = core::RetentionPolicy::parse(current); + auto next = core::RetentionPolicy::parse(candidate); + std::vector added; + for (const auto & error : next.errors) { + if (std::find(now.errors.begin(), now.errors.end(), error) == now.errors.end()) { + added.push_back(prefix + error); + } + } + if (!added.empty()) { + result.successful = false; + result.reason = join(added, "; "); + return result; + } + + std::vector names; + for (const auto & entry : changed) { + retention_given_.insert(entry.first); + names.push_back(prefix + entry.first); + } + if (!config_.snapshots_rosbag_enabled) { + RCLCPP_INFO(get_logger(), + "Rosbag retention parameter %s changed, but snapshots.rosbag.enabled is false. The rules " + "are not used.", + join(names, ", ").c_str()); + return result; + } + if (!next.policy) { + retention_fault_description_ = + "Invalid rosbag retention configuration, the rules are not used: " + join(next.errors, "; "); + RCLCPP_INFO(get_logger(), + "Rosbag retention rules changed (degraded): %s changed, the configuration is still " + "invalid: %s", + join(names, ", ").c_str(), join(next.errors, "; ").c_str()); + return result; + } + + // rclcpp stores the value after this callback returns, and Humble has no post-set callback: every check passed. + retention_policy_ = std::make_shared(std::move(*next.policy)); + rosbag_retention_->set_policy(core::RetentionMode::kConfigured, retention_policy_); + RCLCPP_INFO(get_logger(), "Rosbag retention rules changed (configured): %s", retention_policy_->describe().c_str()); + if (retention_degraded_) { + // The own fault is cleared by the retention timer, on the executor: no storage call here. + retention_degraded_ = false; + retention_fault_description_.clear(); + retention_candidates_.clear(); + retention_reraise_ = false; + retention_startup_pending_ = true; + arm_retention_timer(); + } + auto state = std::make_shared(); + state->mode = core::RetentionMode::kConfigured; + state->policy = retention_policy_; + // The worker is drained in the destructor, before the members this job reads. + retention_worker_->post("retention change", + [this, next_state = std::shared_ptr(std::move(state))]() { + apply_retention_change(next_state); + }); + return result; +} + +void FaultManagerNode::apply_retention_change(const std::shared_ptr & next) { + using StatusChange = core::RosbagRetention::StatusChange; + const auto previous = applied_retention_; + std::vector failed; + std::string error; + size_t capped_codes = 0; + size_t cap_removed = 0; + size_t acted_faults = 0; + size_t action_removed = 0; + + // One read of the rows and one of the faults serve the caps and the status actions. + std::vector rows; + std::vector faults; + try { + rows = storage_->get_all_rosbag_files(); + faults = storage_->get_all_faults(); + } catch (const std::exception & e) { + failed = {"caps", "status actions"}; + error = e.what(); + } + if (failed.empty()) { + std::set codes; + for (const auto & row : rows) { + codes.insert(row.fault_code); + } + std::map fault_by_code; + for (const auto & fault : faults) { + fault_by_code.emplace(fault.fault_code, &fault); + } + // Severity INFO for a code with rows and no fault, as the store resolves it. + const auto severity_of = [&fault_by_code](const std::string & code) { + const auto found = fault_by_code.find(code); + return found != fault_by_code.end() ? found->second->severity : uint8_t{0}; + }; + + std::vector lowered; + for (const auto & code : codes) { + const size_t before = rosbag_retention_->cap_under(*previous, code, severity_of(code)); + const size_t after = rosbag_retention_->cap_under(*next, code, severity_of(code)); + if (after != 0 && (before == 0 || after < before)) { + lowered.push_back(code); + } + } + if (!lowered.empty()) { + try { + const auto outcome = rosbag_retention_->trim_to_caps(lowered); + capped_codes = lowered.size(); + cap_removed = outcome.unlink_paths.size(); + for (const auto & recording : outcome.unlink_paths) { + retention_worker_->remove_recording(recording); + } + } catch (const std::exception & e) { + failed.emplace_back("caps"); + error = e.what(); + } + } + + // A status action that became delete applies to the faults already in that status. + std::vector> actions; + for (const auto & fault : faults) { + if (codes.count(fault.fault_code) == 0) { + continue; + } + StatusChange change = StatusChange::kCleared; + if (fault.status == fd::fault_status::kHealed) { + change = StatusChange::kHealed; + } else if (fault.status != fd::fault_status::kCleared) { + continue; + } + if (!rosbag_retention_->deletes_under(*previous, change, fault.fault_code, fault.severity) && + rosbag_retention_->deletes_under(*next, change, fault.fault_code, fault.severity)) { + actions.emplace_back(change, fault.fault_code); + } + } + bool actions_failed = false; + for (const auto & [change, code] : actions) { + core::RemovalOutcome outcome; + try { + // Under the core mutex the status read again is exact: no report can change it before the removal. + core_->run_locked([&, change_of = change, code_of = code]() { + outcome = rosbag_retention_->apply_status_action_if_current(change_of, code_of); + }); + } catch (const std::exception & e) { + actions_failed = true; + error = e.what(); + continue; + } + if (outcome.deletes) { + ++acted_faults; + action_removed += outcome.unlink_paths.size(); + for (const auto & recording : outcome.unlink_paths) { + retention_worker_->remove_recording(recording); + } + } + } + if (actions_failed) { + failed.emplace_back("status actions"); + } + } + + // Only a change of a max age, the floor or the interval, or a periodic job that starts, runs the passes. + const bool periodic_before = previous->policy && previous->policy->runs_periodic(); + const bool periodic_after = next->policy && next->policy->runs_periodic(); + const bool passes_due = periodic_after && (!periodic_before || !previous->policy->same_passes(*next->policy)); + const std::optional interval = + periodic_after ? std::optional(next->policy->sweep_interval_sec()) : std::nullopt; + std::string periodic = "unchanged"; + // A failed job keeps applied_retention_, so the interval set is compared with periodic_interval_sec_. + if (passes_due || interval != periodic_interval_sec_) { + if (interval) { + // The next periodic pass one interval from now. + retention_worker_->set_periodic(std::chrono::seconds(*interval), [this]() { + run_retention_passes(); + }); + periodic = "every " + std::to_string(*interval) + " s"; + } else { + retention_worker_->clear_periodic(); + periodic = "off"; + } + periodic_interval_sec_ = interval; + } + std::vector passes; + if (passes_due) { + if (next->policy->sweeps()) { + passes.emplace_back("age sweep"); + } + if (next->policy->min_free_disk_mb() > 0) { + passes.emplace_back("floor pass"); + } + for (auto & pass : run_retention_passes()) { + failed.push_back(std::move(pass)); + } + } + + if (!failed.empty()) { + // A failed pass logged its own WARN. + RCLCPP_WARN(get_logger(), + "Rosbag retention change not applied: %s failed%s%s. The parameters keep their new values; set one " + "again to retry.", + join(failed, ", ").c_str(), error.empty() ? "" : ": ", error.c_str()); + return; + } + applied_retention_ = next; + const std::string passes_run = passes.empty() ? "none" : join(passes, ", "); + RCLCPP_INFO(get_logger(), + "Rosbag retention change applied: caps lowered for %zu fault code(s), %zu recording(s) removed; " + "status actions for %zu fault(s), %zu recording(s) removed; passes run: %s; periodic job %s", + capped_codes, cap_removed, acted_faults, action_removed, passes_run.c_str(), periodic.c_str()); +} + +std::vector FaultManagerNode::run_retention_passes() { + std::vector failed; + const auto state = rosbag_retention_->policy_state(); + if (state->policy && state->policy->sweeps() && !sweep_expired_recordings()) { + failed.emplace_back("sweep"); + } + // No recording is stored by this pass: the floor has no priority limit. + if (rosbag_capture_ && !rosbag_capture_->run_floor_pass("")) { + failed.emplace_back("floor"); + } + return failed; +} + void FaultManagerNode::configure_retention(const core::FlatParams & params) { if (params.empty()) { return; @@ -1030,7 +1307,7 @@ void FaultManagerNode::recorded_directory_found(const std::string & recording_id } } -void FaultManagerNode::sweep_expired_recordings() { +bool FaultManagerNode::sweep_expired_recordings() { // The line carries the time the pass decided with, not the time it logged. const int64_t now_ns = wall_clock_.now_ns(); auto outcome = rosbag_retention_->sweep_expired(now_ns); @@ -1038,6 +1315,7 @@ void FaultManagerNode::sweep_expired_recordings() { retention_worker_->remove_recording(recording); } RCLCPP_DEBUG(get_logger(), "retention sweep: now=%" PRId64 " removed=%zu", now_ns, outcome.removed_links); + return !outcome.failed; } void FaultManagerNode::on_confirmed(const std::string & fault_code) { @@ -1089,9 +1367,6 @@ SnapshotConfig FaultManagerNode::create_snapshot_config() { config.rosbag.max_buffer_mb = static_cast(config_.snapshots_rosbag_max_buffer_mb); config.rosbag.max_bags_per_fault = static_cast(config_.snapshots_rosbag_max_bags_per_fault); config.rosbag.auto_cleanup = config_.snapshots_rosbag_auto_cleanup; - // Valid rules only: in degrade the floor is off. - config.rosbag.min_free_disk_mb = - retention_policy_ ? static_cast(retention_policy_->min_free_disk_mb()) : uint64_t{0}; RCLCPP_INFO(get_logger(), "Rosbag capture enabled (duration=%.1fs+%.1fs, topics=%s, qos_match=%s, lazy=%s, format=%s, " diff --git a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp index 6424b95d6..2076fefc5 100644 --- a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp @@ -332,7 +332,6 @@ RosbagCapture::RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const if (!retention_ || !retention_worker_) { throw std::invalid_argument("RosbagCapture requires a retention and a retention worker"); } - floor_bytes_ = mib_to_bytes(config_.min_free_disk_mb); if (const char * capacity_file = std::getenv(kTestCapacityEnv); capacity_file != nullptr && *capacity_file != '\0') { capacity_file_ = capacity_file; RCLCPP_WARN(node_->get_logger(), @@ -1755,54 +1754,38 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, return true; } +uint64_t RosbagCapture::floor_bytes() const { + const auto state = retention_->policy_state(); + return state->policy ? mib_to_bytes(static_cast(state->policy->min_free_disk_mb())) : uint64_t{0}; +} + void RosbagCapture::post_floor_pass(const std::string & recording_id) { - if (floor_bytes_ == 0) { + if (floor_bytes() == 0) { return; } - // Without its priority the pass could delete a recording above it: none is posted, the periodic pass runs later. - try { - const int64_t priority = retention_->recording_priority(recording_id); - // The worker is drained before this capture is destroyed (see the constructor). - retention_worker_->post("floor", [this, priority, recording_id]() { - run_floor_pass(priority, recording_id); - }); - } catch (const std::exception & e) { - RCLCPP_WARN(node_->get_logger(), "No free-space pass after storing '%s': %s", recording_id.c_str(), e.what()); - } catch (...) { - RCLCPP_WARN(node_->get_logger(), "No free-space pass after storing '%s': unknown exception", recording_id.c_str()); - } + // The worker is drained before this capture is destroyed (see the constructor). + retention_worker_->post("floor", [this, recording_id]() { + run_floor_pass(recording_id); + }); } bool RosbagCapture::floor_admits_recording(const std::string & fault_code) { - if (floor_bytes_ == 0) { + const uint64_t floor = floor_bytes(); + if (floor == 0) { return true; } const auto free_bytes = measure_free_bytes(); - if (!free_bytes || *free_bytes >= floor_bytes_) { + if (!free_bytes || *free_bytes >= floor) { return true; } - int64_t priority = 0; - try { - priority = retention_->fault_priority(fault_code); - } catch (const std::exception & e) { - RCLCPP_WARN(node_->get_logger(), "Could not read fault '%s' for the min_free_disk_mb check; recording it: %s", - fault_code.c_str(), e.what()); - return true; - } catch (...) { - RCLCPP_WARN(node_->get_logger(), - "Could not read fault '%s' for the min_free_disk_mb check; recording it: unknown exception", - fault_code.c_str()); - return true; - } - if (retention_->has_space_candidate(priority)) { + if (retention_->has_space_candidate_for_fault(fault_code)) { return true; } RCLCPP_INFO(node_->get_logger(), "Not recording fault '%s': the free space under the storage path is %llu bytes, below " - "snapshots.rosbag.retention.min_free_disk_mb (%llu bytes), and no recording of priority %lld or lower " + "snapshots.rosbag.retention.min_free_disk_mb (%llu bytes), and no recording of its priority or lower " "can be deleted; the buffered history stays for the next fault", - fault_code.c_str(), static_cast(*free_bytes), - static_cast(floor_bytes_), static_cast(priority)); + fault_code.c_str(), static_cast(*free_bytes), static_cast(floor)); return false; } @@ -1843,17 +1826,21 @@ std::optional RosbagCapture::measure_free_bytes() const { return static_cast(space.available); } -void RosbagCapture::run_floor_pass(int64_t priority_limit, const std::string & new_recording_id) { - if (floor_bytes_ == 0) { - return; +bool RosbagCapture::run_floor_pass(const std::string & new_recording_id) { + // One snapshot for the whole pass. + const uint64_t floor = floor_bytes(); + if (floor == 0) { + return true; } // Measured after each removal, never estimated: the listed size of a recording is not what deleting it frees. size_t removed = 0; bool exhausted = false; + bool step_failed = false; auto free_bytes = measure_free_bytes(); - while (free_bytes && *free_bytes < floor_bytes_) { - const auto step = retention_->evict_one_for_space(priority_limit, new_recording_id); + while (free_bytes && *free_bytes < floor) { + const auto step = retention_->evict_one_for_space(new_recording_id); if (step.result == core::SpaceStep::Result::kFailed) { + step_failed = true; break; // the step logged its WARN } if (step.result == core::SpaceStep::Result::kNoCandidate) { @@ -1875,28 +1862,29 @@ void RosbagCapture::run_floor_pass(int64_t priority_limit, const std::string & n "bytes free, the floor is %llu bytes). It could not be removed (%s); the directory stays, " "unreachable and uncounted", freed->path.c_str(), bytes, static_cast(*free_bytes), - static_cast(floor_bytes_), ec.message().c_str()); + static_cast(floor), ec.message().c_str()); } else { RCLCPP_WARN(node_->get_logger(), "Recording '%s' (%zu bytes) dropped, it does not fit snapshots.rosbag.retention.min_free_disk_mb " "(%llu bytes free, the floor is %llu bytes): no recording of the same or a lower priority is left", freed->path.c_str(), bytes, static_cast(*free_bytes), - static_cast(floor_bytes_)); + static_cast(floor)); } } free_bytes = measure_free_bytes(); } - const bool met = free_bytes && *free_bytes >= floor_bytes_; + const bool met = free_bytes && *free_bytes >= floor; if (exhausted) { RCLCPP_WARN(node_->get_logger(), "Rosbag free-space pass stopped below snapshots.rosbag.retention.min_free_disk_mb (%llu bytes) with " "%llu bytes free: no recording that this pass may delete is left", - static_cast(floor_bytes_), static_cast(*free_bytes)); + static_cast(floor), static_cast(*free_bytes)); } const std::string free_text = free_bytes ? std::to_string(*free_bytes) : "unknown"; RCLCPP_DEBUG(node_->get_logger(), "floor pass: removed=%zu free=%s floor=%llu met=%s source=%s", removed, - free_text.c_str(), static_cast(floor_bytes_), met ? "true" : "false", + free_text.c_str(), static_cast(floor), met ? "true" : "false", capacity_file_.empty() ? "filesystem" : "test-capacity"); + return !step_failed && free_bytes.has_value(); } void RosbagCapture::arm_post_fault_timer() { 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 421b4fdca..46a2061ff 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 @@ -34,7 +34,9 @@ from ament_index_python.packages import get_package_prefix from rcl_interfaces.msg import ParameterType -from rcl_interfaces.srv import DescribeParameters, GetParameters, SetParameters +from rcl_interfaces.srv import ( + DescribeParameters, GetParameters, SetParameters, SetParametersAtomically, +) import rclpy from rclpy.duration import Duration from rclpy.node import Node @@ -273,6 +275,7 @@ def wait_for_services(self): (GetParameters, 'get_parameters'), (DescribeParameters, 'describe_parameters'), (SetParameters, 'set_parameters'), + (SetParametersAtomically, 'set_parameters_atomically'), (ListFaultsForEntity, 'list_faults_for_entity')): client = self._client(srv_type, name) if not client.wait_for_service(timeout_sec=SERVICE_TIMEOUT_SEC): diff --git a/src/ros2_medkit_fault_manager/test/integration/test_retention_config.test.py b/src/ros2_medkit_fault_manager/test/integration/test_retention_config.test.py index b151b8efc..df59936c3 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_retention_config.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_retention_config.test.py @@ -33,12 +33,14 @@ import launch_testing.actions import launch_testing.util from rcl_interfaces.msg import Parameter, ParameterType, ParameterValue -from rcl_interfaces.srv import DescribeParameters, GetParameters, SetParameters +from rcl_interfaces.srv import ( + DescribeParameters, GetParameters, SetParameters, SetParametersAtomically, +) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from rosbag_fm_harness import ( # noqa: E402 - base_params, FaultManager, PAYLOAD_TOPIC, poll, RetentionCase, + base_params, FaultManager, PAYLOAD_TOPIC, poll, RetentionCase, rules, running_fault_manager, sqlite_rows, Ticker, ) import yaml # noqa: E402 @@ -643,7 +645,8 @@ def test_rosbag_disabled_warns(self): self.assertEqual(self.own_faults(), []) self.assertEqual(fm.count_lines(POLICY_LINE), 0) - def test_retention_params_read_only(self): + def test_retention_params_writable(self): + """Retention parameters are dynamically typed and writable; an invalid value is refused.""" retention = {'patterns': {'p': {'match': 'A.*'}}, 'pattern_order': ['p']} scalar = 'snapshots.rosbag.retention.defaults.priority' order = 'snapshots.rosbag.retention.pattern_order' @@ -657,7 +660,7 @@ def test_retention_params_read_only(self): DescribeParameters, 'describe_parameters', request).descriptors self.assertEqual([d.name for d in described], [scalar, order]) for descriptor in described: - self.assertTrue(descriptor.read_only, descriptor.name) + self.assertFalse(descriptor.read_only, descriptor.name) self.assertTrue(descriptor.dynamic_typing, descriptor.name) self.assertEqual(described[0].type, ParameterType.PARAMETER_INTEGER) self.assertEqual(described[1].type, ParameterType.PARAMETER_STRING_ARRAY) @@ -672,4 +675,52 @@ def test_retention_params_read_only(self): put.parameters = [Parameter(name=scalar, value=ParameterValue( type=ParameterType.PARAMETER_INTEGER, integer_value=8))] result = self.client.call_node_service(SetParameters, 'set_parameters', put) + self.assertTrue(result.results[0].successful, result.results[0].reason) + + put.parameters = [Parameter(name=scalar, value=ParameterValue( + type=ParameterType.PARAMETER_INTEGER, integer_value=-1))] + result = self.client.call_node_service(SetParameters, 'set_parameters', put) self.assertFalse(result.results[0].successful) + self.assertIn(scalar, result.results[0].reason) + values = self.client.call_node_service(GetParameters, 'get_parameters', get).values + self.assertEqual(values[0].integer_value, 8) + + def test_mixed_set_is_refused(self): + """An atomic set mixing retention and other names is refused; a retention set applies.""" + priority = 'snapshots.rosbag.retention.defaults.priority' + interval = 'snapshots.rosbag.retention.sweep_interval_sec' + + def integer(name, value): + return Parameter(name=name, value=ParameterValue( + type=ParameterType.PARAMETER_INTEGER, integer_value=value)) + + get = GetParameters.Request() + get.names = [priority, interval] + with self.fm_run(**rules({'defaults.priority': 7, 'sweep_interval_sec': 60})) as fm: + self.assert_rules_valid(fm) + mark = fm.mark() + mixed = SetParametersAtomically.Request() + mixed.parameters = [ + Parameter(name='use_sim_time', value=ParameterValue( + type=ParameterType.PARAMETER_BOOL, bool_value=False)), + integer(priority, 9)] + result = self.client.call_node_service( + SetParametersAtomically, 'set_parameters_atomically', mixed).result + self.assertFalse(result.successful, 'a mixed set was applied') + self.assertIn('set the retention parameters on their own', result.reason) + self.assertNotIn('read-only', result.reason) + self.assertNotIn('read only', result.reason) + values = self.client.call_node_service(GetParameters, 'get_parameters', get).values + self.assertEqual([values[0].integer_value, values[1].integer_value], [7, 60]) + + alone = SetParametersAtomically.Request() + alone.parameters = [integer(priority, 9), integer(interval, 30)] + result = self.client.call_node_service( + SetParametersAtomically, 'set_parameters_atomically', alone).result + self.assertTrue(result.successful, result.reason) + values = self.client.call_node_service(GetParameters, 'get_parameters', get).values + self.assertEqual([values[0].integer_value, values[1].integer_value], [9, 30]) + changed = fm.wait_line(r'Rosbag retention rules changed \(configured\)', since=mark) + self.assertIsNotNone(changed, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(r'Rosbag retention rules changed', since=mark), 1, + fm.output()[-3000:]) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_retention_runtime_pg.test.py b/src/ros2_medkit_fault_manager/test/integration/test_retention_runtime_pg.test.py new file mode 100644 index 000000000..7babe2698 --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/test_retention_runtime_pg.test.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +A retention change the fault manager cannot apply while its PostgreSQL server is unreachable. + +A TCP proxy owned by the test sits between the fault manager and the server. The test records three +recordings of one fault, closes the proxy and, in one atomic request, lowers the fault's max_bags +and sets a max age: the change is accepted, its age sweep logs its own WARN, the change logs one +summary WARN, and nothing is removed. Once the proxy is open again, the same values set again apply +the cap. ROS2_MEDKIT_TEST_PG_CONN names the server, as +`postgresql://user:password@host:port/database`; the test creates its own database. +""" + +import os +import pathlib +import re +import socket +import sys +import threading +import urllib.parse +import uuid + +from launch import LaunchDescription +import launch_testing +import launch_testing.actions +import launch_testing.util +import psycopg2 +from rcl_interfaces.msg import Parameter, ParameterType, ParameterValue +from rcl_interfaces.srv import SetParametersAtomically + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rosbag_fm_harness import poll, RetentionCase, rules # noqa: E402 + +CAP_KEY = 'snapshots.rosbag.retention.fault_codes.CAPPED.max_bags' +AGE_KEY = 'snapshots.rosbag.retention.fault_codes.CAPPED.max_age_sec.cleared' +# A changed max age runs the age sweep. CAPPED is active then: its cleared max age removes nothing. +CHANGE = {CAP_KEY: 2, AGE_KEY: 86400} +NOT_APPLIED = r'\[WARN\].*Rosbag retention change not applied: (.*?) failed' +SWEEP_WARN = r'\[WARN\].*Rosbag age sweep could not read the storage' +APPLIED = r'\[INFO\].*Rosbag retention change applied' +CAP_REMOVAL = r'Recording removed: (\S+) \(its max_bags\)' + + +def generate_test_description(): + return LaunchDescription([launch_testing.util.KeepAliveProc(), + launch_testing.actions.ReadyToTest()]), {} + + +class TcpProxy: + """Forward connections while open; while closed, refuse new ones and cut the open ones.""" + + def __init__(self, target_host, target_port): + self._target = (target_host, target_port) + self._lock = threading.Lock() + self._listener = None + self._sockets = [] + probe = socket.socket() + probe.bind(('127.0.0.1', 0)) + self.port = probe.getsockname()[1] + probe.close() + + def accept_connections(self): + listener = socket.socket() + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(('127.0.0.1', self.port)) + listener.listen() + with self._lock: + self._listener = listener + threading.Thread(target=self._accept, args=(listener,), daemon=True).start() + + def refuse_connections(self): + with self._lock: + listener, self._listener = self._listener, None + sockets, self._sockets = self._sockets, [] + if listener is not None: + # A shutdown wakes the thread blocked in accept(); a close alone keeps listening. + try: + listener.shutdown(socket.SHUT_RDWR) + except OSError: + pass + listener.close() + for sock in sockets: + for call in (lambda s=sock: s.shutdown(socket.SHUT_RDWR), sock.close): + try: + call() + except OSError: + pass + + def _accept(self, listener): + while True: + try: + client, _ = listener.accept() + upstream = socket.create_connection(self._target) + except OSError: + return + with self._lock: + self._sockets += [client, upstream] + for source, sink in ((client, upstream), (upstream, client)): + threading.Thread(target=self._pipe, args=(source, sink), daemon=True).start() + + @staticmethod + def _pipe(source, sink): + try: + while True: + data = source.recv(65536) + if not data: + break + sink.sendall(data) + except OSError: + pass + for sock in (source, sink): + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + +class TestRetentionRuntimePostgres(RetentionCase): + + def setUp(self): + super().setUp() + base = os.environ.get('ROS2_MEDKIT_TEST_PG_CONN') + self.assertTrue(base, 'ROS2_MEDKIT_TEST_PG_CONN is not set') + self.database = 'retention_runtime_' + uuid.uuid4().hex[:12] + self._admin(base, 'CREATE DATABASE ' + self.database) + self.addCleanup(self._admin, base, f'DROP DATABASE IF EXISTS {self.database} WITH (FORCE)') + parts = urllib.parse.urlsplit(base) + self.proxy = TcpProxy(parts.hostname, parts.port or 5432) + self.addCleanup(self.proxy.refuse_connections) + netloc = f'{parts.username}:{parts.password}@127.0.0.1:{self.proxy.port}' + self.url = urllib.parse.urlunsplit(parts._replace(netloc=netloc, path='/' + self.database)) + self.direct_url = urllib.parse.urlunsplit(parts._replace(path='/' + self.database)) + + @staticmethod + def _admin(url, statement): + conn = psycopg2.connect(url) + try: + conn.autocommit = True + with conn.cursor() as cur: + cur.execute(statement) + finally: + conn.close() + + def storage_params(self): + return {'storage_type': 'postgres', 'database_url': self.url} + + def stored_rows(self): + """Return (fault_code, file_path) of every rosbag row, read past the proxy.""" + conn = psycopg2.connect(self.direct_url) + try: + with conn.cursor() as cur: + cur.execute('SELECT fault_code, file_path FROM rosbag_files ORDER BY id') + return cur.fetchall() + finally: + conn.close() + + def set_change(self): + """Set CHANGE in one request: one change job applies both values.""" + request = SetParametersAtomically.Request() + request.parameters = [ + Parameter(name=key, value=ParameterValue(type=ParameterType.PARAMETER_INTEGER, + integer_value=value)) + for key, value in CHANGE.items()] + result = self.client.call_node_service(SetParametersAtomically, + 'set_parameters_atomically', request).result + self.assertTrue(result.successful, result.reason) + + def test_failed_apply_changes_nothing_and_the_same_value_applies(self): + self.proxy.accept_connections() + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.auto_cleanup': False, + **rules({'fault_codes.CAPPED.max_bags': 4, + 'fault_codes.CAPPED.max_age_sec.cleared': 0})}) as fm: + self.assert_rules_valid(fm) + paths = self.record_cycle(fm, 'CAPPED', 3) + stored = sorted(self.stored_rows()) + self.assertEqual(stored, sorted(('CAPPED', path) for path in paths)) + + self.proxy.refuse_connections() + mark = fm.mark() + self.set_change() + failed, at = fm.wait_line_at(NOT_APPLIED, since=mark) + self.assertIsNotNone(failed, fm.output()[-3000:]) + self.assertEqual(failed.group(1), 'caps, status actions, sweep', failed.string) + # The sweep logs its own WARN, the change one summary WARN. The storage logs its + # reconnection WARNs under its own logger. + warnings = [line for line in fm.lines_between(mark, at + 1) + if line.startswith('[WARN]') and '[fault_manager]:' in line] + self.assertEqual(len(warnings), 2, warnings) + self.assertTrue(re.search(SWEEP_WARN, warnings[0]), warnings) + self.assertEqual(fm.count_lines(NOT_APPLIED, since=mark), 1, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(APPLIED, since=mark), 0, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(CAP_REMOVAL, since=mark), 0, fm.output()[-3000:]) + self.assertEqual(sorted(self.stored_rows()), stored) + for path in paths: + self.assertTrue(os.path.isdir(path), path) + + self.proxy.accept_connections() + # The storage connects again after its backoff; the listing answers once it has. + self.assertTrue(poll(lambda: self.client.list_rosbags(all_recordings=True).success, + interval=0.5), 'the storage never came back') + mark = fm.mark() + self.set_change() + removed, at = fm.wait_line_at(CAP_REMOVAL, since=mark) + self.assertIsNotNone(removed, fm.output()[-3000:]) + self.assertEqual(removed.group(1), os.path.basename(paths[0])) + self.assertIsNotNone(fm.wait_line(APPLIED, since=at), fm.output()[-3000:]) + self.assertEqual(sorted(self.stored_rows()), + sorted(('CAPPED', path) for path in paths[1:])) + self.assertFalse(os.path.exists(paths[0]), paths[0]) 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 5a3f26b8c..4cf420647 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 @@ -31,6 +31,8 @@ import launch_testing import launch_testing.actions import launch_testing.util +from rcl_interfaces.msg import Parameter, ParameterType, ParameterValue +from rcl_interfaces.srv import SetParameters sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) @@ -45,6 +47,8 @@ # How far back the age case moves the last FAILED report of its fault. LONG_AGO_NS = 3600 * NS_PER_SEC CAP_REMOVAL = r'Recording removed: (\S+) \(its max_bags\)' +APPLIED = (r'\[INFO\].*Rosbag retention change applied: caps lowered for (\d+) fault code\(s\), ' + r'(\d+) recording') QUOTA_OVER_PROTECTED = (r"Recording '(\S+)' is kept over snapshots\.rosbag\.max_total_storage_mb " r'\((\d+) MB\): (\d+) bytes of the total are recordings of the ' r'unavailable storage path') @@ -287,6 +291,36 @@ def test_keep_first_counts_only_unprotected_recordings(self): self.assertEqual(sorted(self.row_paths('KEEPER')), sorted([old, fresh[0], fresh[2]])) self.assertFalse(os.path.exists(fresh[1])) + def test_cap_change_trims_only_unprotected(self): + (old,), rows = self.start_unavailable(('TRIMMED',)) + with self.fm_run(**rules({'fault_codes.TRIMMED.max_bags': 2, + 'fault_codes.TRIMMED.on_cleared': 'keep'})) as fm: + self.assert_started_unavailable(fm, rows) + fresh = [] + for _ in range(2): + # A new recording needs a new confirmation. + self.assertTrue(self.client.clear('TRIMMED').success) + fresh.append(self.record(fm, 'TRIMMED', 0.25)) + self.assertEqual(sorted(self.row_paths('TRIMMED')), sorted([old] + fresh)) + mark = fm.mark() + request = SetParameters.Request() + request.parameters = [Parameter( + name='snapshots.rosbag.retention.fault_codes.TRIMMED.max_bags', + value=ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=1))] + result = self.client.call_node_service(SetParameters, 'set_parameters', + request).results[0] + self.assertTrue(result.successful, result.reason) + applied = fm.wait_line(APPLIED, since=mark) + self.assertIsNotNone(applied, fm.output()[-3000:]) + self.assertEqual(applied.groups(), ('1', '1'), applied.string) + removed = fm.wait_line(CAP_REMOVAL, since=mark) + self.assertIsNotNone(removed, fm.output()[-3000:]) + self.assertEqual(removed.group(1), os.path.basename(fresh[0])) + self.assertEqual(sorted(self.row_paths('TRIMMED')), sorted([old, fresh[1]])) + self.assertFalse(os.path.exists(fresh[0])) + self.assertTrue(os.path.isdir(fresh[1])) + self.assertEqual(self.storage_fault_statuses(), ['CONFIRMED']) + def test_floor_ranks_keep_first_among_unprotected(self): (old,), rows = self.start_unavailable(('KEEPER',)) # Free space is the capacity less the files under the storage path: two 1 MiB recordings diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp index 3d341d317..887e17d08 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp @@ -3478,16 +3478,21 @@ TEST(RosbagCapture, FloorPassWarnsOnceWhenTheStepFails) { RosbagConfig config; config.enabled = false; // no ring buffer: only the floor pass runs config.storage_path = dir.string(); - config.min_free_disk_mb = uint64_t{1} << 40; // far above any disk: the floor is never met auto worker = std::make_shared(test_log_sink(), "test_rosbag_capture", RetentionWorker::Mode::kInline); auto retention = std::make_shared(storage, RosbagRetentionLimits{}, test_log_sink(), "test_rosbag_capture"); + ros2_medkit_fault_manager::core::FlatParams params; + params["min_free_disk_mb"] = int64_t{1} << 40; // far above any disk: the floor is never met + auto parsed = ros2_medkit_fault_manager::core::RetentionPolicy::parse(params); + ASSERT_TRUE(parsed.errors.empty()); + retention->set_policy(ros2_medkit_fault_manager::core::RetentionMode::kConfigured, + std::make_shared(*parsed.policy)); { RosbagCapture capture(node.get(), &storage, config, SnapshotConfig{}, retention, worker); LogCapture logs; worker->post("floor", [&capture]() { - capture.run_floor_pass(std::numeric_limits::max(), ""); + capture.run_floor_pass(""); }); EXPECT_EQ(storage.removals_in_doubt, 1); EXPECT_EQ(logs.count_at(RCUTILS_LOG_SEVERITY_WARN), 1) << "the pass logs one WARN in all"; diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp index b074a751a..3b87d096d 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp @@ -13,6 +13,7 @@ // limitations under the License. #include +#include #include #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -52,6 +54,7 @@ using ros2_medkit_fault_manager::core::RetentionMode; using ros2_medkit_fault_manager::core::RetentionPolicy; using ros2_medkit_fault_manager::core::RosbagRetention; using ros2_medkit_fault_manager::core::RosbagRetentionLimits; +using ros2_medkit_fault_manager::core::SpaceStep; using ros2_medkit_fault_manager::core::StoreResult; constexpr const char * kLogger = "test_rosbag_retention"; @@ -268,6 +271,17 @@ class CapturingLogSink : public ros2_medkit_fault_manager::core::LogSink { std::mutex mutex_; }; +/// A configured policy that sets the priority of each fault code. +std::shared_ptr policy_with_priorities(const std::map & priorities) { + ros2_medkit_fault_manager::core::FlatParams params; + for (const auto & [code, priority] : priorities) { + params["fault_codes." + code + ".priority"] = priority; + } + auto parsed = RetentionPolicy::parse(params); + EXPECT_TRUE(parsed.errors.empty()); + return std::make_shared(std::move(*parsed.policy)); +} + std::shared_ptr policy_with_over_quota(const std::string & over_quota) { ros2_medkit_fault_manager::core::FlatParams params; params["defaults.priority"] = int64_t{10}; @@ -665,6 +679,67 @@ TEST_F(RosbagRetentionStore, KeepFirstSurvivesAnUpsertOfTheFirstLink) { EXPECT_EQ(paths_of(outcome.unlink_paths), std::vector{middle.file_path}); } +TEST_F(RosbagRetentionStore, FloorStepDecidesWithOnePolicy) { + // In process: a rules change between the reads of one step cannot be forced in a real fault manager. The gate holds + // the step at its first fault read while the test publishes new rules. + GatedFaultReadStorage storage((dir_ / "faults.db").string(), test_log_sink()); + for (const std::string code : {"OLD_CODE", "NEW_CODE"}) { + storage.report_fault_event(code, fd::ReportKind::kFailed, kSeverityError, "floor", "/node", 1000, DebounceConfig{}); + } + const auto old_bag = row("OLD_CODE", "fault_OLD_CODE_1", 1000); + const auto new_bag = row("NEW_CODE", "fault_NEW_CODE_2", 2000); + seed_rosbag_rows(storage, {old_bag, new_bag}); + RosbagRetention retention(storage, limits(0), test_log_sink(), kLogger); + // First rules: only the new recording is at or below its own priority, so it goes as the last resort. + retention.set_policy(RetentionMode::kConfigured, policy_with_priorities({{"NEW_CODE", 5}, {"OLD_CODE", 10}})); + // Second rules: the old recording is below the new one and goes first. + const auto second = policy_with_priorities({{"NEW_CODE", 20}, {"OLD_CODE", 10}}); + + storage.arm(); + auto stepped = std::async(std::launch::async, [&retention, &new_bag]() { + return retention.evict_one_for_space(new_bag.recording_id); + }); + GateRelease release(storage); + ASSERT_TRUE(storage.wait_entered(std::chrono::seconds(10))) << "the step never read a fault"; + retention.set_policy(RetentionMode::kConfigured, second); + storage.release(); + const SpaceStep step = stepped.get(); + + // The limit of the first rules with the order of the second removes nothing. + ASSERT_EQ(step.result, SpaceStep::Result::kRemoved) << "the step mixed the limit and the order of two policies"; + ASSERT_TRUE(step.recording.has_value()); + const std::string removed = step.recording->recording_id; + EXPECT_TRUE(removed == new_bag.recording_id || removed == old_bag.recording_id) << removed; + const auto rows = storage.get_all_rosbag_files(); + ASSERT_EQ(rows.size(), 1u); + EXPECT_NE(rows.front().recording_id, removed); +} + +TEST_F(RosbagRetentionStore, OpenTimeFloorCheckDecidesWithOnePolicy) { + // In process, as FloorStepDecidesWithOnePolicy: the gate holds the check at the read of the new fault. + GatedFaultReadStorage storage((dir_ / "faults.db").string(), test_log_sink()); + for (const std::string code : {"STORED_CODE", "OPENING_CODE"}) { + storage.report_fault_event(code, fd::ReportKind::kFailed, kSeverityError, "floor", "/node", 1000, DebounceConfig{}); + } + seed_rosbag_rows(storage, {row("STORED_CODE", "fault_STORED_CODE_1", 1000)}); + RosbagRetention retention(storage, limits(0), test_log_sink(), kLogger); + // Under both rules the stored recording is below the opening fault: both answer true. + retention.set_policy(RetentionMode::kConfigured, policy_with_priorities({{"OPENING_CODE", 5}, {"STORED_CODE", 3}})); + const auto second = policy_with_priorities({{"OPENING_CODE", 20}, {"STORED_CODE", 10}}); + + storage.arm(); + auto checked = std::async(std::launch::async, [&retention]() { + return retention.has_space_candidate_for_fault("OPENING_CODE"); + }); + GateRelease release(storage); + ASSERT_TRUE(storage.wait_entered(std::chrono::seconds(10))) << "the check never read the fault"; + retention.set_policy(RetentionMode::kConfigured, second); + storage.release(); + + // The priority of the first rules with the order of the second finds no candidate. + EXPECT_TRUE(checked.get()) << "the check mixed the priority and the order of two policies"; +} + TEST(RosbagRetention, RecordingPrioritiesReadsDoNotGrowWithRecordings) { // The read count is not observable outside the process: one list call must not cost one // storage transaction per recording. @@ -728,6 +803,57 @@ TEST(RosbagRetention, RecordingPrioritiesReadsDoNotGrowWithRecordings) { EXPECT_GT(one, 0u); } +TEST(RosbagRetention, StatusActionSkipsAFaultActiveAgain) { + // In process: a FAILED report between the job's listing and its action cannot be forced in a + // real fault manager. The action re-reads the fault and acts only while it is still CLEARED. + const auto dir = std::filesystem::temp_directory_path() / ("medkit_status_action_" + std::to_string(::getpid())); + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir / "fault_AGAIN_1"); + SqliteFaultStorage storage((dir / "faults.db").string(), test_log_sink()); + storage.report_fault_event("AGAIN", fd::ReportKind::kFailed, kSeverityError, "again", "/node", 1000, + DebounceConfig{}); + ASSERT_TRUE(storage.clear_fault("AGAIN")); + RosbagFileInfo bag; + bag.fault_code = "AGAIN"; + bag.file_path = (dir / "fault_AGAIN_1").string(); + bag.recording_id = "fault_AGAIN_1"; + bag.format = "mcap"; + bag.size_bytes = 1024; + bag.created_at_ns = 1000; + seed_rosbag_rows(storage, {bag}); + ros2_medkit_fault_manager::core::FlatParams params; + params["fault_codes.AGAIN.on_cleared"] = std::string("delete"); + auto parsed = RetentionPolicy::parse(params); + ASSERT_TRUE(parsed.errors.empty()); + RosbagRetentionLimits no_cap; + no_cap.max_bags_per_fault = 0; + RosbagRetention retention(storage, no_cap, test_log_sink(), kLogger); + retention.set_policy(RetentionMode::kConfigured, std::make_shared(std::move(*parsed.policy))); + + // Listed as CLEARED by the job, then CONFIRMED again before its action. + storage.report_fault_event("AGAIN", fd::ReportKind::kFailed, kSeverityError, "again", "/node", 2000, + DebounceConfig{}); + ASSERT_EQ(storage.get_fault("AGAIN")->status, fd::fault_status::kConfirmed); + const uint64_t generation = retention.delete_generation("AGAIN"); + const auto skipped = retention.apply_status_action_if_current(RosbagRetention::StatusChange::kCleared, "AGAIN"); + EXPECT_FALSE(skipped.deletes); + EXPECT_EQ(skipped.removed_rows, 0u); + EXPECT_TRUE(skipped.unlink_paths.empty()); + EXPECT_EQ(retention.delete_generation("AGAIN"), generation) << "the generation advanced for an active fault"; + EXPECT_EQ(storage.get_rosbag_files("AGAIN").size(), 1u) << "the recording of an active fault was removed"; + + // Cleared again: the same call acts. + ASSERT_TRUE(storage.clear_fault("AGAIN")); + const auto applied = retention.apply_status_action_if_current(RosbagRetention::StatusChange::kCleared, "AGAIN"); + EXPECT_TRUE(applied.deletes); + EXPECT_EQ(applied.removed_rows, 1u); + EXPECT_EQ(paths_of(applied.unlink_paths), std::vector{bag.file_path}); + EXPECT_EQ(retention.delete_generation("AGAIN"), generation + 1); + EXPECT_TRUE(storage.get_rosbag_files("AGAIN").empty()); + std::error_code ec; + std::filesystem::remove_all(dir, ec); +} + TEST(RetentionAge, SaturatesAndNeverNegative) { constexpr int64_t kMax = std::numeric_limits::max(); constexpr int64_t kMin = std::numeric_limits::min(); diff --git a/src/ros2_medkit_gateway/README.md b/src/ros2_medkit_gateway/README.md index d1b286da6..29d8da07a 100644 --- a/src/ros2_medkit_gateway/README.md +++ b/src/ros2_medkit_gateway/README.md @@ -64,6 +64,12 @@ All endpoints are prefixed with `/api/v1` for API versioning. - `DELETE /api/v1/components/{component_id}/configurations/{param}` - Reset parameter to default value - `DELETE /api/v1/components/{component_id}/configurations` - Reset all parameters to default values +A `PUT` converts the JSON value to the type of the parameter's current value, except for a parameter whose +descriptor allows dynamic typing: that one gets the JSON's own type, so the node validates what the client sent. +A rejection answers 403 only when the descriptor says read-only, else 400 with the node's reason; without a +readable descriptor a reason that says "read-only" answers 403. The same holds for the gateway's own parameters +(`/apps/ros2_medkit_gateway/configurations`), such as the read-only `plugins..path`. + ### Bulk Data Endpoints - `GET /api/v1/{entity}/{id}/bulk-data` - List bulk-data categories (configured, plus `rosbags` when the fault manager serves them) diff --git a/src/ros2_medkit_gateway/src/ros2/transports/ros2_parameter_transport.cpp b/src/ros2_medkit_gateway/src/ros2/transports/ros2_parameter_transport.cpp index 878521c57..d1856cbf0 100644 --- a/src/ros2_medkit_gateway/src/ros2/transports/ros2_parameter_transport.cpp +++ b/src/ros2_medkit_gateway/src/ros2/transports/ros2_parameter_transport.cpp @@ -23,6 +23,26 @@ using namespace std::chrono_literals; namespace ros2_medkit_gateway::ros2 { +namespace { + +/// The code of a rejection by a node that answered. A described parameter is read-only only by its descriptor: a +/// reason may quote a name or a value that contains the words. +ParameterErrorCode rejection_code(const std::string & reason, + const std::optional & descriptor) { + const bool read_only_text = reason.find("read-only") != std::string::npos || + reason.find("read only") != std::string::npos || + reason.find("is read_only") != std::string::npos; + if (descriptor ? descriptor->read_only : read_only_text) { + return ParameterErrorCode::READ_ONLY; + } + if (reason.find("type") != std::string::npos) { + return ParameterErrorCode::TYPE_MISMATCH; + } + return ParameterErrorCode::INVALID_VALUE; +} + +} // namespace + Ros2ParameterTransport::Ros2ParameterTransport(rclcpp::Node * node, double service_timeout_sec, double negative_cache_ttl_sec, std::size_t client_cache_size, std::size_t defaults_cache_size, const std::string & client_node_name) @@ -636,6 +656,10 @@ ParameterResult Ros2ParameterTransport::set_parameter(const std::string & node_n return result; } auto current_value = node_->get_parameter(param_name).get_parameter_value(); + const rcl_interfaces::msg::ParameterDescriptor descriptor = node_->describe_parameter(param_name); + // A dynamically typed parameter takes the JSON's own type, as on a remote node. + const rclcpp::ParameterType hint_type = + descriptor.dynamic_typing ? rclcpp::ParameterType::PARAMETER_NOT_SET : current_value.get_type(); // Conversion runs in its own try so a value the CLIENT sent that cannot // become this parameter's type reports as INVALID_VALUE (400), not as the // INTERNAL_ERROR (500) the outer catch would give it. A heterogeneous @@ -644,7 +668,7 @@ ParameterResult Ros2ParameterTransport::set_parameter(const std::string & node_n // fault. rclcpp::ParameterValue param_value; try { - param_value = json_to_parameter_value(value, current_value.get_type()); + param_value = json_to_parameter_value(value, hint_type); } catch (const std::exception & e) { result.success = false; result.error_message = "Value cannot be converted for parameter '" + param_name + "': " + e.what(); @@ -655,7 +679,7 @@ ParameterResult Ros2ParameterTransport::set_parameter(const std::string & node_n if (!set_result.successful) { result.success = false; result.error_message = set_result.reason; - result.error_code = ParameterErrorCode::INVALID_VALUE; + result.error_code = rejection_code(set_result.reason, descriptor); return result; } json param_obj; @@ -725,8 +749,24 @@ ParameterResult Ros2ParameterTransport::set_parameter(const std::string & node_n param_name.c_str(), node_name.c_str()); } } + // The descriptor, best-effort like the pre-read: a failed or empty describe leaves the conversion and the + // rejection classification as they are without it. + std::optional descriptor; + { + auto describe_future = client->describe_parameters({param_name}); + if (spin_for(describe_future) == rclcpp::FutureReturnCode::SUCCESS) { + const auto & descriptors = describe_future.get(); + if (!descriptors.empty()) { + descriptor = descriptors[0]; + } + } else if (node_) { + RCLCPP_DEBUG(node_->get_logger(), "Describe of '%s' on node '%s' did not complete (continuing without it)", + param_name.c_str(), node_name.c_str()); + } + } rclcpp::ParameterType hint_type = rclcpp::ParameterType::PARAMETER_NOT_SET; - if (!current_params.empty()) { + // A dynamically typed parameter takes the JSON's own type, so the node validates what the client sent. + if (!current_params.empty() && !(descriptor && descriptor->dynamic_typing)) { hint_type = current_params[0].get_type(); } @@ -784,19 +824,10 @@ ParameterResult Ros2ParameterTransport::set_parameter(const std::string & node_n } if (!results[0].successful) { - // Legitimate rejection by a RESPONSIVE node (read-only / type / invalid value): - // classify by reason, NOT a timeout. + // Legitimate rejection by a RESPONSIVE node (read-only / type / invalid value), NOT a timeout. result.success = false; result.error_message = results[0].reason; - const auto & reason = results[0].reason; - if (reason.find("read-only") != std::string::npos || reason.find("read only") != std::string::npos || - reason.find("is read_only") != std::string::npos) { - result.error_code = ParameterErrorCode::READ_ONLY; - } else if (reason.find("type") != std::string::npos) { - result.error_code = ParameterErrorCode::TYPE_MISMATCH; - } else { - result.error_code = ParameterErrorCode::INVALID_VALUE; - } + result.error_code = rejection_code(results[0].reason, descriptor); return result; } diff --git a/src/ros2_medkit_integration_tests/CMakeLists.txt b/src/ros2_medkit_integration_tests/CMakeLists.txt index b0aea65fb..e2a887634 100644 --- a/src/ros2_medkit_integration_tests/CMakeLists.txt +++ b/src/ros2_medkit_integration_tests/CMakeLists.txt @@ -416,7 +416,9 @@ if(BUILD_TESTING) test_token_semantics 300 test_renamed_peer_entity_forwarding 300 test_peer_stand_in_forwarding 300 - test_grouping_forwarded_goal_routing 300) + test_grouping_forwarded_goal_routing 300 + # Four fault managers start one after another, and the free-space case records 24 MiB. + test_retention_runtime 300) # Names actually matched against a discovered test_name in the two loops # below. Checked against _MEDKIT_TEST_TIMEOUT_OVERRIDES itself after both # loops finish - see the FATAL_ERROR check at the end of this block - so a diff --git a/src/ros2_medkit_integration_tests/package.xml b/src/ros2_medkit_integration_tests/package.xml index 5c4cd928d..f33db7247 100644 --- a/src/ros2_medkit_integration_tests/package.xml +++ b/src/ros2_medkit_integration_tests/package.xml @@ -39,6 +39,7 @@ rosidl_typesupport_cpp python3-requests python3-jsonschema + python3-yaml ament_cmake_flake8 ros2_medkit_gateway ros2_medkit_fault_manager diff --git a/src/ros2_medkit_integration_tests/ros2_medkit_test_utils/fault_manager_process.py b/src/ros2_medkit_integration_tests/ros2_medkit_test_utils/fault_manager_process.py new file mode 100644 index 000000000..de5898e74 --- /dev/null +++ b/src/ros2_medkit_integration_tests/ros2_medkit_test_utils/fault_manager_process.py @@ -0,0 +1,212 @@ +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""A fault_manager_node process a test starts itself, and a ROS client that records faults on it. + +The test starts each fault manager with its own parameters file, so one launch test can run several +startup configurations one after another behind the same gateway. The process logs at DEBUG and its +output is read on a thread; a test waits on output lines after a cursor, each wait with a deadline. +""" + +import ctypes +import os +import re +import signal +import subprocess +import threading +import time + +from ament_index_python.packages import get_package_prefix +from rcl_interfaces.srv import GetParameters +import rclpy +from rclpy.duration import Duration +from rclpy.qos import HistoryPolicy, QoSProfile, ReliabilityPolicy +from ros2_medkit_msgs.srv import ReportFault +from ros2_medkit_test_utils.constants import get_time_scale +from ros2_medkit_test_utils.coverage import get_coverage_env +from std_msgs.msg import UInt8MultiArray +import yaml + +MIB = 1024 * 1024 +MESSAGE_BYTES = 128 * 1024 +SCALE = get_time_scale() +STARTUP_TIMEOUT_SEC = 60.0 * SCALE +EVENT_TIMEOUT_SEC = 30.0 * SCALE +SERVICE_TIMEOUT_SEC = 20.0 * SCALE +# prctl option: the kernel sends the child this signal when the test process dies. +PR_SET_PDEATHSIG = 1 + + +def _die_with_parent(): + ctypes.CDLL('libc.so.6', use_errno=True).prctl(PR_SET_PDEATHSIG, signal.SIGKILL) + + +def nested(flat): + """Return the ROS parameters YAML tree of `flat`, whose keys are dotted parameter names.""" + tree = {} + for name, value in flat.items(): + node = tree + parts = name.split('.') + for part in parts[:-1]: + node = node.setdefault(part, {}) + node[parts[-1]] = value + return tree + + +class FaultManagerProcess: + """A fault_manager_node at the root namespace, logging at DEBUG, its lines read on a thread.""" + + def __init__(self, params, workdir, name='fault_manager', env_extra=None): + params_file = os.path.join(workdir, f'{name}_params.yaml') + with open(params_file, 'w') as handle: + yaml.safe_dump({name: {'ros__parameters': nested(params)}}, handle) + env = os.environ.copy() + env.update(get_coverage_env('ros2_medkit_fault_manager')) + env.update(env_extra or {}) + env['RCUTILS_LOGGING_BUFFERED_STREAM'] = '0' + env['RCUTILS_CONSOLE_OUTPUT_FORMAT'] = '[{severity}] [{time}] [{name}]: {message}' + binary = os.path.join(get_package_prefix('ros2_medkit_fault_manager'), 'lib', + 'ros2_medkit_fault_manager', 'fault_manager_node') + args = [binary, '--ros-args', '-r', f'__node:={name}', '--params-file', params_file, + '--log-level', f'{name}:=debug'] + self.proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, env=env, preexec_fn=_die_with_parent) + self.lines = [] + self._eof = False + self._seen = threading.Condition() + self._reader = threading.Thread(target=self._read, daemon=True) + self._reader.start() + + def _read(self): + for line in self.proc.stdout: + with self._seen: + self.lines.append(line) + self._seen.notify_all() + with self._seen: + self._eof = True + self._seen.notify_all() + + def mark(self): + """Return the index after the last line read, to search from later.""" + with self._seen: + return len(self.lines) + + def wait_line(self, pattern, since=0, timeout=None): + """Return the match of the first line from index `since` on, or None at the deadline.""" + return self.wait_line_at(pattern, since, timeout)[0] + + def wait_line_at(self, pattern, since=0, timeout=None): + """Return the match and the index of the first line from `since` on, or (None, None).""" + regex = re.compile(pattern) + deadline = time.monotonic() + (EVENT_TIMEOUT_SEC if timeout is None else timeout) + index = since + with self._seen: + while True: + while index < len(self.lines): + match = regex.search(self.lines[index]) + index += 1 + if match: + return match, index - 1 + remaining = deadline - time.monotonic() + if remaining <= 0 or self._eof: + return None, None + self._seen.wait(remaining) + + def count_lines(self, pattern, since=0, until=None): + regex = re.compile(pattern) + with self._seen: + return sum(1 for line in self.lines[since:until] if regex.search(line)) + + def lines_between(self, since, until): + """Return a copy of the lines from index `since` up to `until`, excluded.""" + with self._seen: + return list(self.lines[since:until]) + + def output(self, tail=4000): + with self._seen: + return ''.join(self.lines)[-tail:] + + def terminate(self): + """SIGTERM the process and return its exit code.""" + if self.proc.poll() is None: + self.proc.send_signal(signal.SIGTERM) + try: + code = self.proc.wait(timeout=STARTUP_TIMEOUT_SEC) + except subprocess.TimeoutExpired: + self.proc.kill() + code = self.proc.wait() + self._reader.join(timeout=10) + return code + + +class RecordingClient: + """A payload publisher on the capture topic and a report_fault client of the fault manager.""" + + def __init__(self, node, topic, fm_name='fault_manager'): + self.node = node + qos = QoSProfile(reliability=ReliabilityPolicy.RELIABLE, history=HistoryPolicy.KEEP_LAST, + depth=500) + self.publisher = node.create_publisher(UInt8MultiArray, topic, qos) + self.report_client = node.create_client(ReportFault, f'/{fm_name}/report_fault') + self.params_client = node.create_client(GetParameters, f'/{fm_name}/get_parameters') + + def _call(self, client, request): + if not client.wait_for_service(timeout_sec=SERVICE_TIMEOUT_SEC): + raise AssertionError(f'service {client.srv_name} never appeared') + future = client.call_async(request) + rclpy.spin_until_future_complete(self.node, future, timeout_sec=SERVICE_TIMEOUT_SEC) + if future.result() is None: + raise AssertionError(f'{client.srv_name} did not answer') + return future.result() + + def wait_for_capture_subscriber(self, present=True): + """Block until the fault manager's capture subscription is matched, or gone.""" + deadline = time.monotonic() + STARTUP_TIMEOUT_SEC + while (self.publisher.get_subscription_count() > 0) != present: + if time.monotonic() > deadline: + raise AssertionError('the capture subscription never ' + + ('appeared' if present else 'went away')) + rclpy.spin_once(self.node, timeout_sec=0.1) + + def sync(self): + """Return after one service round trip through the fault manager's executor.""" + request = GetParameters.Request() + request.names = ['snapshots.rosbag.enabled'] + self._call(self.params_client, request) + + def publish(self, mib): + """ + Publish `mib` MiB; return once the fault manager took each message. + + An acknowledged message is ready on the fault manager before the round trip that follows + it, and its single-threaded executor serves ready subscriptions before services. + """ + for _ in range(max(1, int(mib * MIB) // MESSAGE_BYTES)): + msg = UInt8MultiArray() + msg.data = list(os.urandom(MESSAGE_BYTES)) + self.publisher.publish(msg) + if not self.publisher.wait_for_all_acked(Duration(seconds=SERVICE_TIMEOUT_SEC)): + raise AssertionError('the payload was not acknowledged by the fault manager') + self.sync() + + def report(self, code, severity, source_id, failed=True): + request = ReportFault.Request() + request.fault_code = code + request.event_type = (ReportFault.Request.EVENT_FAILED if failed + else ReportFault.Request.EVENT_PASSED) + request.severity = severity + request.description = 'retention runtime e2e' + request.source_id = source_id + if not self._call(self.report_client, request).accepted: + raise AssertionError(f'report of {code} was not accepted') diff --git a/src/ros2_medkit_integration_tests/test/features/test_configuration_api.test.py b/src/ros2_medkit_integration_tests/test/features/test_configuration_api.test.py index f79cf2a08..940d225ef 100644 --- a/src/ros2_medkit_integration_tests/test/features/test_configuration_api.test.py +++ b/src/ros2_medkit_integration_tests/test/features/test_configuration_api.test.py @@ -20,8 +20,10 @@ """ +import os import unittest +from ament_index_python.packages import get_package_prefix import launch_testing import launch_testing.actions import requests @@ -34,10 +36,24 @@ from ros2_medkit_test_utils.launch_helpers import create_test_launch +# A plugin declares the gateway's one read-only parameter, plugins..path. +PLUGIN = 'minimal_plugin' +PLUGIN_PATH_PARAM = f'plugins.{PLUGIN}.path' + + +def _minimal_plugin_path(): + return os.path.join(get_package_prefix('ros2_medkit_gateway'), 'lib', + 'ros2_medkit_gateway', 'libtest_minimal_plugin.so') + + def generate_test_description(): return create_test_launch( demo_nodes=['temp_sensor'], fault_manager=False, + gateway_params={ + 'plugins': [PLUGIN], + PLUGIN_PATH_PARAM: _minimal_plugin_path(), + }, ) @@ -353,6 +369,22 @@ def test_07b_set_configuration_unconvertible_value(self): after = self.get_json('/apps/temp_sensor/configurations/publish_rate') self.assertEqual(after['x-medkit']['parameter']['value'], 2.0) + def test_07c_own_read_only_parameter_is_forbidden(self): + """A read-only parameter of the gateway itself answers 403, as a remote one does.""" + url = (f'{self.BASE_URL}/apps/ros2_medkit_gateway/configurations/' + f'{PLUGIN_PATH_PARAM}') + before = requests.get(url, timeout=10) + self.assertEqual(before.status_code, 200, before.text) + self.assertEqual(before.json()['x-medkit']['parameter']['value'], _minimal_plugin_path()) + + response = requests.put(url, json={'data': '/tmp/other_plugin.so'}, timeout=10) + self.assertEqual(response.status_code, 403, response.text) + self.assertEqual(response.json()['error_code'], 'vendor-error') + self.assertEqual(response.json()['vendor_code'], 'x-medkit-ros2-parameter-read-only') + + after = requests.get(url, timeout=10) + self.assertEqual(after.json()['x-medkit']['parameter']['value'], _minimal_plugin_path()) + def test_08_root_endpoint_includes_configurations(self): """Root endpoint lists configurations endpoints and capability. diff --git a/src/ros2_medkit_integration_tests/test/features/test_retention_runtime.test.py b/src/ros2_medkit_integration_tests/test/features/test_retention_runtime.test.py new file mode 100644 index 000000000..5bc27789b --- /dev/null +++ b/src/ros2_medkit_integration_tests/test/features/test_retention_runtime.test.py @@ -0,0 +1,711 @@ +#!/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. + +"""Rosbag retention parameters changed through the gateway while the fault manager runs. + +The launch holds the gateway alone. Each test class starts its own fault_manager_node at +/fault_manager with its own startup parameters, so one gateway serves a configured, a degraded, an +unconfigured and a rosbag-off fault manager one after another. The test's own node reports the +faults, so their recordings are listed under its app and no other node records anything. Every +change is a PUT or a DELETE on /apps/fault_manager/configurations; the effect is read from the +gateway's bulk-data list, from the recording directories and from the fault manager's DEBUG lines +after a cursor taken before the change. +""" + +import calendar +import os +import re +import shutil +import stat +import tempfile +import threading +import time +import unittest + +import launch_testing +from rcl_interfaces.msg import Parameter, ParameterType +from rcl_interfaces.srv import SetParameters +import rclpy +from rclpy.node import Node +import requests +from ros2_medkit_msgs.msg import Fault + +from ros2_medkit_test_utils.constants import ALLOWED_EXIT_CODES +from ros2_medkit_test_utils.fault_manager_process import ( + EVENT_TIMEOUT_SEC, FaultManagerProcess, MIB, RecordingClient, SCALE, STARTUP_TIMEOUT_SEC, +) +from ros2_medkit_test_utils.gateway_test_case import GatewayTestCase +from ros2_medkit_test_utils.launch_helpers import create_test_launch + +PAYLOAD_TOPIC = '/e2e/retention_runtime_payload' +DRIVER = 'retention_runtime_driver' +APP = f'/apps/{DRIVER}' +FM_APP = '/apps/fault_manager' +SOURCE_FQN = f'/{DRIVER}' +PREFIX = 'snapshots.rosbag.retention.' +OWN_CODE = 'ROSBAG_RETENTION_CONFIG_INVALID' +REMOVAL = r'Recording removed: (\S+) \({}\)' +APPLIED = r'\[INFO\].*Rosbag retention change applied' +PERIODIC = r'retention job done: periodic' +POLICY_CHANGED = r'\[INFO\].*Rosbag retention rules changed \((\w+)\)' +PASSES_RUN = r'passes run: ([^;]+); periodic job (.+)$' +PASS_LINE = r'retention sweep: |floor pass: ' +CHANGE_DONE = r'retention job done: retention change' +FLOOR_PASS = (r'floor pass: removed=(\d+) free=(\d+|unknown) floor=(\d+) met=(true|false) ' + r'source=(filesystem|test-capacity)') +# A change applies at once: this bounds the wait, well under the 60 s sweep interval. +AT_ONCE_SEC = 15.0 * SCALE +CAPACITY_ENV = 'ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE' +CAPACITY_WARN = (r'Free space is computed from (\S+) \(ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE\), ' + r'not measured\.') +FLOOR_MB = 64 + +MAIN_RULES = { + 'fault_codes.MOTOR_OVERHEAT.priority': 10, + 'fault_codes.CAPPED.max_bags': 4, + 'fault_codes.KEPT.on_cleared': 'keep', + 'fault_codes.AGED.on_cleared': 'keep', + 'fault_codes.AGED.max_age_sec.cleared': 0, + 'fault_codes.FAMILY.over_quota': 'keep', + 'fault_codes.FAMILY.keep_first': False, + 'fault_codes.FAMILY.on_healed': 'keep', + 'fault_codes.FAMILY.max_age_sec.active': 0, + 'fault_codes.FAMILY.max_age_sec.healed': 0, + 'fault_codes.SENSOR_read-only.priority': 5, + 'fault_codes.BAD.priority': 20, + 'defaults.priority': 0, + # A max age above 0 makes the periodic job run, every sweep_interval_sec. + 'defaults.max_age_sec.active': 86400, + 'severity.WARN.priority': 1, + 'patterns.motors.match': 'MOTOR_.*', + 'patterns.motors.priority': 3, + 'patterns.remap.match': 'NOTHING_MATCHES_YET', + 'patterns.remap.max_bags': 1, + 'pattern_order': ['motors', 'remap'], + 'sweep_interval_sec': 60, +} + + +def generate_test_description(): + # The reporting node and each fault manager are started by the test classes. + return create_test_launch(demo_nodes=[], fault_manager=False) + + +def poll(predicate, timeout=None, interval=0.1): + """Return True once `predicate()` is true, False at the deadline.""" + deadline = time.monotonic() + (EVENT_TIMEOUT_SEC if timeout is None else timeout) + waiter = threading.Event() + while True: + if predicate(): + return True + if time.monotonic() >= deadline: + return False + waiter.wait(interval) + + +def regular_bytes(path): + """Return the sizes of the regular files under `path`, symlinks not followed.""" + total = 0 + for root, _, files in os.walk(path): + for name in files: + info = os.lstat(os.path.join(root, name)) + if stat.S_ISREG(info.st_mode): + total += info.st_size + return total + + +def iso_to_epoch(text): + """Return the seconds since the epoch of a gateway timestamp, `YYYY-MM-DDTHH:MM:SS.fffZ`.""" + whole, _, fraction = text.rstrip('Z').partition('.') + seconds = calendar.timegm(time.strptime(whole, '%Y-%m-%dT%H:%M:%S')) + return seconds + (float('0.' + fraction) if fraction else 0.0) + + +class RuntimeCase(GatewayTestCase): + """Starts one fault manager for the class and drives it through the gateway.""" + + RULES = {} + ROSBAG = True + + @classmethod + def fm_env(cls): + """Return extra environment variables of the fault manager process.""" + return {} + + @classmethod + def fm_params(cls): + params = { + 'storage_type': 'sqlite', + 'database_path': os.path.join(cls.tmp, 'faults.db'), + 'confirmation_threshold': -1, + 'snapshots.recapture_cooldown_sec': 0.0, + 'snapshots.rosbag.enabled': cls.ROSBAG, + } + if cls.ROSBAG: + params.update({ + 'snapshots.rosbag.topics': 'explicit', + 'snapshots.rosbag.include_topics': [PAYLOAD_TOPIC], + 'snapshots.rosbag.format': 'mcap', + 'snapshots.rosbag.storage_path': cls.storage, + 'snapshots.rosbag.duration_sec': 60.0, + 'snapshots.rosbag.duration_after_sec': 0.0, + 'snapshots.rosbag.lazy_start': False, + 'snapshots.rosbag.max_bag_size_mb': 50, + 'snapshots.rosbag.max_total_storage_mb': 4000, + 'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.auto_cleanup': False, + }) + params.update({PREFIX + key: value for key, value in cls.RULES.items()}) + return params + + @classmethod + def setUpClass(cls): + super().setUpClass() + + # The classes reuse both node names: an app still served from the class before would + # satisfy served() and then vanish. This class starts once the gateway serves neither name. + def gone(): + try: + return all(requests.get(f'{cls.BASE_URL}{path}', timeout=5).status_code == 404 + for path in (APP, FM_APP)) + except requests.exceptions.RequestException: + return False + if not poll(gone, timeout=STARTUP_TIMEOUT_SEC, interval=0.5): + raise AssertionError('the gateway still serves a node of an earlier class') + # Class cleanups release what this class starts, also when setUpClass fails, so a failed + # class leaves nothing for the next one to wait out in gone(). + cls.tmp = tempfile.mkdtemp(prefix='retention_runtime_') + cls.addClassCleanup(shutil.rmtree, cls.tmp, ignore_errors=True) + cls.storage = os.path.join(cls.tmp, 'bags') + rclpy.init() + cls.addClassCleanup(rclpy.shutdown) + cls.node = Node(DRIVER) + cls.addClassCleanup(cls.node.destroy_node) + # The publisher exists before the fault manager: the explicit-topic capture resolves the + # type at startup. + cls.client = RecordingClient(cls.node, PAYLOAD_TOPIC) + params = cls.fm_params() + cls.fm = FaultManagerProcess(params, cls.tmp, env_extra=cls.fm_env()) + cls.addClassCleanup(cls.fm.terminate) + if cls.fm.wait_line(r'FaultManager node started', timeout=STARTUP_TIMEOUT_SEC) is None: + cls.fm.terminate() + raise AssertionError('the fault manager never started:\n' + cls.fm.output()) + if cls.ROSBAG: + cls.client.wait_for_capture_subscriber() + # The gateway serves this process once it reads this run's database path. + url = f'{cls.BASE_URL}{FM_APP}/configurations/database_path' + + def served(): + try: + response = requests.get(url, timeout=5) + driver = requests.get(f'{cls.BASE_URL}{APP}', timeout=5) + except requests.exceptions.RequestException: + return False + return (driver.status_code == 200 and response.status_code == 200 and + response.json()['x-medkit']['parameter']['value'] == params['database_path']) + if not poll(served, timeout=STARTUP_TIMEOUT_SEC, interval=0.5): + cls.fm.terminate() + raise AssertionError('the gateway never served the parameters of this fault manager') + + @classmethod + def tearDownClass(cls): + code = cls.fm.terminate() + if cls.ROSBAG: + cls.client.wait_for_capture_subscriber(present=False) + super().tearDownClass() + if code != 0: + raise AssertionError(f'the fault manager exited with {code}:\n' + cls.fm.output()) + + # -- gateway calls -------------------------------------------------------------------- + + def config_url(self, key, prefixed=True): + return f'{self.BASE_URL}{FM_APP}/configurations/{PREFIX if prefixed else ""}{key}' + + def put(self, key, value, prefixed=True): + return requests.put(self.config_url(key, prefixed), json={'data': value}, timeout=30) + + def value(self, key, prefixed=True): + response = requests.get(self.config_url(key, prefixed), timeout=30) + self.assertEqual(response.status_code, 200, response.text) + return response.json()['x-medkit']['parameter']['value'] + + def assert_put(self, key, value, status=200): + response = self.put(key, value) + self.assertEqual(response.status_code, status, response.text) + return response + + def details(self, response): + return str(response.json().get('parameters', {}).get('details', '')) + + def assert_refused(self, key, value): + """PUT `value`: 400, the reason names the key and never says read-only; return it.""" + response = self.assert_put(key, value, 400) + reason = self.details(response) + self.assertIn(PREFIX + key, reason) + self.assertNotIn('read only', reason) + if 'read-only' not in key: + self.assertNotIn('read-only', reason) + return reason + + def listing(self): + return self.get_json(f'{APP}/bulk-data/rosbags').get('items', []) + + def recordings_of(self, code): + """Return {recording id: priority} of the listed recordings that hold `code`.""" + return {item['id']: item['x-medkit']['priority'] for item in self.listing() + if code in item['x-medkit']['fault_codes']} + + def wait_recordings(self, code, predicate, what): + found = {} + + def reached(): + found.clear() + found.update(self.recordings_of(code)) + return predicate(found) + self.assertTrue(poll(reached), f'{what}: {found}') + return found + + def fault_detail(self, code, app=APP): + return self.get_json(f'{app}/faults/{code}') + + def failed_age(self, code): + """Return the seconds since the last FAILED report of `code`, 0.0 before it is listed.""" + records = self.fault_detail(code)['environment_data']['extended_data_records'] + stamp = records.get('last_occurrence', '') + return time.time() - iso_to_epoch(stamp) if stamp else 0.0 + + def clear(self, code): + response = requests.delete(f'{self.BASE_URL}{APP}/faults/{code}', timeout=30) + self.assertIn(response.status_code, (200, 204), response.text) + + # -- recordings ----------------------------------------------------------------------- + + def record(self, code, mib=0.25, severity=Fault.SEVERITY_ERROR): + """Publish `mib` MiB, confirm `code` and return its stored recording's directory.""" + mark = self.fm.mark() + self.client.publish(mib) + self.client.report(code, severity, SOURCE_FQN) + done = self.fm.wait_line(rf'Bag file created: (\S*fault_{code}_\d+)', since=mark) + self.assertIsNotNone(done, f'no recording for {code}:\n' + self.fm.output()) + path = done.group(1) + self.assertTrue(os.path.isdir(path), path) + return path + + def record_cycle(self, code, count): + """Record `code` `count` times, cleared in between; return the paths, oldest first.""" + paths = [] + for index in range(count): + if index: + self.clear(code) + paths.append(self.record(code)) + return paths + + def removals(self, reason, since, count): + """Wait for `count` removal lines with `reason` from `since` on; return their ids.""" + ids = [] + index = since + for _ in range(count): + line, at = self.fm.wait_line_at(REMOVAL.format(re.escape(reason)), since=index, + timeout=AT_ONCE_SEC) + self.assertIsNotNone(line, f'{len(ids)} of {count} removals ({reason}):\n' + + self.fm.output()) + ids.append(line.group(1)) + index = at + 1 + return ids, index + + +class TestRetentionRuntime1Configured(RuntimeCase): + """A configured fault manager: every field family changes, and each change applies at once.""" + + RULES = MAIN_RULES + + def test_01_listing_shows_the_retention_parameters(self): + """One GET of the configurations lists every retention parameter, the two scalars too.""" + names = {param['name'] for param in + self.get_json(f'{FM_APP}/configurations')['x-medkit']['parameters']} + for key in list(MAIN_RULES) + ['min_free_disk_mb', 'sweep_interval_sec']: + self.assertIn(PREFIX + key, names) + + def test_02_priority_applies_to_the_listed_recording(self): + """PUT priority 10 -> 900: the next list shows 900 for the recording.""" + self.record('MOTOR_OVERHEAT') + listed = self.wait_recordings('MOTOR_OVERHEAT', lambda found: len(found) == 1, + 'MOTOR_OVERHEAT was not listed') + self.assertEqual(list(listed.values()), [10]) + self.assert_put('fault_codes.MOTOR_OVERHEAT.priority', 900) + self.assertEqual(list(self.recordings_of('MOTOR_OVERHEAT').values()), [900]) + + def test_03_delete_restores_the_startup_value(self): + """A DELETE of the configuration sets the startup value again, and the list follows.""" + self.assert_put('fault_codes.MOTOR_OVERHEAT.priority', 700) + self.assertEqual(list(self.recordings_of('MOTOR_OVERHEAT').values()), [700]) + response = requests.delete(self.config_url('fault_codes.MOTOR_OVERHEAT.priority'), + timeout=30) + self.assertEqual(response.status_code, 204, response.text) + self.assertEqual(self.value('fault_codes.MOTOR_OVERHEAT.priority'), 10) + self.assertEqual(list(self.recordings_of('MOTOR_OVERHEAT').values()), [10]) + + def test_04_bad_values_are_rejected_and_change_nothing(self): + """Out of range, a string and a fraction answer 400 naming the key; the values stay.""" + self.assertEqual(self.value('fault_codes.BAD.priority'), 20) + self.assertEqual(self.value('fault_codes.CAPPED.max_bags'), 4) + self.assertIn('1001', self.assert_refused('fault_codes.BAD.priority', 1001)) + for bad in ('many', 1.5): + self.assert_refused('fault_codes.CAPPED.max_bags', bad) + self.assertEqual(self.value('fault_codes.BAD.priority'), 20) + self.assertEqual(self.value('fault_codes.CAPPED.max_bags'), 4) + + def test_05_lower_max_bags_trims_at_once(self): + """Four recordings under max_bags 4; PUT 2: the two oldest go at once.""" + paths = self.record_cycle('CAPPED', 4) + ids = [os.path.basename(path) for path in paths] + self.wait_recordings('CAPPED', lambda found: sorted(found) == sorted(ids), + 'the four recordings were not listed') + mark = self.fm.mark() + self.assert_put('fault_codes.CAPPED.max_bags', 2) + removed, after = self.removals('its max_bags', mark, 2) + self.assertEqual(sorted(removed), sorted(ids[:2])) + self.assertIsNotNone(self.fm.wait_line(APPLIED, since=after), self.fm.output()) + self.assertEqual(sorted(self.recordings_of('CAPPED')), sorted(ids[2:])) + for path in paths[:2]: + self.assertFalse(os.path.exists(path), path) + for path in paths[2:]: + self.assertTrue(os.path.isdir(path), path) + + def test_06_status_action_applies_to_a_cleared_fault(self): + """A cleared fault keeps its recording (on_cleared: keep); PUT delete: it goes.""" + path = self.record('KEPT') + self.clear('KEPT') + self.assertEqual(self.fault_detail('KEPT')['item']['status']['aggregatedStatus'], + 'cleared') + self.assertEqual(list(self.recordings_of('KEPT')), [os.path.basename(path)]) + mark = self.fm.mark() + self.assert_put('fault_codes.KEPT.on_cleared', 'delete') + removed, _ = self.removals('fault cleared', mark, 1) + self.assertEqual(removed, [os.path.basename(path)]) + self.assertEqual(self.recordings_of('KEPT'), {}) + self.assertFalse(os.path.exists(path), path) + + def test_07_max_age_applies_at_once(self): + """A cleared recording older than the new max_age_sec.cleared goes at once, not in 60 s.""" + path = self.record('AGED') + self.clear('AGED') + self.assertEqual(list(self.recordings_of('AGED')), [os.path.basename(path)]) + self.assertEqual(self.value('fault_codes.AGED.max_age_sec.cleared'), 0) + self.assertTrue(poll(lambda: self.failed_age('AGED') > 2.0), + 'the last FAILED time never aged') + mark = self.fm.mark() + self.assert_put('fault_codes.AGED.max_age_sec.cleared', 1) + line, at = self.fm.wait_line_at(REMOVAL.format(r'max_age_sec\.cleared'), since=mark, + timeout=AT_ONCE_SEC) + self.assertIsNotNone(line, self.fm.output()) + self.assertEqual(line.group(1), os.path.basename(path)) + self.assertEqual(self.fm.count_lines(PERIODIC, since=mark, until=at), 0, + 'a periodic pass ran between the PUT and the removal') + self.assertEqual(self.recordings_of('AGED'), {}) + self.assertFalse(os.path.exists(path), path) + + def test_08_interval_change_moves_the_periodic_pass(self): + """sweep_interval_sec 60 -> 1: two periodic passes come within 15 s of the PUT.""" + self.assertEqual(self.value('sweep_interval_sec'), 60) + mark = self.fm.mark() + deadline = time.monotonic() + AT_ONCE_SEC + self.assert_put('sweep_interval_sec', 1) + _, first = self.fm.wait_line_at(PERIODIC, since=mark, + timeout=deadline - time.monotonic()) + self.assertIsNotNone(first, 'no periodic pass after the PUT:\n' + self.fm.output()) + second, _ = self.fm.wait_line_at(PERIODIC, since=first + 1, + timeout=max(0.0, deadline - time.monotonic())) + self.assertIsNotNone(second, 'no second periodic pass:\n' + self.fm.output()) + + def test_09_every_field_family_changes(self): + """A valid value of each field family answers 200 and is read back.""" + changes = { + 'fault_codes.FAMILY.over_quota': 'drop', + 'fault_codes.FAMILY.keep_first': True, + 'fault_codes.FAMILY.on_healed': 'delete', + 'fault_codes.FAMILY.max_age_sec.active': 3600, + 'fault_codes.FAMILY.max_age_sec.healed': 7200, + 'defaults.priority': 2, + 'severity.WARN.priority': 4, + 'patterns.motors.match': 'MOTOR_[A-Z_]+', + 'pattern_order': ['remap', 'motors'], + } + failures = [] + for key, value in changes.items(): + before = self.value(key) + if before != MAIN_RULES[key]: + failures.append(f'{key}: starts at {before!r}') + continue + response = self.put(key, value) + if response.status_code != 200: + failures.append(f'{key}: PUT {value!r} answered {response.status_code} ' + f'{response.text}') + elif self.value(key) != value: + failures.append(f'{key}: reads {self.value(key)!r} after PUT {value!r}') + self.assertEqual(failures, []) + + def test_10_pattern_order_omitting_a_pattern_is_rejected(self): + """A pattern_order without an existing pattern answers 400 naming the pattern.""" + before = self.value('pattern_order') + response = self.assert_put('pattern_order', ['motors'], 400) + self.assertIn('patterns.remap', self.details(response)) + self.assertIn('missing from pattern_order', self.details(response)) + self.assertEqual(self.value('pattern_order'), before) + + def test_11_match_change_moves_a_fault_to_a_lower_cap(self): + """REMAP_ME has no cap; its pattern starts to match a rule with max_bags 1: two go.""" + paths = self.record_cycle('REMAP_ME', 3) + ids = [os.path.basename(path) for path in paths] + self.wait_recordings('REMAP_ME', lambda found: sorted(found) == sorted(ids), + 'the three recordings were not listed') + self.assertEqual(self.value('patterns.remap.match'), 'NOTHING_MATCHES_YET') + mark = self.fm.mark() + self.assert_put('patterns.remap.match', 'REMAP_.*') + removed, _ = self.removals('its max_bags', mark, 2) + self.assertEqual(sorted(removed), sorted(ids[:2])) + self.assertEqual(list(self.recordings_of('REMAP_ME')), ids[2:]) + + def test_12_a_key_naming_read_only_is_not_read_only(self): + """A rule of fault code SENSOR_read-only: an invalid priority is a 400 naming the key.""" + self.assert_refused('fault_codes.SENSOR_read-only.priority', 1001) + self.assertEqual(self.value('fault_codes.SENSOR_read-only.priority'), 5) + self.assert_put('fault_codes.SENSOR_read-only.priority', 6) + self.assertEqual(self.value('fault_codes.SENSOR_read-only.priority'), 6) + + def test_13_other_parameters_behave_as_before(self): + """A read-only parameter still answers 403; a writable one is no retention key.""" + response = requests.put(self.config_url('report_fault_queue_depth', prefixed=False), + json={'data': 5}, timeout=30) + self.assertEqual(response.status_code, 403, response.text) + response = requests.put(self.config_url('healing_threshold', prefixed=False), + json={'data': 5}, timeout=30) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(self.value('healing_threshold', prefixed=False), 5) + + def test_14_a_rule_key_not_given_at_startup_is_not_declared(self): + """Only the parameters given at startup exist: another rule key answers 400.""" + response = self.assert_put('fault_codes.NOT_GIVEN.priority', 5, 400) + self.assertIn('not declared', self.details(response)) + + def test_15_unset_is_refused(self): + """A JSON null and a NOT_SET value are refused; the parameter stays declared.""" + # The gateway sends the JSON null as the string "null". + self.assertIn('got string', self.assert_refused('fault_codes.BAD.priority', None)) + client = self.node.create_client(SetParameters, '/fault_manager/set_parameters') + self.assertTrue(client.wait_for_service(timeout_sec=EVENT_TIMEOUT_SEC)) + request = SetParameters.Request() + unset = Parameter() + unset.name = PREFIX + 'fault_codes.BAD.priority' + unset.value.type = ParameterType.PARAMETER_NOT_SET + request.parameters = [unset] + future = client.call_async(request) + rclpy.spin_until_future_complete(self.node, future, timeout_sec=EVENT_TIMEOUT_SEC) + self.assertIsNotNone(future.result(), 'set_parameters did not answer') + result = future.result().results[0] + self.assertFalse(result.successful, 'the NOT_SET value was accepted') + self.assertNotIn('read-only', result.reason) + self.assertNotIn('read only', result.reason) + self.assertIn(PREFIX + 'fault_codes.BAD.priority', result.reason) + self.node.destroy_client(client) + self.assertEqual(self.value('fault_codes.BAD.priority'), 20) + + +class TestRetentionRuntime2Degraded(RuntimeCase): + """Two invalid values at startup: each is repaired alone, the second repair ends degrade.""" + + RULES = { + 'fault_codes.MOTOR_OVERHEAT.priority': 5000, + 'fault_codes.MOTOR_OVERHEAT.max_bags': 'bad', + } + + def own_status(self): + response = requests.get(f'{self.BASE_URL}{FM_APP}/faults/{OWN_CODE}', timeout=30) + if response.status_code != 200: + return None + return response.json()['item']['status']['aggregatedStatus'] + + def test_01_each_repair_is_accepted_and_the_last_ends_degrade(self): + self.assertTrue(poll(lambda: self.own_status() == 'active'), + f'{OWN_CODE} never became active: {self.own_status()}') + self.record('MOTOR_OVERHEAT') + listed = self.wait_recordings('MOTOR_OVERHEAT', lambda found: len(found) == 1, + 'MOTOR_OVERHEAT was not listed') + self.assertEqual(list(listed.values()), [0]) + + mark = self.fm.mark() + self.assert_put('fault_codes.MOTOR_OVERHEAT.priority', 900) + changed = self.fm.wait_line(POLICY_CHANGED, since=mark, timeout=AT_ONCE_SEC) + self.assertIsNotNone(changed, self.fm.output()) + self.assertEqual(changed.group(1), 'degraded') + self.assertEqual(self.own_status(), 'active') + self.assertEqual(list(self.recordings_of('MOTOR_OVERHEAT').values()), [0]) + + mark = self.fm.mark() + self.assert_put('fault_codes.MOTOR_OVERHEAT.max_bags', 5) + changed = self.fm.wait_line(POLICY_CHANGED, since=mark, timeout=AT_ONCE_SEC) + self.assertIsNotNone(changed, self.fm.output()) + self.assertEqual(changed.group(1), 'configured') + self.assertTrue(poll(lambda: self.own_status() == 'cleared'), + f'{OWN_CODE} was not cleared: {self.own_status()}') + self.assertEqual(list(self.recordings_of('MOTOR_OVERHEAT').values()), [900]) + self.assertEqual(self.value('fault_codes.MOTOR_OVERHEAT.max_bags'), 5) + + +class TestRetentionRuntime3Unconfigured(RuntimeCase): + """No retention parameter at startup: the two scalars exist, a change configures the rules. + + The free space comes from a test capacity file: the capacity less the regular files under the + storage path, so the floor case sets exactly how many removals meet it. + """ + + @classmethod + def fm_env(cls): + return {CAPACITY_ENV: os.path.join(cls.tmp, 'capacity')} + + def set_capacity(self, capacity): + """Replace the capacity file in one step, so the fault manager never reads half of it.""" + path = self.fm_env()[CAPACITY_ENV] + with open(path + '.new', 'w') as handle: + handle.write(f'{capacity}\n') + os.replace(path + '.new', path) + return capacity + + def test_01_a_scalar_change_configures_the_rules(self): + self.assertEqual(self.fm.count_lines(r'Rosbag retention rules'), 0, self.fm.output()) + self.assertEqual(self.value('sweep_interval_sec'), 60) + self.assertEqual(self.value('min_free_disk_mb'), 0) + mark = self.fm.mark() + self.assert_put('sweep_interval_sec', 5) + changed = self.fm.wait_line(POLICY_CHANGED, since=mark, timeout=AT_ONCE_SEC) + self.assertIsNotNone(changed, self.fm.output()) + self.assertEqual(changed.group(1), 'configured') + + def test_02_a_rule_key_not_given_is_not_declared(self): + response = self.assert_put('fault_codes.NOT_GIVEN.priority', 5, 400) + self.assertIn('not declared', self.details(response)) + + def test_03_a_floor_set_at_runtime_applies_at_once(self): + """min_free_disk_mb set at runtime: one pass removes the two oldest and meets the floor.""" + warned = self.fm.wait_line(CAPACITY_WARN, timeout=0) + self.assertIsNotNone(warned, self.fm.output()) + self.assertEqual(warned.group(1), self.fm_env()[CAPACITY_ENV]) + paths = [self.record(code, 8) for code in ('FLOOR_1', 'FLOOR_2', 'FLOOR_3')] + sizes = [regular_bytes(path) for path in paths] + self.assertGreaterEqual(min(sizes), 8 * MIB, f'{sizes}:\n' + self.fm.output()) + used = regular_bytes(self.storage) + floor = FLOOR_MB * MIB + capacity = self.set_capacity(used + floor - sizes[0] - sizes[1] // 2) + # The state the pass starts from: one removal is not enough, two are. + self.assertLess(capacity - used, floor) + self.assertLess(capacity - used + sizes[0], floor) + self.assertGreaterEqual(capacity - used + sizes[0] + sizes[1], floor) + mark = self.fm.mark() + self.assert_put('min_free_disk_mb', FLOOR_MB) + line, at = self.fm.wait_line_at(FLOOR_PASS, since=mark, timeout=AT_ONCE_SEC) + self.assertIsNotNone(line, 'no floor pass after the PUT:\n' + self.fm.output()) + self.assertEqual((line.group(1), line.group(4), line.group(5)), + ('2', 'true', 'test-capacity'), line.string) + self.assertEqual(int(line.group(2)), capacity - regular_bytes(self.storage), line.string) + self.assertEqual(int(line.group(3)), floor, line.string) + removed = [match.group(1) for match in + (re.search(REMOVAL.format('min_free_disk_mb'), text) + for text in self.fm.lines_between(mark, at)) if match] + self.assertEqual(removed, [os.path.basename(path) for path in paths[:2]]) + for path in paths[:2]: + self.assertFalse(os.path.exists(path), path) + self.assertTrue(os.path.isdir(paths[2]), paths[2]) + listed = self.listing() + self.assertEqual([item['id'] for item in listed + if item['id'].startswith('fault_FLOOR_')], [os.path.basename(paths[2])]) + + +class TestRetentionRuntime4RosbagOff(RuntimeCase): + """Rosbag capture off: a change is validated, then not used.""" + + ROSBAG = False + RULES = {'fault_codes.ANY.priority': 1} + + def test_01_a_valid_change_is_kept_and_not_used(self): + self.assertEqual(self.value('fault_codes.ANY.priority'), 1) + mark = self.fm.mark() + self.assert_put('fault_codes.ANY.priority', 2) + self.assertIsNotNone( + self.fm.wait_line(r'snapshots\.rosbag\.enabled is false\. The rules are not used', + since=mark, timeout=AT_ONCE_SEC), self.fm.output()) + self.assertEqual(self.value('fault_codes.ANY.priority'), 2) + self.assert_refused('fault_codes.ANY.priority', 1001) + + +class TestRetentionRuntime5PassesOnlyOnAgeChanges(RuntimeCase): + """Only a change of a max age, the floor or the interval runs the age and floor passes. + + The periodic job runs every 60 s from the start: the case is done before its first pass. + """ + + RULES = { + 'fault_codes.STALE.priority': 1, + 'fault_codes.STALE.on_cleared': 'keep', + 'fault_codes.STALE.max_age_sec.cleared': 1, + 'sweep_interval_sec': 60, + } + + def test_01_a_priority_change_runs_no_pass(self): + """An expired recording stays after a priority PUT; a max age PUT removes it at once.""" + path = self.record('STALE') + recording = os.path.basename(path) + self.clear('STALE') + self.assertEqual(list(self.recordings_of('STALE')), [recording]) + # Above 2 whole seconds, so max_age_sec.cleared 2 below expires it. + self.assertTrue(poll(lambda: self.failed_age('STALE') > 3.0), + 'the last FAILED time never aged') + + mark = self.fm.mark() + self.assert_put('fault_codes.STALE.priority', 2) + applied, at = self.fm.wait_line_at(APPLIED, since=mark, timeout=AT_ONCE_SEC) + self.assertIsNotNone(applied, self.fm.output()) + self.assertIsNotNone(self.fm.wait_line(CHANGE_DONE, since=at, timeout=AT_ONCE_SEC), + self.fm.output()) + self.assertEqual(self.fm.count_lines(PERIODIC), 0, + 'the first periodic pass ran before the check:\n' + self.fm.output()) + self.assertEqual(self.fm.count_lines(PASS_LINE, since=mark), 0, self.fm.output()) + self.assertEqual(self.recordings_of('STALE'), {recording: 2}) + self.assertTrue(os.path.isdir(path), path) + passes = re.search(PASSES_RUN, applied.string) + self.assertIsNotNone(passes, applied.string) + self.assertEqual(passes.groups(), ('none', 'unchanged'), applied.string) + + mark = self.fm.mark() + self.assert_put('fault_codes.STALE.max_age_sec.cleared', 2) + applied = self.fm.wait_line(APPLIED, since=mark, timeout=AT_ONCE_SEC) + self.assertIsNotNone(applied, self.fm.output()) + passes = re.search(PASSES_RUN, applied.string) + self.assertIsNotNone(passes, applied.string) + self.assertEqual(passes.groups(), ('age sweep', 'every 60 s'), applied.string) + line, at = self.fm.wait_line_at(REMOVAL.format(r'max_age_sec\.cleared'), since=mark, + timeout=AT_ONCE_SEC) + self.assertIsNotNone(line, self.fm.output()) + self.assertEqual(line.group(1), recording) + self.assertEqual(self.fm.count_lines(PERIODIC, since=mark, until=at), 0, + 'a periodic pass ran between the PUT and the removal') + self.assertEqual(self.recordings_of('STALE'), {}) + self.assertFalse(os.path.exists(path), path) + + +@launch_testing.post_shutdown_test() +class TestShutdown(unittest.TestCase): + + def test_exit_codes(self, proc_info): + launch_testing.asserts.assertExitCodes(proc_info, allowable_exit_codes=ALLOWED_EXIT_CODES)