gunk-dev/the-valley

timing.go

sourced9f8d2de246bmain's published tip history
10.8 KiB
1package main
2
3// How long each check took, and where that is written down.
4//
5// A timing is not evidence. It is never signed, never stored at a ref and
6// never pushed: run prints one line per check, and with --timings it also
7// appends one JSON line per check to a log file on this machine. The log
8// is the start of a record of where time goes, and nothing reads it to
9// decide anything. So a log that cannot be written is a warning and never
10// a failed run.
11//
12// Nor may timing hold a run up. Every piece of timing output is given
13// timingDeadline to finish, and is dropped when it fails or takes longer:
14// the time line, the warning, and the line appended to the log.
15
16import (
17 "bytes"
18 "context"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "io"
23 "net/url"
24 "os"
25 "path/filepath"
26 "regexp"
27 "strings"
28 "sync"
29 "syscall"
30 "time"
31)
32
33// How a check was satisfied, as far as run can tell.
34const (
35 // satisfiedRan: the command ran, or nix built or fetched the output.
36 satisfiedRan = "ran"
37 // satisfiedCached: the output was already in the local nix store
38 // before the build, so nix built nothing.
39 satisfiedCached = "cached"
40 // satisfiedUnknown: the nix store was not asked whether the output
41 // was already there, because the run has no --timings, or it could
42 // not be asked, or it did not answer within probeDeadline.
43 satisfiedUnknown = "unknown"
44)
45
46// checkTiming is one line of the timing log: one check, run once.
47type checkTiming struct {
48 Time string `json:"time"` // when the check started, UTC
49 Repository string `json:"repository"`
50 Change string `json:"change,omitempty"`
51 Version int `json:"version,omitempty"`
52 Head string `json:"head"`
53 Check string `json:"check"`
54 Runner string `json:"runner"`
55 Cost string `json:"cost,omitempty"`
56 Result string `json:"result"` // passed, failed, or error
57 Satisfied string `json:"satisfied"`
58 // DurationMS is the check's wall time: a command's run, or a pure
59 // check's evaluation, store probe and own build. Pure checks share one
60 // evaluation and build side by side, so these do not add up to a
61 // run's wall time. EvalMS is how long evaluating a pure check took, and
62 // a command check has none.
63 DurationMS int64 `json:"duration_ms"`
64 EvalMS int64 `json:"eval_ms,omitempty"`
65}
66
67// timingsPath is the timing log: $XDG_STATE_HOME/valley/timings.jsonl,
68// where an unset or relative XDG_STATE_HOME means ~/.local/state, as the
69// XDG base directory specification says.
70func timingsPath() (string, error) {
71 state := os.Getenv("XDG_STATE_HOME")
72 if !filepath.IsAbs(state) {
73 home, err := os.UserHomeDir()
74 if err != nil {
75 return "", err
76 }
77 state = filepath.Join(home, ".local", "state")
78 }
79 return filepath.Join(state, "valley", "timings.jsonl"), nil
80}
81
82// timingLog appends check timings to the log. Its zero value logs nothing.
83// After one write fails it warns once and stops trying, so a log that
84// cannot be written costs one line of output and not one per check.
85type timingLog struct {
86 path string
87 warn io.Writer
88 failed bool
89}
90
91func (l *timingLog) append(t checkTiming) {
92 if l.path == "" || l.failed {
93 return
94 }
95 if err := bounded(func() error { return appendLine(l.path, t) }); err != nil {
96 l.failed = true
97 fmt.Fprintf(l.warn, "attest: warning: timings not logged: %v\n", err)
98 }
99}
100
101// appendLine writes v as one JSON line at the end of the file at path,
102// creating the file and its directory when they are missing. The line is
103// one write to a file opened for appending, so two runs logging at once
104// do not interleave within a line.
105//
106// The log is a regular file and nothing else. Whatever else is at its path
107// is refused before it is opened, and again after, since the path can
108// change in between. The open does not wait: opening a FIFO to write would
109// wait for a reader, which may never come. The file and its directory are
110// created readable by their owner alone, and a log others can read, such
111// as one an earlier attest created, is made so before a line is added.
112func appendLine(path string, v any) error {
113 line, err := json.Marshal(v)
114 if err != nil {
115 return err
116 }
117 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
118 return err
119 }
120 if info, err := os.Stat(path); err == nil && !info.Mode().IsRegular() {
121 return fmt.Errorf("%s is not a regular file", path)
122 }
123 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY|syscall.O_NONBLOCK, 0o600)
124 if err != nil {
125 return err
126 }
127 info, err := f.Stat()
128 if err != nil || !info.Mode().IsRegular() {
129 f.Close()
130 return fmt.Errorf("%s is not a regular file", path)
131 }
132 if perm := info.Mode().Perm(); perm&0o077 != 0 {
133 if err := f.Chmod(perm &^ 0o077); err != nil {
134 f.Close()
135 return err
136 }
137 }
138 if _, err := f.Write(append(line, '\n')); err != nil {
139 f.Close()
140 return err
141 }
142 return f.Close()
143}
144
145// timingDeadline is how long one piece of timing output may take.
146const timingDeadline = time.Second
147
148// errDropped is what timing output that was dropped for taking too long
149// says.
150var errDropped = errors.New("dropped: not written within " + timingDeadline.String())
151
152// bounded runs f and waits at most timingDeadline for it. After that it
153// returns errDropped, and f is left to finish or not on its own.
154func bounded(f func() error) error {
155 done := make(chan error, 1)
156 go func() { done <- f() }()
157 timer := time.NewTimer(timingDeadline)
158 defer timer.Stop()
159 select {
160 case err := <-done:
161 return err
162 case <-timer.C:
163 return errDropped
164 }
165}
166
167// droppable writes timing output that may be lost. Each write is bounded,
168// and one that fails or takes too long is dropped. While a write is still
169// stuck, every later one is dropped at once rather than queued behind it.
170type droppable struct {
171 w io.Writer
172 busy chan struct{} // holds a token while a write is in flight
173}
174
175func newDroppable(w io.Writer) *droppable {
176 return &droppable{w: w, busy: make(chan struct{}, 1)}
177}
178
179func (d *droppable) Write(p []byte) (int, error) {
180 select {
181 case d.busy <- struct{}{}:
182 default:
183 return 0, errDropped
184 }
185 line := bytes.Clone(p)
186 err := bounded(func() error {
187 defer func() { <-d.busy }()
188 _, err := d.w.Write(line)
189 return err
190 })
191 if err != nil {
192 return 0, err
193 }
194 return len(p), nil
195}
196
197// timingStdout and timingStderr are where run prints its timing: the time
198// lines, and the warning that the log was not written.
199var (
200 timingStdout = sync.OnceValue(func() io.Writer { return newDroppable(duplicate(syscall.Stdout, "stdout")) })
201 timingStderr = sync.OnceValue(func() io.Writer { return newDroppable(duplicate(syscall.Stderr, "stderr")) })
202)
203
204// duplicate duplicates the descriptor of standard output or standard
205// error. Go ends a process whose write to its own standard output or error
206// fails because nobody reads it, as SIGPIPE would. Through a duplicate,
207// the same write fails with EPIPE and nothing more. A stream that cannot
208// be duplicated gets no timing output.
209func duplicate(fd int, name string) io.Writer {
210 syscall.ForkLock.RLock()
211 dup, err := syscall.Dup(fd)
212 if err == nil {
213 syscall.CloseOnExec(dup)
214 }
215 syscall.ForkLock.RUnlock()
216 if err != nil {
217 return io.Discard
218 }
219 return os.NewFile(uintptr(dup), name)
220}
221
222// timingLine is what run prints after each check: its name, its result,
223// how long it took and how it was satisfied.
224func timingLine(t checkTiming, took time.Duration) string {
225 return fmt.Sprintf("time %-24s %-8s %s (%s)", t.Check, t.Result, shortDuration(took), t.Satisfied)
226}
227
228// shortDuration rounds a duration to what a person reading it wants:
229// milliseconds under a second, tenths of a second above.
230func shortDuration(d time.Duration) string {
231 if d < time.Second {
232 return d.Round(time.Millisecond).String()
233 }
234 return d.Round(100 * time.Millisecond).String()
235}
236
237// repositoryName names the repository a run is in, for the log: its origin
238// remote, as remoteIdentifier reduces it, or, with no origin or one that
239// does not reduce, the directory of its main working tree. run is usually
240// given a throwaway worktree, so the worktree's own directory names nothing.
241func repositoryName(root string) string {
242 if origin, err := gitLine(root, "config", "--get", "remote.origin.url"); err == nil && origin != "" {
243 if name := remoteIdentifier(origin); name != "" {
244 return name
245 }
246 }
247 common, err := gitLine(root, "rev-parse", "--path-format=absolute", "--git-common-dir")
248 if err != nil {
249 return root
250 }
251 if filepath.Base(common) == ".git" {
252 return filepath.Dir(common)
253 }
254 return common
255}
256
257// scpLike is git's other way to write an ssh remote, [user@]host:path, in
258// the shapes that cannot hold a password, a query or a second colon.
259var scpLike = regexp.MustCompile(`^(?:[A-Za-z0-9._-]+@)?([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\]):([^:@?#]+)$`)
260
261// remoteIdentifier reduces a remote to what names its repository, since a
262// remote can carry a token. A URL keeps its scheme, host and path, and
263// loses its user name, password, query and fragment. The scp-like form
264// keeps its host and path. A local path, which has no colon before its
265// first slash, is kept as it is. Anything else is withheld: it returns "".
266func remoteIdentifier(remote string) string {
267 if strings.Contains(remote, "://") {
268 u, err := url.Parse(remote)
269 if err != nil || u.Scheme == "" || u.Opaque != "" {
270 return ""
271 }
272 return (&url.URL{Scheme: u.Scheme, Host: u.Host, Path: u.Path}).String()
273 }
274 if m := scpLike.FindStringSubmatch(remote); m != nil {
275 return m[1] + ":" + m[2]
276 }
277 colon, slash := strings.IndexByte(remote, ':'), strings.IndexByte(remote, '/')
278 if colon < 0 || (slash >= 0 && slash < colon) {
279 return remote
280 }
281 return ""
282}
283
284// costClasses reads the --cost flags: NAME=CLASS, the cost class the
285// policy declares for each check.
286func costClasses(costs repeatable) (map[string]string, error) {
287 classes := map[string]string{}
288 for _, c := range costs {
289 name, class, found := strings.Cut(c, "=")
290 if !found || name == "" {
291 return nil, fmt.Errorf("--cost %q: expected NAME=CLASS", c)
292 }
293 classes[name] = class
294 }
295 return classes, nil
296}
297
298// probeDeadline bounds asking the nix store about a check's outputs. The
299// answer only labels a timing, so a store slow to give it gets "unknown".
300var probeDeadline = 5 * time.Second
301
302// outputsCached says whether every output of a derivation is already in
303// the local nix store, so that building it does nothing. It asks before
304// the build, which is the only time the answer means anything, and only
305// for a run with --timings.
306func outputsCached(drv string) string {
307 ctx, cancel := context.WithTimeout(context.Background(), probeDeadline)
308 defer cancel()
309 outputs, _, err := nixStore(ctx, "--query", "--outputs", drv)
310 if err != nil {
311 return satisfiedUnknown
312 }
313 paths := strings.Fields(outputs)
314 if len(paths) == 0 {
315 return satisfiedUnknown
316 }
317 invalid, _, err := nixStore(ctx, append([]string{"--check-validity", "--print-invalid"}, paths...)...)
318 if err != nil {
319 return satisfiedUnknown
320 }
321 if strings.TrimSpace(invalid) != "" {
322 return satisfiedRan
323 }
324 return satisfiedCached
325}