gunk-dev/the-valley

progress.go

sourceb40fcdedd01cmain's published tip history
6.3 KiB
1package main
2
3// Progress: what a run says about itself while it runs, with --telemetry.
4//
5// A timing (timing.go) is printed when a check is reported, and checks
6// are reported in the order given, so a slow first check holds back the
7// lines of every check after it. Progress records are not held back.
8// Each is stored in the telemetry stream (../telemetry) when the thing it
9// records happens: the shared evaluation, a check queued for a build
10// slot, its build starting and ending, and its result. So a reader sees a
11// fast second check finish while a slow first one still builds.
12//
13// With telemetry, a nix build is run with nix's structured log
14// (--log-format internal-json -L), which carries the builder's output
15// line by line as it is written. That output goes to the check's log in
16// the stream, bounded, as it arrives. nix's own messages are kept as the
17// check's log the terminal shows on a failure, as without telemetry, and
18// go to the stream's log too. The builder's lines are told apart by nix's
19// framing, never by what a line says, so a check cannot write a record.
20//
21// Like a timing, progress is never evidence, and storing it never fails
22// or holds up a run (telemetry.Emitter).
23
24import (
25 "bytes"
26 "encoding/json"
27 "io"
28 "os/exec"
29 "regexp"
30 "strings"
31 "sync"
32 "time"
33
34 "the-valley/telemetry"
35)
36
37// observer stores a run's progress. A nil observer stores nothing.
38type observer struct {
39 tel *telemetry.Emitter
40 capacity string // what the run builds on, as given by --capacity
41 mu sync.Mutex
42 names map[string]string // a derivation's log is named for the first check that builds it
43 logs map[string]logged
44}
45
46type logged struct {
47 bytes int64
48 truncated bool
49 cached bool // nix built and fetched nothing (nixLog.ran)
50}
51
52func newObserver(tel *telemetry.Emitter) *observer {
53 if tel == nil {
54 return nil
55 }
56 return &observer{tel: tel, names: map[string]string{}, logs: map[string]logged{}}
57}
58
59func (o *observer) emit(typ, check string, data map[string]any) {
60 if o == nil {
61 return
62 }
63 o.tel.Emit(typ, telemetry.Record{Check: check}, data)
64}
65
66// name says which check's log a derivation's build writes.
67func (o *observer) name(drv, check string) {
68 if o == nil {
69 return
70 }
71 o.mu.Lock()
72 if _, ok := o.names[drv]; !ok {
73 o.names[drv] = check
74 }
75 o.mu.Unlock()
76}
77
78// logOf is what was logged of a derivation's build.
79func (o *observer) logOf(drv string) logged {
80 if o == nil {
81 return logged{}
82 }
83 o.mu.Lock()
84 defer o.mu.Unlock()
85 return o.logs[drv]
86}
87
88// nixBuild builds one derivation as runPure does, and streams its log.
89// Like runPure's own build, it is killed if attest dies (dieWithParent).
90func (o *observer) nixBuild(tree, drv string) (string, string, error) {
91 o.mu.Lock()
92 name := o.names[drv]
93 o.mu.Unlock()
94 log := o.tel.Log(name)
95 cmd := exec.Command("nix", "build", "--no-link", "--print-out-paths", "--log-format", "internal-json", "-L", drv+"^*")
96 cmd.Dir = tree
97 cmd.SysProcAttr = dieWithParent()
98 var out bytes.Buffer
99 stderr := &nixLog{log: log}
100 cmd.Stdout = &out
101 cmd.Stderr = stderr
102 err := cmd.Run()
103 stderr.Write([]byte("\n")) // whatever was left without a newline
104 written, truncated := log.Close()
105 o.mu.Lock()
106 o.logs[drv] = logged{written, truncated, err == nil && !stderr.ran}
107 o.mu.Unlock()
108 return out.String(), stderr.text.String(), err
109}
110
111// nixLog reads nix's structured log as it is written. The builder's
112// lines go to the check's log alone. nix's messages, and its activities
113// at the level it prints by default, go to the text a failed check shows
114// and to the log. A line that is not nix's framing is kept as text, as
115// nix printed it. ran says nix started a build or a substitution: a
116// build that started neither found its outputs already in the store.
117type nixLog struct {
118 log io.Writer
119 pending []byte
120 text bytes.Buffer
121 ran bool
122}
123
124// The types of nix's activities that make an output: building a
125// derivation and fetching a path from a substituter.
126const (
127 nixActBuild = 105
128 nixActSubstitute = 108
129)
130
131// ansi matches the colour sequences nix writes into its messages.
132var ansi = regexp.MustCompile("\x1b\\[[0-9;]*[A-Za-z]")
133
134func (l *nixLog) Write(p []byte) (int, error) {
135 l.pending = append(l.pending, p...)
136 for {
137 i := bytes.IndexByte(l.pending, '\n')
138 if i < 0 {
139 break
140 }
141 l.line(string(l.pending[:i]))
142 l.pending = l.pending[i+1:]
143 }
144 return len(p), nil
145}
146
147func (l *nixLog) line(line string) {
148 if line == "" {
149 return
150 }
151 payload, framed := strings.CutPrefix(line, "@nix ")
152 if !framed {
153 l.text.WriteString(line + "\n")
154 l.log.Write([]byte(line + "\n"))
155 return
156 }
157 var m struct {
158 Action string `json:"action"`
159 Type int `json:"type"`
160 Level int `json:"level"`
161 Msg string `json:"msg"`
162 Text string `json:"text"`
163 Fields []any `json:"fields"`
164 }
165 if json.Unmarshal([]byte(payload), &m) != nil {
166 return
167 }
168 if m.Action == "start" && (m.Type == nixActBuild || m.Type == nixActSubstitute) {
169 l.ran = true
170 }
171 switch {
172 case m.Action == "result" && m.Type == 101 && len(m.Fields) > 0: // a line of build output
173 if s, ok := m.Fields[0].(string); ok {
174 l.log.Write([]byte(s + "\n"))
175 }
176 case m.Action == "msg":
177 msg := ansi.ReplaceAllString(m.Msg, "") + "\n"
178 l.text.WriteString(msg)
179 l.log.Write([]byte(msg))
180 case m.Action == "start" && m.Text != "" && m.Level <= 3:
181 l.text.WriteString(m.Text + "\n")
182 }
183}
184
185// buildData is what a check's build-end and result records say about
186// its build. drv is the derivation built, whose full log nix keeps on the
187// builder (nix log); checks that share a derivation name the same one.
188// When a dependency's build failed, the failed derivation is not
189// recorded: nix's structured log marks no build as failed, and only its
190// error text, worded differently between nix releases and quoting the
191// builder's last lines, names it.
192func buildData(b *drvBuild, wait time.Duration, began, ended time.Time, lg logged) map[string]any {
193 d := map[string]any{
194 "drv": b.drv,
195 "build_ms": b.took.Milliseconds(),
196 "slot_wait_ms": wait.Milliseconds(),
197 "build_began": telemetry.Stamp(began),
198 "build_ended": telemetry.Stamp(ended),
199 "log_bytes": lg.bytes,
200 "cached": lg.cached,
201 }
202 if lg.truncated {
203 d["log_truncated"] = true
204 }
205 if b.err != nil {
206 d["build_error"] = clipError(b.err.Error())
207 }
208 return d
209}
210
211func clipError(s string) string {
212 if len(s) > 200 {
213 return s[:200] + "…"
214 }
215 return s
216}