gunk-dev/the-valley

telemetry.nix

source9ee95920e399main's published tip history
16.5 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 "on-main" "the onMain bridges, their path units and the units they start" (derived.onMainUnits != [ ])
125 derived.onMainUnits
126 { not_instrumented = [ "no producer records: lifecycle and output only" ]; }
127 )
128 (source "bus" "the NATS bus" cfg.bus.enable [
129 "valley-bus.service"
130 "valley-bus-init.service"
131 ] { })
132 (source "web-publisher" "the web publisher" webPublisher [
133 "valley-web-publish.service"
134 "valley-web-publish.timer"
135 "valley-web-publish-policy.service"
136 ] { })
137 (source "web-receiver" "the web receiver, on this host" webReceiver [
138 "valley-web-receive.service"
139 "valley-web.service"
140 ] { })
141 (source "backup" "the offsite backup" derived.backupEnabled [
142 "restic-backups-valley.service"
143 "restic-backups-valley.timer"
144 ] { })
145 (source "convergence" "valley-init, which converges the repositories and hooks" true [
146 "valley-init.service"
147 ] { })
148 (source "build-slice" "the build slice and the nix daemon whose builds run in it" cfg.buildSlice.enable [
149 "valley-builds.slice"
150 "nix-daemon.service"
151 ] { })
152 (source "telemetry" "the collector's socket" true [ "valley-telemetry.socket" ] {
153 configured.collector = "${package}";
154 })
155 ];
156
157 # The host's own units, catalogued as the module's local sources are.
158 hostSources = map (s: source s.name s.description true s.units { }) tcfg.localSources;
159
160 catalog = {
161 v = 1;
162 host = config.networking.hostName;
163 reporters = tcfg.reporters;
164 sources =
165 ownSources
166 ++ hostSources
167 ++ map (r: {
168 inherit (r) name description;
169 enabled = true;
170 location = "remote";
171 reporter = r.principal;
172 stale_after_s = r.staleAfter;
173 }) tcfg.remoteSources;
174 };
175
176 manifest = pkgs.writeText "valley-telemetry-manifest.json" (builtins.toJSON catalog);
177
178 # Every name the catalog holds, each as many times as it is declared.
179 sourceNames =
180 map (s: s.name) ownSources
181 ++ map (s: s.name) tcfg.localSources
182 ++ map (s: s.name) tcfg.remoteSources;
183in
184{
185 options.services.valley.telemetry = {
186 enable = lib.mkEnableOption ''
187 the telemetry collector: the host's diagnostics, read from a session
188 over ssh with the telemetry command (valley telemetry). Only the
189 principals in {option}`services.valley.telemetry.observers` can read,
190 and only those in {option}`services.valley.telemetry.reporters` can
191 send records'';
192
193 observers = lib.mkOption {
194 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
195 default = [ ];
196 example = [ "operator" ];
197 description = ''
198 Principals that hold the observe grant: they read every source on
199 the host, the shared units' output included, which spans every
200 project. It is a host-wide grant, apart from any project's read
201 consent. A principal is named by its key's tag, as a push is.
202 '';
203 };
204
205 reporters = lib.mkOption {
206 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
207 default = [ ];
208 example = [ "alice" ];
209 description = ''
210 Principals that hold the report grant: they send records about
211 their own approvals and check runs, which the collector stores
212 under their name, stamped with when it received them, in a stream
213 of their own of at most 4 MiB. Reporting grants no reading: a
214 principal that should read its reports back is an observer too.
215 '';
216 };
217
218 remoteSources = lib.mkOption {
219 type = lib.types.listOf (
220 lib.types.submodule {
221 options = {
222 name = lib.mkOption {
223 type = lib.types.strMatching "[a-z0-9][a-z0-9._@-]*";
224 description = "The source's name in the catalog.";
225 };
226 description = lib.mkOption {
227 type = lib.types.str;
228 description = "What the source is.";
229 };
230 principal = lib.mkOption {
231 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
232 description = "The reporter whose reports are the source's records.";
233 };
234 staleAfter = lib.mkOption {
235 type = lib.types.ints.positive;
236 default = 3600;
237 description = "Seconds without a report after which the source reads as stale.";
238 };
239 };
240 }
241 );
242 default = [ ];
243 description = ''
244 Components on other machines, such as a web receiver, that report
245 over the same interface with their own reporter principal. Each is
246 catalogued as remote, and reads as unavailable until it reports
247 and as stale once it stops.
248 '';
249 };
250
251 localSources = lib.mkOption {
252 type = lib.types.listOf (
253 lib.types.submodule {
254 options = {
255 name = lib.mkOption {
256 type = lib.types.strMatching "[a-z0-9][a-z0-9._@-]{0,95}";
257 description = "The source's name in the catalog. It must differ from every other source's.";
258 };
259 description = lib.mkOption {
260 type = lib.types.str;
261 description = "What the source is.";
262 };
263 units = lib.mkOption {
264 type = lib.types.nonEmptyListOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9:_.@-]*\\.[a-z]+");
265 example = [ "converge.service" ];
266 description = "The systemd units whose state, lifecycle and journal output the source reports.";
267 };
268 };
269 }
270 );
271 default = [ ];
272 description = ''
273 Units on this host that are not the valley's own, such as the
274 service that converges or deploys the host. Each is catalogued as a
275 local source and read as the module's own sources are: its units'
276 state, their lifecycle, and with logs their journal output. The
277 collector reads only the units listed here.
278 '';
279 };
280
281 shellFlags = lib.mkOption {
282 type = lib.types.str;
283 default = "";
284 internal = true;
285 description = "The flags the git user's shell serves the telemetry command with; set by this module.";
286 };
287 };
288
289 options.services.valley.telemetry.catalog = lib.mkOption {
290 type = lib.types.attrs;
291 internal = true;
292 readOnly = true;
293 default = catalog;
294 description = "The manifest the collector reads, before it is written as JSON; module-eval reads it.";
295 };
296
297 options.services.valley.packages.telemetry = lib.mkOption {
298 type = lib.types.package;
299 internal = true;
300 default = (import ./packages.nix { inherit pkgs lib; }).telemetry;
301 description = "The collector, valley-telemetry serve.";
302 };
303
304 config = lib.mkIf (cfg.enable && tcfg.enable) {
305 assertions = [
306 {
307 assertion = lib.all (r: lib.elem r.principal tcfg.reporters) tcfg.remoteSources;
308 message = "services.valley.telemetry.remoteSources names a principal that is not in services.valley.telemetry.reporters.";
309 }
310 {
311 assertion = lib.length (lib.unique sourceNames) == lib.length sourceNames;
312 message = "services.valley.telemetry source names must be unique, and localSources or remoteSources repeats one: ${
313 lib.concatStringsSep ", " (lib.unique (lib.filter (n: lib.count (m: m == n) sourceNames > 1) sourceNames))
314 }";
315 }
316 {
317 assertion = lib.all (s: !lib.hasPrefix "report." s.name) (tcfg.localSources ++ tcfg.remoteSources);
318 message = "services.valley.telemetry source names must not start with \"report.\", which names a reporter's own stream.";
319 }
320 ];
321
322 services.valley.telemetry.shellFlags = "--telemetry-socket ${socket} --telemetry-grants ${grantsFile}";
323
324 users.users.valley-telemetry = {
325 isSystemUser = true;
326 group = "valley-telemetry";
327 description = "The valley telemetry collector";
328 };
329 users.groups.valley-telemetry = { };
330
331 systemd.tmpfiles.rules = [
332 "d ${root} 0755 root root - -"
333 "d ${collectorState} 0700 valley-telemetry valley-telemetry - -"
334 ]
335 ++ lib.optional cfg.worker.enable "d ${workerDir} 2750 valley-worker valley-telemetry - -"
336 ++ lib.optional cfg.integrator.enable "d ${integratorDir} 2750 ${cfg.integrator.user} valley-telemetry - -";
337
338 # The producers export into their own directories, and are told where
339 # by VALLEY_TELEMETRY_DIR. Each directory is setgid to the collector's
340 # group, so what a producer makes in it is the collector's to read, and
341 # a producer runs with a umask that keeps group read for it. Nothing
342 # else a producer makes is in a directory others can enter: the
343 # worker's own directory stays 0700, its key 0400.
344 systemd.services.valley-worker = lib.mkIf cfg.worker.enable {
345 environment.VALLEY_TELEMETRY_DIR = workerDir;
346 serviceConfig.ReadWritePaths = [ workerDir ];
347 serviceConfig.UMask = lib.mkForce "0027";
348 unitConfig.RequiresMountsFor = [ workerDir ];
349 };
350 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
351 environment.VALLEY_TELEMETRY_DIR = "${integratorDir}/stream";
352 # Its own umask, 0002, already keeps group read.
353 serviceConfig.ReadWritePaths = [ integratorDir ];
354 };
355
356 # One collector per connection, which only the git user can make. At
357 # most 16 at once; each principal's own slots are the collector's
358 # (four follows, five bounded requests, one report), so one principal
359 # at every bound holds 10 of them. A connection that outlives the
360 # longest follow is killed.
361 systemd.sockets.valley-telemetry = {
362 description = "The valley telemetry collector's socket";
363 wantedBy = [ "sockets.target" ];
364 socketConfig = {
365 ListenStream = socket;
366 Accept = true;
367 SocketUser = cfg.user;
368 SocketGroup = cfg.group;
369 SocketMode = "0600";
370 MaxConnections = 16;
371 };
372 };
373
374 systemd.services."valley-telemetry@" = {
375 description = "The valley telemetry collector, for one connection";
376 path = [ config.systemd.package ];
377 serviceConfig = {
378 ExecStart = lib.concatStringsSep " " [
379 "${package}/bin/valley-telemetry serve"
380 "--manifest ${manifest}"
381 "--grants ${grantsFile}"
382 "--state ${collectorState}"
383 "--peer-user ${cfg.user}"
384 ];
385 StandardInput = "socket";
386 StandardOutput = "socket";
387 StandardError = "journal";
388 User = "valley-telemetry";
389 Group = "valley-telemetry";
390 SupplementaryGroups = [ "systemd-journal" ];
391 RuntimeMaxSec = 360;
392 MemoryMax = "256M";
393 TasksMax = 32;
394 CPUQuota = "50%";
395 NoNewPrivileges = true;
396 ProtectSystem = "strict";
397 ReadWritePaths = [ collectorState ];
398 ProtectHome = true;
399 PrivateTmp = true;
400 PrivateDevices = true;
401 PrivateNetwork = false;
402 ProtectClock = true;
403 ProtectHostname = true;
404 ProtectKernelLogs = true;
405 ProtectKernelModules = true;
406 ProtectKernelTunables = true;
407 ProtectControlGroups = true;
408 RestrictAddressFamilies = [ "AF_UNIX" ];
409 RestrictNamespaces = true;
410 RestrictRealtime = true;
411 RestrictSUIDSGID = true;
412 LockPersonality = true;
413 CapabilityBoundingSet = "";
414 SystemCallArchitectures = "native";
415 SystemCallFilter = [ "@system-service" ];
416 UMask = "0077";
417 };
418 };
419 };
420}