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