| 1 | package 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 | import ( |
| 13 | "encoding/json" |
| 14 | "fmt" |
| 15 | "io" |
| 16 | "net/url" |
| 17 | "os" |
| 18 | "path/filepath" |
| 19 | "strings" |
| 20 | "time" |
| 21 | ) |
| 22 | |
| 23 | // How a check was satisfied, as far as run can tell. |
| 24 | const ( |
| 25 | // satisfiedRan: the command ran, or nix built or fetched the output. |
| 26 | satisfiedRan = "ran" |
| 27 | // satisfiedCached: the output was already in the local nix store |
| 28 | // before the build, so nix built nothing. |
| 29 | satisfiedCached = "cached" |
| 30 | // satisfiedUnknown: the nix store could not be asked whether the |
| 31 | // output was already there. |
| 32 | satisfiedUnknown = "unknown" |
| 33 | ) |
| 34 | |
| 35 | // checkTiming is one line of the timing log: one check, run once. |
| 36 | type checkTiming struct { |
| 37 | Time string `json:"time"` // when the check started, UTC |
| 38 | Repository string `json:"repository"` |
| 39 | Change string `json:"change,omitempty"` |
| 40 | Version int `json:"version,omitempty"` |
| 41 | Head string `json:"head"` |
| 42 | Check string `json:"check"` |
| 43 | Runner string `json:"runner"` |
| 44 | Cost string `json:"cost,omitempty"` |
| 45 | Result string `json:"result"` // passed, failed, or error |
| 46 | Satisfied string `json:"satisfied"` |
| 47 | DurationMS int64 `json:"duration_ms"` |
| 48 | } |
| 49 | |
| 50 | // timingsPath is the timing log: $XDG_STATE_HOME/valley/timings.jsonl, |
| 51 | // where an unset or relative XDG_STATE_HOME means ~/.local/state, as the |
| 52 | // XDG base directory specification says. |
| 53 | func timingsPath() (string, error) { |
| 54 | state := os.Getenv("XDG_STATE_HOME") |
| 55 | if !filepath.IsAbs(state) { |
| 56 | home, err := os.UserHomeDir() |
| 57 | if err != nil { |
| 58 | return "", err |
| 59 | } |
| 60 | state = filepath.Join(home, ".local", "state") |
| 61 | } |
| 62 | return filepath.Join(state, "valley", "timings.jsonl"), nil |
| 63 | } |
| 64 | |
| 65 | // timingLog appends check timings to the log. Its zero value logs nothing. |
| 66 | // After one write fails it warns once and stops trying, so a log that |
| 67 | // cannot be written costs one line of output and not one per check. |
| 68 | type timingLog struct { |
| 69 | path string |
| 70 | warn io.Writer |
| 71 | failed bool |
| 72 | } |
| 73 | |
| 74 | func (l *timingLog) append(t checkTiming) { |
| 75 | if l.path == "" || l.failed { |
| 76 | return |
| 77 | } |
| 78 | if err := appendLine(l.path, t); err != nil { |
| 79 | l.failed = true |
| 80 | fmt.Fprintf(l.warn, "attest: warning: timings not logged: %v\n", err) |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // appendLine writes v as one JSON line at the end of the file at path, |
| 85 | // creating the file and its directory when they are missing. The line is |
| 86 | // one write to a file opened for appending, so two runs logging at once |
| 87 | // do not interleave within a line. |
| 88 | func appendLine(path string, v any) error { |
| 89 | line, err := json.Marshal(v) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 94 | return err |
| 95 | } |
| 96 | f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | if _, err := f.Write(append(line, '\n')); err != nil { |
| 101 | f.Close() |
| 102 | return err |
| 103 | } |
| 104 | return f.Close() |
| 105 | } |
| 106 | |
| 107 | // timingLine is what run prints after each check: its name, its result, |
| 108 | // how long it took and how it was satisfied. |
| 109 | func timingLine(t checkTiming, took time.Duration) string { |
| 110 | return fmt.Sprintf("time %-24s %-8s %s (%s)", t.Check, t.Result, shortDuration(took), t.Satisfied) |
| 111 | } |
| 112 | |
| 113 | // shortDuration rounds a duration to what a person reading it wants: |
| 114 | // milliseconds under a second, tenths of a second above. |
| 115 | func shortDuration(d time.Duration) string { |
| 116 | if d < time.Second { |
| 117 | return d.Round(time.Millisecond).String() |
| 118 | } |
| 119 | return d.Round(100 * time.Millisecond).String() |
| 120 | } |
| 121 | |
| 122 | // repositoryName names the repository a run is in, for the log: the URL of |
| 123 | // its origin remote with any user name or password removed, or, with no |
| 124 | // origin, the directory of its main working tree. run is usually given a |
| 125 | // throwaway worktree, so the worktree's own directory names nothing. |
| 126 | func repositoryName(root string) string { |
| 127 | if origin, err := gitLine(root, "config", "--get", "remote.origin.url"); err == nil && origin != "" { |
| 128 | return withoutUserinfo(origin) |
| 129 | } |
| 130 | common, err := gitLine(root, "rev-parse", "--path-format=absolute", "--git-common-dir") |
| 131 | if err != nil { |
| 132 | return root |
| 133 | } |
| 134 | if filepath.Base(common) == ".git" { |
| 135 | return filepath.Dir(common) |
| 136 | } |
| 137 | return common |
| 138 | } |
| 139 | |
| 140 | // withoutUserinfo drops the user name and password from a URL, since an |
| 141 | // https remote can carry a token there. Anything that is not a URL with a |
| 142 | // scheme, such as a path or user@host:path, is returned as it is. |
| 143 | func withoutUserinfo(remote string) string { |
| 144 | u, err := url.Parse(remote) |
| 145 | if err != nil || u.Scheme == "" || u.User == nil { |
| 146 | return remote |
| 147 | } |
| 148 | u.User = nil |
| 149 | return u.String() |
| 150 | } |
| 151 | |
| 152 | // costClasses reads the --cost flags: NAME=CLASS, the cost class the |
| 153 | // policy declares for each check. |
| 154 | func costClasses(costs repeatable) (map[string]string, error) { |
| 155 | classes := map[string]string{} |
| 156 | for _, c := range costs { |
| 157 | name, class, found := strings.Cut(c, "=") |
| 158 | if !found || name == "" { |
| 159 | return nil, fmt.Errorf("--cost %q: expected NAME=CLASS", c) |
| 160 | } |
| 161 | classes[name] = class |
| 162 | } |
| 163 | return classes, nil |
| 164 | } |
| 165 | |
| 166 | // outputsCached says whether every output of a derivation is already in |
| 167 | // the local nix store, so that building it does nothing. It asks before |
| 168 | // the build, which is the only time the answer means anything. |
| 169 | func outputsCached(drv string) string { |
| 170 | outputs, _, err := nixStore("--query", "--outputs", drv) |
| 171 | if err != nil { |
| 172 | return satisfiedUnknown |
| 173 | } |
| 174 | paths := strings.Fields(outputs) |
| 175 | if len(paths) == 0 { |
| 176 | return satisfiedUnknown |
| 177 | } |
| 178 | invalid, _, err := nixStore(append([]string{"--check-validity", "--print-invalid"}, paths...)...) |
| 179 | if err != nil { |
| 180 | return satisfiedUnknown |
| 181 | } |
| 182 | if strings.TrimSpace(invalid) != "" { |
| 183 | return satisfiedRan |
| 184 | } |
| 185 | return satisfiedCached |
| 186 | } |