gunk-dev/the-valley

telemetry.nix

source40b311d8f0demain's published tip history
16.2 KiB
1# Telemetry on a valley host (services.valley.telemetry): the collector a
2# session reads the host's diagnostics through, and the diagnostic
3# directories the host's producers export to it.
4#
5# valley-host.nix imports this with what it derives from the declaration,
6# so the catalog below names exactly the units the host runs.
7#
8# A session reaches the collector only through the git user's shell, over
9# ssh, with the telemetry command (../telemetry/protocol.go). The shell
10# derives the principal from the authenticated key, holds it to the
11# observe or report grant this module writes, and passes the collector one
12# request line on a socket only the git user can open. systemd starts one
13# collector per connection (Accept=yes), as its own unprivileged user,
14# under the limits below, and kills one that outlives them.
15#
16# The collector reads what the manifest names and nothing else: the
17# enumerated units' properties (an explicit list, never the environment)
18# and journal, the streams the worker and the integrator export, and the
19# reports it keeps itself. It is in the systemd-journal group, which lets
20# its account read the whole system journal; its code asks only for the
21# manifest's units. It holds no grant on the repositories, no key, and no
22# way into the worker's private directory.
23#
24# Each producer exports into a directory of its own here, owned by it and
25# group-readable by the collector alone, apart from its private state: the
26# worker's key stays in its 0700 state directory.
27derived:
28{
29 config,
30 lib,
31 pkgs,
32 ...
33}:
34let
35 cfg = config.services.valley;
36 tcfg = cfg.telemetry;
37 package = cfg.packages.telemetry;
38
39 root = "/var/lib/valley-telemetry";
40 collectorState = "${root}/collector";
41 workerDir = "${root}/worker";
42 integratorDir = "${root}/integrator";
43 socket = "/run/valley-telemetry.sock";
44
45 grantsFile = pkgs.writeText "valley-telemetry-grants" (
46 ''
47 # Declared in services.valley.telemetry — do not edit.
48 ''
49 + lib.concatMapStrings (p: "observe ${p}\n") tcfg.observers
50 + lib.concatMapStrings (p: "report ${p}\n") tcfg.reporters
51 );
52
53 webPublisher = config.services.valley.webPublisher.enable or false;
54 webReceiver = config.services.valley.webReceiver.enable or false;
55 integrated = lib.attrNames derived.integratedProjects;
56 published = lib.attrNames derived.publishedProjects;
57
58 source =
59 name: description: enabled: units: extra:
60 {
61 inherit
62 name
63 description
64 enabled
65 units
66 ;
67 location = "local";
68 }
69 // extra;
70
71 ownSources = [
72 (source "worker" "the check worker, and the attest runs its passes start" cfg.worker.enable
73 [
74 "valley-worker.service"
75 "valley-worker.timer"
76 "valley-worker.path"
77 ]
78 {
79 stream = "${workerDir}/stream";
80 state = "${workerDir}/state.json";
81 configured = {
82 worker = "${derived.workerPackage}";
83 attest = "${derived.attestPackage}";
84 };
85 instruments = [
86 "passes, the change, version, head and tree each reads, batches, publication and backoff with its reason"
87 "each check's evaluation, slot wait, build and result as it happens, and its build output, bounded"
88 "a pass killed before its end, inferred at the next pass"
89 ];
90 }
91 )
92 (source "integrator" "the per-project integrators" cfg.integrator.enable
93 (map (p: "valley-integrator@${p}.service") integrated)
94 {
95 stream = "${integratorDir}/stream";
96 configured.integrator = "${derived.integratorPackage}";
97 instruments = [
98 "each decision's outcome and its stages, from when it began judging the request"
99 "when its process first listed each request at its head, and the pass that decided it"
100 ];
101 not_instrumented = [
102 "when the host accepted a request ref, and anything before the integrator's process started"
103 ];
104 }
105 )
106 (source "restacker" "the per-project restackers" cfg.restacker.enable
107 (map (p: "valley-restacker@${p}.service") cfg.restacker.projects)
108 {
109 configured.restacker = "${derived.restackerPackage}";
110 not_instrumented = [ "no producer records: lifecycle and output only" ];
111 }
112 )
113 (source "identity" "the registry compiler" cfg.identity.enable [
114 "valley-identity.service"
115 "valley-identity.timer"
116 ] { not_instrumented = [ "no producer records: lifecycle and output only" ]; })
117 (source "signers" "the known-signers publisher" derived.publishesSigners [
118 "valley-signers.service"
119 "valley-signers.path"
120 ] { not_instrumented = [ "no producer records: lifecycle and output only" ]; })
121 (source "mirrors" "the publish queues and their drains" (published != [ ]) (
122 map (p: "valley-publish@${p}.service") published ++ map (p: "valley-publish@${p}.path") published
123 ) { not_instrumented = [ "no producer records: lifecycle and output only" ]; })
124 (source "bus" "the NATS bus" cfg.bus.enable [
125 "valley-bus.service"
126 "valley-bus-init.service"
127 ] { })
128 (source "web-publisher" "the web publisher" webPublisher [
129 "valley-web-publish.service"
130 "valley-web-publish.timer"
131 "valley-web-publish-policy.service"
132 ] { })
133 (source "web-receiver" "the web receiver, on this host" webReceiver [
134 "valley-web-receive.service"
135 "valley-web.service"
136 ] { })
137 (source "backup" "the offsite backup" derived.backupEnabled [
138 "restic-backups-valley.service"
139 "restic-backups-valley.timer"
140 ] { })
141 (source "convergence" "valley-init, which converges the repositories and hooks" true [
142 "valley-init.service"
143 ] { })
144 (source "build-slice" "the build slice and the nix daemon whose builds run in it" cfg.buildSlice.enable [
145 "valley-builds.slice"
146 "nix-daemon.service"
147 ] { })
148 (source "telemetry" "the collector's socket" true [ "valley-telemetry.socket" ] {
149 configured.collector = "${package}";
150 })
151 ];
152
153 # The host's own units, catalogued as the module's local sources are.
154 hostSources = map (s: source s.name s.description true s.units { }) tcfg.localSources;
155
156 catalog = {
157 v = 1;
158 host = config.networking.hostName;
159 reporters = tcfg.reporters;
160 sources =
161 ownSources
162 ++ hostSources
163 ++ map (r: {
164 inherit (r) name description;
165 enabled = true;
166 location = "remote";
167 reporter = r.principal;
168 stale_after_s = r.staleAfter;
169 }) tcfg.remoteSources;
170 };
171
172 manifest = pkgs.writeText "valley-telemetry-manifest.json" (builtins.toJSON catalog);
173
174 # Every name the catalog holds, each as many times as it is declared.
175 sourceNames =
176 map (s: s.name) ownSources
177 ++ map (s: s.name) tcfg.localSources
178 ++ map (s: s.name) tcfg.remoteSources;
179in
180{
181 options.services.valley.telemetry = {
182 enable = lib.mkEnableOption ''
183 the telemetry collector: the host's diagnostics, read from a session
184 over ssh with the telemetry command (valley telemetry). Only the
185 principals in {option}`services.valley.telemetry.observers` can read,
186 and only those in {option}`services.valley.telemetry.reporters` can
187 send records'';
188
189 observers = lib.mkOption {
190 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
191 default = [ ];
192 example = [ "operator" ];
193 description = ''
194 Principals that hold the observe grant: they read every source on
195 the host, the shared units' output included, which spans every
196 project. It is a host-wide grant, apart from any project's read
197 consent. A principal is named by its key's tag, as a push is.
198 '';
199 };
200
201 reporters = lib.mkOption {
202 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
203 default = [ ];
204 example = [ "alice" ];
205 description = ''
206 Principals that hold the report grant: they send records about
207 their own approvals and check runs, which the collector stores
208 under their name, stamped with when it received them, in a stream
209 of their own of at most 4 MiB. Reporting grants no reading: a
210 principal that should read its reports back is an observer too.
211 '';
212 };
213
214 remoteSources = lib.mkOption {
215 type = lib.types.listOf (
216 lib.types.submodule {
217 options = {
218 name = lib.mkOption {
219 type = lib.types.strMatching "[a-z0-9][a-z0-9._@-]*";
220 description = "The source's name in the catalog.";
221 };
222 description = lib.mkOption {
223 type = lib.types.str;
224 description = "What the source is.";
225 };
226 principal = lib.mkOption {
227 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
228 description = "The reporter whose reports are the source's records.";
229 };
230 staleAfter = lib.mkOption {
231 type = lib.types.ints.positive;
232 default = 3600;
233 description = "Seconds without a report after which the source reads as stale.";
234 };
235 };
236 }
237 );
238 default = [ ];
239 description = ''
240 Components on other machines, such as a web receiver, that report
241 over the same interface with their own reporter principal. Each is
242 catalogued as remote, and reads as unavailable until it reports
243 and as stale once it stops.
244 '';
245 };
246
247 localSources = lib.mkOption {
248 type = lib.types.listOf (
249 lib.types.submodule {
250 options = {
251 name = lib.mkOption {
252 type = lib.types.strMatching "[a-z0-9][a-z0-9._@-]{0,95}";
253 description = "The source's name in the catalog. It must differ from every other source's.";
254 };
255 description = lib.mkOption {
256 type = lib.types.str;
257 description = "What the source is.";
258 };
259 units = lib.mkOption {
260 type = lib.types.nonEmptyListOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9:_.@-]*\\.[a-z]+");
261 example = [ "converge.service" ];
262 description = "The systemd units whose state, lifecycle and journal output the source reports.";
263 };
264 };
265 }
266 );
267 default = [ ];
268 description = ''
269 Units on this host that are not the valley's own, such as the
270 service that converges or deploys the host. Each is catalogued as a
271 local source and read as the module's own sources are: its units'
272 state, their lifecycle, and with logs their journal output. The
273 collector reads only the units listed here.
274 '';
275 };
276
277 shellFlags = lib.mkOption {
278 type = lib.types.str;
279 default = "";
280 internal = true;
281 description = "The flags the git user's shell serves the telemetry command with; set by this module.";
282 };
283 };
284
285 options.services.valley.telemetry.catalog = lib.mkOption {
286 type = lib.types.attrs;
287 internal = true;
288 readOnly = true;
289 default = catalog;
290 description = "The manifest the collector reads, before it is written as JSON; module-eval reads it.";
291 };
292
293 options.services.valley.packages.telemetry = lib.mkOption {
294 type = lib.types.package;
295 internal = true;
296 default = (import ./packages.nix { inherit pkgs lib; }).telemetry;
297 description = "The collector, valley-telemetry serve.";
298 };
299
300 config = lib.mkIf (cfg.enable && tcfg.enable) {
301 assertions = [
302 {
303 assertion = lib.all (r: lib.elem r.principal tcfg.reporters) tcfg.remoteSources;
304 message = "services.valley.telemetry.remoteSources names a principal that is not in services.valley.telemetry.reporters.";
305 }
306 {
307 assertion = lib.length (lib.unique sourceNames) == lib.length sourceNames;
308 message = "services.valley.telemetry source names must be unique, and localSources or remoteSources repeats one: ${
309 lib.concatStringsSep ", " (lib.unique (lib.filter (n: lib.count (m: m == n) sourceNames > 1) sourceNames))
310 }";
311 }
312 {
313 assertion = lib.all (s: !lib.hasPrefix "report." s.name) (tcfg.localSources ++ tcfg.remoteSources);
314 message = "services.valley.telemetry source names must not start with \"report.\", which names a reporter's own stream.";
315 }
316 ];
317
318 services.valley.telemetry.shellFlags = "--telemetry-socket ${socket} --telemetry-grants ${grantsFile}";
319
320 users.users.valley-telemetry = {
321 isSystemUser = true;
322 group = "valley-telemetry";
323 description = "The valley telemetry collector";
324 };
325 users.groups.valley-telemetry = { };
326
327 systemd.tmpfiles.rules = [
328 "d ${root} 0755 root root - -"
329 "d ${collectorState} 0700 valley-telemetry valley-telemetry - -"
330 ]
331 ++ lib.optional cfg.worker.enable "d ${workerDir} 2750 valley-worker valley-telemetry - -"
332 ++ lib.optional cfg.integrator.enable "d ${integratorDir} 2750 ${cfg.integrator.user} valley-telemetry - -";
333
334 # The producers export into their own directories, and are told where
335 # by VALLEY_TELEMETRY_DIR. Each directory is setgid to the collector's
336 # group, so what a producer makes in it is the collector's to read, and
337 # a producer runs with a umask that keeps group read for it. Nothing
338 # else a producer makes is in a directory others can enter: the
339 # worker's own directory stays 0700, its key 0400.
340 systemd.services.valley-worker = lib.mkIf cfg.worker.enable {
341 environment.VALLEY_TELEMETRY_DIR = workerDir;
342 serviceConfig.ReadWritePaths = [ workerDir ];
343 serviceConfig.UMask = lib.mkForce "0027";
344 unitConfig.RequiresMountsFor = [ workerDir ];
345 };
346 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
347 environment.VALLEY_TELEMETRY_DIR = "${integratorDir}/stream";
348 # Its own umask, 0002, already keeps group read.
349 serviceConfig.ReadWritePaths = [ integratorDir ];
350 };
351
352 # One collector per connection, which only the git user can make. At
353 # most 16 at once; each principal's own slots are the collector's
354 # (four follows, four bounded requests, one report), so one principal
355 # at every bound holds 9 of them. A connection that outlives the
356 # longest follow is killed.
357 systemd.sockets.valley-telemetry = {
358 description = "The valley telemetry collector's socket";
359 wantedBy = [ "sockets.target" ];
360 socketConfig = {
361 ListenStream = socket;
362 Accept = true;
363 SocketUser = cfg.user;
364 SocketGroup = cfg.group;
365 SocketMode = "0600";
366 MaxConnections = 16;
367 };
368 };
369
370 systemd.services."valley-telemetry@" = {
371 description = "The valley telemetry collector, for one connection";
372 path = [ config.systemd.package ];
373 serviceConfig = {
374 ExecStart = lib.concatStringsSep " " [
375 "${package}/bin/valley-telemetry serve"
376 "--manifest ${manifest}"
377 "--grants ${grantsFile}"
378 "--state ${collectorState}"
379 "--peer-user ${cfg.user}"
380 ];
381 StandardInput = "socket";
382 StandardOutput = "socket";
383 StandardError = "journal";
384 User = "valley-telemetry";
385 Group = "valley-telemetry";
386 SupplementaryGroups = [ "systemd-journal" ];
387 RuntimeMaxSec = 360;
388 MemoryMax = "256M";
389 TasksMax = 32;
390 CPUQuota = "50%";
391 NoNewPrivileges = true;
392 ProtectSystem = "strict";
393 ReadWritePaths = [ collectorState ];
394 ProtectHome = true;
395 PrivateTmp = true;
396 PrivateDevices = true;
397 PrivateNetwork = false;
398 ProtectClock = true;
399 ProtectHostname = true;
400 ProtectKernelLogs = true;
401 ProtectKernelModules = true;
402 ProtectKernelTunables = true;
403 ProtectControlGroups = true;
404 RestrictAddressFamilies = [ "AF_UNIX" ];
405 RestrictNamespaces = true;
406 RestrictRealtime = true;
407 RestrictSUIDSGID = true;
408 LockPersonality = true;
409 CapabilityBoundingSet = "";
410 SystemCallArchitectures = "native";
411 SystemCallFilter = [ "@system-service" ];
412 UMask = "0077";
413 };
414 };
415 };
416}