Skip to content

eBPF-based security platform

status: print the keepalive body with --keepalive

John Fastabend780db77f0e20
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 41cff6d9..a597fa2f 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -518,6 +518,12 @@ signed config image.
malformed, on an ``add``, a ``delete`` and an operation without a
match, syncs with the outcomes, state and tree eventlog of the
same operations without it
+ * - ``t7109-bpm-tree-keepalive``
+ - ``status --keepalive``: the keys of the body in order, its tree
+ keys and mask as ``state.json`` and the outcomes record have them,
+ flags bit 4 after a sync is killed after its load, and after the
+ sync the loaded set its mask folds to and the masks of node A and
+ node B
``otel`` (8)
~~~~~~~~~~~~
@@ -743,7 +749,7 @@ Coverage by area
* - upatch tree
- ``t3011``, ``t5004``, ``t7005``, ``t7007``, ``t7101``,
``t7102``, ``t7103``, ``t7104``, ``t7105``, ``t7106``,
- ``t7107``, ``t9105``. Fuzz: ``tree``,
+ ``t7107``, ``t7109``, ``t9105``. Fuzz: ``tree``,
``tree-state``, ``kconfig``. Unit: ``bpm_tree``,
``bpm_tree_overlap``, ``bpm_tree_state``, ``kernel_build_id``,
``kernel_release``
@@ -752,9 +758,10 @@ Coverage by area
Unauthorized policy-xattr changes: ``t6111``. Task and socket
inheritance: ``t6141``, ``t6142``
* - Telemetry
- - ``t6139``, ``t8001`` to ``t8007``, ``t8101`` to ``t8105``,
- ``t9101`` to ``t9105``. Fuzz: ``otel``, ``quote-check``,
- ``serializer``. Unit: ``sysinfo``
+ - ``t6139``, ``t7109``, ``t8001`` to ``t8007``, ``t8101`` to
+ ``t8105``, ``t9101`` to ``t9105``. Fuzz: ``otel``,
+ ``quote-check``, ``serializer``. Unit: ``keepalive``,
+ ``sysinfo``
* - Decoders
- ``t3002``, ``t8102``, ``t9101``. Fuzz: ``decoder``
* - Tamper counters
diff --git a/Documentation/operate/run/telemetry.rst b/Documentation/operate/run/telemetry.rst
index 3fcd0114..ac0ae906 100644
--- a/Documentation/operate/run/telemetry.rst
+++ b/Documentation/operate/run/telemetry.rst
@@ -43,6 +43,16 @@ Both timers start their service 5 seconds after boot and again 5 seconds
after each run ends. ``shirudo-map-export.service`` runs only while
``/run/shirudo/bpffs/lsm_link`` exists.
+A keepalive and a ``bpm tree sync`` stall each other rather than run at
+once. Every target command holds the config operation lock for its whole
+run, and a sync holds it until its last operation is applied. A
+keepalive that starts during a sync waits up to 30 seconds for the lock;
+when the sync is still running then, that run fails and sends nothing,
+and the next run of the timer tries again. A sync that fetches and
+applies for minutes therefore leaves a gap of about that length in the
+node's keepalives, which a backend's threshold for a stale node must
+allow for. See :doc:`/reference/systemd-units`.
+
The keepalive record has the event name ``shirudo.keepalive``. Its body
is the ``shirudo status --json`` document with the system section, and
its attributes are ``shirudo.status`` (the verdict),
diff --git a/Documentation/reference/cli/status.rst b/Documentation/reference/cli/status.rst
index f20f6d46..402bec4c 100644
--- a/Documentation/reference/cli/status.rst
+++ b/Documentation/reference/cli/status.rst
@@ -9,7 +9,7 @@ shirudo status
==============
Report the local readiness and state of this host, and optionally send the
-report as an OTLP keepalive.
+report as an OTLP keepalive or print the keepalive body.
Runs on: any host, and on a target as root with the runtime binary. It is the
only command that runs while a config activation is pending or cannot be
@@ -21,8 +21,8 @@ Usage
.. code-block:: none
- shirudo status [--json | --otel] [--check] [--show-full]
- [--include-system] [--include-eventlog]
+ shirudo status [--json | --otel | --keepalive] [--check]
+ [--show-full] [--include-system] [--include-eventlog]
Description
-----------
@@ -87,6 +87,77 @@ says nothing, except while a config activation is pending or unverifiable,
when it prints a warning. ``--otel`` alone prints nothing on standard
output. Add ``--json`` to print the document too.
+With ``--keepalive``, ``status`` prints the keepalive body, the compact
+status record a node's TPM is to quote, as one line on standard output.
+It neither quotes nor sends it and needs no TPM, so an operator can see
+what a node reports. The body has 22 keys in a fixed order: ``schema``
+(``shirudo.keepalive/1``), ``boot_id``, ``version_id``, ``config_root``,
+``kernel_release``, ``image_id``, ``image_version``, ``image_root``,
+``verdict``, ``cond``, ``flags``, ``tamper``, ``tree_id``,
+``generation``, ``base_seq``, ``last_seq``, ``base_root``,
+``projection_root``, ``mask``, ``set_sha256``, ``count`` and ``not_ok``.
+A key that does not apply is ``null``:
+
+- ``config_root`` unless the selected config is active;
+- the seven tree keys, ``tree_id`` to ``mask``, when the node follows no
+ tree or its tree state cannot be read.
+
+``mask`` holds two bits per operation from ``base_seq + 1`` to the head
+of the recorded publication, read from the outcomes record of
+:doc:`/reference/formats/bpm-formats`: ``01`` applied, ``10`` passed
+over, ``11`` module absent, ``00`` not reached. ``set_sha256`` is
+SHA-256 over a ``<payload_sha256> <name>`` line for every loaded upatch,
+sorted by name, the ``set_digest`` form of the ``init`` event.
+``not_ok`` counts the loaded upatches the tree holds a status file for.
+The bits of ``flags``:
+
+.. list-table::
+ :header-rows: 1
+ :widths: 8 24 68
+
+ * - Bit
+ - Name
+ - Set when
+ * - 0
+ - ``register_rebound``
+ - The register was bound more than once for this TPM reset.
+ * - 1
+ - ``bound_late``
+ - This boot's ``init`` record says the register was bound from the
+ root file system, not from the initrd.
+ * - 2
+ - ``tree_log_mismatch``
+ - The tree eventlog does not replay to the ``projection_root`` of
+ ``state.json``, or the outcomes record lacks a line the window
+ needs; ``base_root`` and ``mask`` are then ``null``.
+ * - 3
+ - ``tamper_unavailable``
+ - The tamper counters cannot be read; ``tamper`` is ``null``.
+ * - 4
+ - ``tree_op_pending``
+ - A tree operation was left in flight: ``pending.json`` existed
+ before or after the read, after a sync stopped mid-operation.
+ * - 5
+ - ``snapshot_unsettled``
+ - ``state.json`` kept changing while the body was read, which the
+ config operation lock leaves to a writer outside it.
+
+``status`` holds the config operation lock for its whole run, as every
+target command does, a ``bpm tree sync`` included. It therefore never
+reads a tree a sync is changing: while one runs, ``status`` waits up to
+30 seconds for the lock and then fails, and no body is printed. A sync
+writes ``pending.json`` before it loads or unloads anything and removes
+it only after ``state.json`` has the new ``last_seq``, so bit 4 says a
+sync stopped in the middle of an operation and the next sync completes
+it. ``status`` still reads ``state.json``, looks for ``pending.json``,
+reads the outcomes up to that ``last_seq`` and the loaded upatches, then
+looks for ``pending.json`` and reads ``state.json`` again, and starts
+over when the second ``state.json`` differs from the first, three times
+in all, printing the last read with bit 5 set; under the lock that
+happens only if something writes the tree without it. With bits 4 and 5
+clear the tree keys and the loaded set describe one point. The two bits
+say the node is busy, not that it is unhealthy.
+
Options
-------
@@ -106,6 +177,11 @@ Options
- none
- off
- Send the JSON report as an OTLP keepalive log record.
+ * - ``--keepalive``
+ - none
+ - off
+ - Print the keepalive body without quoting or sending it. Not with
+ ``--json`` or ``--otel``.
* - ``--include-system``
- none
- off
@@ -146,10 +222,11 @@ reads ``.status`` and the conditions from the JSON document.
- With ``--check``: the verdict is ``tampered``. With ``--otel``:
the configuration cannot be loaded or the OTLP request failed.
With ``--json``: the document does not fit the output buffer.
- Also an allocation failure.
+ With ``--keepalive``: the body cannot be built. Also an allocation
+ failure.
* - 2
- - An unknown option, or with ``--otel`` an invalid ``map_export``
- configuration.
+ - An unknown option, ``--keepalive`` with ``--json`` or ``--otel``,
+ or with ``--otel`` an invalid ``map_export`` configuration.
Files and environment
---------------------
@@ -159,6 +236,11 @@ Files and environment
``/var/lib/shirudo/eventlog``, ``/var/lib/shirudo/keys``, the config
certificate the runtime image's bootstrap names and the config
activation records
+- With ``--keepalive``: ``state.json``, ``pending.json``, ``outcomes``,
+ ``tree-eventlog`` and ``status/`` under
+ ``/var/lib/shirudo/bpm/upatch-tree``, ``/etc/os-release`` (else
+ ``/usr/lib/os-release``), ``/proc/cmdline`` and
+ ``/proc/sys/kernel/random/boot_id``
- With ``--otel``: ``map_export.*`` and the ``OTEL_EXPORTER_OTLP_*``
variables (see :doc:`/reference/environment`).
``shirudo-keepalive.service`` reads them from
@@ -300,6 +382,13 @@ Read the verdict in a script:
target# shirudo status --json | jq -r .status
ok
+Print the keepalive body of the same target, which follows no tree:
+
+.. code-block:: console
+
+ target# shirudo status --keepalive
+ {"schema":"shirudo.keepalive/1","boot_id":"82639935-1127-4dab-91b5-f818eabc7f13","version_id":"d0d7aa800303439023907d1979d917d46a21bec21f816689c138728a28e84af9","config_root":"6d5ed552f448a1c07e3b9d24f5a86c1e0b7d93f2c4e5a6b7180c9d2e3f4a5b6c","kernel_release":"7.3.0-bpf-next+","image_id":null,"image_version":null,"image_root":null,"verdict":"ok","cond":5461,"flags":0,"tamper":[15,0,0,0,0,1,0,0,0,0,0,8,0,0,0,0,0,1,0,0,1,0,0,0,0,0,7,0,0,2,0,0,0,0,0,0,0],"tree_id":null,"generation":null,"base_seq":null,"last_seq":null,"base_root":null,"projection_root":null,"mask":null,"set_sha256":"5f0c2e8b7a1d4c3f9e6b2a0d8c7f1e3b5a9d4c2e6f8b0a1d3c5e7f9b2d4a6c8e","count":1,"not_ok":0}
+
Add this boot's eventlog to the report:
.. code-block:: console
diff --git a/Documentation/reference/systemd-units.rst b/Documentation/reference/systemd-units.rst
index f27711ed..39225f7e 100644
--- a/Documentation/reference/systemd-units.rst
+++ b/Documentation/reference/systemd-units.rst
@@ -194,6 +194,16 @@ The keepalive is sent only when ``map_export.otel_endpoint``,
``OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`` or ``OTEL_EXPORTER_OTLP_ENDPOINT``
names an endpoint. See :doc:`/reference/formats/otlp`.
+A keepalive and a ``bpm tree sync`` do not run at once. Every target
+command holds the config operation lock for its whole run, and a sync
+holds it until its last operation is applied. A keepalive that starts
+during a sync waits up to 30 seconds for the lock; when the sync is
+still running then, that run fails and sends nothing, and the next
+run of the timer tries again. A sync that fetches and applies for
+minutes therefore leaves a gap of about that length in the node's
+keepalives, which a backend's threshold for a stale node must allow
+for.
+
shirudo-xdp-reconcile.service
-----------------------------
diff --git a/builtin-status.c b/builtin-status.c
index 2603e1ff..53af3ab0 100644
--- a/builtin-status.c
+++ b/builtin-status.c
@@ -41,6 +41,7 @@
#include "util/io.h"
#include "util/json.h"
#include "util/identity.h"
+#include "util/keepalive.h"
#include "util/image_bootstrap.h"
#include "util/image_runtime.h"
#include "util/keyring.h"
@@ -337,6 +338,7 @@ static void print_system_human(const struct sysinfo *si)
static const struct help_item status_options[] = {
{ "--json", "print the report as one JSON document" },
{ "--otel", "send the JSON report as an OTLP keepalive log" },
+ { "--keepalive", "print the keepalive body, unquoted and unsent" },
{ "--check", "exit 1 when the verdict is tampered" },
{ "--show-full", "print every section, folded or not, and the "
"system and eventlog sections" },
@@ -351,9 +353,9 @@ static const struct help_section status_help_sections[] = {
};
static const struct help status_help = {
- .usage = "shirudo status [--json | --otel] [--check] "
- "[--show-full]\n"
- " [--include-system] "
+ .usage = "shirudo status [--json | --otel | --keepalive] "
+ "[--check]\n"
+ " [--show-full] [--include-system] "
"[--include-eventlog]",
.summary = "Report the state of this host: the verdict, the "
"conditions behind it, the\ntamper counters and the "
@@ -481,6 +483,212 @@ static bool status_otel_endpoint_configured(const struct config *cfg)
return endpoint && endpoint[0];
}
+/* What a keepalive snapshot reads past the tree state, for one try. */
+struct keepalive_view {
+ __s64 base_seq;
+ int outcomes_rc;
+ __u8 codes[KEEPALIVE_MASK_OPS];
+ char base_root[2 * CHAIN_DIGEST_LEN + 1];
+ char mask[KEEPALIVE_MASK_B64_MAX];
+ bool log_mismatch;
+ char set_sha256[2 * CHAIN_DIGEST_LEN + 1];
+ __u64 count;
+ __u64 not_ok;
+};
+
+static int keepalive_read_state(void *ctx, struct tree_state *state)
+{
+ return tree_state_read(state);
+}
+
+static bool keepalive_pending(void *ctx)
+{
+ return access(BPM_TREE_PENDING_PATH, F_OK) == 0;
+}
+
+static void keepalive_window(struct keepalive_view *v,
+ const struct tree_state *s)
+{
+ __u8 projection[CHAIN_DIGEST_LEN], history[CHAIN_DIGEST_LEN];
+
+ v->base_seq = max_t(__s64, s->head_seq - KEEPALIVE_MASK_OPS, 0);
+ memset(v->codes, 0, sizeof(v->codes));
+ if (s->last_seq < v->base_seq || s->last_seq > s->head_seq) {
+ v->outcomes_rc = -EBADMSG;
+ return;
+ }
+ v->outcomes_rc = tree_outcomes_read(v->base_seq, s->last_seq, v->codes,
+ projection, history);
+ if (!v->outcomes_rc)
+ v->outcomes_rc = keepalive_mask(v->codes,
+ s->head_seq - v->base_seq,
+ v->mask, sizeof(v->mask));
+ if (!v->outcomes_rc)
+ hex_encode(projection, sizeof(projection), v->base_root);
+}
+
+/* eventlog_matches_state of the status document, false only. */
+static bool keepalive_log_mismatch(const struct tree_state *s, int state_rc)
+{
+ __u8 live[CHAIN_DIGEST_LEN], replay[CHAIN_DIGEST_LEN];
+
+ if (tree_event_replay(replay))
+ return false;
+ return state_rc || hex_decode(s->projection_root, live, sizeof(live)) ||
+ memneq_explicit(live, replay, sizeof(live));
+}
+
+/* A tree status file says why the tree left the upatch not loaded. */
+static bool keepalive_upatch_not_ok(const char *name)
+{
+ char path[PATH_MAX];
+
+ if (strsprintf(path, sizeof(path), "%s/%s", BPM_TREE_STATUS_DIR,
+ name) < 0)
+ return false;
+ return access(path, F_OK) == 0;
+}
+
+/* The set_digest of an init event, over every upatch pinned now. */
+static int keepalive_loaded_set(struct keepalive_view *v)
+{
+ __u8 none[CHAIN_DIGEST_LEN] = {}, digest[CHAIN_DIGEST_LEN];
+ struct measured_upatch *set = NULL;
+ __u8 event[CHAIN_DIGEST_LEN];
+ struct dirent **ups = NULL;
+ int n, i, ret = 0;
+ size_t m = 0;
+
+ n = scandir(BPFFS_UPATCHES_DIR, &ups, notdot, alphasort);
+ if (n < 0)
+ n = 0;
+ if (n) {
+ set = xcalloc((size_t)n, sizeof(*set));
+ if (!set)
+ ret = -ENOMEM;
+ }
+ v->not_ok = 0;
+ for (i = 0; !ret && i < n; i++) {
+ struct measured_upatch *u = &set[m];
+
+ if (upatch_name_from_bpffs(u->name, sizeof(u->name),
+ ups[i]->d_name))
+ continue;
+ upatch_payload_sha256(u->name, u->payload_hex,
+ sizeof(u->payload_hex));
+ if (keepalive_upatch_not_ok(u->name))
+ v->not_ok++;
+ m++;
+ }
+ if (!ret)
+ ret = chain_init_event(none, set, m, none, digest, event);
+ if (!ret) {
+ hex_encode(digest, sizeof(digest), v->set_sha256);
+ v->count = m;
+ }
+ for (i = 0; i < n; i++)
+ libc_free(ups[i]);
+ libc_free(ups);
+ xfree(set, (size_t)n * sizeof(*set));
+ return ret;
+}
+
+static int keepalive_collect(void *ctx, const struct tree_state *state,
+ int state_rc)
+{
+ struct keepalive_view *v = ctx;
+
+ if (!state_rc)
+ keepalive_window(v, state);
+ v->log_mismatch = keepalive_log_mismatch(state, state_rc);
+ return keepalive_loaded_set(v);
+}
+
+static const struct keepalive_snapshot_ops keepalive_ops = {
+ .read_state = keepalive_read_state,
+ .pending = keepalive_pending,
+ .collect = keepalive_collect,
+};
+
+static __u32 keepalive_flags(const struct chain_status *cst, int tamper_rc,
+ const struct keepalive_view *v, int state_rc)
+{
+ __u32 flags = 0;
+
+ if (cst->rebound)
+ flags |= KEEPALIVE_REGISTER_REBOUND;
+ if (cst->logged && !cst->init.initrd)
+ flags |= KEEPALIVE_BOUND_LATE;
+ if (v->log_mismatch || (!state_rc && v->outcomes_rc))
+ flags |= KEEPALIVE_TREE_LOG_MISMATCH;
+ if (tamper_rc)
+ flags |= KEEPALIVE_TAMPER_UNAVAILABLE;
+ return flags;
+}
+
+/* A tree state that cannot be read is a node that follows no tree. */
+static noinline_for_stack int
+print_keepalive(const struct conditions_input *cin,
+ const struct chain_status *cst,
+ const struct tamper_counts *tamper, int tamper_rc,
+ const char *config_root_hex)
+{
+ struct condition conds[CONDITIONS_MAX];
+ struct keepalive_input in = {};
+ struct keepalive_view v = {};
+ char body[KEEPALIVE_BODY_MAX];
+ struct sysinfo_image img;
+ struct tree_state state;
+ struct sysinfo si = {};
+ int state_rc, ret;
+ __u32 flags = 0;
+ size_t nc, len;
+
+ ret = keepalive_snapshot(&keepalive_ops, &v, &state, &state_rc,
+ &flags);
+ if (ret) {
+ pr_err("status: read the keepalive inputs: %s", strerror(-ret));
+ return 1;
+ }
+ sysinfo_gather(&si);
+ sysinfo_image_read(&img);
+ nc = conditions(cin, conds, ARRAY_SIZE(conds));
+ in = (struct keepalive_input){
+ .boot_id = si.boot_id,
+ .version_id = shirudo_version_id,
+ .config_root = config_root_hex,
+ .kernel_release = si.kernel_release,
+ .image_id = img.id,
+ .image_version = img.version,
+ .image_root = img.root,
+ .verdict = status_verdict(cin),
+ .cond = keepalive_cond(conds, nc),
+ .flags = flags | keepalive_flags(cst, tamper_rc,
+ &v, state_rc),
+ .tamper = tamper_rc ? NULL : tamper->count,
+ .set_sha256 = v.set_sha256,
+ .count = v.count,
+ .not_ok = v.not_ok,
+ };
+ if (!state_rc) {
+ in.tree = true;
+ in.tree_id = state.tree_id;
+ in.generation = (__u64)state.generation;
+ in.base_seq = (__u64)v.base_seq;
+ in.last_seq = (__u64)state.last_seq;
+ in.base_root = v.outcomes_rc ? NULL : v.base_root;
+ in.projection_root = state.projection_root;
+ in.mask = v.outcomes_rc ? NULL : v.mask;
+ }
+ ret = keepalive_emit(&in, body, sizeof(body), &len);
+ if (ret) {
+ pr_err("status: build the keepalive body: %s", strerror(-ret));
+ return 1;
+ }
+ printf("%s\n", body);
+ return 0;
+}
+
#define STATUS_SUBJECT_MAX 256
/* A certificate a keyring should hold, and the link that holds it. */
@@ -830,7 +1038,7 @@ static void print_keyring_serials(const struct status_keyring *k)
int cmd_status(int argc, const char **argv)
{
bool json = false;
- bool json_stdout = false, otel = false;
+ bool json_stdout = false, otel = false, keepalive = false;
bool include_system = false, include_eventlog = false;
bool show_full = false, check = false;
char hostname[256] = "?";
@@ -894,6 +1102,8 @@ int cmd_status(int argc, const char **argv)
json_stdout = true;
} else if (strcmp(argv[i], "--otel") == 0) {
otel = true;
+ } else if (strcmp(argv[i], "--keepalive") == 0) {
+ keepalive = true;
} else if (strcmp(argv[i], "--include-system") == 0) {
include_system = true;
} else if (strcmp(argv[i], "--include-eventlog") == 0) {
@@ -911,6 +1121,11 @@ int cmd_status(int argc, const char **argv)
return 2;
}
}
+ if (keepalive && (json_stdout || otel)) {
+ fprintf(stderr, "status: --keepalive goes without --json and --otel\n");
+ usage();
+ return 2;
+ }
json = json_stdout || otel;
if (otel) {
int err = config_load(&otel_cfg);
@@ -1076,7 +1291,10 @@ int cmd_status(int argc, const char **argv)
cin.xdp_coverage_rc = xdp_coverage_rc;
keyring_cond_input(&cin, &bpf, &dmv);
- if (json) {
+ if (keepalive) {
+ ret = print_keepalive(&cin, &cst, &tamper, tamper_rc,
+ config_state ? NULL : config_root_hex);
+ } else if (json) {
struct json_emit e;
/*
diff --git a/completion/shirudo.bash b/completion/shirudo.bash
index 3feda1b6..98060119 100644
--- a/completion/shirudo.bash
+++ b/completion/shirudo.bash
@@ -198,7 +198,7 @@ _shirudo()
COMPREPLY=( $(compgen -W "--check-only --json" -- "$cur") )
;;
status)
- COMPREPLY=( $(compgen -W "--json --otel --check --show-full \
+ COMPREPLY=( $(compgen -W "--json --otel --keepalive --check --show-full \
--include-system --include-eventlog" -- "$cur") )
;;
attest)
diff --git a/testing/functional/bpm/t7109-bpm-tree-keepalive.sh b/testing/functional/bpm/t7109-bpm-tree-keepalive.sh
new file mode 100644
index 00000000..6891162c
--- /dev/null
+++ b/testing/functional/bpm/t7109-bpm-tree-keepalive.sh
@@ -0,0 +1,297 @@
+#!/bin/sh
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+#
+# t7109 -- status --keepalive reads the tree keys and the loaded set of
+# one point: a body taken while a sync is stopped between its load and its
+# state says so in flags bit 4, and one taken after a sync carries the mask
+# and roots of the outcomes record and state.json and the set the applied
+# operations fold to.
+
+cd "$(dirname "$0")/../.."
+. ./integration-lib.sh
+target_guard
+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"
+
+FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}
+REGISTRY="$FIXTURES/tree-oci"
+TREE_REPO="$REGISTRY/shirudo/upatch-tree"
+TREE_DIR=/var/lib/shirudo/bpm/upatch-tree
+OUTCOMES=$TREE_DIR/outcomes
+TREE_EVENTLOG=$TREE_DIR/tree-eventlog
+PENDING=$TREE_DIR/pending.json
+EVENTLOG=/var/lib/shirudo/eventlog
+MATCH_PIN=/run/shirudo/bpffs/upatches/shirudo-test-tree-match/link
+WORK=$(mktemp -d)
+HOLDER_PID=
+
+for fixture in \
+ "$TREE_REPO/manifests/keepalive" \
+ "$TREE_REPO/manifests/unmatched" \
+ "$FIXTURES/shirudo-test-tree-match.unload.upatch" \
+ "$FIXTURES/cert.der" \
+ "./helper/test-oci-registry.py"
+do
+ [ -s "$fixture" ] || test_skip_all "missing tree fixture: $fixture"
+done
+
+[ "$(tree_state_field tree_id)" = shirudo-test-tree ] &&
+ [ "$(tree_state_field last_seq)" = 16 ] &&
+ [ "$(tree_state_field head_seq)" = 16 ] &&
+ [ ! -e "$PENDING" ] && [ ! -e "$MATCH_PIN" ] ||
+ test_skip_all "tree state is not where t7107 leaves it"
+
+release_tree_eventlog()
+{
+ [ -n "$HOLDER_PID" ] || return 0
+ kill "$HOLDER_PID" 2>/dev/null || true
+ wait "$HOLDER_PID" 2>/dev/null || true
+ HOLDER_PID=
+}
+
+cleanup()
+{
+ release_tree_eventlog
+ tree_registry_stop
+ [ ! -e "$MATCH_PIN" ] ||
+ "$SHIRUDO_BIN" upatch unload \
+ "$FIXTURES/shirudo-test-tree-match.unload.upatch" \
+ --no-precheck >/dev/null 2>&1 || true
+ tree_cleanup_config
+ rm -rf "$WORK"
+}
+trap cleanup EXIT
+
+# Hold the lock tree_event_append() takes, so that a sync stops where it
+# appends an operation's line: after its load and the register extend,
+# before the outcomes line and the state.
+hold_tree_eventlog()
+{
+ python3 -c '
+import fcntl, os, sys, time
+fd = os.open(sys.argv[1], os.O_RDONLY)
+fcntl.flock(fd, fcntl.LOCK_EX)
+open(sys.argv[2], "w").close()
+time.sleep(600)
+' "$TREE_EVENTLOG" "$WORK/held" &
+ HOLDER_PID=$!
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
+ [ -e "$WORK/held" ] && return 0
+ sleep 1
+ done
+ return 1
+}
+
+# Wait until this boot's eventlog has the tree_op record of seq $1.
+tree_op_measured()
+{
+ python3 - "$EVENTLOG" "$1" <<'PY'
+import json
+import sys
+import time
+
+seq = int(sys.argv[2])
+for _ in range(600):
+ with open(sys.argv[1], encoding="utf-8") as stream:
+ for text in stream:
+ try:
+ record = json.loads(text)
+ except ValueError:
+ continue
+ if record.get("type") == "tree_op" and \
+ record.get("tree", {}).get("seq") == seq:
+ sys.exit(0)
+ time.sleep(0.1)
+sys.exit(1)
+PY
+}
+
+# The body in $1 is compact, has the keys of the format in their order,
+# and its tree keys are those of state.json and the outcomes record. With
+# settled as $2, flags bits 2, 4 and 5 are clear and the loaded set is the
+# fold of the operations the mask has applied in the publication of the
+# reference $3; with pending, flags bit 4 is set.
+keepalive_agrees()
+{
+ python3 - "$1" "$2" "$TREE_STATE_FILE" "$OUTCOMES" \
+ "$TREE_REPO" "${3:-}" <<'PY'
+import base64
+import hashlib
+import json
+import pathlib
+import sys
+
+KEYS = ["schema", "boot_id", "version_id", "config_root", "kernel_release",
+ "image_id", "image_version", "image_root", "verdict", "cond", "flags",
+ "tamper", "tree_id", "generation", "base_seq", "last_seq",
+ "base_root", "projection_root", "mask", "set_sha256", "count",
+ "not_ok"]
+TREE_LOG_MISMATCH, TREE_OP_PENDING, SNAPSHOT_UNSETTLED = 4, 16, 32
+
+body_path, mode, state_path, outcomes_path, repo = sys.argv[1:6]
+reference = sys.argv[6]
+raw = pathlib.Path(body_path).read_bytes()
+if not raw.endswith(b"\n"):
+ sys.exit("the body does not end in a newline")
+raw = raw[:-1]
+pairs = json.loads(raw, object_pairs_hook=lambda kv: kv)
+if [key for key, _ in pairs] != KEYS:
+ sys.exit(f"the keys are {[key for key, _ in pairs]}")
+body = dict(pairs)
+if json.dumps(body, separators=(",", ":")).encode() != raw:
+ sys.exit("the body is not compact")
+
+state = json.loads(pathlib.Path(state_path).read_bytes())
+lines = [json.loads(text) for text in
+ pathlib.Path(outcomes_path).read_text(encoding="utf-8").splitlines()]
+outcome = {line["seq"]: line["outcome"] for line in lines}
+head, last = state["head_seq"], state["last_seq"]
+base = max(0, head - 512)
+for key in ("tree_id", "generation", "last_seq", "projection_root"):
+ if body[key] != state[key]:
+ sys.exit(f"{key} is {body[key]}, state.json has {state[key]}")
+if body["base_seq"] != base or body["base_root"] != "00" * 32:
+ sys.exit(f"the window starts at {body['base_seq']} {body['base_root']}")
+
+mask = base64.b64decode(body["mask"], validate=True)
+if len(mask) != (head - base + 3) // 4:
+ sys.exit(f"the mask has {len(mask)} bytes for {head - base} operations")
+for i in range(4 * len(mask)):
+ seq = base + 1 + i
+ code = mask[i // 4] >> (6 - 2 * (i % 4)) & 3
+ want = outcome[seq] if seq <= last else 0
+ if code != want:
+ sys.exit(f"the mask gives {code} for {seq}, not {want}")
+
+flags = body["flags"]
+if mode == "pending":
+ if not flags & TREE_OP_PENDING:
+ sys.exit(f"flags {flags} lack the pending operation")
+ sys.exit(0)
+if flags & (TREE_LOG_MISMATCH | TREE_OP_PENDING | SNAPSHOT_UNSETTLED):
+ sys.exit(f"flags {flags} say the tree is busy or does not agree")
+if not reference:
+ sys.exit(0)
+
+manifest = json.loads((pathlib.Path(repo) / "manifests" / reference)
+ .read_bytes())
+document = (pathlib.Path(repo) / "blobs" / manifest["layers"][0]["digest"])
+operations = json.loads(document.read_bytes())["operations"]
+loaded = {}
+for op in operations:
+ if op["seq"] > last or outcome[op["seq"]] != 1:
+ continue
+ if op["op"] == "add":
+ loaded[op["id"]] = op["artifact"]["payload_sha256"][len("sha256:"):]
+ else:
+ loaded.pop(op["id"], None)
+listing = "".join(f"{loaded[name]} {name}\n" for name in sorted(loaded))
+want = hashlib.sha256(listing.encode()).hexdigest()
+if body["set_sha256"] != want or body["count"] != len(loaded):
+ sys.exit(f"the set is {body['set_sha256']} of {body['count']}, the "
+ f"mask folds to {want} of {len(loaded)}")
+if body["not_ok"] != 0:
+ sys.exit(f"{body['not_ok']} loaded upatches are not ok")
+PY
+}
+
+# The mask of the operations $2 to $3 alone, from the body in $1.
+mask_of()
+{
+ python3 - "$1" "$2" "$3" <<'PY'
+import base64
+import json
+import sys
+
+body = json.load(open(sys.argv[1], encoding="utf-8"))
+first, last = int(sys.argv[2]), int(sys.argv[3])
+mask = base64.b64decode(body["mask"])
+codes = [mask[(seq - 1 - body["base_seq"]) // 4] >>
+ (6 - 2 * ((seq - 1 - body["base_seq"]) % 4)) & 3
+ for seq in range(first, last + 1)]
+packed = bytearray((len(codes) + 3) // 4)
+for i, code in enumerate(codes):
+ packed[i // 4] |= code << (6 - 2 * (i % 4))
+print(base64.b64encode(bytes(packed)).decode())
+PY
+}
+
+keepalive()
+{
+ "$SHIRUDO_BIN" status --keepalive >"$1"
+}
+
+# set -e reaches into $(...) under dash, so the status is caught here
+# rather than read from $? after a failing command.
+exit_status()
+{
+ status=0
+ "$@" >/dev/null 2>&1 || status=$?
+ echo "$status"
+}
+
+tree_registry_start "$REGISTRY" "$WORK"
+
+test_expect_success 'the body carries the tree keys of state.json and the outcomes record' '
+ keepalive "$WORK/before.json" &&
+ keepalive_agrees "$WORK/before.json" settled
+'
+
+test_expect_success 'status --keepalive goes without --json and --otel' '
+ [ "$(exit_status "$SHIRUDO_BIN" status --keepalive --json)" = 2 ] &&
+ [ "$(exit_status "$SHIRUDO_BIN" status --keepalive --otel)" = 2 ]
+'
+
+# A test body runs in a subshell, which could not hand the lock holder
+# to the cleanup: kill the sync here and let the body look at what is left.
+# A running sync holds the config operation lock that status waits for, so
+# the body is taken once the sync is gone and pending.json is all it left.
+tree_configure keepalive
+STOPPED=no
+if hold_tree_eventlog; then
+ BPM_OCI_SCHEME=http "$SHIRUDO_BIN" bpm tree sync \
+ --report "$WORK/stopped.json" >/dev/null 2>&1 &
+ SYNC_PID=$!
+ if tree_op_measured 17; then
+ STOPPED=yes
+ fi
+ kill -9 "$SYNC_PID" 2>/dev/null || true
+ wait "$SYNC_PID" 2>/dev/null || true
+fi
+release_tree_eventlog
+if [ "$STOPPED" = yes ] && ! keepalive "$WORK/stopped-body.json"; then
+ STOPPED=no
+fi
+
+test_expect_success 'a body taken after a sync is killed after its load has flags bit 4' '
+ [ "$STOPPED" = yes ] &&
+ [ -e "$PENDING" ] &&
+ [ -e "$MATCH_PIN" ] &&
+ [ "$(tree_state_field last_seq)" = 16 ] &&
+ [ "$(tree_state_field head_seq)" = 19 ] &&
+ [ "$(report_field last_seq <"$WORK/stopped-body.json")" = 16 ] &&
+ keepalive_agrees "$WORK/stopped-body.json" pending
+'
+
+test_expect_success 'a body taken after the sync finishes has the set its mask folds to' '
+ tree_sync "$WORK/finished.json" &&
+ [ "$(report_field last_seq <"$WORK/finished.json")" = 19 ] &&
+ [ ! -e "$PENDING" ] &&
+ [ -e "$MATCH_PIN" ] &&
+ keepalive "$WORK/finished-body.json" &&
+ keepalive_agrees "$WORK/finished-body.json" settled keepalive &&
+ [ "$(mask_of "$WORK/finished-body.json" 17 19)" = VA== ]
+'
+
+test_expect_success 'operations the node passes over give the mask of node B' '
+ tree_configure unmatched &&
+ tree_sync "$WORK/unmatched.json" &&
+ [ "$(report_field skipped <"$WORK/unmatched.json")" = 3 ] &&
+ [ "$(tree_state_field last_seq)" = 22 ] &&
+ keepalive "$WORK/unmatched-body.json" &&
+ keepalive_agrees "$WORK/unmatched-body.json" settled unmatched &&
+ [ "$(mask_of "$WORK/unmatched-body.json" 17 19)" = VA== ] &&
+ [ "$(mask_of "$WORK/unmatched-body.json" 20 22)" = qA== ]
+'
+
+test_done
diff --git a/testing/unit/keepalive.c b/testing/unit/keepalive.c
index 6ba277b4..cd4cd214 100644
--- a/testing/unit/keepalive.c
+++ b/testing/unit/keepalive.c
@@ -748,6 +748,162 @@ static void body_of_the_largest_values_fits(void)
EXPECT_EQ(keepalive_emit(&in, body, whole + 1, &len), 0);
}
+/*
+ * A node read by a snapshot. Each state read gives the next of seqs as
+ * last_seq and the last one past the end, or with no seqs a last_seq
+ * that moves on every read; each pending() call gives the next of
+ * pending, false past the end.
+ */
+struct fake_node {
+ const __s64 *seqs;
+ int n_seqs;
+ const bool *pending;
+ int n_pending;
+ int state_rc;
+ int collect_ret;
+ int reads;
+ int pending_calls;
+ int collects;
+};
+
+#define SEQS(...) .seqs = (const __s64[]){ __VA_ARGS__ }, \
+ .n_seqs = ARRAY_SIZE(((const __s64[]){ __VA_ARGS__ }))
+#define PENDING(...) .pending = (const bool[]){ __VA_ARGS__ }, \
+ .n_pending = ARRAY_SIZE(((const bool[]){ __VA_ARGS__ }))
+
+#define MOVING_FROM 100
+
+static int fake_read_state(void *ctx, struct tree_state *state)
+{
+ struct fake_node *node = ctx;
+ int read = node->reads++;
+
+ *state = (struct tree_state){ .schema = 1, .generation = 1,
+ .head_seq = KEEPALIVE_MASK_OPS };
+ strscpy(state->tree_id, "fleet-base", sizeof(state->tree_id));
+ if (!node->n_seqs)
+ state->last_seq = MOVING_FROM + read;
+ else
+ state->last_seq = node->seqs[min(read, node->n_seqs - 1)];
+ return node->state_rc;
+}
+
+static bool fake_pending(void *ctx)
+{
+ struct fake_node *node = ctx;
+ int call = node->pending_calls++;
+
+ return call < node->n_pending && node->pending[call];
+}
+
+static int fake_collect(void *ctx, const struct tree_state *state,
+ int state_rc)
+{
+ struct fake_node *node = ctx;
+
+ node->collects++;
+ return node->collect_ret;
+}
+
+static const struct keepalive_snapshot_ops fake_ops = {
+ .read_state = fake_read_state,
+ .pending = fake_pending,
+ .collect = fake_collect,
+};
+
+static __u32 snapshot_of(struct fake_node *node, struct tree_state *state)
+{
+ __u32 flags = 0;
+ int state_rc;
+
+ ASSERT_EQ(keepalive_snapshot(&fake_ops, node, state, &state_rc,
+ &flags), 0);
+ EXPECT_EQ(state_rc, node->state_rc);
+ return flags;
+}
+
+static void snapshot_of_a_still_tree_reads_it_twice(void)
+{
+ struct fake_node node = { SEQS(7) };
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), 0);
+ EXPECT_EQ(node.reads, 2);
+ EXPECT_EQ(node.collects, 1);
+ EXPECT_EQ(state.last_seq, 7);
+}
+
+static void snapshot_tries_again_after_a_state_that_moved(void)
+{
+ struct fake_node node = { SEQS(7, 8) };
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), 0);
+ EXPECT_EQ(node.reads, 4);
+ EXPECT_EQ(node.collects, 2);
+ EXPECT_EQ(state.last_seq, 8);
+}
+
+static void snapshot_gives_up_on_a_state_that_keeps_moving(void)
+{
+ struct fake_node node = {};
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), KEEPALIVE_SNAPSHOT_UNSETTLED);
+ EXPECT_EQ(node.reads, 2 * KEEPALIVE_SNAPSHOT_TRIES);
+ EXPECT_EQ(node.collects, KEEPALIVE_SNAPSHOT_TRIES);
+ /* The first read of the last try is what the body sends. */
+ EXPECT_EQ(state.last_seq,
+ MOVING_FROM + 2 * (KEEPALIVE_SNAPSHOT_TRIES - 1));
+}
+
+static void snapshot_sees_a_pending_operation_before_it_reads(void)
+{
+ struct fake_node node = { SEQS(7), PENDING(true, false) };
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), KEEPALIVE_TREE_OP_PENDING);
+}
+
+static void snapshot_sees_a_pending_operation_after_it_reads(void)
+{
+ struct fake_node node = { SEQS(7), PENDING(false, true) };
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), KEEPALIVE_TREE_OP_PENDING);
+}
+
+static void snapshot_tells_the_pending_operation_of_its_last_try(void)
+{
+ struct fake_node node = { SEQS(7, 8), PENDING(true, true) };
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), 0);
+ EXPECT_EQ(node.pending_calls, 4);
+}
+
+static void snapshot_of_no_tree_settles(void)
+{
+ struct fake_node node = { .state_rc = -ENOENT };
+ struct tree_state state;
+
+ EXPECT_UEQ(snapshot_of(&node, &state), 0);
+ EXPECT_EQ(node.collects, 1);
+}
+
+static void snapshot_stops_at_a_failed_collect(void)
+{
+ struct fake_node node = { SEQS(7), .collect_ret = -ENOMEM };
+ struct tree_state state;
+ __u32 flags = 0;
+ int state_rc;
+
+ EXPECT_EQ(keepalive_snapshot(&fake_ops, &node, &state, &state_rc,
+ &flags), -ENOMEM);
+ EXPECT_EQ(node.reads, 1);
+ EXPECT_UEQ(flags, 0);
+}
+
static const struct unit_case cases[] = {
UNIT_CASE(mask_of_one_operation),
UNIT_CASE(mask_of_the_release_example),
@@ -779,6 +935,14 @@ static const struct unit_case cases[] = {
UNIT_CASE(body_refuses_a_string_that_is_not_utf8),
UNIT_CASE(body_refuses_a_buffer_one_byte_short),
UNIT_CASE(body_of_the_largest_values_fits),
+ UNIT_CASE(snapshot_of_a_still_tree_reads_it_twice),
+ UNIT_CASE(snapshot_tries_again_after_a_state_that_moved),
+ UNIT_CASE(snapshot_gives_up_on_a_state_that_keeps_moving),
+ UNIT_CASE(snapshot_sees_a_pending_operation_before_it_reads),
+ UNIT_CASE(snapshot_sees_a_pending_operation_after_it_reads),
+ UNIT_CASE(snapshot_tells_the_pending_operation_of_its_last_try),
+ UNIT_CASE(snapshot_of_no_tree_settles),
+ UNIT_CASE(snapshot_stops_at_a_failed_collect),
{}
};
diff --git a/testing/vm/build-bundle.sh b/testing/vm/build-bundle.sh
index e951a013..e256f6e1 100755
--- a/testing/vm/build-bundle.sh
+++ b/testing/vm/build-bundle.sh
@@ -448,7 +448,7 @@ build_tree_test_registry()
local payloads="$FIXTURE_WORK/tree-payload"
local reference
- # One append-only tree that t7101 to t7107 walk in order:
+ # One append-only tree that t7101 to t7107 and t7109 walk in order:
# the tree state a target writes is sealed, so no test can start
# over, and each generation extends the one before it.
python3 - "$registry_dir" \
@@ -579,10 +579,20 @@ operations = [
operation(16, "shirudo-test-tree-match", other_node, match_artifact,
fixes=["", "B", "A", "A", "x y\n"] +
["ID-%d" % i for i in range(17)]),
+ # t7109: an add, a delete and an add this node takes, then three it
+ # passes over, the masks of node A and node B of the release example.
+ operation(17, "shirudo-test-tree-match", this_node, match_artifact),
+ operation(18, "shirudo-test-tree-match", this_node,
+ match_unload_artifact, op="delete"),
+ operation(19, "shirudo-test-tree-match", this_node, match_artifact),
+ operation(20, "shirudo-test-tree-skip", other_node, skip_artifact),
+ operation(21, "shirudo-test-tree-skip", other_node,
+ skip_unload_artifact, op="delete"),
+ operation(22, "shirudo-test-tree-skip", other_node, skip_artifact),
]
heads = {"stable": 2, "updated": 3, "deleted": 4, "restored": 5,
"kconfig": 6, "reloaded": 7, "outcomes": 10, "stopped": 12,
- "fetched": 13, "fixes": 16}
+ "fetched": 13, "fixes": 16, "keepalive": 19, "unmatched": 22}
for generation, (reference, head) in enumerate(heads.items(), start=1):
publication = {
"schema": 1,
@@ -598,7 +608,7 @@ for generation, (reference, head) in enumerate(heads.items(), start=1):
PY
for reference in stable updated deleted restored kconfig reloaded \
- outcomes stopped fetched fixes; do
+ outcomes stopped fetched fixes keepalive unmatched; do
openssl cms -sign -binary -md sha512 \
-in "$payloads-$reference.json" \
-signer "$FIXTURE_WORK/trusted/cert.der" \
@@ -627,7 +637,8 @@ def write(path, body):
for reference in ("stable", "updated", "deleted", "restored", "kconfig",
- "reloaded", "outcomes", "stopped", "fetched", "fixes"):
+ "reloaded", "outcomes", "stopped", "fetched", "fixes",
+ "keepalive", "unmatched"):
stem = payloads.name + "-" + reference
payload = payloads.with_name(stem + ".json").read_bytes()
signature = payloads.with_name(stem + ".sig").read_bytes()
diff --git a/testing/vm/image-fixtures.sh b/testing/vm/image-fixtures.sh
index d3dd94b9..ff054848 100755
--- a/testing/vm/image-fixtures.sh
+++ b/testing/vm/image-fixtures.sh
@@ -74,6 +74,7 @@ for name in config-boot-keys config-live-new-key config-live-revoke-a config-a c
config-tree-stable config-tree-updated config-tree-deleted config-tree-restored \
config-tree-kconfig config-tree-reloaded config-tree-outcomes \
config-tree-stopped config-tree-fetched config-tree-fixes \
+ config-tree-keepalive config-tree-unmatched \
config-otel config-jsonl config-jsonl-bad config-interrupted config-end2end \
config-local-stack config-builtin config-untrusted; do
[ "$name" != config-builtin ] || [ -n "$builtin_key" ] || continue
diff --git a/util/keepalive.c b/util/keepalive.c
index 899fa56b..3461b1aa 100644
--- a/util/keepalive.c
+++ b/util/keepalive.c
@@ -222,6 +222,44 @@ static void body(struct json_emit *e, const struct keepalive_input *in)
json_obj_close(e);
}
+static bool tree_state_same(const struct tree_state *a, int a_rc,
+ const struct tree_state *b, int b_rc)
+{
+ if (a_rc || b_rc)
+ return a_rc == b_rc;
+ return a->schema == b->schema && a->generation == b->generation &&
+ a->last_seq == b->last_seq && a->head_seq == b->head_seq &&
+ a->segment_base_seq == b->segment_base_seq &&
+ !strcmp(a->tree_id, b->tree_id) &&
+ !strcmp(a->projection_root, b->projection_root) &&
+ !strcmp(a->projection_root_tpm, b->projection_root_tpm) &&
+ !strcmp(a->manifest_digest, b->manifest_digest);
+}
+
+int keepalive_snapshot(const struct keepalive_snapshot_ops *ops, void *ctx,
+ struct tree_state *state, int *state_rc, __u32 *flags)
+{
+ bool pending = false, settled = false;
+ struct tree_state again;
+ int tries, again_rc, ret;
+
+ for (tries = 0; tries < KEEPALIVE_SNAPSHOT_TRIES && !settled; tries++) {
+ *state_rc = ops->read_state(ctx, state);
+ pending = ops->pending(ctx);
+ ret = ops->collect(ctx, state, *state_rc);
+ if (ret)
+ return ret;
+ pending = ops->pending(ctx) || pending;
+ again_rc = ops->read_state(ctx, &again);
+ settled = tree_state_same(state, *state_rc, &again, again_rc);
+ }
+ if (pending)
+ *flags |= KEEPALIVE_TREE_OP_PENDING;
+ if (!settled)
+ *flags |= KEEPALIVE_SNAPSHOT_UNSETTLED;
+ return 0;
+}
+
int keepalive_emit(const struct keepalive_input *in, char *buf, size_t cap,
size_t *len)
{
diff --git a/util/keepalive.h b/util/keepalive.h
index 492b32e4..be9f56a0 100644
--- a/util/keepalive.h
+++ b/util/keepalive.h
@@ -15,6 +15,7 @@
#include <shirudo/misc.h>
#include "bpf/lib/tamper.h"
+#include "bpm_tree.h"
#include "conditions.h"
#define KEEPALIVE_MASK_OPS 512
@@ -24,6 +25,19 @@
/* Holds the largest body and its terminator. */
#define KEEPALIVE_BODY_MAX 4096
+#define KEEPALIVE_REGISTER_REBOUND (1u << 0)
+#define KEEPALIVE_BOUND_LATE (1u << 1)
+#define KEEPALIVE_TREE_LOG_MISMATCH (1u << 2)
+#define KEEPALIVE_TAMPER_UNAVAILABLE (1u << 3)
+#define KEEPALIVE_TREE_OP_PENDING (1u << 4)
+#define KEEPALIVE_SNAPSHOT_UNSETTLED (1u << 5)
+
+/*
+ * How many times a snapshot reads the tree before it gives up on a state
+ * that keeps moving; kept here alone so that system testing can tune it.
+ */
+#define KEEPALIVE_SNAPSHOT_TRIES 3
+
/*
* A hash is 64 lowercase hex digits. A string that may be null is so when
* it is NULL or, but for mask, empty, as sysinfo and the tree state leave
@@ -78,4 +92,31 @@ int keepalive_mask(const __u8 *codes, size_t n, char *b64,
/* Each pair by type name, so that a condition conditions() adds moves none. */
__u16 keepalive_cond(const struct condition *conds, size_t n);
+/*
+ * The reads of a snapshot. read_state() is tree_state_read() and
+ * pending() whether pending.json exists. collect() reads what follows
+ * the state it is given, the outcomes up to its last_seq and the loaded
+ * set, into ctx, and fails the snapshot with a nonzero return.
+ */
+struct keepalive_snapshot_ops {
+ int (*read_state)(void *ctx, struct tree_state *state);
+ bool (*pending)(void *ctx);
+ int (*collect)(void *ctx, const struct tree_state *state,
+ int state_rc);
+};
+
+/*
+ * Reads the tree keys and the loaded set of one point without the tree
+ * lock, which a sync holds for minutes: the state, pending.json, what
+ * collect() reads, pending.json and the state again, over again while
+ * the second state differs from the first, at most
+ * KEEPALIVE_SNAPSHOT_TRIES times. *state and *state_rc are the first
+ * read of the last try. Sets KEEPALIVE_TREE_OP_PENDING in *flags when
+ * that try saw pending.json and KEEPALIVE_SNAPSHOT_UNSETTLED when the
+ * tries ran out. 0, or what collect() returned.
+ */
+int keepalive_snapshot(const struct keepalive_snapshot_ops *ops, void *ctx,
+ struct tree_state *state, int *state_rc,
+ __u32 *flags) __must_check;
+
#endif /* SHIRUDO_KEEPALIVE_H */