From 54193a60a668db9b1ef04d415d501973cc792219 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:06 +0100 Subject: [PATCH] fault_manager: max_age_sec per rosbag retention rule and the age sweep * feat(fault_manager): max_age_sec per rosbag retention rule and the age sweep * fix(fault_manager): the age sweep logs the time it decided with --- docs/config/fault-manager.rst | 61 +++- docs/tutorials/snapshots.rst | 8 +- src/ros2_medkit_fault_manager/CMakeLists.txt | 5 + src/ros2_medkit_fault_manager/README.md | 19 +- .../config/rosbag_retention.example.yaml | 17 +- .../design/index.rst | 37 +- .../core/retention_policy.hpp | 23 +- .../core/rosbag_retention.hpp | 32 +- .../fault_manager_node.hpp | 5 + .../retention_worker.hpp | 40 ++- .../src/core/retention_policy.cpp | 133 ++++++- .../src/core/rosbag_retention.cpp | 117 +++++- .../src/fault_manager_node.cpp | 18 + .../src/retention_worker.cpp | 77 +++- .../test/integration/rosbag_fm_harness.py | 70 +++- .../integration/test_rosbag_max_age.test.py | 334 ++++++++++++++++++ .../integration/test_rosbag_quota_pg.test.py | 3 + .../test/test_retention_policy.cpp | 102 +++++- .../test/test_rosbag_retention.cpp | 149 ++++++++ 19 files changed, 1185 insertions(+), 65 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_max_age.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 24cf9b9c2..6cbdb9745 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -791,8 +791,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``, and what happens to the fault's recordings -when it heals (``on_healed``) or is cleared (``on_cleared``). They are read at startup, validated and +``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 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 @@ -805,8 +806,12 @@ before. An example file is ``config/rosbag_retention.example.yaml``. snapshots: rosbag: retention: + sweep_interval_sec: 60 defaults: priority: 10 + max_age_sec: + healed: 604800 + cleared: 86400 severity: INFO: on_healed: delete @@ -844,6 +849,11 @@ Grammar, relative to ``snapshots.rosbag.retention.``: - Rule of the faults the pattern matches. * - ``pattern_order`` - 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. + * - ``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``. Fields: @@ -875,6 +885,12 @@ Fields: - ``keep`` or ``delete``; default ``delete`` when ``rosbag.auto_cleanup`` is true and the fault's ``max_bags`` is 1, else ``keep`` - What happens to the fault's recordings when it becomes CLEARED. + * - ``max_age_sec`` + - keys ``active``, ``healed``, ``cleared``; each an integer ``0`` or more in seconds, default + ``0`` (no limit) + - Delete the fault's recordings when the fault is in that status and its last FAILED report is + older than the limit. ``active`` means PREFAILED, PREPASSED or CONFIRMED: a fault reported + once and never again ages out while it is still CONFIRMED. **The cap per fault code.** When a recording is stored, each of its fault codes keeps at most its rule's ``max_bags`` recordings, resolved with the fault's severity as it is stored now. Over the cap the @@ -916,6 +932,36 @@ code becomes CLEARED. Its recordings are deleted only when its rule says ``on_cl explicitly; the default of ``on_cleared`` does not apply there. A restart with healing turned off thus deletes nothing that no rule asks to delete. +**The age.** ``max_age_sec`` counts from the fault's last FAILED report (``last_occurred``). A new +FAILED report starts the age again, in every status: a heal or a clear stores no new time, so a +fault that healed or was cleared long after its last FAILED report can lose its recordings at the +first pass after the change. A recording goes when its age in whole seconds is above the limit of +the fault's current status, resolved with the fault's current severity. Each ``max_age_sec`` key +resolves on its own across the four levels, and an explicit ``0`` at a more specific level wins for +that key: ``fault_codes..max_age_sec.active: 0`` keeps that code's recordings while +``defaults.max_age_sec.active`` is set. The age removes the link of the fault concerned, in any +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, +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 +wall-clock time the pass decided with. A storage failure logs one WARN +and the next pass tries again. A removal whose commit outcome is unknown logs one WARN and leaves +the directories; a committed removal then leaves a directory with no row. A FAILED report that +arrives while a pass runs, between its read and its delete, can lose the old recording the report +would have kept; the next confirmation records again. A recording stored after its fault's age +expired is removed by the next pass. While the configuration is invalid there is no age deletion. + +The age uses the system clock and is not paused after a start or a clock jump. On a robot without a +battery-backed clock the fault manager must start after time synchronisation (with systemd: +``After=time-sync.target`` together with ``chrony-wait.service`` or +``systemd-time-wait-sync.service``), or recordings made before it can be deleted after it. A last +FAILED time in the future (a negative age) never deletes. + With ``audit_log.fail_closed: true``, a failed audit append stops the status actions that follow it: a heal stops before its ``on_healed``, a startup reclassification before its ``on_cleared``, and a symptom auto-cleared with its root cause stops its own ``on_cleared`` and that of the root cause. The @@ -960,7 +1006,7 @@ 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``). +every fault code. A heal keeps the recordings (``on_healed`` is ``keep``). Nothing is deleted by age. A failed attempt to open a recording keeps the ring buffer, so the next fault within ``duration_sec`` still gets its history. @@ -994,13 +1040,18 @@ A file the fault manager cannot read is reported with a warning and skipped. - a value of the wrong type (``priority: 5.0`` is a double, not an integer, ``max_bags: "3"`` is a 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); + ``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; +- ``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; - ``match`` outside ``patterns``, a pattern without ``match``, a ``match`` that is not a valid regular expression; - a pattern missing from ``pattern_order``, a label in ``pattern_order`` that names no pattern, or twice. A key with more segments than the grammar allows (``fault_codes.A.B.priority``), from a parameters -file or from ``-p``, stops the fault manager with exit code 1 too, also with rosbag capture off. An +file or from ``-p``, stops the fault manager with exit code 1 too, also with rosbag capture off. Only +``max_age_sec`` takes one more segment, for its status: ``fault_codes.A.B.max_age_sec.active`` (a +dotted code) and ``fault_codes.A.B.max_age_sec`` are such keys. An empty list (``pattern_order: []``, leave the key out) fails while the node is built: the fault manager logs "Fault manager did not start" and exits with code 1. An empty key segment (``fault_codes..priority`` through ``-p``, or an empty YAML key) aborts inside ROS initialisation, before the fault manager runs. diff --git a/docs/tutorials/snapshots.rst b/docs/tutorials/snapshots.rst index 87d327f3a..7d1b8ea4d 100644 --- a/docs/tutorials/snapshots.rst +++ b/docs/tutorials/snapshots.rst @@ -62,7 +62,9 @@ configuration always overrides the zero-config fallback when present. ``snapshots.rosbag.max_total_storage_mb`` bounds it. A retention rule's ``on_cleared`` (``keep`` or ``delete``) overrides all of this for the faults it covers, and its ``on_healed: delete`` removes the fault's links when the - fault heals. + fault heals. Its ``max_age_sec`` (``active``, ``healed``, ``cleared``) removes the + fault's link to the recording once the fault's last FAILED report is older than + the limit of its status; the recording goes with its last link. Quick Start ----------- @@ -513,7 +515,9 @@ off or ``snapshots.rosbag.max_bags_per_fault`` keeps a history, which takes over the retention decision. A recording is deleted with its last link. A retention rule's ``max_bags`` replaces ``max_bags_per_fault`` for the faults it covers, and its ``on_cleared`` (``keep`` or ``delete``) overrides the clear decision. A rule's -``on_healed: delete`` removes the fault's links when the fault heals. +``on_healed: delete`` removes the fault's links when the fault heals, and its +``max_age_sec`` removes the fault's link to a recording once the fault's last +FAILED report is older than the limit of its status. **Key differences from JSON snapshots:** diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index aa2676c1e..4795f661c 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -304,6 +304,11 @@ endif() medkit_add_launch_test(test_rosbag_status_actions test/integration/test_rosbag_status_actions.test.py TIMEOUT 600 LABELS "integration") + # max_age_sec per retention rule and the age sweep: each status, a new FAILED report, a shared + # recording, a time in the future, the invalid values. + medkit_add_launch_test(test_rosbag_max_age test/integration/test_rosbag_max_age.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 593517a2e..310778cbb 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -135,7 +135,8 @@ parameter list and recording lifecycle. #### Rosbag Retention Rules `snapshots.rosbag.retention.*` sets a `priority` (0-1000), an `over_quota` choice (`keep` or `drop`), a -`max_bags` cap, `keep_first`, `on_healed` and `on_cleared` (`keep` or `delete`) per fault, from four levels: fault code, the first matching pattern of +`max_bags` cap, `keep_first`, `on_healed` and `on_cleared` (`keep` or `delete`) and `max_age_sec` (`active`, +`healed`, `cleared`) per fault, from four levels: fault code, the first matching pattern of `pattern_order`, severity, defaults. They are read at startup and validated. Each fault code keeps at most its rule's `max_bags` recordings (`max_bags_per_fault` when no level sets it, `0` = no cap); with `keep_first` and a `max_bags` of 2 or more the first recording stays and the second oldest goes. "First" is the oldest recording of @@ -145,13 +146,20 @@ needs `healing_enabled: true`). A clear deletes them with `on_cleared: delete` a is 1. A fault the startup turns from HEALED into CLEARED, because healing is now disabled, loses its recordings only with an explicit `on_cleared: delete`. A recording made before such a delete never survives it, also when 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. 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. Without any retention parameter the quota evicts the oldest recordings first. +evicted for it, and nothing is deleted by age. 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`. @@ -602,8 +610,8 @@ and some of them build an `rclcpp::Clock`. - `core::FaultManagerCore`: `report`, `clear`, `list`, `get`, `list_for_entity`, `record_transition` 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 and the - stale-row cleanup) on top of `FaultStorage::apply_rosbag_changes`. It returns + 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. The core reaches the outside through four interfaces. The ROS adapter implements them. @@ -629,7 +637,8 @@ 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. It +the `RetentionWorker` thread that removes the directories of cleared and stale recordings and runs the age +sweep. 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 7af187018..0ced10d13 100644 --- a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml +++ b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml @@ -5,8 +5,9 @@ # fault code, then severity. of the fault, then defaults, then the built-in value. # Fields: priority (integer 0-1000, built-in 0), over_quota (keep or drop, built-in keep), # max_bags (integer 0 or more, built-in snapshots.rosbag.max_bags_per_fault), keep_first (true or -# false, built-in false), on_healed (keep or delete, built-in keep) and on_cleared (keep or delete, -# built-in: the clear default below). +# false, built-in false), on_healed (keep or delete, built-in keep), on_cleared (keep or delete, +# built-in: the clear default below) and max_age_sec (keys active, healed, cleared; seconds, built-in +# 0 = no limit; each key falls through on its own, an explicit 0 wins). # max_bags is the number of recordings kept per fault code, 0 = no cap. Over the cap the oldest # recording goes; with keep_first and a max_bags of 2 or more the first recording stays and the # second oldest goes. "First" is the oldest recording of the fault code still stored. keep_first @@ -16,6 +17,11 @@ # snapshots.rosbag.auto_cleanup is true and its max_bags is 1. A fault turned from HEALED into # CLEARED at startup, because healing is now disabled, loses its recordings only with an explicit # 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. # 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. @@ -31,9 +37,13 @@ fault_manager: snapshots: rosbag: retention: + sweep_interval_sec: 60 defaults: priority: 10 over_quota: keep + max_age_sec: + healed: 604800 + cleared: 86400 severity: # Severity names: INFO, WARN, ERROR, CRITICAL. INFO: @@ -44,6 +54,9 @@ fault_manager: priority: 100 over_quota: keep max_bags: 5 + max_age_sec: + healed: 0 + cleared: 0 fault_codes: # A fault code has no dot here. Hyphens are allowed. MOTOR-STALL: diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index c9e32f0ab..4fbf6d240 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -627,6 +627,19 @@ Rosbag retention - ``forget_recording``: removes the rows of a recording whose directory is gone, for ``GetRosbag`` and ``ListRosbags``. The node builds the retention also with rosbag capture off, so this cleanup runs then too. +- ``sweep_expired(now_ns)``: one pass of the age sweep. It returns at once unless ``kConfigured`` + and ``RetentionPolicy::sweeps()`` (a level sets a ``max_age_sec`` key above 0). Otherwise it reads + ``get_all_rosbag_files`` and ``get_all_faults`` once each, and removes in one change set the link of + every row whose fault's age is over the limit of the fault's status in its rule (resolved with the + fault's current severity). The age is ``now_ns - last_occurred_ns``, saturated at the int64 bounds + and compared in whole seconds (``age_exceeds``), so a negative age never expires and no limit is + converted to ns. A row whose fault the storage does not hold is not aged. It returns the + directories the change orphaned, each with ``RemovalReason::kAgeActive``, ``kAgeHealed`` or + ``kAgeCleared`` (the reason of the path's first removed link), and the number of links removed. A + read or apply failure logs one WARN and returns nothing; ``RosbagCommitInDoubt`` logs one WARN that + 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. **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 @@ -651,8 +664,9 @@ early; ``auto_cleanup`` is only the clear default. ``core::RetentionPolicy`` (``core/retention_policy.*``, no ROS types) parses the ``snapshots.rosbag.retention.*`` parameters, flattened by the node into a map of keys relative to the prefix, and resolves the rule of a fault code and severity field by field: fault code, the first -matching pattern of ``pattern_order``, severity, defaults, built-in. ``parse`` reports every error -and every shifted key (a key with more segments than the grammar allows). +matching pattern of ``pattern_order``, severity, defaults, built-in; each ``max_age_sec`` key +resolves on its own. ``parse`` reports every error and every shifted key (a key with more segments +than the grammar allows; only a ``max_age_sec`` key takes one more, for its status). At the start of the constructor the node reads each parameters file rcl lists for the process and the node twice: with ``rcl_parse_yaml_file``, the loader it used, and with ``core::read_params_file`` (yaml-cpp, no @@ -713,6 +727,21 @@ depends on the path: - Clear, heal, startup reclassification and stale rows (the executor): the rows go inside the service call or the constructor. The node's ``RetentionWorker``, one thread with a FIFO queue, removes the directories, so the clear and report services return before a large bag is removed. +- Age sweep (the retention worker): the periodic job calls ``sweep_expired`` with the system clock, + 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. + +**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 +stop is asked, the periodic job changes, or the deadline passes. At the deadline, with the queue +empty, it runs the periodic job once and sets the next deadline one interval after the run ends, so +periods missed behind a long job give one run. Without a periodic job the wait has no deadline and +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()``. 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: @@ -720,6 +749,8 @@ removal after it succeeded. No line announces a removal that has not happened ye - a cap victim: ``Recording removed: (its max_bags)``; - a recording of a cleared fault: ``Recording removed: (fault cleared)``; - 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 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. @@ -732,7 +763,7 @@ 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. A ``RosbagCapture`` constructed +which runs the removals the clear and stale-row paths 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 06797e286..f0f2fbb0e 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 @@ -47,6 +47,10 @@ struct RetentionRule { std::optional keep_first; std::optional on_healed; std::optional on_cleared; + /// max_age_sec. in seconds, 0 = no limit. Each key falls through on its own. + std::optional max_age_active; + std::optional max_age_healed; + std::optional max_age_cleared; }; /// The rule of one fault. @@ -57,6 +61,10 @@ struct ResolvedRule { bool keep_first{false}; StatusAction on_healed{StatusAction::kKeep}; std::optional on_cleared; ///< Unset when no level sets it: the caller applies the clear default + /// Age limits in seconds from the fault's last FAILED report, per status. 0 = no limit. + int64_t max_age_active{0}; ///< PREFAILED, PREPASSED or CONFIRMED + int64_t max_age_healed{0}; + int64_t max_age_cleared{0}; }; struct RetentionParse; @@ -79,9 +87,18 @@ class RetentionPolicy { return configured_; } - /// One line naming each level, its fields and the pattern order. + /// One line naming each level, its fields, the pattern order and the sweep (`sweep: off` or + /// `sweep: every s`). 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; + + /// `sweep_interval_sec`, 1 to 86400, default 60. + int64_t sweep_interval_sec() const { + return sweep_interval_sec_; + } + /// 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; @@ -99,13 +116,15 @@ class RetentionPolicy { std::map codes_; std::map patterns_; std::vector pattern_order_; + int64_t sweep_interval_sec_{60}; }; /// Outcome of RetentionPolicy::parse. `policy` is set only when there is no error and no shifted key. struct RetentionParse { std::optional policy; std::vector errors; - std::vector shifted_keys; ///< Keys with more segments than the grammar allows. + /// Keys with more segments than the grammar allows. Only `max_age_sec` takes one more. + std::vector shifted_keys; }; } // namespace ros2_medkit_fault_manager::core 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 7df6487f3..1d3ca5eed 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 @@ -51,13 +51,21 @@ struct RetentionPolicyState { /// Why a recording's directory is no longer named by any row. enum class RemovalReason { - kCap, ///< The per-fault cap (max_bags) - kQuota, ///< The quota (max_total_storage_mb) - kCleared, ///< The fault was cleared: its on_cleared, else auto_cleanup with a max_bags of 1 - kHealed, ///< The fault healed and its on_healed is delete - kStale, ///< The directory was already missing + kCap, ///< The per-fault cap (max_bags) + kQuota, ///< The quota (max_total_storage_mb) + kCleared, ///< The fault was cleared: its on_cleared, else auto_cleanup with a max_bags of 1 + kHealed, ///< The fault healed and its on_healed is delete + kStale, ///< The directory was already missing + kAgeActive, ///< max_age_sec.active: the fault is active and its last FAILED is too old + kAgeHealed, ///< max_age_sec.healed + kAgeCleared, ///< max_age_sec.cleared }; +/// Whether the age at @p now_ns of a fault whose last FAILED report was at @p last_failed_ns is +/// over @p limit_sec whole seconds. The age saturates at the int64 bounds. A negative age and a +/// limit of 0 or less are never over. +bool age_exceeds(int64_t now_ns, int64_t last_failed_ns, int64_t limit_sec); + /// Per fault code, the delete generation the code read when it joined a recording. using DeleteGenerations = std::unordered_map; @@ -104,6 +112,11 @@ struct RemovalOutcome { bool deletes{false}; ///< A status change decided to delete the fault's recordings }; +struct SweepOutcome { + size_t removed_links{0}; ///< Rows the pass removed + std::vector unlink_paths; ///< Directories no row names any more, each path once +}; + /// Every rosbag retention decision of the fault manager, on FaultStorage::apply_rosbag_changes(). /// /// Each public method holds one mutex for its whole decision. Lock order: the caller's outer @@ -191,6 +204,15 @@ class RosbagRetention { /// may be gone RemovalOutcome forget_recording(const std::string & recording_id); + /// The age sweep at @p now_ns. Removes, in one change set, every link whose fault's age from its + /// last FAILED report (last_occurred_ns) is over the max_age_sec of the fault's rule for its + /// status. Only that fault's link goes: a shared recording keeps its other links. A link whose + /// fault the storage does not hold is not aged. Returns at once with nothing unless kConfigured + /// and a level sets a max age above 0. Two reads per pass: the rosbag rows and the faults. + /// A storage failure: one WARN, nothing returned. RosbagCommitInDoubt: one WARN, nothing returned. + /// Never throws. + SweepOutcome sweep_expired(int64_t now_ns); + private: struct Eviction { std::vector unlink_paths; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp index 3a9924e80..8b7045a75 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp @@ -205,6 +205,11 @@ class FaultManagerNode : public rclcpp::Node { void arm_retention_timer(); + /// One pass of the age sweep, on the retention worker: the rows go under the retention mutex, + /// the directories after it is released. Logs `retention sweep: now= removed=`, with + /// the time the pass decided with. + void sweep_expired_recordings(); + /// Create snapshot configuration from the validated config SnapshotConfig create_snapshot_config(); 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 7d4cc6570..b29d934ec 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 @@ -14,7 +14,9 @@ #pragma once +#include #include +#include #include #include #include @@ -31,10 +33,11 @@ namespace ros2_medkit_fault_manager { /// Runs the file system work that follows a rosbag row change, such as removing a directory /// no row names any more. /// -/// kThread: one thread runs the posted jobs in FIFO order. kInline: post() runs the job at once -/// on the calling thread. In both modes a job that throws is logged as an ERROR, and every job -/// ends with the DEBUG line `retention job done: `. post() after drain_and_stop() logs a -/// WARN and drops the job. +/// kThread: one thread runs the posted jobs in FIFO order, and a periodic job when one is set. +/// kInline: post() runs the job at once on the calling thread; there is no periodic job. In both +/// modes a job that throws is logged as an ERROR, and every job ends with the DEBUG line +/// `retention job done: ` (`periodic` for the periodic job). post() after drain_and_stop() +/// logs a WARN and drops the job. class RetentionWorker { public: enum class Mode { kThread, kInline }; @@ -50,8 +53,22 @@ class RetentionWorker { void post(std::string kind, std::function job); + /// Run @p job every @p interval on the worker thread, the first time one interval from now. It + /// runs only while no posted job waits, and the next interval starts when it ends, so periods + /// missed behind a long job give one run. Replaces an earlier periodic job. kInline stores + /// nothing: it has no thread that could wait for the deadline. + void set_periodic(std::chrono::seconds interval, std::function job); + + /// Remove the periodic job. Without one the thread waits for posted jobs alone, with no deadline. + void clear_periodic(); + + /// How often the thread came out of its wait: for a job, a stop, a periodic deadline or a change + /// of the periodic job. For tests: a wake is not observable from outside the process. + 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)` or `(fault healed)`, or main's + /// reason: `Recording removed: (its max_bags)`, `(fault cleared)`, `(fault healed)` or + /// `(max_age_sec.active)`, `.healed`, `.cleared`, 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. @@ -62,7 +79,8 @@ class RetentionWorker { /// @p recordings is empty. void post_removals(std::string kind, std::vector recordings); - /// Run every job posted so far, then stop the thread. Idempotent. + /// Run every job posted so far, then stop the thread. Does not wait for the periodic job's + /// deadline and does not run the periodic job again. Idempotent. void drain_and_stop(); private: @@ -76,11 +94,19 @@ class RetentionWorker { core::LogSink & log_sink_; const std::string logger_name_; + using Clock = std::chrono::steady_clock; + const Mode mode_; - std::mutex mutex_; + mutable std::mutex mutex_; std::condition_variable cv_; std::deque queue_; bool stopping_{false}; + std::function periodic_; ///< Empty: no periodic job and no deadline + std::chrono::seconds periodic_interval_{0}; + Clock::time_point periodic_due_; + uint64_t periodic_version_{0}; ///< Advanced by each set_periodic() and clear_periodic() + bool periodic_changed_{false}; ///< Wakes the thread to take the new deadline + uint64_t wakes_{0}; std::thread thread_; }; 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 33bcd44b2..980d57845 100644 --- a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp +++ b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp @@ -29,6 +29,8 @@ namespace { namespace fd_severity = ros2_medkit::fault_detection::severity; constexpr int64_t kMaxPriority = 1000; +constexpr int64_t kMinSweepIntervalSec = 1; +constexpr int64_t kMaxSweepIntervalSec = 86400; const std::pair kSeverityNames[] = { {"INFO", fd_severity::kInfo}, @@ -101,9 +103,39 @@ void set_status_action(const std::string & key, const std::string & field, const } } -/// Applies a field value to @p rule, or adds the reason it is invalid to @p errors. -void set_field(const std::string & key, const std::string & field, const ParamValue & value, RetentionRule & rule, - std::vector & errors) { +/// Applies a max_age_sec. value to @p rule, or adds the reason it is invalid to @p errors. +/// @p status is null for a max_age_sec key without a status. +void set_max_age(const std::string & key, const std::string * status, const ParamValue & value, RetentionRule & rule, + std::vector & errors) { + if (status == nullptr) { + errors.push_back(key + ": max_age_sec takes the keys active, healed and cleared, got " + type_name(value)); + return; + } + std::optional * slot = nullptr; + if (*status == "active") { + slot = &rule.max_age_active; + } else if (*status == "healed") { + slot = &rule.max_age_healed; + } else if (*status == "cleared") { + slot = &rule.max_age_cleared; + } else { + errors.push_back(key + ": unknown max_age_sec key '" + *status + "' (known: active, healed, cleared)"); + return; + } + const auto * seconds = std::get_if(&value); + if (seconds == nullptr) { + errors.push_back(key + ": max_age_sec." + *status + " must be an integer, got " + type_name(value)); + } else if (*seconds < 0) { + errors.push_back(key + ": max_age_sec." + *status + " must be 0 or more, got " + std::to_string(*seconds)); + } else { + *slot = *seconds; + } +} + +/// Applies a field value to @p rule, or adds the reason it is invalid to @p errors. @p sub is the +/// segment after the field, null when there is none; only max_age_sec has one. +void set_field(const std::string & key, const std::string & field, const std::string * sub, const ParamValue & value, + RetentionRule & rule, std::vector & errors) { if (field == "priority") { const auto * number = std::get_if(&value); if (number == nullptr) { @@ -145,16 +177,29 @@ void set_field(const std::string & key, const std::string & field, const ParamVa set_status_action(key, field, value, rule.on_healed, errors); } else if (field == "on_cleared") { set_status_action(key, field, value, rule.on_cleared, errors); + } else if (field == "max_age_sec") { + set_max_age(key, sub, value, rule, errors); } else if (field == "match") { errors.push_back(key + ": match is only valid under patterns.