gunk-dev/the-valley

telemetry.go

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