gunk-dev/the-valley

timing.go

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