gunk-dev/the-valley

workertelemetry.go

source9ee95920e399main's published tip history
14.1 KiB
1package main
2
3// What the check worker says about its own passes, with --telemetry DIR.
4//
5// DIR is the worker's diagnostic directory, apart from its state
6// directory and its key: the host makes it group-readable by the
7// collector, and the worker writes nothing else there. It holds two
8// things:
9//
10// - stream/, the telemetry stream (../telemetry) of the worker's passes
11// and of the attest runs a pass starts, whose progress attest records
12// itself;
13// - state.json, the worker's state now: the pass running and what it is
14// doing, each batch it runs, the last attempts and how each ended, and
15// every failure waiting out its backoff, with the change, version,
16// head and tree it was about and why it failed.
17//
18// Batches run at once, so nothing a record says about a batch or a push
19// comes from what else the pass is doing: each names its own project,
20// change, version, head and tree (identity), and its class, and a batch's
21// records name its attest run too. The class is what the batch is for:
22// ready, a ready change's active version; follow, a follow run on main's
23// tip; or request, a check request. A follow run and a request carry no
24// change, so a reader tells their batches apart by the class alone. The
25// check.result records attest writes name no class; a reader judges them
26// by the tree they are about (mainstate.go). Records from a worker that
27// names no class are a ready change's when they carry a change, and a
28// follow run's when they carry none. The pass's own fields in state.json
29// describe the change it reads during a scan, and otherwise its newest
30// running batch; batches lists every running batch.
31//
32// failures.json in the state directory stays what decides a backoff, in
33// its own format; state.json only describes it. A pass that starts and
34// finds state.json naming a pass that never ended records that pass as
35// interrupted, and each batch it was running: a pass that is killed
36// cannot say so itself, so this is an inference, and is marked as one.
37
38import (
39 "encoding/json"
40 "fmt"
41 "os"
42 "path/filepath"
43 "sort"
44 "time"
45
46 "the-valley/telemetry"
47)
48
49type workerTelemetry struct {
50 dir string
51 tel *telemetry.Emitter
52 state workerState
53}
54
55type workerState struct {
56 V int `json:"v"`
57 Updated string `json:"updated"`
58 Pass *passState `json:"pass"`
59 Recent []attempt `json:"recent"`
60 Failures []failureState `json:"failures"`
61}
62
63type passState struct {
64 Run string `json:"run"`
65 PID int `json:"pid"`
66 Exe string `json:"exe,omitempty"`
67 Version string `json:"version,omitempty"`
68 Started string `json:"started"`
69 Phase string `json:"phase"`
70 Project string `json:"project,omitempty"`
71 Change string `json:"change,omitempty"`
72 CV int `json:"change_version,omitempty"`
73 Head string `json:"head,omitempty"`
74 Tree string `json:"tree,omitempty"`
75 Checks []string `json:"checks,omitempty"`
76 // Batches is every batch running, oldest first, each with the result
77 // running.
78 Batches []attempt `json:"batches,omitempty"`
79}
80
81type attempt struct {
82 Kind string `json:"kind"` // pass, batch or push
83 Run string `json:"run"`
84 Project string `json:"project,omitempty"`
85 Change string `json:"change,omitempty"`
86 CV int `json:"change_version,omitempty"`
87 Head string `json:"head,omitempty"`
88 Tree string `json:"tree,omitempty"`
89 Checks []string `json:"checks,omitempty"`
90 Started string `json:"started,omitempty"`
91 Ended string `json:"ended,omitempty"`
92 Result string `json:"result"` // passed, failed, cancelled or interrupted, or running in batches
93 Reason string `json:"reason,omitempty"`
94 Inferred bool `json:"inferred,omitempty"`
95 // Class is what the batch or push is for: ready, follow or request.
96 Class string `json:"class,omitempty"`
97 // AttestRun is a batch's attest run, which names its progress records.
98 AttestRun string `json:"attest_run,omitempty"`
99}
100
101// identity is what a batch or a push is about.
102type identity struct {
103 project, change string
104 cv int
105 head, tree string
106}
107
108func (id identity) record() telemetry.Record {
109 return telemetry.Record{Project: id.project, Change: id.change, Version: id.cv, Head: id.head, Tree: id.tree}
110}
111
112type failureState struct {
113 Project string `json:"project"`
114 Key string `json:"key"`
115 Failures int `json:"failures"`
116 Retry string `json:"retry"`
117 FailedAt string `json:"failed_at,omitempty"`
118 Change string `json:"change,omitempty"`
119 CV int `json:"change_version,omitempty"`
120 Head string `json:"head,omitempty"`
121 Tree string `json:"tree,omitempty"`
122 Reason string `json:"reason,omitempty"`
123}
124
125const recentAttempts = 20
126
127// openWorkerTelemetry starts a pass's telemetry in dir, or returns nil
128// without a dir. The previous pass, if state.json still names it as
129// running, is recorded as interrupted.
130func openWorkerTelemetry(dir string) *workerTelemetry {
131 if dir == "" {
132 return nil
133 }
134 t := &workerTelemetry{dir: dir}
135 if data, err := os.ReadFile(t.statePath()); err == nil {
136 json.Unmarshal(data, &t.state)
137 }
138 self := telemetry.Self("valley-worker", versionStamp)
139 t.tel = telemetry.NewEmitter(filepath.Join(dir, "stream"), self, "")
140 if prev := t.state.Pass; prev != nil {
141 reason := fmt.Sprintf("pass %s (pid %d) recorded no end: it was killed, or the host stopped, during its %s", prev.Run, prev.PID, prev.Phase)
142 t.remember(attempt{Kind: "pass", Run: prev.Run, Project: prev.Project, Change: prev.Change, CV: prev.CV,
143 Head: prev.Head, Tree: prev.Tree, Checks: prev.Checks, Started: prev.Started, Result: "interrupted", Reason: reason, Inferred: true})
144 var runs []string
145 for _, b := range prev.Batches {
146 b.Result, b.Inferred = "interrupted", true
147 b.Reason = fmt.Sprintf("batch %s of pass %s (pid %d) recorded no end: it was killed, or the host stopped, while it ran", b.AttestRun, prev.Run, prev.PID)
148 t.remember(b)
149 runs = append(runs, b.AttestRun)
150 }
151 t.tel.Emit("pass.interrupted", telemetry.Record{Project: prev.Project, Change: prev.Change, Version: prev.CV, Head: prev.Head},
152 map[string]any{"previous_run": prev.Run, "previous_pid": prev.PID, "phase": prev.Phase, "inferred": true, "batches": runs})
153 }
154 t.state.V = 1
155 t.state.Pass = &passState{Run: t.tel.Run(), PID: self.PID, Exe: self.Exe, Version: self.Version,
156 Started: telemetry.Stamp(time.Now()), Phase: "reading"}
157 t.save()
158 t.tel.Emit("pass.start", telemetry.Record{}, nil)
159 return t
160}
161
162func (t *workerTelemetry) statePath() string { return filepath.Join(t.dir, "state.json") }
163
164func (t *workerTelemetry) stream() string { return filepath.Join(t.dir, "stream") }
165
166func (t *workerTelemetry) remember(a attempt) {
167 t.state.Recent = append([]attempt{a}, t.state.Recent...)
168 if len(t.state.Recent) > recentAttempts {
169 t.state.Recent = t.state.Recent[:recentAttempts]
170 }
171}
172
173// reading says which change a scan is reading now. The pass says it saw
174// the change only the first time it reads the change's version.
175func (t *workerTelemetry) reading(project string, c jsonChange, v jsonVersion, first bool) {
176 if t == nil {
177 return
178 }
179 p := t.state.Pass
180 p.Phase, p.Project, p.Change, p.CV, p.Head, p.Tree, p.Checks = "deriving", project, c.ChangeID, v.N, v.Head, "", nil
181 if first {
182 t.tel.Emit("change.seen", telemetry.Record{Project: project, Change: c.ChangeID, Version: v.N, Head: v.Head},
183 map[string]any{"handle": c.Handle})
184 }
185 t.save()
186}
187
188// settle says what the pass is doing between scans: building, as its
189// newest running batch, or reading.
190func (t *workerTelemetry) settle() {
191 if t == nil {
192 return
193 }
194 p := t.state.Pass
195 if len(p.Batches) == 0 {
196 p.Phase = "reading"
197 } else {
198 b := p.Batches[len(p.Batches)-1]
199 p.Phase, p.Project, p.Change, p.CV, p.Head, p.Tree, p.Checks = "build", b.Project, b.Change, b.CV, b.Head, b.Tree, b.Checks
200 }
201 t.save()
202}
203
204// begin says the pass is building or publishing for id, of the class
205// given, and returns the attempt it makes. A batch names its attest run.
206func (t *workerTelemetry) begin(kind, class string, id identity, checks []string, attestRun string, data map[string]any) *attempt {
207 if t == nil {
208 return nil
209 }
210 p := t.state.Pass
211 p.Phase, p.Project, p.Change, p.CV, p.Head, p.Tree, p.Checks = kind, id.project, id.change, id.cv, id.head, id.tree, checks
212 a := &attempt{Kind: kind, Run: t.tel.Run(), Project: id.project, Change: id.change, CV: id.cv, Head: id.head, Tree: id.tree,
213 Checks: checks, Started: telemetry.Stamp(time.Now()), Class: class, AttestRun: attestRun}
214 if kind == "build" {
215 running := *a
216 running.Result = "running"
217 p.Batches = append(p.Batches, running)
218 }
219 if data == nil {
220 data = map[string]any{}
221 }
222 data["checks"] = checks
223 data["class"] = class
224 t.tel.Emit(map[string]string{"build": "batch.start", "push": "publish.start"}[kind], id.record(), data)
225 t.save()
226 return a
227}
228
229// end records how an attempt ended, as result: passed, failed, or
230// cancelled when the pass stopped a batch, with the reason for either of
231// the last two, and its backoff when it failed. A batch's records name its
232// attest run, so each attempt pairs with its start from its own records.
233func (t *workerTelemetry) end(a *attempt, result, reason string, key string, f *backoff) {
234 if t == nil || a == nil {
235 return
236 }
237 id := identity{project: a.Project, change: a.Change, cv: a.CV, head: a.Head, tree: a.Tree}
238 a.Ended, a.Result, a.Reason = telemetry.Stamp(time.Now()), result, reason
239 data := map[string]any{"result": result, "class": a.Class}
240 if a.AttestRun != "" {
241 data["attest_run"] = a.AttestRun
242 }
243 if reason != "" {
244 data["reason"] = reason
245 }
246 t.remember(*a)
247 if a.Kind == "build" {
248 p := t.state.Pass
249 for i, b := range p.Batches {
250 if b.AttestRun == a.AttestRun {
251 p.Batches = append(p.Batches[:i:i], p.Batches[i+1:]...)
252 break
253 }
254 }
255 }
256 t.tel.Emit(map[string]string{"build": "batch.end", "push": "publish.end"}[a.Kind], id.record(), data)
257 if f != nil {
258 backoff := map[string]any{"key": key, "failures": f.Failures, "retry": telemetry.Stamp(f.Retry), "reason": reason}
259 if a.AttestRun != "" {
260 backoff["attest_run"] = a.AttestRun
261 }
262 t.tel.Emit("backoff", id.record(), backoff)
263 t.failure(failureState{Project: a.Project, Key: key, Failures: f.Failures, Retry: telemetry.Stamp(f.Retry),
264 FailedAt: a.Ended, Change: a.Change, CV: a.CV, Head: a.Head, Tree: a.Tree, Reason: reason})
265 }
266 t.save()
267}
268
269// spent records that a check request's batch failed, or that no batch can
270// build what it lacks, so the request is not built again until its ref
271// moves or goes: a backoff with no retry, naming the request's ref.
272func (t *workerTelemetry) spent(id identity, ref, reason string) {
273 if t == nil {
274 return
275 }
276 t.tel.Emit("backoff", id.record(), map[string]any{"class": classNames[classRequest], "ref": ref, "reason": reason})
277 t.save()
278}
279
280// failure keeps what a failure waiting out its backoff was about.
281func (t *workerTelemetry) failure(f failureState) {
282 for i, old := range t.state.Failures {
283 if old.Project == f.Project && old.Key == f.Key {
284 t.state.Failures[i] = f
285 return
286 }
287 }
288 t.state.Failures = append(t.state.Failures, f)
289}
290
291// capacity says a batch's evaluation is estimated at more than the whole
292// evaluation budget, so it evaluates alone.
293func (t *workerTelemetry) capacity(id identity, estimate, budget int64, source string) {
294 if t == nil {
295 return
296 }
297 t.tel.Emit("capacity", id.record(), map[string]any{"eval_estimate_bytes": estimate, "eval_budget_bytes": budget, "budget_from": source})
298}
299
300// finish ends the pass, and keeps only the failures the failure record
301// still holds, with their waits as it holds them.
302func (t *workerTelemetry) finish(r *failureRecord, troubles int, err error) {
303 if t == nil {
304 return
305 }
306 var kept []failureState
307 for project, failures := range r.Projects {
308 for key, b := range failures {
309 f := failureState{Project: project, Key: key}
310 for _, old := range t.state.Failures {
311 if old.Project == project && old.Key == key {
312 f = old
313 }
314 }
315 f.Failures, f.Retry = b.Failures, telemetry.Stamp(b.Retry)
316 kept = append(kept, f)
317 }
318 }
319 sort.Slice(kept, func(i, j int) bool { return kept[i].Project+kept[i].Key < kept[j].Project+kept[j].Key })
320 t.state.Failures = kept
321 p := t.state.Pass
322 result := "passed"
323 reason := ""
324 if err != nil {
325 result, reason = "failed", err.Error()
326 }
327 t.remember(attempt{Kind: "pass", Run: p.Run, Started: p.Started, Ended: telemetry.Stamp(time.Now()), Result: result, Reason: reason})
328 t.state.Pass = nil
329 t.tel.Emit("pass.end", telemetry.Record{}, map[string]any{"result": result, "troubles": troubles, "waiting": len(kept)})
330 t.save()
331}
332
333// save writes state.json whole, through a file renamed into place,
334// readable by the collector's group. A state that cannot be written is
335// dropped: it describes the pass and decides nothing.
336func (t *workerTelemetry) save() {
337 t.state.Updated = telemetry.Stamp(time.Now())
338 data, err := json.MarshalIndent(t.state, "", " ")
339 if err != nil {
340 return
341 }
342 tmp, err := os.CreateTemp(t.dir, ".state-*")
343 if err != nil {
344 return
345 }
346 _, err = tmp.Write(append(data, '\n'))
347 if err == nil {
348 err = tmp.Chmod(0o640)
349 }
350 if cerr := tmp.Close(); err == nil {
351 err = cerr
352 }
353 if err == nil {
354 err = os.Rename(tmp.Name(), t.statePath())
355 }
356 if err != nil {
357 os.Remove(tmp.Name())
358 }
359}
360
361// failedChecks names the checks an attest run recorded as not passing in
362// the stream at dir, among the records after the one numbered after. It
363// reads files and nothing else, so a batch's goroutine calls it. Other
364// batches' records come between a run's own, so it reads to the end.
365func failedChecks(dir, run string, after int64) []string {
366 if dir == "" {
367 return nil
368 }
369 st := &telemetry.Stream{Dir: dir}
370 var failed []string
371 for pages := 0; pages < 100; pages++ {
372 recs, _, err := st.Read(after, 1000, 1<<20)
373 if err != nil || len(recs) == 0 {
374 break
375 }
376 for _, r := range recs {
377 if r.Run == run && r.Type == "check.result" && r.Data["result"] != "passed" {
378 failed = append(failed, fmt.Sprintf("%s %v", r.Check, r.Data["result"]))
379 }
380 }
381 after = recs[len(recs)-1].Seq
382 }
383 return failed
384}
385
386// streamEnd is the number of the stream's newest record.
387func (t *workerTelemetry) streamEnd() int64 {
388 if t == nil {
389 return 0
390 }
391 rng, _ := (&telemetry.Stream{Dir: t.stream()}).Range()
392 return rng.Last
393}