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