eBPF-based security platform
backend: load the labels of nodes out of band
John Fastabenda0b6ad169af1
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 554f5bd5..534d105b 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -979,7 +979,8 @@ retention script and the views that keep boot baselines, the treeingest job on a single publication and on a walk over sealed segments,the SBOM scan job on a store that holds an image in every state, theSBOM put job into a ``file://`` and an ``s3://`` store, again and with-another SBOM, and what it refuses (``test/sbom-put``), and the queries+another SBOM, and what it refuses (``test/sbom-put``), the label put job+and the labels each node reads from it (``test/labels-put``), and the queriesof :src:`tools/xtop/sql/`, with the names and types of their columns,over nodes healthy, unhealthy, stale and without a tree or an image, atree with one upatch deployed and one still rolling out, and thediff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 00b0e5c3..2dc435ad 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -1206,7 +1206,9 @@ prints the report in ``test/trivy/`` named by the SHA-256 of the SBOM itis given. ``test/sbom-put`` stores two of those SBOMs with``jobs/sbom-put`` into a ``file://`` store and through the same AWS stubinto an ``s3://`` one, runs ``--scan`` on the first, and checks what it-refuses. A script that exits with status 77 skips its test and says+refuses. ``test/labels-put`` loads label sets with ``jobs/labels-put``+by ``node_id`` and by ``ak_name``, replaces and clears some, and checks+what it refuses. A script that exits with status 77 skips its test and sayswhy. ``test/sbom-scan-trivy`` is skipped unless ``trivy`` is on the hostand ``SBOM_TRIVY_CACHE`` names a Trivy cache directory with a database,since its findings would change with every database CI could fetch.diff --git a/Documentation/operate/backend/index.rst b/Documentation/operate/backend/index.rstindex 6359f13b..6d09cf51 100644--- a/Documentation/operate/backend/index.rst+++ b/Documentation/operate/backend/index.rst@@ -78,6 +78,9 @@ Fileskeeps a record and ``shirudo.boot_first`` a boot.* - :src:`tools/backend/jobs/tree-ingest`- Loads every segment of a upatch tree into the reference tables.+ * - :src:`tools/backend/jobs/labels-put`+ - Loads the labels the operator gives the nodes, out of band+ (:doc:`labels-put`).* - :src:`tools/backend/jobs/sbom-put`- Stores the CycloneDX SBOM of an image in the SBOM store, for animage pipeline to call (:doc:`sbom-put`).@@ -102,6 +105,7 @@ Filestree-ingestsbom-scansbom-put+ labels-putmaintainboot-baselinesxtopdiff --git a/Documentation/operate/backend/labels-put.rst b/Documentation/operate/backend/labels-put.rstnew file mode 100644index 00000000..74c57073--- /dev/null+++ b/Documentation/operate/backend/labels-put.rst@@ -0,0 +1,98 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators++Label the nodes+===============++A tree selector picks nodes by their labels (:doc:`/operate/run/deliver-packages`),+but a node's keepalive does not carry them, so the backend cannot show+which nodes a selector reaches. :src:`tools/backend/jobs/labels-put` gives+the backend the labels out of band: the operator, or the pipeline that+builds the config images, loads the same labels it writes into each+node's ``etc/shirudo/node.labels``. It is POSIX shell around+``clickhouse-client``, with :src:`tools/backend/jobs/labels-rows.py` to+read the file, so the host that runs it needs ``python3`` and+``clickhouse-client``.++The backend's labels are what the operator says, not what the node+matches: tree sync on the node reads its own ``node.labels``, and nothing+the job loads reaches a node. Load them from the same source as the+config images, after each change, or the two drift apart.++1. Write the sets, one per node, each named by its ``node_id`` or by its+ ``ak_name``:++ .. code-block:: json++ {"nodes": [+ {"node_id": "edge-01", "labels": {"role": "edge", "site": "fra"}},+ {"node_id": "edge-02", "labels": {"role": "edge", "site": "ams"}},+ {"ak_name": "000b9d72e08380a1", "labels": {"role": "core"}}+ ]}++2. Check it, which loads nothing:++ .. code-block:: console++ $ jobs/labels-put --check labels.json++3. Load it:++ .. code-block:: console++ $ jobs/labels-put labels.json+ labels-put: node_id edge-01: 2 labels+ labels-put: node_id edge-02: 2 labels+ labels-put: ak_name 000b9d72e08380a1: 1 label+ labels-put: loaded sets: 3++``-`` in place of the file reads standard input.++What a set does+---------------++A set replaces the whole set stored under its name: a label it leaves out+is gone. An empty set, ``"labels": {}``, clears it. A node the file does+not name keeps its labels. The file is loaded in one insert, whole or+not at all.++A node gets the set put under its ``ak_name``, else the one put under its+``node_id``, else none, as the view ``shirudo.node_labels`` reads them+(:doc:`tables/status`). Name a node by its ``node_id``, the name+:doc:`maintain` gives it, so that the labels stay with it when it gets a+new key; name it by its ``ak_name`` to give one key labels of its own. A+name no node has yet keeps its set until one has it.++What it refuses+---------------++A label is one ``node.labels`` could hold, so that a set copied from that+file loads as it is and a selector's key and value can match it. The job+refuses the whole file, with status 1 and a message naming the set, when:++- it is not UTF-8 JSON, or not an object whose one key is ``nodes``, an+ array; or an object has a key twice;+- a set is not an object with ``labels`` and exactly one of ``node_id``,+ 1 to 255 characters with no control character, and ``ak_name``, 1 to+ 255 lowercase hex digits; or has another key;+- two sets name the same ``node_id`` or ``ak_name``;+- ``labels`` is not an object of strings, or holds more than 64 labels;+- a key is empty, has ``=``, starts with ``#``, or a key or value has a+ blank at either end, a control character, or more than 255 bytes.++Exit status+-----------++0 when every set is loaded, or checked with ``--check``; 1 when the file+is refused or the load fails, with nothing loaded; 2 for wrong usage.++Connection+----------++As :src:`tools/backend/jobs/tree-ingest`, the job runs+``clickhouse-client`` or the command ``CLICKHOUSE_CLIENT`` names. Its user+needs ``SELECT`` and ``INSERT`` on ``shirudo.label_sets``.diff --git a/Documentation/operate/backend/status.rst b/Documentation/operate/backend/status.rstindex 66631404..a3e04d35 100644--- a/Documentation/operate/backend/status.rst+++ b/Documentation/operate/backend/status.rst@@ -25,6 +25,9 @@ follows. The objects that do it are in :src:`tools/backend/sql/40-status.sql`, a* - ``shirudo.latest``- view- The newest record of every node, from ``keepalive_latest``, with the node's ``node_id`` and ``trust``.+ * - ``shirudo.node_labels``+ - view+ - The labels of every node, from ``label_sets``, see :doc:`labels-put`.* - ``shirudo.node_ops``- ReplacingMergeTree, ``ORDER BY (ak_name, tree_id, seq)``, no TTL- The history of every node: what it did at each operation of its tree the backend has seen it reach, see `History`_.diff --git a/Documentation/operate/backend/tables/reference.rst b/Documentation/operate/backend/tables/reference.rstindex 00aa588a..cafe80d4 100644--- a/Documentation/operate/backend/tables/reference.rst+++ b/Documentation/operate/backend/tables/reference.rst@@ -8,9 +8,10 @@Reference=========-What the checks compare a record against. nodes fills itself from accepted-records; tree-ingest loads the tree tables; the operator writes builds,-manual fixes and settings.+What the checks compare a record against, and what the operator says of a+node. nodes fills itself from accepted records; tree-ingest loads the tree+tables; labels-put loads label_sets; the operator writes builds, manual+fixes and settings.Schema: :src:`tools/backend/sql/20-reference.sql`@@ -29,6 +30,12 @@ Views, functions and jobsyet loaded into tree_pubs, tree_ops and upatch_fixes (source fixes). Allor nothing on a conflict.+``jobs/labels-put``+ external job.++ Checks a file of label sets and loads it into label_sets in one insert,+ all or nothing, each row with one put_at later than any before.+shirudo.nodes-------------@@ -197,3 +204,28 @@ shirudo.settings:sbom_stale_seconds: 172800 (2 days). Age after which a scan marks node_vulns rowssbom_stale.:updated: Version column: the newest row wins.++shirudo.label_sets+------------------++.. clickhouse-table:: shirudo.label_sets+ :kind: ref+ :written-by: jobs/labels-put+ :row-size: ~200 B (estimate: a few short labels).+ :scale: Every node and key ever labeled, each put once more until a merge.+ :reference: 10,000 rows ≈ 2 MB+ :bytes: 2e+06++ The labels the operator gives a node out of band, one set per node_id+ or ak_name. Not what the node's node.labels holds: tree sync matches+ selectors against that file, and nothing here reaches the node.++ - Read with FINAL, or through node_labels: the newest put of a name+ replaces the set.+ - An empty map clears the set; node_labels then falls back to the+ other name, or none.++ :by: Whether node names a node_id or an ak_name.+ :node: The node_id or ak_name.+ :labels: The whole set, key to value.+ :put_at: When labels-put loaded it; the version ReplacingMergeTree keeps the newest of.diff --git a/Documentation/operate/backend/tables/status.rst b/Documentation/operate/backend/tables/status.rstindex 0997f741..5d998939 100644--- a/Documentation/operate/backend/tables/status.rst+++ b/Documentation/operate/backend/tables/status.rst@@ -30,6 +30,13 @@ Views, functions and jobskeepalive_latest FINAL joined to nodes: the newest record of every nodewith node_id and trust.+``shirudo.node_labels``+ view.++ label_sets FINAL joined to nodes: per key, the labels put under its+ ak_name, else those put under its node_id, else none, and by, which of+ the three it is. An empty set counts as none.+``shirudo.history_conflicts``view.diff --git a/tools/backend/jobs/labels-put b/tools/backend/jobs/labels-putnew file mode 100755index 00000000..6a43a3e7--- /dev/null+++ b/tools/backend/jobs/labels-put@@ -0,0 +1,88 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/labels-put -- load the label sets of nodes into shirudo.label_sets,+# out of band from what the nodes report.+#+# jobs/labels-put [--check] <sets.json>|-+#+# The file names each node by node_id or by ak_name and gives its whole+# set of labels, which replaces the one stored under that name; an empty+# set clears it. Nodes the file does not name keep theirs. The file is+# loaded whole or not at all. --check reads and checks it, and loads+# nothing.+#+# CLICKHOUSE_CLIENT the client command and its options, split at+# spaces. Default: clickhouse-client, which reads+# CLICKHOUSE_HOST, CLICKHOUSE_USER and+# CLICKHOUSE_PASSWORD itself.+#+# Exit status: 0 when every set is loaded, or checked with --check; 1+# when the file is refused or the load fails, with nothing loaded; 2 for+# wrong usage.++set -eu++here=$(cd "$(dirname "$0")" && pwd)+check=0+work=++die()+{+ printf 'labels-put: %s\n' "$1" >&2+ exit 1+}++usage()+{+ printf '%s\n' 'usage: labels-put [--check] <sets.json>|-' >&2+ exit 2+}++cleanup()+{+ [ -z "$work" ] || rm -rf "$work"+}++client()+{+ # shellcheck disable=SC2086 # a command with its options, to be split+ ${CLICKHOUSE_CLIENT:-clickhouse-client} "$@"+}++[ "${1:-}" = --check ] && { check=1; shift; }+[ $# -eq 1 ] || usage+case "$1" in+-) ;;+-*) usage ;;+esac++trap cleanup EXIT+trap 'exit 1' HUP INT TERM+work=$(mktemp -d)+if [ "$1" = - ]; then+ cat >"$work/sets.json"+else+ cp "$1" "$work/sets.json" 2>/dev/null || die "cannot read $1, nothing loaded"+fi++if [ "$check" -eq 1 ]; then+ python3 "$here/labels-rows.py" "$work/sets.json" "$work/rows.jsonl" 0+ exit+fi++# Every put gets a time of its own, after every put before it, so that+# the newest set of a name is the one ReplacingMergeTree keeps.+put_at=$(client --query 'SELECT toUnixTimestamp64Milli(greatest(now64(3),+ (SELECT max(put_at) FROM shirudo.label_sets) + toIntervalMillisecond(1)))' \+ </dev/null) || die 'cannot read shirudo.label_sets, nothing loaded'+python3 "$here/labels-rows.py" "$work/sets.json" "$work/rows.jsonl" \+ "$put_at" >"$work/summary" || exit 1+# One insert, one block: the sets land together or not at all.+if [ -s "$work/rows.jsonl" ]; then+ client --query 'INSERT INTO shirudo.label_sets FORMAT JSONEachRow' \+ <"$work/rows.jsonl" || die 'cannot insert into shirudo.label_sets, nothing loaded'+fi+cat "$work/summary"+printf 'labels-put: loaded sets: %d\n' "$(wc -l <"$work/rows.jsonl")"diff --git a/tools/backend/jobs/labels-rows.py b/tools/backend/jobs/labels-rows.pynew file mode 100644index 00000000..2bd943f1--- /dev/null+++ b/tools/backend/jobs/labels-rows.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/labels-rows.py -- the part of jobs/labels-put that shell does not+# reach: reading and checking the label sets.+#+# labels-rows.py <sets.json> <rows.jsonl> <put_at>+#+# Reads {"nodes": [{"node_id": <name>, "labels": {<key>: <value>, ...}},+# {"ak_name": <key>, "labels": {...}}, ...]} and writes one row of+# shirudo.label_sets per set, in ClickHouse's JSONEachRow format, with+# put_at, milliseconds since the epoch, on every row. Prints a line per+# set. A label is one that etc/shirudo/node.labels could hold, so that a+# set copied from that file loads as it is and a selector's key and value+# can match it.+#+# Exit status: 0; 1 when the file is refused, named on standard error,+# with nothing written; 2 for wrong usage.++import json+import re+import sys++PROG = "labels-put"+# As TREE_MAX_LABELS and TREE_STRING_MAX of util/bpm_tree.h.+MAX_LABELS = 64+MAX_TEXT = 255+NODE_ID = re.compile(r"[^\x00-\x1f\x7f]{1,255}")+AK_NAME = re.compile(r"[0-9a-f]{1,255}")+CONTROL = re.compile(r"[\x00-\x1f\x7f]")+++class Refused(Exception):+ pass+++def unique_keys(pairs):+ seen = {}+ for key, value in pairs:+ if key in seen:+ raise Refused('the key "%s" is given twice in one object'+ % printable(key))+ seen[key] = value+ return seen+++def not_a_number(name):+ raise Refused("%s is not a JSON number" % name)+++def printable(text):+ return "".join(c if c.isprintable() else "?" for c in text)+++def parse(data):+ try:+ text = data.decode("utf-8")+ except UnicodeDecodeError:+ raise Refused("the file is not UTF-8")+ decoder = json.JSONDecoder(object_pairs_hook=unique_keys,+ parse_constant=not_a_number)+ try:+ return decoder.decode(text)+ except (ValueError, RecursionError):+ raise Refused("the file is not a JSON value")+++def text_ok(text):+ """What a node.labels line keeps of a key or value: no blank at either+ end, no control character, at most MAX_TEXT bytes."""+ return (text == text.strip() and not CONTROL.search(text)+ and len(text.encode("utf-8")) <= MAX_TEXT)+++def check_label(where, key, value):+ if type(value) is not str:+ raise Refused("%s: the value of %s is not a string"+ % (where, printable(key)))+ if not key or not text_ok(key) or "=" in key or key.startswith("#"):+ raise Refused('%s: the key "%s" is not one node.labels can hold: 1 to'+ ' %d bytes, no "=", no "#" first, no blank at either'+ ' end, no control character'+ % (where, printable(key), MAX_TEXT))+ if not text_ok(value):+ raise Refused('%s: the value of %s is not one node.labels can hold:'+ ' at most %d bytes, no blank at either end, no control'+ ' character' % (where, printable(key), MAX_TEXT))+++def node_of(n, entry):+ """The set's (by, node) from its one name."""+ if type(entry) is not dict:+ raise Refused("set %d is not an object" % n)+ extra = set(entry) - {"node_id", "ak_name", "labels"}+ if extra:+ raise Refused('set %d has the key "%s", which is not node_id,'+ ' ak_name or labels' % (n, printable(sorted(extra)[0])))+ names = [k for k in ("node_id", "ak_name") if k in entry]+ if len(names) != 1:+ raise Refused("set %d names its node by neither or both of node_id"+ " and ak_name" % n)+ by = names[0]+ node = entry[by]+ pattern = NODE_ID if by == "node_id" else AK_NAME+ if type(node) is not str or not pattern.fullmatch(node):+ raise Refused("set %d: %s is not %s" % (+ n, by, "1 to 255 characters with no control character"+ if by == "node_id" else "1 to 255 lowercase hex digits"))+ return by, node+++def sets_of(doc):+ if type(doc) is not dict or set(doc) != {"nodes"}:+ raise Refused('the file is not an object whose one key is "nodes"')+ if type(doc["nodes"]) is not list:+ raise Refused("nodes is not an array")+ out, seen = [], set()+ for n, entry in enumerate(doc["nodes"], 1):+ by, node = node_of(n, entry)+ where = "%s %s" % (by, printable(node))+ if (by, node) in seen:+ raise Refused("%s has two sets" % where)+ seen.add((by, node))+ labels = entry.get("labels")+ if type(labels) is not dict:+ raise Refused("%s: labels is not an object" % where)+ if len(labels) > MAX_LABELS:+ raise Refused("%s: more than %d labels" % (where, MAX_LABELS))+ for key, value in labels.items():+ check_label(where, key, value)+ out.append((by, node, labels))+ return out+++def count_of(n):+ if not n:+ return "cleared"+ return "1 label" if n == 1 else "%d labels" % n+++def main():+ if len(sys.argv) != 4 or not sys.argv[3].isdigit():+ print("usage: labels-rows.py <sets.json> <rows.jsonl> <put_at>",+ file=sys.stderr)+ return 2+ path, rows, put_at = sys.argv[1], sys.argv[2], int(sys.argv[3])+ try:+ with open(path, "rb") as f:+ sets = sets_of(parse(f.read()))+ except Refused as reason:+ print("%s: %s, nothing loaded" % (PROG, reason), file=sys.stderr)+ return 1+ except OSError as error:+ print("%s: cannot read %s, nothing loaded"+ % (PROG, printable(error.filename or path)), file=sys.stderr)+ return 1+ with open(rows, "w", encoding="utf-8") as f:+ for by, node, labels in sets:+ f.write(json.dumps({"by": by, "node": node, "labels": labels,+ "put_at": put_at / 1000},+ ensure_ascii=False, separators=(",", ":")))+ f.write("\n")+ for by, node, labels in sets:+ print("%s: %s %s: %s" % (PROG, by, printable(node),+ count_of(len(labels))))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/backend/sql/20-reference.sql b/tools/backend/sql/20-reference.sqlindex 98ffe1ea..3d0f356c 100644--- a/tools/backend/sql/20-reference.sql+++ b/tools/backend/sql/20-reference.sql@@ -101,6 +101,21 @@ CREATE TABLE IF NOT EXISTS shirudo.upatch_fixesENGINE = ReplacingMergeTreeORDER BY (tree_id, seq, advisory, source);+-- The labels the operator gives a node, out of band: what jobs/labels-put+-- loads, not what the node's own node.labels holds, which only its tree+-- sync reads. One row per set, by node_id or by ak_name; a newer put of+-- the same name replaces it, and an empty map clears it. Read it with+-- FINAL, or through shirudo.node_labels.+CREATE TABLE IF NOT EXISTS shirudo.label_sets+(+ by Enum8('node_id' = 1, 'ak_name' = 2),+ node String,+ labels Map(String, String),+ put_at DateTime64(3) DEFAULT now64(3)+)+ENGINE = ReplacingMergeTree(put_at)+ORDER BY (by, node);+-- The thresholds of the checks, the retention of shirudo.keepalive and-- shirudo.boot_first and the age at which an SBOM's scan is stale, in one-- row. Read it with FINAL; to change a value, insert the whole row againdiff --git a/tools/backend/sql/40-status.sql b/tools/backend/sql/40-status.sqlindex d2685818..16f974b1 100644--- a/tools/backend/sql/40-status.sql+++ b/tools/backend/sql/40-status.sql@@ -27,6 +27,27 @@ INNER JOINGROUP BY ak_name) AS n ON n.ak_name = k.ak_name;+-- The labels of every node: the set put under its ak_name, else the one+-- put under its node_id, else none. by says which.+CREATE VIEW IF NOT EXISTS shirudo.node_labels AS+WITH sets AS+(+ SELECT by, node, labels FROM shirudo.label_sets FINAL WHERE notEmpty(labels)+)+SELECT+ n.ak_name AS ak_name,+ n.node_id AS node_id,+ if(a.node != '', a.labels, i.labels) AS labels,+ multiIf(a.node != '', 'ak_name', i.node != '', 'node_id', 'none') AS by+FROM+(+ SELECT ak_name, argMinMerge(node_id) AS node_id+ FROM shirudo.nodes+ GROUP BY ak_name+) AS n+LEFT JOIN (SELECT node, labels FROM sets WHERE by = 'ak_name') AS a ON a.node = n.ak_name+LEFT JOIN (SELECT node, labels FROM sets WHERE by = 'node_id') AS i ON i.node = n.node_id;+-- History: what each node did at every operation of its tree that the-- backend has seen it reach, so that checks 4 and 6 and node_vulns can-- look below the window of the last 512 operations a keepalive covers.diff --git a/tools/backend/test/labels-put.expected b/tools/backend/test/labels-put.expectednew file mode 100644index 00000000..57b0a92b--- /dev/null+++ b/tools/backend/test/labels-put.expected@@ -0,0 +1,51 @@+labels-put: node_id edge-01: 2 labels+labels-put: node_id edge-02: 2 labels+labels-put: ak_name 000b03: 1 label+labels-put: loaded sets: 3+first put: status 0+labels-put: node_id edge-02: cleared+labels-put: ak_name 000b01: 3 labels+labels-put: loaded sets: 2+second put: status 0+labels-put: node_id edge-01: 2 labels+labels-put: node_id edge-02: 2 labels+labels-put: ak_name 000b03: 1 label+check: status 0+labels-put: the file is not a JSON value, nothing loaded+not json: status 1+labels-put: the file is not an object whose one key is "nodes", nothing loaded+not the form: status 1+labels-put: the file is not an object whose one key is "nodes", nothing loaded+another top key: status 1+labels-put: set 1 names its node by neither or both of node_id and ak_name, nothing loaded+both names: status 1+labels-put: set 1 names its node by neither or both of node_id and ak_name, nothing loaded+no name: status 1+labels-put: set 1: ak_name is not 1 to 255 lowercase hex digits, nothing loaded+ak not hex: status 1+labels-put: set 1 has the key "label", which is not node_id, ak_name or labels, nothing loaded+unknown key: status 1+labels-put: node_id a has two sets, nothing loaded+two sets: status 1+labels-put: the key "x" is given twice in one object, nothing loaded+key twice: status 1+labels-put: node_id a: the key "a=b" is not one node.labels can hold: 1 to 255 bytes, no "=", no "#" first, no blank at either end, no control character, nothing loaded+equals in key: status 1+labels-put: node_id a: the key "#a" is not one node.labels can hold: 1 to 255 bytes, no "=", no "#" first, no blank at either end, no control character, nothing loaded+hash first: status 1+labels-put: node_id a: the value of a is not one node.labels can hold: at most 255 bytes, no blank at either end, no control character, nothing loaded+blank at end: status 1+labels-put: node_id a: the value of a is not a string, nothing loaded+value not text: status 1+labels-put: node_id a: the value of a is not one node.labels can hold: at most 255 bytes, no blank at either end, no control character, nothing loaded+long value: status 1+labels-put: node_id a: more than 64 labels, nothing loaded+too many: status 1+labels-put: cannot read none.json, nothing loaded+no file: status 1+usage: labels-put [--check] <sets.json>|-+no argument: status 2+core-01 000b03 {'role':'core'} ak_name+edge-01 000b01 {'role':'edge','site':'fra','rack':'r 7'} ak_name+edge-02 000b02 {} none+sets 5diff --git a/tools/backend/test/labels-put.setup.sql b/tools/backend/test/labels-put.setup.sqlnew file mode 100644index 00000000..89d20647--- /dev/null+++ b/tools/backend/test/labels-put.setup.sql@@ -0,0 +1,9 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Three keys the backend knows, named edge-01, edge-02 and core-01.++INSERT INTO shirudo.nodes (ak_name, node_id)+SELECT record.1, argMinState(record.2, toDateTime64(0, 3))+FROM (SELECT arrayJoin([('000b01', 'edge-01'), ('000b02', 'edge-02'), ('000b03', 'core-01')]) AS record)+GROUP BY record.1;diff --git a/tools/backend/test/labels-put.sh b/tools/backend/test/labels-put.shnew file mode 100644index 00000000..6b99f0dd--- /dev/null+++ b/tools/backend/test/labels-put.sh@@ -0,0 +1,75 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# jobs/labels-put: a file of sets by node_id and by ak_name loads whole,+# from a file and from standard input; a second put replaces the sets it+# names, clears one with an empty set, and keeps those it does not name;+# --check loads nothing. Then what it refuses, each with a message and+# nothing loaded: a file that is not JSON or not of the form, a set that+# names its node twice or not at all, two sets for one name, a key or+# value node.labels could not hold, too many labels, a missing file and+# wrong usage.++set -eu++test=$(cd "$(dirname "$0")" && pwd)+job=$test/../jobs/labels-put++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT++# run <what> <command>...: run a command, then name its status.+run()+{+ what=$1+ shift+ status=0+ "$@" 2>&1 || status=$?+ printf '%s: status %d\n' "$what" "$status"+}++# refused <what> <file content>: the job on that file.+refused()+{+ printf '%s\n' "$2" >"$work/bad.json"+ run "$1" "$job" "$work/bad.json"+}++cat >"$work/first.json" <<'SETS'+{"nodes": [+ {"node_id": "edge-01", "labels": {"role": "edge", "site": "fra"}},+ {"node_id": "edge-02", "labels": {"role": "edge", "site": "ams"}},+ {"ak_name": "000b03", "labels": {"role": "core"}}+]}+SETS+run 'first put' "$job" "$work/first.json"++cat >"$work/second.json" <<'SETS'+{"nodes": [+ {"node_id": "edge-02", "labels": {}},+ {"ak_name": "000b01", "labels": {"role": "edge", "site": "fra", "rack": "r 7"}}+]}+SETS+run 'second put' "$job" - <"$work/second.json"+run 'check' "$job" --check "$work/first.json"++long=$(printf '%0256d' 0)+many=$(i=0; while [ $i -lt 65 ]; do printf '"k%d": "v",' $i; i=$((i + 1)); done)+refused 'not json' '{"nodes": ['+refused 'not the form' '[]'+refused 'another top key' '{"nodes": [], "extra": 1}'+refused 'both names' '{"nodes": [{"node_id": "a", "ak_name": "0b", "labels": {}}]}'+refused 'no name' '{"nodes": [{"labels": {}}]}'+refused 'ak not hex' '{"nodes": [{"ak_name": "000B", "labels": {}}]}'+refused 'unknown key' '{"nodes": [{"node_id": "a", "labels": {}, "label": {}}]}'+refused 'two sets' '{"nodes": [{"node_id": "a", "labels": {}}, {"node_id": "a", "labels": {"x": "y"}}]}'+refused 'key twice' '{"nodes": [{"node_id": "a", "labels": {"x": "1", "x": "2"}}]}'+refused 'equals in key' '{"nodes": [{"node_id": "a", "labels": {"a=b": "c"}}]}'+refused 'hash first' '{"nodes": [{"node_id": "a", "labels": {"#a": "c"}}]}'+refused 'blank at end' '{"nodes": [{"node_id": "a", "labels": {"a": "c "}}]}'+refused 'value not text' '{"nodes": [{"node_id": "a", "labels": {"a": 1}}]}'+refused 'long value' "{\"nodes\": [{\"node_id\": \"a\", \"labels\": {\"a\": \"$long\"}}]}"+refused 'too many' "{\"nodes\": [{\"node_id\": \"a\", \"labels\": {${many%,}}}]}"+(cd "$work" && run 'no file' "$job" none.json)+run 'no argument' "$job"diff --git a/tools/backend/test/labels-put.sql b/tools/backend/test/labels-put.sqlnew file mode 100644index 00000000..3a1591bb--- /dev/null+++ b/tools/backend/test/labels-put.sql@@ -0,0 +1,10 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- The labels of each node after test/labels-put.sh: edge-01 by its key,+-- which the second put gave it over its node_id's set, edge-02 cleared,+-- core-01 by its key from the first put, which the second left alone.+-- The refused files loaded nothing.++SELECT node_id, ak_name, labels, by FROM shirudo.node_labels ORDER BY node_id;+SELECT 'sets', count() FROM shirudo.label_sets;diff --git a/tools/backend/test/schema.expected b/tools/backend/test/schema.expectedindex 647a6460..d8108151 100644--- a/tools/backend/test/schema.expected+++ b/tools/backend/test/schema.expected@@ -13,7 +13,9 @@ shirudo keepalive_latest ReplacingMergeTree ak_nameshirudo keepalive_latest_mv MaterializedViewshirudo keepalive_mv MaterializedViewshirudo kernel_vulns ReplacingMergeTree vuln_id, introduced+shirudo label_sets ReplacingMergeTree by, nodeshirudo latest View+shirudo node_labels Viewshirudo node_ops ReplacingMergeTree ak_name, tree_id, seqshirudo node_ops_mv MaterializedViewshirudo node_sets ReplacingMergeTree ak_name, tree_id, id