gunk-dev/the-valley

telemetry.go

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