gunk-dev/the-valley

progress.go

source9e4736a353f5main's published tip history
5.7 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 mu sync.Mutex
41 names map[string]string // a derivation's log is named for the first check that builds it
42 logs map[string]logged
43}
44
45type logged struct {
46 bytes int64
47 truncated bool
48 cached bool // nix built and fetched nothing (nixLog.ran)
49}
50
51func newObserver(tel *telemetry.Emitter) *observer {
52 if tel == nil {
53 return nil
54 }
55 return &observer{tel: tel, names: map[string]string{}, logs: map[string]logged{}}
56}
57
58func (o *observer) emit(typ, check string, data map[string]any) {
59 if o == nil {
60 return
61 }
62 o.tel.Emit(typ, telemetry.Record{Check: check}, data)
63}
64
65// name says which check's log a derivation's build writes.
66func (o *observer) name(drv, check string) {
67 if o == nil {
68 return
69 }
70 o.mu.Lock()
71 if _, ok := o.names[drv]; !ok {
72 o.names[drv] = check
73 }
74 o.mu.Unlock()
75}
76
77// logOf is what was logged of a derivation's build.
78func (o *observer) logOf(drv string) logged {
79 if o == nil {
80 return logged{}
81 }
82 o.mu.Lock()
83 defer o.mu.Unlock()
84 return o.logs[drv]
85}
86
87// nixBuild builds one derivation as runPure does, and streams its log.
88func (o *observer) nixBuild(tree, drv string) (string, string, error) {
89 o.mu.Lock()
90 name := o.names[drv]
91 o.mu.Unlock()
92 log := o.tel.Log(name)
93 cmd := exec.Command("nix", "build", "--no-link", "--print-out-paths", "--log-format", "internal-json", "-L", drv+"^*")
94 cmd.Dir = tree
95 var out bytes.Buffer
96 stderr := &nixLog{log: log}
97 cmd.Stdout = &out
98 cmd.Stderr = stderr
99 err := cmd.Run()
100 stderr.Write([]byte("\n")) // whatever was left without a newline
101 written, truncated := log.Close()
102 o.mu.Lock()
103 o.logs[drv] = logged{written, truncated, err == nil && !stderr.ran}
104 o.mu.Unlock()
105 return out.String(), stderr.text.String(), err
106}
107
108// nixLog reads nix's structured log as it is written. The builder's
109// lines go to the check's log alone. nix's messages, and its activities
110// at the level it prints by default, go to the text a failed check shows
111// and to the log. A line that is not nix's framing is kept as text, as
112// nix printed it. ran says nix started a build or a substitution: a
113// build that started neither found its outputs already in the store.
114type nixLog struct {
115 log io.Writer
116 pending []byte
117 text bytes.Buffer
118 ran bool
119}
120
121// The types of nix's activities that make an output: building a
122// derivation and fetching a path from a substituter.
123const (
124 nixActBuild = 105
125 nixActSubstitute = 108
126)
127
128// ansi matches the colour sequences nix writes into its messages.
129var ansi = regexp.MustCompile("\x1b\\[[0-9;]*[A-Za-z]")
130
131func (l *nixLog) Write(p []byte) (int, error) {
132 l.pending = append(l.pending, p...)
133 for {
134 i := bytes.IndexByte(l.pending, '\n')
135 if i < 0 {
136 break
137 }
138 l.line(string(l.pending[:i]))
139 l.pending = l.pending[i+1:]
140 }
141 return len(p), nil
142}
143
144func (l *nixLog) line(line string) {
145 if line == "" {
146 return
147 }
148 payload, framed := strings.CutPrefix(line, "@nix ")
149 if !framed {
150 l.text.WriteString(line + "\n")
151 l.log.Write([]byte(line + "\n"))
152 return
153 }
154 var m struct {
155 Action string `json:"action"`
156 Type int `json:"type"`
157 Level int `json:"level"`
158 Msg string `json:"msg"`
159 Text string `json:"text"`
160 Fields []any `json:"fields"`
161 }
162 if json.Unmarshal([]byte(payload), &m) != nil {
163 return
164 }
165 if m.Action == "start" && (m.Type == nixActBuild || m.Type == nixActSubstitute) {
166 l.ran = true
167 }
168 switch {
169 case m.Action == "result" && m.Type == 101 && len(m.Fields) > 0: // a line of build output
170 if s, ok := m.Fields[0].(string); ok {
171 l.log.Write([]byte(s + "\n"))
172 }
173 case m.Action == "msg":
174 msg := ansi.ReplaceAllString(m.Msg, "") + "\n"
175 l.text.WriteString(msg)
176 l.log.Write([]byte(msg))
177 case m.Action == "start" && m.Text != "" && m.Level <= 3:
178 l.text.WriteString(m.Text + "\n")
179 }
180}
181
182// buildData is what a check's build-end and result records say about
183// its build.
184func buildData(b *drvBuild, wait time.Duration, began, ended time.Time, lg logged) map[string]any {
185 d := map[string]any{
186 "build_ms": b.took.Milliseconds(),
187 "slot_wait_ms": wait.Milliseconds(),
188 "build_began": telemetry.Stamp(began),
189 "build_ended": telemetry.Stamp(ended),
190 "log_bytes": lg.bytes,
191 "cached": lg.cached,
192 }
193 if lg.truncated {
194 d["log_truncated"] = true
195 }
196 if b.err != nil {
197 d["build_error"] = clipError(b.err.Error())
198 }
199 return d
200}
201
202func clipError(s string) string {
203 if len(s) > 200 {
204 return s[:200] + "…"
205 }
206 return s
207}