From 957d7db2039ed62cc6d57731cbd502714b50ca13 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:07 +0100 Subject: [PATCH] fault_manager: min_free_disk_mb keeps free space under the rosbag storage path * feat(fault_manager): min_free_disk_mb keeps free space under the rosbag storage path * feat(fault_manager): a test capacity file replaces the free-space measurement in tests * fix(fault_manager): no floor pass after a store that kept nothing; one WARN per failed step * test(fault_manager): the in-doubt floor test counts every WARN of the pass --- docs/config/fault-manager.rst | 82 +++- src/ros2_medkit_fault_manager/CMakeLists.txt | 6 + src/ros2_medkit_fault_manager/README.md | 30 +- .../config/rosbag_retention.example.yaml | 13 +- .../design/index.rst | 55 ++- .../core/retention_policy.hpp | 13 +- .../core/rosbag_retention.hpp | 47 ++ .../retention_worker.hpp | 4 +- .../rosbag_capture.hpp | 37 +- .../snapshot_capture.hpp | 5 + .../src/core/retention_policy.cpp | 22 +- .../src/core/rosbag_retention.cpp | 161 ++++++- .../src/fault_manager_node.cpp | 16 +- .../src/retention_worker.cpp | 3 + .../src/rosbag_capture.cpp | 225 +++++++++- .../test/integration/rosbag_fm_harness.py | 27 +- .../integration/test_retention_config.test.py | 2 +- .../test_rosbag_free_space.test.py | 408 ++++++++++++++++++ .../test/test_rosbag_capture.cpp | 86 +++- 19 files changed, 1185 insertions(+), 57 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_free_space.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 6cbdb9745..c03769a7b 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -792,8 +792,9 @@ Rosbag Retention Rules The parameters under ``snapshots.rosbag.retention.`` set a rule per fault: a ``priority``, an ``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``), and how long they are kept in each status -(``max_age_sec``). They are read at startup, validated and +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 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 @@ -806,6 +807,7 @@ before. An example file is ``config/rosbag_retention.example.yaml``. snapshots: rosbag: retention: + min_free_disk_mb: 1024 sweep_interval_sec: 60 defaults: priority: 10 @@ -851,9 +853,13 @@ Grammar, relative to ``snapshots.rosbag.retention.``: - List of every pattern label, in the order they are tried. With no patterns, leave the key out. * - ``.max_age_sec.`` - The ``max_age_sec`` field at any of the four levels above, one key per status. + * - ``min_free_disk_mb`` + - Free space in MiB that must stay on the filesystem of ``storage_path``, integer ``0`` or more, + default ``0`` (off). Below it, recordings are deleted in eviction order. * - ``sweep_interval_sec`` - - Seconds between two passes of the age sweep, integer 1-86400, default ``60``. The sweep runs - only when a level sets a ``max_age_sec`` key above ``0``. + - Seconds between two runs of the periodic job (the age sweep and the free-space floor), integer + 1-86400, default ``60``. The job runs only when a level sets a ``max_age_sec`` key above ``0`` + or ``min_free_disk_mb`` is above ``0``. Fields: @@ -943,9 +949,11 @@ that key: ``fault_codes..max_age_sec.active: 0`` keeps that code's recordi status and regardless of ``keep_first``: a recording shared by a burst loses only that link, and the directory goes with its last link. A link whose fault the storage no longer holds is not aged. -The age sweep runs on the retention worker every ``sweep_interval_sec``, only while a level sets a -``max_age_sec`` key above ``0``; without one there is no timer. The policy line at startup ends -with ``sweep: off`` or ``sweep: every s``. Each pass reads the rosbag rows and the faults once, +The periodic job runs on the retention worker every ``sweep_interval_sec``, only while a level sets a +``max_age_sec`` key above ``0`` or ``min_free_disk_mb`` is above ``0``; without either there is no +timer. The age sweep runs in it only while a ``max_age_sec`` key is above ``0``. The policy line at +startup ends with ``sweep: off`` or ``sweep: every s``, then ``floor: off`` or +``floor: MB``. Each age pass reads the rosbag rows and the faults once, removes every expired link in one transaction, then removes the directories no row names any more and logs ``Recording removed: (max_age_sec.active)`` (``.healed``, ``.cleared``) for each. Each pass logs ``retention sweep: now= removed=`` at DEBUG, ``now`` being the @@ -987,6 +995,60 @@ quota and logs a warning; ``keep`` also deletes the recordings it was allowed to the new recording alone and deletes nothing. The log line of a drop names the path, the size, the quota and the reason. +**The free-space floor.** With ``min_free_disk_mb`` above ``0`` the fault manager keeps that much +free space on the filesystem of the effective storage path: ``storage_path``, or the system temp +directory when it is empty. All recordings are written under it, so they sit on that one +filesystem. A path not created yet is measured on its nearest existing parent directory. The free +space is what an unprivileged process may still write (``statvfs`` ``f_bavail``). + +The floor is enforced by measuring, never by estimating. A pass measures the free space; while it is +below the floor, it deletes one whole recording in the eviction order above, removes its directory, +and measures again. It stops when the floor is met or nothing more can be deleted; the second case +logs one WARN that names the floor and the free space. The size a recording is listed with is not +used: a file held open by a download, hard links and block rounding make it differ from what the +deletion frees. Each removed recording is logged as ``Recording removed: (min_free_disk_mb)``. +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: + +- 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 + with a higher priority. The new recording goes only when nothing else of its priority or lower is + left; then it is dropped and logged like a quota drop, with ``min_free_disk_mb`` as the reason. + ``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. + +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 +also its headroom. + +**Open-time floor check.** When a new recording is about to open (not when a fault joins the post-fault +window of an open one) and the free space is already below the floor, the recording starts only when +a recording of the fault's priority or lower can be deleted. Otherwise it is not started: one INFO line +names the floor, and the ring buffer stays for the next fault. The quota estimate of the open-time check +below is unchanged. + +A failed read of the free space logs one WARN, and that pass or check skips the floor. A storage +failure during a pass logs one WARN and stops the pass with no directory removed; a removal whose +commit outcome is unknown logs one WARN, leaves the directory and stops the pass. Each of these ends the +pass with that one WARN. A recording directory whose removal fails stays on disk with no row, as on every +removal path; the floor still sees its space and can remove other recordings. + +A configuration that sets only ``min_free_disk_mb`` (or only ``sweep_interval_sec``) is a configured +retention: quota eviction then follows the eviction order above, with every priority ``0``. +``min_free_disk_mb: 0`` keeps the floor off and is still a configured retention. While the +configuration is invalid, the floor is off. + +**Test capacity (tests only).** When the environment variable +``ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE`` names a file when the fault manager starts, the free space +is not measured: it is the decimal capacity in that file, read again at each measurement, less the +sizes of the regular files under the storage path (symlinks not followed), and at least 0. A missing +or unreadable file is a failed measurement. The fault manager logs one WARN at startup, and each pass +line ends with ``source=test-capacity`` instead of ``source=filesystem``. It is not a parameter and +cannot be set over the API. Never set it on a robot. + **The priority in the list.** ``~/list_rosbags`` and the gateway's ``GET .../bulk-data/rosbags`` show each recording's priority (``priorities``, ``x-medkit.priority``): the rank above, read when the list is served. It is ``0`` without rules and while the configuration is invalid. @@ -1006,7 +1068,8 @@ it in its post-fault window is dropped when it is stored. new recordings: a recording that does not fit after the per-fault cap is dropped, and nothing is evicted for the quota. The open-time check runs for every fault. The per-fault cap and the removal of a cleared fault's recording (``auto_cleanup``) work as without rules, with ``max_bags_per_fault`` for -every fault code. A heal keeps the recordings (``on_healed`` is ``keep``). Nothing is deleted by age. +every fault code. A heal keeps the recordings (``on_healed`` is ``keep``). Nothing is deleted by age, +and the free-space floor is off. A failed attempt to open a recording keeps the ring buffer, so the next fault within ``duration_sec`` still gets its history. @@ -1041,7 +1104,8 @@ A file the fault manager cannot read is reported with a warning and skipped. string, ``keep_first: "yes"`` is a string, not a boolean), ``priority`` outside 0-1000, ``max_bags`` below 0, ``over_quota`` other than ``keep`` or ``drop``, ``on_healed`` or ``on_cleared`` other than ``keep`` or ``delete`` (``on_cleared: 1`` is an integer), a ``max_age_sec`` value below 0 or not an - integer, ``sweep_interval_sec`` outside 1-86400 or not an integer; + integer, ``sweep_interval_sec`` outside 1-86400 or not an integer, ``min_free_disk_mb`` below 0 or + not an integer; - ``max_age_sec`` with a value instead of its keys (``max_age_sec: 5``), or with a key other than ``active``, ``healed`` and ``cleared``; - an unknown severity name, an unknown field or an unknown key under the prefix; diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index 4795f661c..73a00b187 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -309,6 +309,12 @@ endif() medkit_add_launch_test(test_rosbag_max_age test/integration/test_rosbag_max_age.test.py TIMEOUT 600 LABELS "integration") + # min_free_disk_mb: the floor pass after a store and in the periodic job, the open-time check, a + # storage path not created yet, the invalid values. The cases set the free space with the test + # capacity file; one case measures the real filesystem. + medkit_add_launch_test(test_rosbag_free_space test/integration/test_rosbag_free_space.test.py + TIMEOUT 600 LABELS "integration") + if(POSTGRES_SUPPORT) medkit_add_launch_test(test_rosbag_quota_pg test/integration/test_rosbag_quota_pg.test.py TIMEOUT 300 LABELS "integration") diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 310778cbb..0e58cc4ae 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -148,18 +148,29 @@ only with an explicit `on_cleared: delete`. A recording made before such a delet the fault fails again before the recording is stored; a burst's shared recording loses only that fault's link. `max_age_sec.` deletes a fault's link to its recordings when the fault is in that status and its last FAILED report is older than the limit (`0` = no limit; a new FAILED report starts the age again). Each key -resolves on its own, an explicit `0` wins. The age sweep runs on the retention worker every `sweep_interval_sec` -(default 60), only when a key is above 0; the startup policy line says `sweep: off` or `sweep: every s`. The -age uses the system clock: on a robot without a battery-backed clock, start the fault manager after time -synchronisation. A time in the future never deletes. +resolves on its own, an explicit `0` wins. The periodic job runs on the retention worker every +`sweep_interval_sec` (default 60), only when a `max_age_sec` key or `min_free_disk_mb` is above 0; the startup +policy line says `sweep: off` or `sweep: every s`, then `floor: off` or `floor: MB`. The age uses the +system clock: on a robot without a battery-backed clock, start the fault manager after time synchronisation. A +time in the future never deletes. +`min_free_disk_mb` (default 0 = off) is the free space kept on the filesystem of `storage_path` (the system temp +directory when it is empty; a path not created yet is measured on its nearest existing parent). Below it, whole +recordings are deleted one at a time in eviction order, and the free space is measured again after each one: +the size a recording is listed with is not used. A pass runs on the retention worker after each store that kept its recording, +at its priority (never deleting a higher one; the new recording goes last and is then dropped), and in the +periodic job with no priority limit. A new recording below the floor with nothing of its priority or lower to +delete is not started. `over_quota: keep` does not keep a recording below the floor. The floor is a target, not a +reservation: other writers can change the free space between two measurements. With PostgreSQL on the same disk +it is also its headroom. A new recording evicts only recordings of equal or lower priority, lowest priority first, then cleared before healed before active, then a recording `keep_first` protects after the others, then oldest. A recording that still does not fit follows `over_quota`: `keep` (default) stores it over the quota, `drop` drops it and deletes nothing. A recording that is predicted not to fit is not started when its fault says `drop` (the ring buffer stays for the next fault). With an invalid configuration the quota is a hard stop for new recordings and nothing is -evicted for it, and nothing is deleted by age. Without any retention parameter the quota evicts the oldest -recordings first. +evicted for it, nothing is deleted by age and the floor is off. A configuration with only `min_free_disk_mb` or +only `sweep_interval_sec` is a configured retention (every priority 0). Without any retention parameter the quota +evicts the oldest recordings first. A parameter the ROS YAML loader moved (found by reading each parameters file a second time) or that has too many key segments stops the node with exit code 1. Any other error keeps the node 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`. @@ -611,8 +622,9 @@ and some of them build an `rclcpp::Clock`. and `tick`. These calls run under one internal mutex. - `core::RosbagRetention`: every rosbag retention decision (the per-fault cap, the storage quota with the retention rules, the open-time quota check, the clear, the heal, the startup reclassification, the - age sweep and the stale-row cleanup) on top of `FaultStorage::apply_rosbag_changes`. It returns - the directories to remove and never removes one itself. + age sweep, the removal step of the free-space floor and the stale-row cleanup) on top of + `FaultStorage::apply_rosbag_changes`. It returns the directories to remove and never removes one itself, + and never reads the free space. The core reaches the outside through four interfaces. The ROS adapter implements them. @@ -638,7 +650,7 @@ nanosecond times. **ROS adapter** (`fault_manager_lib` and `fault_manager_node`): the services, the `FaultEvent` publisher, wall timers that call `tick`, the capture thread pool, snapshot and rosbag capture, and the `RetentionWorker` thread that removes the directories of cleared and stale recordings and runs the age -sweep. It +sweep and the free-space floor passes. It implements the four interfaces: `ros2::RosEventSink`, `ros2::RosCaptureHooks`, `ros2::SystemWallClock` and `ros2::RosLogSink`. It converts between the core values and the messages in `ros2/fault_msg_conversions.hpp`. 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 0ced10d13..9b7b9c927 100644 --- a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml +++ b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml @@ -19,9 +19,15 @@ # on_cleared: delete. A recording shared by a burst loses only the link of that fault. # max_age_sec deletes a fault's recordings when the fault is in that status (active: PREFAILED, # PREPASSED or CONFIRMED) and its last FAILED report is older than the limit; a new FAILED report -# starts the age again. A shared recording loses only that fault's link. The age sweep runs every -# sweep_interval_sec (1-86400, default 60), only when a max_age_sec key is above 0. The age uses -# the system clock: start the fault manager after time synchronisation. +# starts the age again. A shared recording loses only that fault's link. The periodic job runs every +# sweep_interval_sec (1-86400, default 60), only when a max_age_sec key or min_free_disk_mb is above +# 0; the age sweep runs in it only with a max_age_sec key. The age uses the system clock: start the +# fault manager after time synchronisation. +# min_free_disk_mb (MiB, default 0 = off) is the free space kept on the filesystem of storage_path. +# Below it, whole recordings are deleted one at a time in the eviction order below, and the free +# space is measured again after each one. After a store the new recording deletes only recordings of +# its priority or lower, itself last (then it is dropped); the periodic job has no priority limit. +# A recording below the floor with nothing of its priority or lower to delete is not started. # A new recording evicts only recordings of equal or lower priority: lowest priority first, then # cleared, healed, active; inside that, a recording kept by keep_first after the others, then # oldest first. If it still does not fit, keep stores it over the quota and drop discards it alone. @@ -37,6 +43,7 @@ fault_manager: snapshots: rosbag: retention: + min_free_disk_mb: 1024 sweep_interval_sec: 60 defaults: priority: 10 diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 4fbf6d240..93b62cf46 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -640,6 +640,18 @@ Rosbag retention 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 + (``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``. **Delete generation.** A recording closes on the executor and is stored later on the store worker, so a fault can heal or be cleared, and fail again, between the two. The status at the store then @@ -731,6 +743,38 @@ 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 + 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 + stops when the floor is met or no step is left. The size a row lists is never used for the floor. + When the step returns the new recording, the pass removes its directory and logs the drop line + with ``min_free_disk_mb`` instead of a removal line. ``kFailed`` ends the pass with the step's WARN + and no second read; ``kNoCandidate`` ends it below the floor with one WARN that names the floor and + the free space. A directory whose removal fails stays with no row, and its space counts in the next + measurement. Every + pass ends with ``floor pass: removed= free= floor= met= + source=`` at DEBUG. A failed measurement logs one WARN and ends the pass + (``free=unknown``). For tests, ``ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE``, read with + ``std::getenv`` when the node's capture is built, replaces the measurement: the decimal capacity in + that file, read at each measurement, less the regular files under the storage path + (``recursive_directory_iterator``, symlinks not followed), at least 0. The value moves with each + removal, as on a disk that holds only the recordings, so a test sets the floor to be met after an + exact number of removals while other writers share the disk. Standard C++ only, so the switch works + on every POSIX target; the capture logs one WARN at startup, and ``source=test-capacity`` marks + 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. +- 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 + checked. **The periodic job.** ``RetentionWorker::set_periodic(interval, job)`` gives the worker thread a deadline one interval ahead. The thread waits on its condition variable until a job is posted, a @@ -740,8 +784,10 @@ periods missed behind a long job give one run. Without a periodic job the wait h the thread does not wake on its own; ``clear_periodic()`` returns it to that state. ``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 ``sweeps()``, with ``sweep_interval_sec``; the startup -policy line ends with ``sweep: off`` or ``sweep: every s`` from the same ``sweeps()``. +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 +``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``. Every path removes a directory through ``RetentionWorker::remove_recording()``, which logs the removal after it succeeded. No line announces a removal that has not happened yet: @@ -751,6 +797,8 @@ removal after it succeeded. No line announces a removal that has not happened ye - a recording of a fault that healed: ``Recording removed: (fault healed)``; - a recording whose last link aged out: ``Recording removed: (max_age_sec.active)``, ``(max_age_sec.healed)`` or ``(max_age_sec.cleared)``; +- a recording the free-space floor deleted: ``Recording removed: (min_free_disk_mb)``; + the new recording of a post-store pass gets the drop line instead; - a quota eviction: ``Deleted old bag '' to enforce storage limit``; - a stale row: no line, because its directory was already missing; - a removal that failed: a WARN with the path, the reason and the error. @@ -763,7 +811,8 @@ the bag. A heal logs ``Heal cleanup: deleted the recordings of fault ''`` The node shuts down in this order: the capture pool, then ``RosbagCapture::stop()``, which finalizes an open post-fault window and stores it, then ``RetentionWorker::drain_and_stop()``, -which runs the removals the clear and stale-row paths posted and lets a running sweep pass end. A ``RosbagCapture`` constructed +which runs the removals the clear and stale-row paths posted and the floor passes the stores posted, +and lets a running sweep pass end. A ``RosbagCapture`` constructed without a retention builds its own, with an inline worker that removes on the clearing thread. All fault manager service callbacks run on one executor thread (``rclcpp::spin`` in 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 f0f2fbb0e..64588d4eb 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 @@ -87,18 +87,26 @@ class RetentionPolicy { return configured_; } - /// One line naming each level, its fields, the pattern order and the sweep (`sweep: off` or - /// `sweep: every s`). + /// One line naming each level, its fields, the pattern order, the periodic job (`sweep: off` or + /// `sweep: every s`) and the floor (`floor: off` or `floor: MB`). std::string describe() const; /// True when a level sets a max_age_sec key above 0: only then can the age sweep remove anything. bool sweeps() const; + /// True when the periodic job runs: sweeps(), or min_free_disk_mb above 0. + bool runs_periodic() const; + /// `sweep_interval_sec`, 1 to 86400, default 60. int64_t sweep_interval_sec() const { return sweep_interval_sec_; } + /// `min_free_disk_mb`: free space in MiB kept on the filesystem of the storage path. 0 = off. + int64_t min_free_disk_mb() const { + return min_free_disk_mb_; + } + /// The first level that sets max_bags to a value other than @p value: its key relative to the /// retention prefix and the value. Levels in the order defaults, severity, fault_codes, patterns. std::optional> max_bags_other_than(int64_t value) const; @@ -117,6 +125,7 @@ class RetentionPolicy { std::map patterns_; std::vector pattern_order_; int64_t sweep_interval_sec_{60}; + int64_t min_free_disk_mb_{0}; }; /// Outcome of RetentionPolicy::parse. `policy` is set only when there is no error and no shifted key. 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 1d3ca5eed..24b532c8d 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 @@ -16,8 +16,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -59,6 +61,7 @@ enum class RemovalReason { kAgeActive, ///< max_age_sec.active: the fault is active and its last FAILED is too old kAgeHealed, ///< max_age_sec.healed kAgeCleared, ///< max_age_sec.cleared + kFreeSpace, ///< min_free_disk_mb: the free space under the storage path is below the floor }; /// Whether the age at @p now_ns of a fault whose last FAILED report was at @p last_failed_ns is @@ -95,6 +98,8 @@ struct StoreOutcome { StoreResult result{StoreResult::kStored}; DropReason drop_reason{DropReason::kNone}; + /// kStored and at least one row of the new recording was inserted: the store kept it. + bool new_rows_stored{false}; size_t recording_bytes{0}; ///< Set with kDroppedOverQuota: size of the dropped recording size_t limit_bytes{0}; ///< Set with kDroppedOverQuota: the quota /// The quota read or an eviction threw. The rows stay stored, and so do the evictions before it. @@ -112,6 +117,19 @@ struct RemovalOutcome { bool deletes{false}; ///< A status change decided to delete the fault's recordings }; +/// One removal step of the free-space floor. +struct SpaceStep { + enum class Result { + kRemoved, ///< The rows of one recording were removed + kNoCandidate, ///< No recording the step may delete is left + kFailed, ///< A storage failure or RosbagCommitInDoubt: one WARN, no directory freed + }; + + Result result{Result::kNoCandidate}; + /// With kRemoved: the directory no row names any more, with RemovalReason::kFreeSpace. + std::optional recording; +}; + struct SweepOutcome { size_t removed_links{0}; ///< Rows the pass removed std::vector unlink_paths; ///< Directories no row names any more, each path once @@ -213,6 +231,23 @@ class RosbagRetention { /// 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. + /// @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); + + /// 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); + private: struct Eviction { std::vector unlink_paths; @@ -221,6 +256,7 @@ class RosbagRetention { struct FaultFacts; struct RecordingRank; struct QuotaDecision; + struct SpaceCandidate; using FactsCache = std::unordered_map; /// A status change that may delete a fault's recordings. @@ -254,6 +290,17 @@ class RosbagRetention { RecordingRank rank_of(const RetentionPolicyState & state, const std::vector & fault_codes, FactsCache & cache); + /// Whether @p path is the first recording of one of @p fault_codes whose rule keeps the first. + /// @p first_path_by_code holds the first path of each code, from the rows before the decision. + /// @throws a failure of a fault read + bool kept_first(const RetentionPolicyState & state, const std::string & path, + const std::vector & fault_codes, + const std::map & first_path_by_code, FactsCache & cache); + + /// The recordings the floor may delete at @p priority_limit, in eviction order. Expects mutex_ held. + /// @throws a failure of a read + std::vector space_candidates(const RetentionPolicyState & state, int64_t priority_limit); + /// Whether a clear of @p fault_code deletes its recordings (on_fault_cleared). Expects mutex_ held. /// @throws a failure of the fault read bool clear_deletes(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp index b29d934ec..02f85e275 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp @@ -67,8 +67,8 @@ class RetentionWorker { uint64_t wakes() const; /// Remove the directory of @p recording on the calling thread, then log the removal with its - /// reason: `Recording removed: (its max_bags)`, `(fault cleared)`, `(fault healed)` or - /// `(max_age_sec.active)`, `.healed`, `.cleared`, or main's + /// reason: `Recording removed: (its max_bags)`, `(fault cleared)`, `(fault healed)`, + /// `(max_age_sec.active)`, `.healed`, `.cleared` or `(min_free_disk_mb)`, or main's /// `Deleted old bag '' to enforce storage limit` for the quota. No line when nothing was /// removed, and none for a stale row. A failure logs a WARN with the path, the reason and the /// error. diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp index 75c5f61f2..2e55748e2 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 @@ -90,9 +90,10 @@ class RosbagCapture { const SnapshotConfig & snapshot_config, StorageProbeFn storage_probe = {}); /// 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(). + /// 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. /// @param retention Retention decisions over @p storage - /// @param retention_worker Removes the directories a clear frees + /// @param retention_worker Removes the directories a clear frees, runs the floor passes RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const RosbagConfig & config, const SnapshotConfig & snapshot_config, std::shared_ptr retention, std::shared_ptr retention_worker, StorageProbeFn storage_probe = {}); @@ -144,6 +145,16 @@ class RosbagCapture { /// @param fault_code The fault code that healed void on_fault_healed(const std::string & fault_code); + /// 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 + /// `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); + /// Get current configuration const RosbagConfig & config() const { return config_; @@ -288,6 +299,19 @@ class RosbagCapture { /// under buffer_mutex_ and releases it before the retention is asked. bool quota_admits_recording(const std::string & fault_code); + /// The open-time floor check: false when the free space is already below the floor and no + /// recording at the priority of @p fault_code can be deleted. A failed read lets it start. + bool floor_admits_recording(const std::string & fault_code); + + /// Free bytes on the filesystem of the storage path, measured on its nearest existing directory, + /// so a path not created yet is measured where it will be created. With a test capacity file: + /// the capacity it holds less the regular files under the storage path. A failed read: one WARN, + /// nothing. + std::optional measure_free_bytes() const; + + /// After a stored recording: post a floor pass at its priority to the retention worker. + void post_floor_pass(const std::string & recording_id); + /// 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. @@ -443,6 +467,10 @@ 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_; /// Ring buffer for messages mutable std::mutex buffer_mutex_; @@ -484,10 +512,13 @@ class RosbagCapture { /// node rosbag mutex -> post_fault_timer_mutex_ -> capture_topics_mutex_ /// node rosbag mutex -> post_fault_timer_mutex_ -> writer_mutex_ /// node rosbag mutex -> post_fault_timer_mutex_ -> node_ops_mutex_ - /// node rosbag mutex -> retention mutex -> storage lock (the delete generation, the open-time quota check) + /// node rosbag mutex -> retention mutex -> storage lock (the delete generation, the open-time quota and + /// floor checks) /// core mutex -> retention mutex -> storage lock (the clear and heal hooks decide and remove) /// core mutex -> post_fault_timer_mutex_ (then the hooks detach a code the retention deleted) /// core mutex -> retention worker queue lock (the hooks post the removals) + /// node rosbag mutex -> retention worker queue lock (a store on the capture pool posts its floor pass) + /// retention mutex -> storage lock, with no lock of this class held (a floor pass on the retention worker) /// plugin_mutex() (file-scope, in rosbag_capture.cpp) -> writer_mutex_ /// The hooks hold neither the retention mutex nor post_fault_timer_mutex_ while they take the /// other, and no path takes the core mutex or a lock of this class under the retention mutex. 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 c0705c55e..41a2cc832 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 @@ -15,6 +15,7 @@ #pragma once #include +#include #include #include #include @@ -97,6 +98,10 @@ 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/retention_policy.cpp b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp index 980d57845..81bd11ebb 100644 --- a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp +++ b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp @@ -267,7 +267,7 @@ RetentionParse RetentionPolicy::parse(const FlatParams & params) { max_segments = 2; } else if (root == "severity" || root == "fault_codes" || root == "patterns") { max_segments = 3; - } else if (root == "pattern_order" || root == "sweep_interval_sec") { + } else if (root == "pattern_order" || root == "sweep_interval_sec" || root == "min_free_disk_mb") { max_segments = 1; } else { errors.push_back(key + ": unknown key"); @@ -305,6 +305,15 @@ RetentionParse RetentionPolicy::parse(const FlatParams & params) { } else { policy.sweep_interval_sec_ = *seconds; } + } else if (root == "min_free_disk_mb") { + const auto * mib = std::get_if(&value); + if (mib == nullptr) { + errors.push_back(key + ": must be an integer, got " + type_name(value)); + } else if (*mib < 0) { + errors.push_back(key + ": must be 0 or more, got " + std::to_string(*mib)); + } else { + policy.min_free_disk_mb_ = *mib; + } } else if (root == "defaults") { if (parts.size() < 2) { errors.push_back(key + ": expected defaults."); @@ -467,6 +476,10 @@ bool RetentionPolicy::sweeps() const { }); } +bool RetentionPolicy::runs_periodic() const { + return sweeps() || min_free_disk_mb_ > 0; +} + 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; @@ -526,11 +539,16 @@ std::string RetentionPolicy::describe() const { out << (i == 0 ? "" : ", ") << pattern_order_[i]; } out << "]"; - if (sweeps()) { + if (runs_periodic()) { out << "; sweep: every " << sweep_interval_sec_ << " s"; } else { out << "; sweep: off"; } + if (min_free_disk_mb_ > 0) { + out << "; floor: " << min_free_disk_mb_ << " MB"; + } else { + out << "; floor: off"; + } return out.str(); } 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 7d5b8089d..ff16f5e0f 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -183,6 +183,12 @@ struct RosbagRetention::RecordingRank { int status{kStatusCleared}; }; +struct RosbagRetention::SpaceCandidate { + std::string path; + std::string recording_id; + std::vector links; ///< Every row of the recording +}; + struct RosbagRetention::QuotaDecision { bool drop{false}; StoreOutcome::DropReason reason{StoreOutcome::DropReason::kNone}; @@ -330,6 +336,7 @@ bool RosbagRetention::apply_store(const std::vector & rows, cons for (const auto & row : changes.insert) { inserted_paths.insert(row.file_path); } + outcome.new_rows_stored = !inserted_paths.empty(); for (const auto & row : rows) { if (inserted_paths.count(row.file_path) == 0) { append_unique(outcome.unlink_paths, freed({row.file_path}, recording_ids, RemovalReason::kCap)); @@ -507,13 +514,7 @@ RosbagRetention::QuotaDecision RosbagRetention::decide_quota(const std::vector fresh.priority) { continue; } - for (const auto & code : codes) { - const auto first = first_path_by_code.find(code); - if (first != first_path_by_code.end() && first->second == candidate.path) { - const FaultFacts facts = fault_facts(state, code, cache); - candidate.kept_first = candidate.kept_first || (facts.keep_first && facts.cap >= 2); - } - } + candidate.kept_first = kept_first(state, candidate.path, codes, first_path_by_code, cache); allowed.push_back(candidate); } // Within one priority and one status, a recording keep_first protects goes after the others. @@ -602,6 +603,20 @@ RosbagRetention::RecordingRank RosbagRetention::rank_of(const RetentionPolicySta return rank; } +bool RosbagRetention::kept_first(const RetentionPolicyState & state, const std::string & path, + const std::vector & fault_codes, + const std::map & first_path_by_code, FactsCache & cache) { + bool kept = false; + for (const auto & code : fault_codes) { + const auto first = first_path_by_code.find(code); + if (first != first_path_by_code.end() && first->second == path) { + const FaultFacts facts = fault_facts(state, code, cache); + kept = kept || (facts.keep_first && facts.cap >= 2); + } + } + return kept; +} + int64_t RosbagRetention::recording_priority(const std::string & recording_id) { std::lock_guard lock(mutex_); const auto state = std::atomic_load(&state_); @@ -890,6 +905,138 @@ SweepOutcome RosbagRetention::sweep_expired(int64_t now_ns) { return outcome; } +std::vector RosbagRetention::space_candidates(const RetentionPolicyState & state, + int64_t priority_limit) { + struct Ranked { + SpaceCandidate candidate; + std::vector codes; + size_t age{0}; + RecordingRank rank; + bool kept_first{false}; + }; + std::vector ranked; + std::map index_by_path; + // The first recording of each fault code: the storage reads the rows oldest first. + std::map first_path_by_code; + for (const auto & row : storage_.get_all_rosbag_files()) { + first_path_by_code.emplace(row.fault_code, row.file_path); + const auto known = index_by_path.emplace(row.file_path, ranked.size()); + if (known.second) { + Ranked entry; + entry.candidate.path = row.file_path; + entry.candidate.recording_id = row.recording_id.empty() ? rosbag_recording_id(row.file_path) : row.recording_id; + entry.age = ranked.size(); + ranked.push_back(std::move(entry)); + } + auto & entry = ranked[known.first->second]; + entry.candidate.links.push_back({row.fault_code, row.file_path}); + entry.codes.push_back(row.fault_code); + } + + FactsCache cache; + std::vector allowed; + for (auto & entry : ranked) { + entry.rank = rank_of(state, entry.codes, cache); + if (entry.rank.priority > priority_limit) { + continue; + } + entry.kept_first = kept_first(state, entry.candidate.path, entry.codes, first_path_by_code, cache); + allowed.push_back(std::move(entry)); + } + // The quota's order: within one priority and one status, a recording keep_first protects goes after the others. + std::sort(allowed.begin(), allowed.end(), [](const Ranked & a, const Ranked & b) { + return std::tie(a.rank.priority, a.rank.status, a.kept_first, a.age) < + std::tie(b.rank.priority, b.rank.status, b.kept_first, b.age); + }); + std::vector candidates; + candidates.reserve(allowed.size()); + for (auto & entry : allowed) { + candidates.push_back(std::move(entry.candidate)); + } + return candidates; +} + +SpaceStep RosbagRetention::evict_one_for_space(int64_t priority_limit, const std::string & last_resort_recording_id) { + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + SpaceStep step; + std::vector candidates; + try { + candidates = space_candidates(*state, priority_limit); + } 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()); + step.result = SpaceStep::Result::kFailed; + return step; + } catch (...) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Rosbag free-space pass could not read the storage; nothing is removed until the next pass: unknown " + "exception"); + step.result = SpaceStep::Result::kFailed; + return step; + } + 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; + }); + if (chosen == candidates.end()) { + chosen = candidates.begin(); // the last resort is the only candidate left + } + + RosbagChangeSet changes; + changes.remove = chosen->links; + std::vector orphaned; + try { + orphaned = storage_.apply_rosbag_changes(changes).orphaned_paths; + } catch (const RosbagCommitInDoubt & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Rosbag free-space pass: the outcome of removing recording '%s' is unknown; its directory stays: %s", + chosen->recording_id.c_str(), e.what()); + step.result = SpaceStep::Result::kFailed; + return step; + } catch (const std::exception & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Rosbag free-space pass failed to remove recording '%s'; the next pass tries again: %s", + chosen->recording_id.c_str(), e.what()); + step.result = SpaceStep::Result::kFailed; + return step; + } catch (...) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Rosbag free-space pass failed to remove recording '%s'; the next pass tries again: unknown exception", + chosen->recording_id.c_str()); + step.result = SpaceStep::Result::kFailed; + return step; + } + step.result = SpaceStep::Result::kRemoved; + // Every row of the path went in this change set, so no row names the directory any more. + if (std::find(orphaned.begin(), orphaned.end(), chosen->path) != orphaned.end()) { + step.recording = FreedRecording{chosen->path, chosen->recording_id, RemovalReason::kFreeSpace}; + } + return step; +} + +bool RosbagRetention::has_space_candidate(int64_t priority_limit) { + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + try { + return !space_candidates(*state, priority_limit).empty(); + } 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; + } + FactsCache cache; + return fault_facts(*state, fault_code, cache).priority; +} + bool RosbagRetention::clear_deletes(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache) { if (state.mode != RetentionMode::kConfigured) { 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 895db5795..640274c26 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -433,10 +434,16 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" } // Last, so a constructor that throws leaves no job running on members being destroyed. Only a - // valid policy with a max age can remove anything by age. - if (retention_policy_ && retention_policy_->sweeps()) { + // 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]() { - sweep_expired_recordings(); + 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(), ""); + } }); } } @@ -951,6 +958,9 @@ 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/retention_worker.cpp b/src/ros2_medkit_fault_manager/src/retention_worker.cpp index 7f93c3b0b..ed23422d7 100644 --- a/src/ros2_medkit_fault_manager/src/retention_worker.cpp +++ b/src/ros2_medkit_fault_manager/src/retention_worker.cpp @@ -41,6 +41,8 @@ const char * removal_reason_name(core::RemovalReason reason) { return "max_age_sec.healed"; case core::RemovalReason::kAgeCleared: return "max_age_sec.cleared"; + case core::RemovalReason::kFreeSpace: + return "min_free_disk_mb"; } return "unknown"; } @@ -207,6 +209,7 @@ bool RetentionWorker::remove_recording(const core::FreedRecording & recording) { case core::RemovalReason::kAgeActive: case core::RemovalReason::kAgeHealed: case core::RemovalReason::kAgeCleared: + case core::RemovalReason::kFreeSpace: core::logf(log_sink_, core::LogLevel::kInfo, logger_name_, "Recording removed: %s (%s)", recording.recording_id.c_str(), removal_reason_name(recording.reason)); break; diff --git a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp index dc452846d..6424b95d6 100644 --- a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp @@ -20,10 +20,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -34,6 +36,9 @@ #include #include #include +#include +#include +#include #include #include "ros2_medkit_fault_manager/core/recording_manifest.hpp" @@ -165,6 +170,67 @@ void destroy_writer_under_plugin_lock(std::unique_ptr & wri writer.reset(); } +/// @p mib MiB in bytes, saturating at the largest uint64_t. +uint64_t mib_to_bytes(uint64_t mib) { + constexpr uint64_t kMib = 1024ULL * 1024ULL; + return mib > std::numeric_limits::max() / kMib ? std::numeric_limits::max() : mib * kMib; +} + +/// Names the test capacity file. Read once, when the capture is built; never a parameter. +constexpr const char * kTestCapacityEnv = "ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE"; + +/// Free bytes as the test capacity file sets them: the decimal capacity in @p capacity_file, read +/// now, less the sizes of the regular files under @p storage (symlinks not followed), floored at 0. +/// Nothing when it fails; @p error then says why. +std::optional test_capacity_free_bytes(const std::string & capacity_file, + const std::filesystem::path & storage, std::string & error) { + std::ifstream in(capacity_file); + if (!in) { + error = "the file cannot be read"; + return std::nullopt; + } + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + const auto first = text.find_first_not_of(" \t\r\n"); + const auto last = text.find_last_not_of(" \t\r\n"); + text = first == std::string::npos ? std::string() : text.substr(first, last - first + 1); + const bool digits = !text.empty() && std::all_of(text.begin(), text.end(), [](unsigned char c) { + return std::isdigit(c) != 0; + }); + uint64_t capacity = 0; + try { + capacity = digits ? std::stoull(text) : 0; + } catch (const std::out_of_range &) { + error = "'" + text + "' does not fit 64 bits"; + return std::nullopt; + } + if (!digits) { + error = "'" + text + "' is not a decimal integer"; + return std::nullopt; + } + + uint64_t used = 0; + std::error_code ec; + if (std::filesystem::exists(storage, ec)) { + for (auto it = std::filesystem::recursive_directory_iterator(storage, ec); + !ec && it != std::filesystem::recursive_directory_iterator(); it.increment(ec)) { + std::error_code entry_ec; + if (it->is_symlink(entry_ec) || !it->is_regular_file(entry_ec)) { + continue; + } + // A file removed since the listing counts as gone. + const auto size = it->file_size(entry_ec); + if (!entry_ec) { + used += size; + } + } + } + if (ec) { + error = "the storage path cannot be walked: " + ec.message(); + return std::nullopt; + } + return capacity > used ? capacity - used : 0; +} + /// Bound the probe reason so a verbose pluginlib error does not flood the log. std::string truncate_reason(const std::string & reason, size_t max_len = 200) { if (reason.size() <= max_len) { @@ -266,6 +332,13 @@ 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(), + "Free space is computed from %s (%s), not measured. This is a test setting; never set it on a robot.", + capacity_file_.c_str(), kTestCapacityEnv); + } init(std::move(storage_probe)); } @@ -575,7 +648,7 @@ void RosbagCapture::on_fault_confirmed(const std::string & fault_code) { } // A recording the store would drop anyway must not take the history the next fault needs. - if (!quota_admits_recording(fault_code)) { + if (!quota_admits_recording(fault_code) || !floor_admits_recording(fault_code)) { return; } @@ -1674,10 +1747,158 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, return false; } - // A failed quota leaves the rows stored, so the bag stays: the retention has logged it. + // A failed quota leaves the rows stored, so the bag stays: the retention has logged it. A store whose cap + // removed every new row kept nothing, and has no pass of its own. + if (outcome.new_rows_stored) { + post_floor_pass(rosbag_recording_id(bag_path)); + } return true; } +void RosbagCapture::post_floor_pass(const std::string & recording_id) { + 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()); + } +} + +bool RosbagCapture::floor_admits_recording(const std::string & fault_code) { + if (floor_bytes_ == 0) { + return true; + } + const auto free_bytes = measure_free_bytes(); + if (!free_bytes || *free_bytes >= floor_bytes_) { + 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)) { + 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 " + "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)); + return false; +} + +std::optional RosbagCapture::measure_free_bytes() const { + std::error_code ec; + std::filesystem::path path(config_.storage_path); + if (config_.storage_path.empty()) { + path = std::filesystem::temp_directory_path(ec); + } + if (!ec) { + path = std::filesystem::absolute(path, ec); + } + if (!ec && !capacity_file_.empty()) { + std::string error; + const auto free_bytes = test_capacity_free_bytes(capacity_file_, path, error); + if (!free_bytes) { + RCLCPP_WARN(node_->get_logger(), + "Could not compute the free space from %s (%s): %s; this min_free_disk_mb check is skipped", + capacity_file_.c_str(), kTestCapacityEnv, error.c_str()); + } + return free_bytes; + } + // A storage path not created yet: the nearest existing directory is on the filesystem it will use. + while (!ec && !std::filesystem::exists(path, ec) && !ec && path.has_relative_path()) { + path = path.parent_path(); + } + std::filesystem::space_info space{}; + if (!ec) { + space = std::filesystem::space(path, ec); + } + if (ec) { + RCLCPP_WARN(node_->get_logger(), + "Could not read the free space under the rosbag storage path ('%s'): %s; this min_free_disk_mb check " + "is skipped", + path.string().c_str(), ec.message().c_str()); + return std::nullopt; + } + 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; + } + // 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; + 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); + if (step.result == core::SpaceStep::Result::kFailed) { + break; // the step logged its WARN + } + if (step.result == core::SpaceStep::Result::kNoCandidate) { + exhausted = true; + break; + } + ++removed; + const auto & freed = step.recording; + if (freed && freed->recording_id != new_recording_id) { + retention_worker_->remove_recording(*freed); + } else if (freed) { + // The new recording itself: nothing of the same or a lower priority was left. + const size_t bytes = calculate_bag_size(freed->path); + std::error_code ec; + std::filesystem::remove_all(freed->path, ec); + if (ec) { + RCLCPP_WARN(node_->get_logger(), + "Recording '%s' (%zu bytes) does not fit snapshots.rosbag.retention.min_free_disk_mb (%llu " + "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()); + } 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_)); + } + } + free_bytes = measure_free_bytes(); + } + const bool met = free_bytes && *free_bytes >= floor_bytes_; + 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)); + } + 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", + capacity_file_.empty() ? "filesystem" : "test-capacity"); +} + void RosbagCapture::arm_post_fault_timer() { // Re-arm rather than replace. rcl_timer_reset() restarts the period from now and // clears the cancelled flag, so one timer serves every recording and no timer is 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 37d07377f..1ec413fbc 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 @@ -108,8 +108,9 @@ class FaultManager: # The newest process, named in a failed call's message. latest = None - def __init__(self, params, params_file=None, namespace=None): + def __init__(self, params, params_file=None, namespace=None, env_extra=None): env = os.environ.copy() + env.update(env_extra or {}) env['RCUTILS_LOGGING_BUFFERED_STREAM'] = '0' # Each line carries the wall-clock time it was logged at (line_stamp_ns). env['RCUTILS_CONSOLE_OUTPUT_FORMAT'] = '[{severity}] [{time}] [{name}]: {message}' @@ -208,14 +209,15 @@ def kill(self): @contextlib.contextmanager -def running_fault_manager(params, wait_for_subscription=True, params_file=None): +def running_fault_manager(params, wait_for_subscription=True, params_file=None, env_extra=None): """ Start a fault manager, yield it once ready, end it with SIGTERM and assert exit code 0. A sanitizer report inside the process shows as a non-zero exit code. The body may end the - process itself (a SIGTERM inside it); the exit code is checked either way. + process itself (a SIGTERM inside it); the exit code is checked either way. `env_extra` adds + environment variables to the process. """ - fm = FaultManager(params, params_file=params_file) + fm = FaultManager(params, params_file=params_file, env_extra=env_extra) try: if fm.wait_line(r'FaultManager node started', timeout=STARTUP_TIMEOUT_SEC) is None: raise AssertionError('the fault manager never started:\n' + fm.output()[-4000:]) @@ -571,6 +573,9 @@ def base_params(db_path, storage_path, **overrides): # A pass logs this after its removal lines; `now` is the time it decided with. SWEEP_LINE = r'retention sweep: now=(\d+) removed=(\d+)' AGE_REMOVAL = r'Recording removed: (\S+) \(max_age_sec\.{}\)' +# The DEBUG line that ends every min_free_disk_mb pass: removed, free, floor, met, source. +FLOOR_PASS = (r'floor pass: removed=(\d+) free=(\d+|unknown) floor=(\d+) met=(true|false) ' + r'source=(filesystem|test-capacity)') def expired_at(last_failed_ns, limit_sec=AGE_SEC): @@ -613,13 +618,13 @@ def row_paths(self, code): return [path for row_code, path in self.stored_rows() if row_code == code] @contextlib.contextmanager - def fm_run(self, params_file=None, **overrides): + def fm_run(self, params_file=None, env_extra=None, **overrides): """Start a fault manager on this case's storage and yield it ready for faults.""" params = base_params(self.db, self.storage, **overrides) params.update(self.storage_params()) self.client.reset_clients() self.client.wait_for_no_payload_subscriber() - with running_fault_manager(params, params_file=params_file) as fm: + with running_fault_manager(params, params_file=params_file, env_extra=env_extra) as fm: self.client.wait_for_services() if params.get('snapshots.rosbag.enabled'): self.client.wait_for_payload_subscriber() @@ -774,6 +779,16 @@ def check_heal_deletes(self): self.assertEqual(fm.count_lines(HEALED_REMOVAL, since=mark), 1, fm.output()[-3000:]) self.assertEqual(bag_dirs(self.storage), []) + def wait_floor_pass(self, fm, since=0): + """ + Wait for the end of a min_free_disk_mb pass from index `since` on; return match and index. + + The pass runs on the retention worker, after the store's own lines. + """ + line, at = fm.wait_line_at(FLOOR_PASS, since=since) + self.assertIsNotNone(line, 'no floor pass:\n' + fm.output()[-3000:]) + return line, at + def last_failed_ns(self, code): """Return the time of the last FAILED report of `code`.""" return time_ns(self.client.get_fault(code).fault.last_occurred) 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 0723fdc3d..b151b8efc 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 @@ -104,7 +104,7 @@ ['defaults.over_quota', 'maybe']), 'unknown severity': ({'severity': {'FATAL': {'priority': 1}}}, ['FATAL']), 'unknown field': ({'defaults': {'max_count': 3}}, ['defaults.max_count', 'unknown field']), - 'unknown key': ({'min_free_disk_mb': 100}, ['min_free_disk_mb', 'unknown key']), + 'unknown key': ({'reserve_disk_mb': 100}, ['reserve_disk_mb', 'unknown key']), 'match outside patterns': ({'defaults': {'match': 'A.*'}}, ['defaults.match', 'patterns']), 'pattern without match': ({'patterns': {'p': {'priority': 1}}, 'pattern_order': ['p']}, ['patterns.p', 'no match']), diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_free_space.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_free_space.test.py new file mode 100644 index 000000000..0eeb6651f --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_free_space.test.py @@ -0,0 +1,408 @@ +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +The retention field min_free_disk_mb against a real fault_manager_node on SQLite. + +Other writers move the free space of a shared filesystem. The cases that need the floor met or +broken by a known amount therefore start the fault manager with a test capacity file +(ROS2_MEDKIT_TEST_STORAGE_CAPACITY_FILE): its free space is the capacity less the regular files +under the storage path. The test computes the same sum with its own walk, sets the capacity so that +the floor is met after an exact number of removals, and asserts its precondition from its own +computation. One case keeps the real measurement, with a floor far above the free space. +""" + +import math +import os +import pathlib +import re +import stat +import sys +import time + +from launch import LaunchDescription +import launch_testing +import launch_testing.actions +import launch_testing.util + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rosbag_fm_harness import ( # noqa: E402 + bag_dirs, FLOOR_PASS, HEALING, MESSAGE_SIZE, MIB, NS_PER_SEC, poll, RetentionCase, rules, + SEVERITY_CRITICAL, SEVERITY_ERROR, SEVERITY_WARN, SIZE_SLACK, sqlite_exec, SWEEP_EVERY_SECOND, + SWEEP_LINE, +) +import yaml # noqa: E402 + +POLICY_LINE = r'Rosbag retention rules: (.*)' +FREE_REMOVAL = r'Recording removed: (\S+) \(min_free_disk_mb\)' +BELOW_FLOOR = r'free-space pass stopped below snapshots\.rosbag\.retention\.min_free_disk_mb' +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\. This is a test setting; never set it on a robot\.') +# No cap, a quota far above what the cases write, and a clear that keeps. +COMMON = {'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 4000, + 'snapshots.rosbag.auto_cleanup': False} +PRIORITIES = {'severity.WARN.priority': 10, 'severity.ERROR.priority': 50, + 'severity.CRITICAL.priority': 100} +# The periodic pass stays out of the store-time cases. +NO_PERIODIC_PASS = {'sweep_interval_sec': 86400} +RECORD_MIB = 8 +FLOOR_MB = 64 +FLOOR = FLOOR_MB * MIB +# The real filesystem case puts the floor this far above the measured free space. +REAL_MARGIN = 20 * 1024 * MIB + +INVALID_CASES = { + 'negative': ({'min_free_disk_mb': -1}, ['min_free_disk_mb', 'got -1']), + 'string': ({'min_free_disk_mb': '10'}, ['min_free_disk_mb', 'string']), +} + + +def generate_test_description(): + return LaunchDescription([launch_testing.util.KeepAliveProc(), + launch_testing.actions.ReadyToTest()]), {} + + +def free_bytes(path): + """Return the bytes available on the filesystem of `path` or of its nearest existing parent.""" + while not os.path.exists(path): + path = os.path.dirname(path) + stats = os.statvfs(path) + return stats.f_bavail * stats.f_frsize + + +def regular_bytes(path): + """Return the sizes of the regular files under `path`, symlinks not followed; 0 when absent.""" + 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 + + +class TestRosbagFreeSpace(RetentionCase): + + def capacity_file(self): + return os.path.join(os.path.dirname(self.db), 'capacity') + + def set_capacity(self, capacity): + """Replace the capacity file in one step, so the fault manager never reads half of it.""" + self.assertIsInstance(capacity, int) + staged = self.capacity_file() + '.new' + with open(staged, 'w') as handle: + handle.write(f'{capacity}\n') + os.replace(staged, self.capacity_file()) + return capacity + + def used(self): + return regular_bytes(self.storage) + + def write_params(self, retention): + """Write a parameters file holding `retention` under snapshots.rosbag.retention.""" + path = os.path.join(os.path.dirname(self.db), 'retention.yaml') + tree = {'fault_manager': {'ros__parameters': {'snapshots': {'rosbag': { + 'retention': retention}}}}} + with open(path, 'w') as handle: + yaml.safe_dump(tree, handle) + return path + + def policy(self, fm): + policy = fm.wait_line(POLICY_LINE) + self.assertIsNotNone(policy, fm.output()[-3000:]) + return policy.group(1) + + def capacity_run(self, retention, **overrides): + """Start a fault manager with the floor, `retention` and the test capacity file.""" + return self.fm_run(env_extra={CAPACITY_ENV: self.capacity_file()}, **COMMON, **overrides, + **rules({**retention, 'min_free_disk_mb': FLOOR_MB})) + + def assert_test_capacity(self, fm): + """Fail unless the startup WARN names the capacity file and the rules hold the floor.""" + self.assert_rules_valid(fm) + self.assertIn(f'floor: {FLOOR_MB} MB', self.policy(fm)) + warned = fm.wait_line(CAPACITY_WARN) + self.assertIsNotNone(warned, fm.output()[-3000:]) + self.assertEqual(warned.group(1), self.capacity_file()) + self.assertEqual(fm.count_lines(CAPACITY_WARN), 1) + + def assert_pass(self, end, removed, met, free): + """Check the end line of a test-capacity pass: removals, met, the free bytes it saw.""" + self.assertEqual((end.group(1), end.group(4), end.group(5)), + (str(removed), met, 'test-capacity'), end.string) + self.assertEqual(int(end.group(2)), free, end.string) + self.assertEqual(int(end.group(3)), FLOOR, end.string) + + def free_removals(self, fm, since, until): + """Return the recording ids the floor removed between two line indexes, in order.""" + found = (re.search(FREE_REMOVAL, line) for line in fm.lines_between(since, until)) + return [match.group(1) for match in found if match] + + def check_store_drops_new(self, code, retention, higher=()): + """ + Check that a new recording of `code` below the floor is dropped when nothing else can go. + + The floor is met when `code` confirms, so the open-time check lets it start; the stored + recording breaks it, and the pass drops it. `higher` holds (code, path) of recordings it + may not delete. + """ + used = self.used() + capacity = self.set_capacity(used + FLOOR + RECORD_MIB * MIB // 2) + # The open-time check passes, and the payload alone breaks the floor at the store. + self.assertGreaterEqual(capacity - used, FLOOR) + self.assertLess(capacity - used - RECORD_MIB * MIB, FLOOR) + with self.capacity_run({**retention, **NO_PERIODIC_PASS}) as fm: + self.assert_test_capacity(fm) + mark = fm.mark() + self.client.publish_bytes(RECORD_MIB * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report(code, SEVERITY_WARN).accepted) + end, index = self.wait_floor_pass(fm, since=mark) + created = fm.wait_line(rf'Bag file created: (\S*fault_{code}_\d+)', since=mark) + self.assertIsNotNone(created, fm.output()[-3000:]) + path = created.group(1) + dropped = fm.wait_line( + rf"Recording '{re.escape(path)}' \((\d+) bytes\) dropped.*min_free_disk_mb", + since=mark) + self.assertIsNotNone(dropped, fm.output()[-3000:]) + self.assertGreaterEqual(int(dropped.group(1)), RECORD_MIB * MIB) + self.assert_pass(end, 1, 'true', capacity - self.used()) + self.assertEqual(self.free_removals(fm, mark, index), []) + self.assertEqual(fm.count_lines(BELOW_FLOOR, since=mark), 0, fm.output()[-3000:]) + self.assert_recording_gone(code, path) + for other, kept in higher: + self.assert_recording_present(other, kept) + + def test_store_deletes_lower_priorities_first(self): + """After a store the floor deletes WARN recordings oldest first until it is met.""" + with self.fm_run(**COMMON, **rules(PRIORITIES)) as fm: + self.assert_rules_valid(fm) + warns = [self.record(fm, code, RECORD_MIB, severities={code: SEVERITY_WARN}) + for code in ('WARN_1', 'WARN_2', 'WARN_3')] + sizes = [regular_bytes(path) for path in warns] + used = self.used() + # The floor is met after two removals; the new recording is its payload plus some slack. + estimate = RECORD_MIB * MIB + int(SIZE_SLACK) // 2 + capacity = self.set_capacity(used + FLOOR + estimate - sizes[0] - sizes[1] // 2) + with self.capacity_run({**PRIORITIES, **NO_PERIODIC_PASS}) as fm: + self.assert_test_capacity(fm) + mark = fm.mark() + critical = self.record(fm, 'CRIT', RECORD_MIB, severities={'CRIT': SEVERITY_CRITICAL}) + end, index = self.wait_floor_pass(fm, since=mark) + # The state the pass started from: one removal is not enough, two are. + at_store = capacity - used - regular_bytes(critical) + self.assertLess(at_store, FLOOR) + self.assertLess(at_store + sizes[0], FLOOR) + self.assertGreaterEqual(at_store + sizes[0] + sizes[1], FLOOR) + self.assert_pass(end, 2, 'true', capacity - self.used()) + self.assertEqual(self.free_removals(fm, mark, index), + [os.path.basename(path) for path in warns[:2]]) + self.assertEqual(fm.count_lines(BELOW_FLOOR, since=mark), 0, fm.output()[-3000:]) + self.assert_recording_gone('WARN_1', warns[0]) + self.assert_recording_gone('WARN_2', warns[1]) + self.assert_recording_present('WARN_3', warns[2]) + self.assert_recording_present('CRIT', critical) + + def test_store_that_kept_nothing_posts_no_pass(self): + """A recording the cap discards at its store posts no floor pass.""" + capped = {'fault_codes.CAPPED.max_bags': 1, 'fault_codes.CAPPED.priority': 50, + 'fault_codes.LATER.priority': 10, 'fault_codes.LATER.on_cleared': 'delete'} + with self.fm_run(**COMMON, **rules(capped)) as fm: + self.assert_rules_valid(fm) + stored = self.record(fm, 'CAPPED', RECORD_MIB) + # The clear keeps the recording; the next FAILED report confirms again and records. + self.assertTrue(self.client.clear('CAPPED').success) + self.assertEqual(self.row_paths('CAPPED'), [stored]) + # The stored row is newer than any recording to come: max_bags 1 keeps it, drops the next. + future_ns = time.time_ns() + 365 * 86400 * NS_PER_SEC + sqlite_exec(self.db, 'UPDATE rosbag_files SET created_at_ns = ? WHERE fault_code = ?', + future_ns, 'CAPPED') + capacity = self.set_capacity(self.used() + FLOOR - MIB) + with self.capacity_run({**capped, **NO_PERIODIC_PASS}) as fm: + self.assert_test_capacity(fm) + mark = fm.mark() + self.client.publish_bytes(RECORD_MIB * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('CAPPED').accepted) + created = fm.wait_line(r'Bag file created: (\S*fault_CAPPED_\d+)', since=mark) + self.assertIsNotNone(created, fm.output()[-3000:]) + discarded = fm.wait_line(r'Recording removed: (\S+) \(its max_bags\)', since=mark) + self.assertIsNotNone(discarded, fm.output()[-3000:]) + self.assertEqual(discarded.group(1), os.path.basename(created.group(1))) + # A pass after this store would act: the floor is broken. + self.assertLess(capacity - self.used(), FLOOR) + + # The worker runs its jobs in order. A later store posts its pass, and a clear posts + # its removal after it: once the clear's job ran, every pass posted before it ran. + self.set_capacity(self.used() + FLOOR + 8 * RECORD_MIB * MIB) + self.record(fm, 'LATER', RECORD_MIB) + self.assertTrue(self.client.clear('LATER').success) + cleaned = fm.wait_line(r"Auto-cleanup: deleted bag file for fault 'LATER'", since=mark) + self.assertIsNotNone(cleaned, fm.output()[-3000:]) + passes = [re.search(FLOOR_PASS, line) for line in fm.lines_between(mark, fm.mark())] + passes = [match for match in passes if match] + self.assertEqual([(match.group(1), match.group(4)) for match in passes], + [('0', 'true')], fm.output()[-3000:]) + self.assertEqual(fm.count_lines(BELOW_FLOOR, since=mark), 0, fm.output()[-3000:]) + self.assertFalse(os.path.exists(created.group(1))) + self.assert_recording_present('CAPPED', stored) + + def test_store_never_deletes_higher(self): + """Only CRITICAL recordings exist: a WARN recording below the floor is dropped instead.""" + with self.fm_run(**COMMON, **rules(PRIORITIES)) as fm: + critical = [(code, self.record(fm, code, RECORD_MIB, + severities={code: SEVERITY_CRITICAL})) + for code in ('CRIT_1', 'CRIT_2')] + self.check_store_drops_new('WARN_NEW', PRIORITIES, higher=critical) + + def test_keep_does_not_break_the_floor(self): + """over_quota: keep does not keep a recording that leaves free space below the floor.""" + self.check_store_drops_new('KEEPER', {'fault_codes.KEEPER.over_quota': 'keep', + 'fault_codes.KEEPER.priority': 1000}) + + def test_open_refused_below_the_floor(self): + """ + Below the floor with nothing at the fault's priority to delete, no recording starts. + + The ring buffer stays: the next recording holds what was buffered before the refusal. + """ + self.set_capacity(self.used() + FLOOR + 8 * RECORD_MIB * MIB) + with self.capacity_run({**PRIORITIES, **NO_PERIODIC_PASS}) as fm: + self.assert_test_capacity(fm) + mark = fm.mark() + held = self.record(fm, 'CRIT_HELD', RECORD_MIB, + severities={'CRIT_HELD': SEVERITY_CRITICAL}) + end, _ = self.wait_floor_pass(fm, since=mark) + self.assertEqual((end.group(1), end.group(4)), ('0', 'true'), end.string) + + self.client.publish_bytes(RECORD_MIB * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + capacity = self.set_capacity(self.used() + FLOOR - MIB) + self.assertLess(capacity - self.used(), FLOOR) + known = bag_dirs(self.storage) + mark = fm.mark() + self.assertTrue(self.client.report('WARN_OPEN', SEVERITY_WARN).accepted) + refused = fm.wait_line(r"Not recording fault 'WARN_OPEN': .*min_free_disk_mb", + since=mark) + self.assertIsNotNone(refused, fm.output()[-3000:]) + self.assertEqual(bag_dirs(self.storage), known) + self.assertEqual(self.row_paths('WARN_OPEN'), []) + + self.set_capacity(self.used() + FLOOR + 8 * RECORD_MIB * MIB) + self.assertTrue(self.client.clear('WARN_OPEN').success) + mark = fm.mark() + self.assertTrue(self.client.report('WARN_OPEN', SEVERITY_WARN).accepted) + done = fm.wait_line(r'Bag file created: (\S*fault_WARN_OPEN_\d+)', since=mark) + self.assertIsNotNone(done, fm.output()[-3000:]) + self.check_size(done.group(1), RECORD_MIB) + self.assert_recording_present('CRIT_HELD', held) + + def test_missing_nested_path_is_measured_on_its_ancestor(self): + """A storage path not created yet is measured on the filesystem of its nearest parent.""" + root = os.path.dirname(self.db) + self.storage = os.path.join(root, 'not', 'yet') + self.assertFalse(os.path.exists(os.path.join(root, 'not'))) + floor_mb = math.ceil((free_bytes(root) + REAL_MARGIN) / MIB) + with self.fm_run(**COMMON, **rules({**PRIORITIES, **SWEEP_EVERY_SECOND, + 'min_free_disk_mb': floor_mb})) as fm: + self.assert_rules_valid(fm) + self.assertEqual(fm.count_lines(CAPACITY_WARN), 0, fm.output()[-3000:]) + self.assertLess(free_bytes(root), floor_mb * MIB) + self.client.publish_bytes(RECORD_MIB * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + mark = fm.mark() + self.assertTrue(self.client.report('NESTED', SEVERITY_WARN).accepted) + refused = fm.wait_line(r"Not recording fault 'NESTED': .*min_free_disk_mb", + since=mark) + self.assertIsNotNone(refused, fm.output()[-3000:]) + self.assertFalse(os.path.exists(os.path.join(root, 'not'))) + end, _ = self.wait_floor_pass(fm) + self.assertEqual((end.group(1), end.group(4), end.group(5)), + ('0', 'false', 'filesystem'), end.string) + + def test_periodic_pass_has_no_priority_limit(self): + """With no recording being made the pass deletes in eviction order, the highest last.""" + recorded = [('ERR_ACTIVE', SEVERITY_ERROR), ('WARN_ACTIVE', SEVERITY_WARN), + ('WARN_CLEARED', SEVERITY_WARN), ('CRIT_ACTIVE', SEVERITY_CRITICAL), + ('WARN_HEALED', SEVERITY_WARN), ('ERR_CLEARED', SEVERITY_ERROR)] + severities = dict(recorded) + paths = {} + with self.fm_run(**COMMON, **HEALING, **rules(PRIORITIES)) as fm: + self.assert_rules_valid(fm) + for code, _ in recorded: + paths[code] = self.record(fm, code, RECORD_MIB, severities=severities) + self.assertTrue(self.client.clear('WARN_CLEARED').success) + self.assertTrue(self.client.clear('ERR_CLEARED').success) + self.heal('WARN_HEALED') + # Lowest priority first; inside one priority cleared, healed, active; then oldest first. + expected = ['WARN_CLEARED', 'WARN_HEALED', 'WARN_ACTIVE', 'ERR_CLEARED', 'ERR_ACTIVE', + 'CRIT_ACTIVE'] + # Free space is 0 now, and deleting every recording still leaves it below the floor. + capacity = self.set_capacity(self.used()) + self.assertLess(capacity, FLOOR) + with self.capacity_run({**PRIORITIES, **SWEEP_EVERY_SECOND}, **HEALING) as fm: + self.assert_test_capacity(fm) + self.assertEqual(self.client.get_fault('WARN_HEALED').fault.status, 'HEALED') + self.assertEqual(self.client.get_fault('ERR_CLEARED').fault.status, 'CLEARED') + end, index = self.wait_floor_pass(fm) + self.assert_pass(end, 6, 'false', capacity) + self.assertEqual(self.free_removals(fm, 0, index), + [os.path.basename(paths[code]) for code in expected]) + below = [line for line in fm.lines_between(0, index) if re.search(BELOW_FLOOR, line)] + self.assertEqual(len(below), 1, below) + self.assertEqual(bag_dirs(self.storage), []) + self.assertEqual(self.stored_rows(), []) + + def test_floor_off(self): + """min_free_disk_mb: 0 is a configured retention with no floor: no pass, no removal.""" + with self.fm_run(**COMMON, **rules({'min_free_disk_mb': 0, + 'defaults.max_age_sec.cleared': 3600, + **SWEEP_EVERY_SECOND})) as fm: + self.assert_rules_valid(fm) + policy = self.policy(fm) + self.assertIn('floor: off', policy) + self.assertIn('sweep: every 1 s', policy) + mark = fm.mark() + path = self.record(fm, 'FLOOR_OFF', RECORD_MIB, + severities={'FLOOR_OFF': SEVERITY_ERROR}) + _, stored = fm.wait_line_at(r'Bag file created: ', since=mark) + # The worker runs posted jobs before its periodic job: a pass posted by the store has + # run once a periodic pass that started after the store ended. + _, first = fm.wait_line_at(SWEEP_LINE, since=stored + 1) + self.assertIsNotNone(first, fm.output()[-3000:]) + second, _ = fm.wait_line_at(SWEEP_LINE, since=first + 1) + self.assertIsNotNone(second, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(FLOOR_PASS), 0, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(FREE_REMOVAL), 0, fm.output()[-3000:]) + self.assert_recording_present('FLOOR_OFF', path) + + def test_invalid_values_degrade(self): + """Each invalid value degrades with the own fault naming the key; no floor pass runs.""" + for name, (retention, expected) in INVALID_CASES.items(): + with self.subTest(name): + self.new_scratch() + with self.fm_run(params_file=self.write_params(retention)) as fm: + self.assertIsNotNone(fm.wait_line(r'Invalid rosbag retention configuration'), + fm.output()[-3000:]) + found = [] + + def confirmed(): + found[:] = [fault for fault in self.own_faults() + if fault.status == 'CONFIRMED'] + return bool(found) + + self.assertTrue(poll(confirmed), fm.output()[-3000:]) + for text in expected: + self.assertIn(text, found[0].description) + self.assertIsNone(re.search(POLICY_LINE, fm.output())) + self.assertEqual(fm.count_lines(FLOOR_PASS), 0, fm.output()[-3000:]) 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 12e8087c6..3d341d317 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp @@ -13,6 +13,7 @@ // limitations under the License. #include +#include #include #include @@ -100,8 +101,16 @@ class LogCapture { /// How many captured lines contain `needle`. int count(const std::string & needle) const { std::lock_guard lk(mutex_); - return static_cast(std::count_if(lines_.begin(), lines_.end(), [&needle](const std::string & line) { - return line.find(needle) != std::string::npos; + return static_cast(std::count_if(lines_.begin(), lines_.end(), [&needle](const Line & line) { + return line.text.find(needle) != std::string::npos; + })); + } + + /// How many captured lines have `severity` (an RCUTILS_LOG_SEVERITY value). + int count_at(int severity) const { + std::lock_guard lk(mutex_); + return static_cast(std::count_if(lines_.begin(), lines_.end(), [severity](const Line & line) { + return line.severity == severity; })); } @@ -111,7 +120,12 @@ class LogCapture { return current; } - static void handler(const rcutils_log_location_t * /*location*/, int /*severity*/, const char * /*name*/, + struct Line { + int severity; + std::string text; + }; + + static void handler(const rcutils_log_location_t * /*location*/, int severity, const char * /*name*/, rcutils_time_point_value_t /*timestamp*/, const char * format, va_list * args) { char buf[1024]; va_list copy; @@ -132,11 +146,11 @@ class LogCapture { return; } std::lock_guard lk(capture->mutex_); - capture->lines_.emplace_back(buf); + capture->lines_.push_back({severity, buf}); } mutable std::mutex mutex_; - std::vector lines_; + std::vector lines_; }; /// The apt package name the storage warnings must name for `format`, built the @@ -3425,3 +3439,65 @@ TEST_F(RosbagCaptureIntegrationTest, ConcurrentCapturesInOneProcessSurviveEachOt capture.stop(); } + +/// Storage whose rosbag link removals are applied and then reported in doubt, as a commit whose +/// reply never arrived. Reads keep working. +class InDoubtRemovalStorage : public InMemoryFaultStorage { + public: + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + auto applied = InMemoryFaultStorage::apply_rosbag_changes(changes); + if (!changes.remove.empty()) { + ++removals_in_doubt; + throw ros2_medkit_fault_manager::RosbagCommitInDoubt("the reply to COMMIT never arrived"); + } + return applied; + } + + int removals_in_doubt = 0; +}; + +// A step in doubt ends the pass with its own WARN. A read after it finds the applied removal, and +// must not add a WARN that nothing is left. +TEST(RosbagCapture, FloorPassWarnsOnceWhenTheStepFails) { + rclcpp::init(0, nullptr); + auto node = std::make_shared("floor_pass_in_doubt_node"); + InDoubtRemovalStorage storage; + const auto dir = std::filesystem::temp_directory_path() / ("floor_in_doubt_" + std::to_string(::getpid())); + const auto bag = dir / "fault_IN_DOUBT_1"; + std::filesystem::create_directories(bag); + std::ofstream(bag / "data.mcap") << "payload"; + ros2_medkit_fault_manager::RosbagFileInfo row; + row.fault_code = "IN_DOUBT"; + row.file_path = bag.string(); + row.recording_id = ros2_medkit_fault_manager::rosbag_recording_id(row.file_path); + row.format = "mcap"; + row.size_bytes = 7; + row.created_at_ns = 1; + seed_rosbag_rows(storage, {row}); + + 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"); + { + RosbagCapture capture(node.get(), &storage, config, SnapshotConfig{}, retention, worker); + LogCapture logs; + worker->post("floor", [&capture]() { + capture.run_floor_pass(std::numeric_limits::max(), ""); + }); + EXPECT_EQ(storage.removals_in_doubt, 1); + EXPECT_EQ(logs.count_at(RCUTILS_LOG_SEVERITY_WARN), 1) << "the pass logs one WARN in all"; + EXPECT_EQ(logs.count("the outcome of removing recording"), 1); + EXPECT_EQ(logs.count("free-space pass stopped below"), 0); + EXPECT_TRUE(storage.get_all_rosbag_files().empty()) << "the removal was not applied"; + EXPECT_TRUE(std::filesystem::exists(bag)) << "a removal in doubt removed the directory"; + } + node.reset(); + rclcpp::shutdown(); + std::error_code ec; + std::filesystem::remove_all(dir, ec); +}