gunk-dev/the-valley

workertelemetry.go

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