gunk-dev/the-valley

timing.go

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