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