| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "io" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "regexp" |
| 10 | "slices" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "syscall" |
| 15 | "time" |
| 16 | |
| 17 | "the-valley/telemetry" |
| 18 | ) |
| 19 | |
| 20 | // A valley invocation's command record (valley help telemetry): its verb, |
| 21 | // the names of the flags it was given, its exit status, its wall time, |
| 22 | // and the time and processes each phase of it took. It carries no |
| 23 | // argument's value, since a report goes to the host and a project may be |
| 24 | // public. bin/valley execs this program for most verbs, so this program |
| 25 | // records them itself, once it has run; the verbs bin/valley runs itself |
| 26 | // it records with `valley-go telemetry command` as it exits. |
| 27 | |
| 28 | // phaseClock is where this process's wall time goes: to the phase current |
| 29 | // when it passes, and to "other" outside every phase. A phase's time |
| 30 | // leaves out the phases entered from it. Work on another goroutine counts |
| 31 | // toward whichever phase is current, so the times are a reading guide, |
| 32 | // not a profile. |
| 33 | type phaseClock struct { |
| 34 | mu sync.Mutex |
| 35 | began time.Time |
| 36 | current string |
| 37 | since time.Time |
| 38 | spent map[string]time.Duration |
| 39 | procs map[string]int64 |
| 40 | } |
| 41 | |
| 42 | var phases = &phaseClock{began: time.Now(), current: "other", since: time.Now(), |
| 43 | spent: map[string]time.Duration{}, procs: map[string]int64{}} |
| 44 | |
| 45 | // phase enters the phase name, and returns what leaves it for the phase |
| 46 | // it was entered from. |
| 47 | func phase(name string) (end func()) { |
| 48 | c := phases |
| 49 | c.mu.Lock() |
| 50 | defer c.mu.Unlock() |
| 51 | from := c.switchTo(name) |
| 52 | return func() { |
| 53 | c.mu.Lock() |
| 54 | defer c.mu.Unlock() |
| 55 | c.switchTo(from) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | func (c *phaseClock) switchTo(name string) (from string) { |
| 60 | now := time.Now() |
| 61 | c.spent[c.current] += now.Sub(c.since) |
| 62 | from, c.current, c.since = c.current, name, now |
| 63 | return from |
| 64 | } |
| 65 | |
| 66 | // processStarted counts a process toward the current phase. |
| 67 | func processStarted() { |
| 68 | phases.mu.Lock() |
| 69 | phases.procs[phases.current]++ |
| 70 | phases.mu.Unlock() |
| 71 | } |
| 72 | |
| 73 | // invocation is the valley command a process records: the arguments it |
| 74 | // was run with, when bin/valley started it, and bin/valley's version. |
| 75 | type invocation struct { |
| 76 | args []string |
| 77 | since time.Time |
| 78 | version string |
| 79 | } |
| 80 | |
| 81 | // execed is the invocation bin/valley execs this process as, or nil. The |
| 82 | // variables are removed, so no program this one runs takes them for its |
| 83 | // own. |
| 84 | func execed(args []string) *invocation { |
| 85 | since, version := os.Getenv("VALLEY_TELEMETRY_SINCE"), os.Getenv("VALLEY_TELEMETRY_VERSION") |
| 86 | os.Unsetenv("VALLEY_TELEMETRY_SINCE") |
| 87 | os.Unsetenv("VALLEY_TELEMETRY_VERSION") |
| 88 | return invocationOf(args, since, version) |
| 89 | } |
| 90 | |
| 91 | // invocationOf is an invocation started at since, in microseconds of the |
| 92 | // Unix epoch as bash's EPOCHREALTIME reads with its point removed. |
| 93 | func invocationOf(args []string, since, version string) *invocation { |
| 94 | us, err := strconv.ParseInt(since, 10, 64) |
| 95 | if err != nil || us <= 0 || len(args) == 0 { |
| 96 | return nil |
| 97 | } |
| 98 | return &invocation{args: args, since: time.UnixMicro(us), version: version} |
| 99 | } |
| 100 | |
| 101 | // record stores the invocation's command record in the spool, when the |
| 102 | // checkout has valley.telemetry on, and starts a flusher to send it. |
| 103 | // Telemetry off costs no process and writes nothing. Like every |
| 104 | // workstation record it is best effort: whatever goes wrong costs this |
| 105 | // record, and never the command's output or exit status. |
| 106 | func (inv *invocation) record(status int, timed bool) { |
| 107 | if inv == nil || !telemetryMentioned() { |
| 108 | return |
| 109 | } |
| 110 | elapsed := time.Since(inv.since) |
| 111 | data := inv.data(status, elapsed, timed) |
| 112 | g := git{env: gitEnvironment(os.Environ()), stderr: io.Discard} |
| 113 | listed, err := g.output(true, "config", "--get-regexp", `^(valley\.telemetry(\.remote)?|remote\..*\.url)$`) |
| 114 | if err != nil { |
| 115 | return |
| 116 | } |
| 117 | settings := map[string]string{} |
| 118 | for _, line := range strings.Split(listed, "\n") { |
| 119 | key, value, given := strings.Cut(line, " ") |
| 120 | if !given { |
| 121 | value = "true" // a key with no value is a true boolean |
| 122 | } |
| 123 | // git prints the section and the name in lower case, and the |
| 124 | // subsection, such as a remote's name, as it is. |
| 125 | settings[key] = value |
| 126 | } |
| 127 | switch strings.ToLower(settings["valley.telemetry"]) { |
| 128 | case "true", "yes", "on", "1": |
| 129 | default: |
| 130 | return |
| 131 | } |
| 132 | dest, err := remoteDest(func(key string) (string, bool) { |
| 133 | v, ok := settings[key] |
| 134 | return strings.TrimSpace(v), ok |
| 135 | }, "") |
| 136 | if err != nil { |
| 137 | return |
| 138 | } |
| 139 | dir, err := bindSpool(dest) |
| 140 | if err != nil { |
| 141 | return |
| 142 | } |
| 143 | version := inv.version |
| 144 | if version == "" { |
| 145 | version = "unstamped" |
| 146 | } |
| 147 | // No executable: its path can name the user's home. |
| 148 | p := telemetry.Self("valley", version) |
| 149 | p.Exe = "" |
| 150 | telemetry.NewEmitter(dir, p, telemetry.NewRunID()). |
| 151 | Emit("command", telemetry.Record{Project: dest.project()}, data) |
| 152 | startFlusher() |
| 153 | } |
| 154 | |
| 155 | // data is the record's data: the verb, its subverb for knot and |
| 156 | // telemetry, the flag names given, the exit status, the wall time since |
| 157 | // bin/valley started, and, when this process timed the command, each |
| 158 | // phase's milliseconds and processes started. shell is bin/valley's time |
| 159 | // before this process started, such as pending's fetch of origin. |
| 160 | func (inv *invocation) data(status int, elapsed time.Duration, timed bool) map[string]any { |
| 161 | verb, sub, flags := commandWords(inv.args) |
| 162 | d := map[string]any{"verb": verb, "flags": flags, "status": int64(status), "elapsed_ms": elapsed.Milliseconds()} |
| 163 | if sub != "" { |
| 164 | d["subverb"] = sub |
| 165 | } |
| 166 | if !timed { |
| 167 | return d |
| 168 | } |
| 169 | c := phases |
| 170 | c.mu.Lock() |
| 171 | defer c.mu.Unlock() |
| 172 | c.switchTo(c.current) |
| 173 | d["shell_ms"] = max(c.began.Sub(inv.since).Milliseconds(), 0) |
| 174 | for name, t := range c.spent { |
| 175 | d[name+"_ms"] = t.Milliseconds() |
| 176 | d[name+"_procs"] = c.procs[name] |
| 177 | } |
| 178 | return d |
| 179 | } |
| 180 | |
| 181 | // knownFlags is every flag a valley verb takes, from the usage texts and |
| 182 | // bin/valley's own verbs. A word that looks like a flag and is not one |
| 183 | // may be an argument's value, so it is left out. |
| 184 | var knownFlags = func() map[string]bool { |
| 185 | flagRE := regexp.MustCompile(`(?:^|[\s\[|(])(--?[a-z][a-z0-9-]*)`) |
| 186 | shell := " --build-here --checks --change --head --verbose --cost --instance --names --project --schema -v -h --help" |
| 187 | known := map[string]bool{} |
| 188 | for _, m := range flagRE.FindAllStringSubmatch(usage+knotUsage+telemetryUsage+shell, -1) { |
| 189 | known[m[1]] = true |
| 190 | } |
| 191 | return known |
| 192 | }() |
| 193 | |
| 194 | // The subverbs a record names: knot's verbs and telemetry's operations. |
| 195 | var ( |
| 196 | knotVerbs = func() map[string]bool { |
| 197 | known := map[string]bool{} |
| 198 | for _, m := range regexp.MustCompile(`(?m)^ ([a-z]+) `).FindAllStringSubmatch(knotUsage, -1) { |
| 199 | known[m[1]] = true |
| 200 | } |
| 201 | return known |
| 202 | }() |
| 203 | telemetryOps = map[string]bool{"sources": true, "snapshot": true, "read": true, "follow": true, |
| 204 | "flush": true, "start": true, "emit": true, "command": true} |
| 205 | ) |
| 206 | |
| 207 | // commandWords is an invocation's verb, its subverb, and the names of the |
| 208 | // known flags it was given, each once, in the order given. Nothing after |
| 209 | // -- is read, since everything there is a value. |
| 210 | func commandWords(args []string) (verb, sub string, flags []string) { |
| 211 | verb, flags = args[0], []string{} |
| 212 | if !knownVerbs[verb] { |
| 213 | verb = "unknown" |
| 214 | } |
| 215 | for _, arg := range args[1:] { |
| 216 | if arg == "--" { |
| 217 | break |
| 218 | } |
| 219 | name, _, _ := strings.Cut(arg, "=") |
| 220 | switch { |
| 221 | case knownFlags[name] && strings.HasPrefix(name, "-"): |
| 222 | if !slices.Contains(flags, name) { |
| 223 | flags = append(flags, name) |
| 224 | } |
| 225 | case sub == "" && verb == "knot" && knotVerbs[arg], sub == "" && verb == "telemetry" && telemetryOps[arg]: |
| 226 | sub = arg |
| 227 | } |
| 228 | } |
| 229 | return verb, sub, flags |
| 230 | } |
| 231 | |
| 232 | // knownVerbs is valley's verbs (bin/valley's main). |
| 233 | var knownVerbs = map[string]bool{"pending": true, "changes": true, "review": true, "approve": true, |
| 234 | "rebase": true, "status": true, "ready": true, "unready": true, "withdraw": true, "knot": true, |
| 235 | "plan": true, "checks": true, "tail": true, "replay": true, "self-update": true, "telemetry": true} |
| 236 | |
| 237 | // telemetryMentioned reports whether a configuration file git reads here |
| 238 | // may set valley.telemetry, without starting git: it is false only when |
| 239 | // none of them mentions telemetry or includes another file. So a |
| 240 | // checkout with telemetry off starts no process to find that out, and git |
| 241 | // itself answers whenever the files could say yes. |
| 242 | func telemetryMentioned() bool { |
| 243 | for _, v := range []string{"GIT_DIR", "GIT_COMMON_DIR", "GIT_CONFIG", "GIT_CONFIG_GLOBAL", |
| 244 | "GIT_CONFIG_SYSTEM", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"} { |
| 245 | if os.Getenv(v) != "" { |
| 246 | return true |
| 247 | } |
| 248 | } |
| 249 | home := os.Getenv("HOME") |
| 250 | xdg := os.Getenv("XDG_CONFIG_HOME") |
| 251 | if xdg == "" { |
| 252 | xdg = filepath.Join(home, ".config") |
| 253 | } |
| 254 | files := []string{"/etc/gitconfig", filepath.Join(home, ".gitconfig"), filepath.Join(xdg, "git", "config")} |
| 255 | dirs, found := gitDirs() |
| 256 | if !found { |
| 257 | return true |
| 258 | } |
| 259 | for _, dir := range dirs { |
| 260 | files = append(files, filepath.Join(dir, "config"), filepath.Join(dir, "config.worktree")) |
| 261 | } |
| 262 | for _, f := range files { |
| 263 | data, err := os.ReadFile(f) |
| 264 | if err != nil { |
| 265 | continue |
| 266 | } |
| 267 | data = bytes.ToLower(data) |
| 268 | if bytes.Contains(data, []byte("telemetry")) || bytes.Contains(data, []byte("include")) { |
| 269 | return true |
| 270 | } |
| 271 | } |
| 272 | return false |
| 273 | } |
| 274 | |
| 275 | // gitDirs is the repository's git directory above the working directory |
| 276 | // and, for a linked worktree, its common directory. |
| 277 | func gitDirs() ([]string, bool) { |
| 278 | dir, err := os.Getwd() |
| 279 | if err != nil { |
| 280 | return nil, false |
| 281 | } |
| 282 | for { |
| 283 | dotgit := filepath.Join(dir, ".git") |
| 284 | if st, err := os.Stat(dotgit); err == nil { |
| 285 | if st.IsDir() { |
| 286 | return []string{dotgit}, true |
| 287 | } |
| 288 | data, err := os.ReadFile(dotgit) |
| 289 | linked, ok := strings.CutPrefix(strings.TrimSpace(string(data)), "gitdir: ") |
| 290 | if err != nil || !ok { |
| 291 | return nil, false |
| 292 | } |
| 293 | if !filepath.IsAbs(linked) { |
| 294 | linked = filepath.Join(dir, linked) |
| 295 | } |
| 296 | dirs := []string{linked} |
| 297 | if common, err := os.ReadFile(filepath.Join(linked, "commondir")); err == nil { |
| 298 | c := strings.TrimSpace(string(common)) |
| 299 | if !filepath.IsAbs(c) { |
| 300 | c = filepath.Join(linked, c) |
| 301 | } |
| 302 | dirs = append(dirs, c) |
| 303 | } |
| 304 | return dirs, true |
| 305 | } |
| 306 | parent := filepath.Dir(dir) |
| 307 | if parent == dir { |
| 308 | return nil, false |
| 309 | } |
| 310 | dir = parent |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | // startFlusher sends the spools in the background, in a session of its |
| 315 | // own, so the command neither waits for the host nor takes it down on |
| 316 | // exit. |
| 317 | func startFlusher() { |
| 318 | exe, err := os.Executable() |
| 319 | if err != nil { |
| 320 | return |
| 321 | } |
| 322 | cmd := exec.Command(exe, "telemetry", "flush", "--watch", strconv.Itoa(os.Getpid())) |
| 323 | cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| 324 | if cmd.Start() == nil { |
| 325 | _ = cmd.Process.Release() |
| 326 | } |
| 327 | } |