gunk-dev/the-valley

telemetry.go

sourcec2411381d337main's published tip history
28.7 KiB
1package main
2
3// valley telemetry: reading a valley host's diagnostics from a session,
4// and the workstation's half of them.
5//
6// The reading verbs (sources, snapshot, read, follow) run one telemetry
7// command on the host over ssh, as the git user, with the key the remote
8// already uses (../telemetry/protocol.go). The host's shell derives the
9// principal from that key and holds it to the observe grant. The remote
10// is the checkout's origin, or the one --remote names: a remote's name,
11// an ssh URL, or user@host:path. Its URL is read, never run, so no
12// configured ssh command takes part. The answer is JSON lines, which
13// --json prints as they come and which are otherwise rendered as text.
14// An error, or an answer that never ended, exits 1: it never reads as
15// nothing to report.
16//
17// The workstation's records: each approval attempt starts a run (start),
18// which binds the run to the destination its checkout's telemetry remote
19// names at that moment. The run's records (emit), and the progress attest
20// records of the checks it runs, go into that destination's own spool,
21// owner-only, under $XDG_STATE_HOME/valley/telemetry/spools/. A spool
22// names its destination in a file written once, and flush sends a spool
23// to that destination and nowhere else, whichever checkout or remote the
24// flush runs from. Each spool has its own acknowledgement, lock and log
25// offsets, so one host's acknowledgement never stands for another's.
26//
27// flush sends what a spool holds and its host has not acknowledged, with
28// the report command, and remembers how far the host acknowledged. A
29// record the host already holds is not stored twice. Each spool is
30// bounded like any stream, and loses its oldest records first; the host
31// records the gap. At most maxSpools spools exist at once. Nothing in this
32// ever fails or holds up an approval: approve runs flush in the
33// background, and a flush that fails leaves the spool for the next.
34
35import (
36 "bufio"
37 "bytes"
38 "context"
39 "crypto/sha256"
40 "encoding/hex"
41 "encoding/json"
42 "errors"
43 "flag"
44 "fmt"
45 "io"
46 "net/url"
47 "os"
48 "os/exec"
49 "path"
50 "path/filepath"
51 "regexp"
52 "sort"
53 "strconv"
54 "strings"
55 "syscall"
56 "time"
57
58 "the-valley/telemetry"
59)
60
61const telemetryUsage = `usage: valley telemetry [--remote <remote>] [--json] sources
62 valley telemetry [--remote <remote>] [--json] snapshot
63 valley telemetry [--remote <remote>] [--json] read [--source <name>] [--since <cursor>] [--limit <n>] [--logs]
64 valley telemetry [--remote <remote>] [--json] follow [--source <name>] [--since <cursor>] [--seconds <n>] [--logs]
65 valley telemetry flush [--remote <remote>]`
66
67func runTelemetry(g git, args []string, stdout, stderr io.Writer) error {
68 remote, asJSON := "", false
69 for len(args) > 0 {
70 switch {
71 case args[0] == "--json":
72 asJSON, args = true, args[1:]
73 case args[0] == "--remote" && len(args) > 1:
74 remote, args = args[1], args[2:]
75 case strings.HasPrefix(args[0], "--remote="):
76 remote, args = strings.TrimPrefix(args[0], "--remote="), args[1:]
77 default:
78 goto verb
79 }
80 }
81verb:
82 if len(args) == 0 {
83 return failure(telemetryUsage)
84 }
85 switch args[0] {
86 case "start":
87 // A new run, bound to its destination: the run ID, the spool of
88 // that destination for approve and the attest it runs to record
89 // into, and the project the destination's path names.
90 dest, err := telemetryRemote(g, remote)
91 if err != nil {
92 return failure(err.Error())
93 }
94 dir, err := bindSpool(dest)
95 if err != nil {
96 return failure(err.Error())
97 }
98 fmt.Fprintf(stdout, "%s\t%s\t%s\n", telemetry.NewRunID(), dir, dest.project())
99 return nil
100 case "emit":
101 return runEmit(args[1:])
102 case "flush":
103 return runFlush(g, remote, args[1:], stderr)
104 case telemetry.OpSources, telemetry.OpSnapshot, telemetry.OpRead, telemetry.OpFollow:
105 default:
106 return failure(telemetryUsage)
107 }
108 req := telemetry.Request{V: 1, Op: args[0]}
109 fs := flag.NewFlagSet("telemetry", flag.ContinueOnError)
110 fs.SetOutput(io.Discard)
111 fs.StringVar(&req.Source, "source", "", "")
112 fs.StringVar(&req.Cursor, "since", "", "")
113 fs.IntVar(&req.Limit, "limit", 0, "")
114 fs.IntVar(&req.Seconds, "seconds", 0, "")
115 fs.BoolVar(&req.Logs, "logs", false, "")
116 if err := fs.Parse(args[1:]); err != nil || fs.NArg() > 0 {
117 return failure(telemetryUsage)
118 }
119 cmd := req.Command()
120 if _, err := telemetry.ParseCommand(cmd); err != nil {
121 return failure(err.Error())
122 }
123 dest, err := telemetryRemote(g, remote)
124 if err != nil {
125 return failure(err.Error())
126 }
127 timeout := 60 * time.Second
128 if req.Op == telemetry.OpFollow {
129 timeout = time.Duration(max(req.Seconds, telemetry.DefaultFollowSeconds)+60) * time.Second
130 }
131 ctx, cancel := context.WithTimeout(context.Background(), timeout)
132 defer cancel()
133 ssh := sshCommand(ctx, dest, cmd)
134 out, err := ssh.StdoutPipe()
135 if err != nil {
136 return err
137 }
138 var sshErr bytes.Buffer
139 ssh.Stderr = &sshErr
140 if err := ssh.Start(); err != nil {
141 return failure(fmt.Sprintf("could not run ssh: %v", err))
142 }
143 r := &renderer{w: stdout, json: asJSON}
144 sc := bufio.NewScanner(out)
145 sc.Buffer(make([]byte, 64<<10), telemetry.MaxResponseBytes)
146 for sc.Scan() {
147 r.line(sc.Bytes())
148 }
149 waitErr := ssh.Wait()
150 switch {
151 case r.err != "":
152 return failure("the host refused: " + r.err)
153 case !r.ended:
154 why := strings.TrimSpace(telemetry.Sanitize(sshErr.String()))
155 if why == "" && waitErr != nil {
156 why = waitErr.Error()
157 }
158 return failure(fmt.Sprintf("the telemetry answer from %s did not end; nothing above is complete. %s", dest.host, why))
159 }
160 return nil
161}
162
163// sshDest is where a telemetry command goes.
164type sshDest struct {
165 host string // [user@]host, which ssh resolves through its own config
166 port string
167 path string // the repository's path on the host, where the remote names one
168}
169
170// identity names a destination as the remote spelled it:
171// ssh://[user@]host[:port]. Two spellings of one host are two
172// destinations: an alias in ssh's configuration can stand for another
173// host, port or key, and nothing here can tell.
174func (d sshDest) identity() string {
175 if d.port != "" {
176 return "ssh://" + d.host + ":" + d.port
177 }
178 return "ssh://" + d.host
179}
180
181// project is the project a destination's path names: its last element,
182// less .git, or nothing.
183func (d sshDest) project() string {
184 name := strings.TrimSuffix(path.Base(strings.TrimRight(d.path, "/")), ".git")
185 if projectName.MatchString(name) {
186 return name
187 }
188 return ""
189}
190
191var projectName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
192
193// destination reads an identity back.
194func destination(identity string) (sshDest, error) {
195 u, err := url.Parse(identity)
196 if err != nil || u.Scheme != "ssh" || u.Path != "" || u.RawQuery != "" {
197 return sshDest{}, fmt.Errorf("%q names no ssh destination", identity)
198 }
199 d := sshDest{host: u.Hostname(), port: u.Port()}
200 if u.User != nil {
201 d.host = u.User.Username() + "@" + d.host
202 }
203 if !sshHost.MatchString(d.host) || d.identity() != identity {
204 return sshDest{}, fmt.Errorf("%q names no ssh destination", identity)
205 }
206 return d, nil
207}
208
209var (
210 scpRemote = regexp.MustCompile(`^((?:[A-Za-z0-9._-]+@)?[A-Za-z0-9][A-Za-z0-9.-]*):[^:]`)
211 sshHost = regexp.MustCompile(`^(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9][A-Za-z0-9.-]*$`)
212)
213
214// telemetryRemote resolves --remote, or the checkout's telemetry remote
215// (valley.telemetry.remote, else origin), to an ssh destination. A remote
216// that is not reached over ssh is refused.
217func telemetryRemote(g git, remote string) (sshDest, error) {
218 return remoteDest(func(key string) (string, bool) {
219 v, err := g.output(true, "config", "--get", key)
220 return strings.TrimSpace(v), err == nil
221 }, remote)
222}
223
224// remoteDest is telemetryRemote with the checkout's configuration read
225// from config.
226func remoteDest(config func(key string) (string, bool), remote string) (sshDest, error) {
227 if remote == "" {
228 if r, ok := config("valley.telemetry.remote"); ok && r != "" {
229 remote = r
230 } else {
231 remote = "origin"
232 }
233 }
234 location := remote
235 if !strings.Contains(remote, ":") {
236 u, ok := config("remote." + remote + ".url")
237 if !ok || u == "" {
238 return sshDest{}, fmt.Errorf("no remote %s to read telemetry from; name one with --remote", remote)
239 }
240 location = u
241 }
242 if strings.Contains(location, "://") {
243 u, err := url.Parse(location)
244 if err != nil || u.Scheme != "ssh" || u.Hostname() == "" {
245 return sshDest{}, fmt.Errorf("%s is not an ssh remote; telemetry is read over ssh", remote)
246 }
247 host := u.Hostname()
248 if u.User != nil {
249 host = u.User.Username() + "@" + host
250 }
251 if !sshHost.MatchString(host) {
252 return sshDest{}, fmt.Errorf("%s does not name an ssh host", remote)
253 }
254 return sshDest{host: host, port: u.Port(), path: u.Path}, nil
255 }
256 if m := scpRemote.FindStringSubmatch(location); m != nil {
257 return sshDest{host: m[1], path: location[len(m[1])+1:]}, nil
258 }
259 if sshHost.MatchString(location) {
260 return sshDest{host: location}, nil
261 }
262 return sshDest{}, fmt.Errorf("%s is not an ssh remote; telemetry is read over ssh", remote)
263}
264
265// sshCommand runs one command on dest. The command is built from parsed
266// flags, never from text the caller wrote. The ssh is killed when this
267// process dies, however it dies (dieWithParent), so a request never
268// outlives the command that made it, nor holds one of the principal's
269// observe requests open after it. ForkAfterAuthentication=no keeps an ssh
270// configuration that forks ssh into the background, out of reach of both,
271// from doing so; the option needs OpenSSH 8.7 or later. A ProxyCommand the
272// user configures is ssh's own child, outside this control.
273func sshCommand(ctx context.Context, dest sshDest, command string) *exec.Cmd {
274 args := []string{"-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15", "-o", "ForkAfterAuthentication=no"}
275 if dest.port != "" {
276 args = append(args, "-p", dest.port)
277 }
278 args = append(args, "--", dest.host, command)
279 cmd := exec.CommandContext(ctx, "ssh", args...)
280 cmd.WaitDelay = sshWaitDelay
281 cmd.SysProcAttr = dieWithParent()
282 return cmd
283}
284
285// sshWaitDelay is how long a wait for ssh goes on, once ssh has ended or
286// been killed, for output a process it started still holds.
287const sshWaitDelay = 2 * time.Second
288
289// renderer prints answer lines: as they are with --json, or as text.
290// Every string from the host is made safe to show again here.
291type renderer struct {
292 w io.Writer
293 json bool
294 ended bool
295 err string
296}
297
298func (r *renderer) line(raw []byte) {
299 var m map[string]any
300 if json.Unmarshal(raw, &m) != nil {
301 r.err = "an answer line is not JSON"
302 return
303 }
304 kind, _ := m["kind"].(string)
305 switch kind {
306 case "error":
307 r.err = telemetry.Sanitize(fmt.Sprint(m["error"]))
308 case "end":
309 r.ended = true
310 }
311 if r.json {
312 fmt.Fprintf(r.w, "%s\n", raw)
313 return
314 }
315 s := func(k string) string {
316 v, ok := m[k]
317 if !ok || v == nil {
318 return ""
319 }
320 return telemetry.Sanitize(fmt.Sprint(v))
321 }
322 switch kind {
323 case "header":
324 fmt.Fprintf(r.w, "%s at %s (%s)\n", s("host"), s("server_time"), s("format"))
325 case "source":
326 fmt.Fprintf(r.w, "\n%-20s %-11s %s\n", s("name"), s("state"), s("detail"))
327 if d := s("description"); d != "" {
328 fmt.Fprintf(r.w, " %s; %s\n", d, s("location"))
329 }
330 if units, ok := m["unit_states"].([]any); ok {
331 for _, u := range units {
332 r.unit(u)
333 }
334 }
335 if st, ok := m["stream"].(map[string]any); ok {
336 fmt.Fprintf(r.w, " stream %v: records %v..%v, newest %v at %v\n", st["name"], num(st["first"]), num(st["last"]), st["last_type"], st["last_time"])
337 }
338 if j := s("journal_since"); j != "" {
339 fmt.Fprintf(r.w, " journal reaches back to %s\n", j)
340 }
341 if c, ok := m["configured"].(map[string]any); ok {
342 for _, k := range sortedKeysAny(c) {
343 fmt.Fprintf(r.w, " configured %s: %s\n", k, telemetry.Sanitize(fmt.Sprint(c[k])))
344 }
345 }
346 if miss, ok := m["not_instrumented"].([]any); ok {
347 for _, x := range miss {
348 fmt.Fprintf(r.w, " not instrumented: %s\n", telemetry.Sanitize(fmt.Sprint(x)))
349 }
350 }
351 for _, key := range []string{"open_runs", "latest_runs"} {
352 if runs, ok := m[key].([]any); ok {
353 for _, x := range runs {
354 run, _ := x.(map[string]any)
355 label := "run"
356 if key == "open_runs" {
357 label = "open"
358 }
359 fmt.Fprintf(r.w, " %s %v %v %v..%v last %v %v\n", label, run["run"], run["producer"], run["first"], run["last"], run["last_type"], checksOf(run["checks"]))
360 }
361 }
362 }
363 if st, ok := m["exported_state"]; ok {
364 b, _ := json.MarshalIndent(st, " ", " ")
365 fmt.Fprintf(r.w, " exported state:\n %s\n", telemetry.Sanitize(string(b)))
366 }
367 case "record":
368 if s("type") == "check.output" {
369 d, _ := m["data"].(map[string]any)
370 fmt.Fprintf(r.w, "--- untrusted output: %s#%s run %s check %s at byte %s\n%s\n", s("stream"), num(m["seq"]), s("run"), s("check"),
371 num(d["offset"]), strings.TrimRight(telemetry.Sanitize(fmt.Sprint(d["text"])), "\n"))
372 return
373 }
374 fmt.Fprintf(r.w, "%s %s#%s %s%s\n", s("time"), s("stream"), num(m["seq"]), s("type"), recordDetail(m))
375 case "gap":
376 fmt.Fprintf(r.w, "! gap in %s: %s %s %s %s\n", s("stream"), s("reason"), num(m["from"]), num(m["to"]), s("detail"))
377 case "lifecycle":
378 fmt.Fprintf(r.w, "%s %s [systemd] %s\n", s("time"), s("unit"), s("message"))
379 case "log":
380 where := s("unit")
381 if where == "" {
382 where = fmt.Sprintf("%s run %s check %s, bytes %s..%s of %s", s("stream"), s("run"), s("check"), num(m["from"]), num(m["to"]), num(m["size"]))
383 }
384 fmt.Fprintf(r.w, "--- untrusted output: %s %s\n%s\n", where, s("time"), strings.TrimRight(s("text"), "\n"))
385 case "unavailable":
386 fmt.Fprintf(r.w, "! %s unavailable: %s\n", s("what"), s("error"))
387 case "ack":
388 fmt.Fprintf(r.w, "reported: %s accepted, %s already held, %s refused\n", num(m["accepted"]), num(m["duplicates"]), num(m["rejected"]))
389 case "end":
390 if c := s("cursor"); c != "" {
391 fmt.Fprintf(r.w, "\ncursor %s\n", c)
392 }
393 if t, _ := m["truncated"].(bool); t {
394 fmt.Fprintln(r.w, "the answer was cut short at its size bound; read on from the cursor")
395 }
396 }
397}
398
399func (r *renderer) unit(x any) {
400 u, _ := x.(map[string]any)
401 g := func(k string) string { return telemetry.Sanitize(fmt.Sprint(u[k])) }
402 line := fmt.Sprintf(" %s: %s/%s", g("Id"), g("ActiveState"), g("SubState"))
403 if res := g("Result"); res != "" && res != "<nil>" {
404 line += " result " + res
405 }
406 if st := g("ExecMainStatus"); st != "" && st != "0" && st != "<nil>" {
407 line += " status " + st
408 }
409 if n := g("NRestarts"); n != "" && n != "0" && n != "<nil>" {
410 line += " restarts " + n
411 }
412 if t := g("StateChangeTimestamp"); t != "" && t != "<nil>" {
413 line += " since " + t
414 }
415 fmt.Fprintln(r.w, line)
416}
417
418func num(v any) string {
419 if f, ok := v.(float64); ok {
420 return strconv.FormatInt(int64(f), 10)
421 }
422 return telemetry.Sanitize(fmt.Sprint(v))
423}
424
425func sortedKeysAny(m map[string]any) []string {
426 keys := make([]string, 0, len(m))
427 for k := range m {
428 keys = append(keys, k)
429 }
430 sort.Strings(keys)
431 return keys
432}
433
434func checksOf(v any) string {
435 m, _ := v.(map[string]any)
436 if len(m) == 0 {
437 return ""
438 }
439 var parts []string
440 for _, k := range sortedKeysAny(m) {
441 parts = append(parts, telemetry.Sanitize(fmt.Sprintf("%s=%v", k, m[k])))
442 }
443 return "checks " + strings.Join(parts, " ")
444}
445
446// recordDetail is what a record is about, and its data, on one line.
447func recordDetail(m map[string]any) string {
448 var b strings.Builder
449 for _, k := range []string{"principal", "project", "change", "version", "head", "check", "run"} {
450 if v, ok := m[k]; ok && v != nil && v != "" {
451 s := num(v)
452 if k == "head" && len(s) > 12 {
453 s = s[:12]
454 }
455 fmt.Fprintf(&b, " %s=%s", k, s)
456 }
457 }
458 if d, ok := m["data"].(map[string]any); ok {
459 for _, k := range sortedKeysAny(d) {
460 fmt.Fprintf(&b, " %s=%s", k, num(d[k]))
461 }
462 }
463 if rcv, ok := m["received"].(string); ok && rcv != "" {
464 fmt.Fprintf(&b, " (received %s)", telemetry.Sanitize(rcv))
465 }
466 return b.String()
467}
468
469// The spools: $XDG_STATE_HOME/valley/telemetry/spools/<key>, one for each
470// destination, where an unset or relative XDG_STATE_HOME means
471// ~/.local/state, and key is the start of the SHA-256 of the destination's
472// identity. A spool's destination file names the identity; it is written
473// once, and a spool without one is no spool. The spool of earlier CLIs,
474// .../telemetry/spool, named no destination: it is kept as it is and
475// never sent.
476func spoolsRoot() (string, error) {
477 state, err := stateDirectory()
478 if err != nil {
479 return "", err
480 }
481 return filepath.Join(filepath.Dir(state), "telemetry", "spools"), nil
482}
483
484func legacySpool() (string, error) {
485 state, err := stateDirectory()
486 if err != nil {
487 return "", err
488 }
489 return filepath.Join(filepath.Dir(state), "telemetry", "spool"), nil
490}
491
492// maxSpools is how many destinations' spools exist at once. Each spool is
493// a stream of at most 8 MiB, with the logs of its newest 16 runs, so the
494// spools together stay bounded too.
495const maxSpools = 4
496
497// idleAfter is how long a spool whose records were all acknowledged stays
498// before it may be removed to make room for another destination's.
499const idleAfter = time.Hour
500
501func mkdirPrivate(dir string) error {
502 if err := os.MkdirAll(dir, 0o700); err != nil {
503 return err
504 }
505 return os.Chmod(dir, 0o700)
506}
507
508// bindSpool returns the spool of dest, making it, and its destination
509// file, when there is none. Making one when maxSpools exist first removes
510// those idle for idleAfter with nothing left to send, and fails when that
511// leaves no room.
512func bindSpool(dest sshDest) (string, error) {
513 root, err := spoolsRoot()
514 if err != nil {
515 return "", err
516 }
517 if err := mkdirPrivate(root); err != nil {
518 return "", err
519 }
520 id := dest.identity()
521 sum := sha256.Sum256([]byte(id))
522 dir := filepath.Join(root, hex.EncodeToString(sum[:8]))
523 if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
524 if err := makeRoom(root); err != nil {
525 return "", err
526 }
527 }
528 if err := mkdirPrivate(dir); err != nil {
529 return "", err
530 }
531 named, err := spoolDestination(dir)
532 if errors.Is(err, os.ErrNotExist) {
533 if err := writeDestination(dir, id); err != nil {
534 return "", err
535 }
536 named, err = spoolDestination(dir)
537 }
538 if err != nil {
539 return "", err
540 }
541 if named.identity() != id {
542 return "", fmt.Errorf("the spool %s is bound to %s, not %s", dir, named.identity(), id)
543 }
544 return dir, nil
545}
546
547// writeDestination names a spool's destination, once: the file is written
548// whole under another name and linked into place, and of two runs making
549// it at once, one names it.
550func writeDestination(dir, id string) error {
551 tmp, err := os.CreateTemp(dir, ".destination-*")
552 if err != nil {
553 return err
554 }
555 defer os.Remove(tmp.Name())
556 _, err = tmp.WriteString(id + "\n")
557 if cerr := tmp.Close(); err == nil {
558 err = cerr
559 }
560 if err != nil {
561 return err
562 }
563 if err := os.Link(tmp.Name(), filepath.Join(dir, "destination")); err != nil && !errors.Is(err, os.ErrExist) {
564 return err
565 }
566 return nil
567}
568
569// spoolDestination is the destination a spool is bound to.
570func spoolDestination(dir string) (sshDest, error) {
571 data, err := os.ReadFile(filepath.Join(dir, "destination"))
572 if err != nil {
573 return sshDest{}, err
574 }
575 return destination(strings.TrimSpace(string(data)))
576}
577
578// spools lists the bound spools.
579func spools() []string {
580 root, err := spoolsRoot()
581 if err != nil {
582 return nil
583 }
584 entries, _ := os.ReadDir(root)
585 var dirs []string
586 for _, e := range entries {
587 dir := filepath.Join(root, e.Name())
588 if _, err := spoolDestination(dir); e.IsDir() && err == nil {
589 dirs = append(dirs, dir)
590 }
591 }
592 return dirs
593}
594
595// unsent is how many of a spool's records its host has not acknowledged,
596// and when the spool last stored one.
597func unsent(dir string) (int64, time.Time) {
598 var last time.Time
599 if entries, err := os.ReadDir(dir); err == nil {
600 for _, e := range entries {
601 if info, err := e.Info(); err == nil && info.ModTime().After(last) {
602 last = info.ModTime()
603 }
604 }
605 }
606 rng, err := (&telemetry.Stream{Dir: dir}).Range()
607 if err != nil {
608 return 0, last
609 }
610 return max(rng.Last-ackedOf(dir, rng.Epoch), 0), last
611}
612
613// ackedOf is the number of the newest record a spool's host acknowledged.
614func ackedOf(dir, epoch string) int64 {
615 data, err := os.ReadFile(filepath.Join(dir, "acked"))
616 if err != nil {
617 return 0
618 }
619 e, seq, ok := strings.Cut(strings.TrimSpace(string(data)), ":")
620 if !ok || e != epoch {
621 return 0
622 }
623 n, _ := strconv.ParseInt(seq, 10, 64)
624 return n
625}
626
627func makeRoom(root string) error {
628 dirs := spools()
629 for _, dir := range dirs {
630 if len(dirs) < maxSpools {
631 return nil
632 }
633 if n, last := unsent(dir); n == 0 && time.Since(last) > idleAfter {
634 os.RemoveAll(dir)
635 dirs = spools()
636 }
637 }
638 if len(spools()) >= maxSpools {
639 return fmt.Errorf("the telemetry spools of %d other destinations still hold records to send or are in use; this run is not recorded", maxSpools)
640 }
641 return nil
642}
643
644// runEmit stores one record of the workstation's own in the spool. It
645// never fails the caller: a record that cannot be stored is dropped, and
646// emit exits 0 all the same.
647func runEmit(args []string) error {
648 fs := flag.NewFlagSet("emit", flag.ContinueOnError)
649 fs.SetOutput(io.Discard)
650 var r telemetry.Record
651 var typ, run, version, exe string
652 data := map[string]any{}
653 var spool string
654 fs.StringVar(&typ, "type", "", "")
655 fs.StringVar(&run, "run", "", "")
656 fs.StringVar(&spool, "spool", "", "")
657 fs.StringVar(&version, "producer-version", "", "")
658 fs.StringVar(&exe, "producer-exe", "", "")
659 fs.StringVar(&r.Project, "project", "", "")
660 fs.StringVar(&r.Change, "change", "", "")
661 fs.IntVar(&r.Version, "version", 0, "")
662 fs.StringVar(&r.Head, "head", "", "")
663 fs.StringVar(&r.Tree, "tree", "", "")
664 fs.StringVar(&r.Check, "check", "", "")
665 fs.Func("data", "key=value", func(kv string) error {
666 k, v, _ := strings.Cut(kv, "=")
667 data[k] = v
668 return nil
669 })
670 fs.Func("number", "key=n", func(kv string) error {
671 k, v, _ := strings.Cut(kv, "=")
672 n, err := strconv.ParseInt(v, 10, 64)
673 data[k] = n
674 return err
675 })
676 fs.Func("list", "key=a,b", func(kv string) error {
677 k, v, _ := strings.Cut(kv, "=")
678 list := []string{}
679 if v != "" {
680 list = strings.Split(v, ",")
681 }
682 data[k] = list
683 return nil
684 })
685 if err := fs.Parse(args); err != nil || typ == "" || run == "" || spool == "" {
686 return failure("usage: valley telemetry emit --spool <dir> --type <type> --run <id> [--project --change --version --head --tree --check] [--data k=v] [--number k=n] [--list k=a,b]")
687 }
688 // Only a spool start bound stores a record: one that names no
689 // destination would have nowhere to go.
690 dir := filepath.Clean(spool)
691 if _, err := spoolDestination(dir); err != nil {
692 return nil
693 }
694 p := telemetry.Self("valley", version)
695 if exe != "" {
696 p.Exe = exe
697 }
698 telemetry.NewEmitter(dir, p, run).Emit(typ, r, data)
699 return nil
700}
701
702// Flushing.
703const (
704 flushBatch = 500
705 flushDeadline = 20 * time.Second
706 watchEvery = 2 * time.Second
707 watchLongest = 12 * time.Hour
708)
709
710// runFlush sends every spool's unacknowledged records, each to the
711// destination it is bound to, or with --remote only the spool bound to the
712// destination that remote names. With --watch PID, it sends every
713// watchEvery while that process lives, and once more after it ends.
714func runFlush(g git, remote string, args []string, stderr io.Writer) error {
715 watch := 0
716 if len(args) == 2 && args[0] == "--watch" {
717 n, err := strconv.Atoi(args[1])
718 if err != nil || n <= 0 {
719 return failure("usage: valley telemetry flush [--watch <pid>]")
720 }
721 watch = n
722 } else if len(args) != 0 {
723 return failure("usage: valley telemetry flush [--watch <pid>]")
724 }
725 if watch != 0 {
726 end := time.Now().Add(watchLongest)
727 for time.Now().Before(end) {
728 alive := syscall.Kill(watch, 0) == nil
729 for _, dir := range spools() {
730 flushSpool(dir, false)
731 }
732 if !alive {
733 return nil
734 }
735 time.Sleep(watchEvery)
736 }
737 return nil
738 }
739 dirs := spools()
740 if remote != "" {
741 dest, err := telemetryRemote(g, remote)
742 if err != nil {
743 return failure(err.Error())
744 }
745 var only []string
746 for _, dir := range dirs {
747 if d, _ := spoolDestination(dir); d.identity() == dest.identity() {
748 only = append(only, dir)
749 }
750 }
751 dirs = only
752 if len(dirs) == 0 {
753 fmt.Fprintf(stderr, "valley: nothing is spooled for %s\n", dest.identity())
754 }
755 }
756 var failed []string
757 for _, dir := range dirs {
758 d, _ := spoolDestination(dir)
759 n, err := flushSpool(dir, true)
760 if err != nil {
761 failed = append(failed, err.Error())
762 continue
763 }
764 fmt.Fprintf(stderr, "valley: %d records sent to %s\n", n, d.identity())
765 }
766 if legacy, err := legacySpool(); err == nil {
767 if rng, err := (&telemetry.Stream{Dir: legacy}).Range(); err == nil && rng.Last >= rng.First {
768 fmt.Fprintf(stderr, "valley: %s holds records from before each spool named its destination; they are kept and never sent. Remove it to drop them.\n", legacy)
769 }
770 }
771 if len(failed) > 0 {
772 return failure(strings.Join(failed, "; "))
773 }
774 return nil
775}
776
777// flushSpool sends what the spool holds after what the host acknowledged,
778// a batch at a time, to the destination it is bound to, and returns how
779// many records it sent. Only one flush
780// runs at a time. A background flush that finds another running leaves the
781// work to it; one asked for by hand (wait) waits for it, up to
782// flushDeadline, and then sends what is left itself.
783func flushSpool(dir string, wait bool) (int, error) {
784 st := &telemetry.Stream{Dir: dir}
785 rng, err := st.Range()
786 if errors.Is(err, os.ErrNotExist) {
787 return 0, nil
788 }
789 if err != nil {
790 return 0, err
791 }
792 lock, err := os.OpenFile(filepath.Join(dir, "flush.lock"), os.O_CREATE|os.O_RDWR, 0o600)
793 if err != nil {
794 return 0, err
795 }
796 defer lock.Close()
797 for waited := time.Duration(0); syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) != nil; waited += 100 * time.Millisecond {
798 if !wait {
799 return 0, nil
800 }
801 if waited > flushDeadline {
802 return 0, errors.New("another flush has held the spool for too long")
803 }
804 time.Sleep(100 * time.Millisecond)
805 }
806 // The destination is the spool's own, never the checkout's or the
807 // caller's.
808 dest, err := spoolDestination(dir)
809 if err != nil {
810 return 0, err
811 }
812 spoolOutput(st)
813 ackPath := filepath.Join(dir, "acked")
814 acked := ackedOf(dir, rng.Epoch)
815 sent := 0
816 for {
817 recs, _, err := st.Read(acked, flushBatch, telemetry.MaxReportBytes/2)
818 if err != nil || len(recs) == 0 {
819 return sent, err
820 }
821 var body bytes.Buffer
822 for _, r := range recs {
823 r.ClientID = fmt.Sprintf("%s:%d", rng.Epoch, r.Seq)
824 r.Seq, r.Stream = 0, ""
825 line, _ := json.Marshal(r)
826 body.Write(append(line, '\n'))
827 }
828 ctx, cancel := context.WithTimeout(context.Background(), flushDeadline)
829 cmd := sshCommand(ctx, dest, telemetry.Request{V: 1, Op: telemetry.OpReport}.Command())
830 cmd.Stdin = &body
831 out, err := cmd.Output()
832 cancel()
833 if err != nil {
834 return sent, fmt.Errorf("the report to %s did not complete: %v", dest.identity(), err)
835 }
836 got := int64(-1)
837 for _, line := range strings.Split(string(out), "\n") {
838 var m struct {
839 Kind string `json:"kind"`
840 Error string `json:"error"`
841 Acked map[string]int64 `json:"acked"`
842 }
843 if json.Unmarshal([]byte(line), &m) != nil {
844 continue
845 }
846 if m.Kind == "error" {
847 return sent, fmt.Errorf("the host refused the report: %s", telemetry.Sanitize(m.Error))
848 }
849 if m.Kind == "ack" {
850 got = m.Acked[rng.Epoch]
851 }
852 }
853 if got < recs[len(recs)-1].Seq {
854 return sent, fmt.Errorf("the host acknowledged %d of the spool, not %d", got, recs[len(recs)-1].Seq)
855 }
856 sent += len(recs)
857 acked = got
858 if err := os.WriteFile(ackPath+".new", []byte(fmt.Sprintf("%s:%d\n", rng.Epoch, acked)), 0o600); err == nil {
859 os.Rename(ackPath+".new", ackPath)
860 }
861 }
862}
863
864// outputPerFlush bounds how much check output one flush turns into
865// records.
866const outputPerFlush = 256 << 10
867
868// spoolOutput turns what the spool's check logs gained since the last
869// flush into check.output records in the spool, so a check's output
870// reaches the host while it runs. Each record holds at most
871// telemetry.OutputChunk bytes of it, made safe to show; the host serves
872// them only to a reader asking for logs, marked untrusted.
873func spoolOutput(st *telemetry.Stream) {
874 sentPath := filepath.Join(st.Dir, "output-sent.json")
875 sent := map[string]int64{}
876 if data, err := os.ReadFile(sentPath); err == nil {
877 json.Unmarshal(data, &sent)
878 }
879 budget := int64(outputPerFlush)
880 now := map[string]int64{}
881 for _, l := range st.Logs() {
882 key := l.Run + "/" + l.Check
883 from := sent[key]
884 now[key] = from
885 if l.Size <= from || budget <= 0 {
886 continue
887 }
888 f, err := os.Open(l.Path)
889 if err != nil {
890 continue
891 }
892 buf := make([]byte, min(l.Size-from, budget))
893 n, _ := f.ReadAt(buf, from)
894 f.Close()
895 buf = buf[:n]
896 e := telemetry.NewEmitter(st.Dir, telemetry.Self("attest", ""), l.Run)
897 for len(buf) > 0 {
898 chunk := buf[:min(len(buf), telemetry.OutputChunk)]
899 if i := bytes.LastIndexByte(chunk, '\n'); i > 0 && len(chunk) < len(buf) {
900 chunk = chunk[:i+1]
901 }
902 e.Emit("check.output", telemetry.Record{Check: l.Check}, map[string]any{"offset": from, "text": telemetry.Sanitize(string(chunk))})
903 from += int64(len(chunk))
904 budget -= int64(len(chunk))
905 buf = buf[len(chunk):]
906 }
907 now[key] = from
908 }
909 if data, err := json.Marshal(now); err == nil {
910 if os.WriteFile(sentPath+".new", data, 0o600) == nil {
911 os.Rename(sentPath+".new", sentPath)
912 }
913 }
914}