| 1 | // Copyright 2024 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package telemetry |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "log" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "golang.org/x/sync/errgroup" |
| 17 | "golang.org/x/telemetry/counter" |
| 18 | "golang.org/x/telemetry/internal/crashmonitor" |
| 19 | "golang.org/x/telemetry/internal/telemetry" |
| 20 | "golang.org/x/telemetry/internal/upload" |
| 21 | ) |
| 22 | |
| 23 | // Config controls the behavior of [Start]. |
| 24 | type Config struct { |
| 25 | // ReportCrashes, if set, will enable crash reporting. |
| 26 | // ReportCrashes uses the [debug.SetCrashOutput] mechanism, which is a |
| 27 | // process-wide resource. |
| 28 | // Do not make other calls to that function within your application. |
| 29 | // ReportCrashes is a non-functional unless the program is built with go1.23+. |
| 30 | ReportCrashes bool |
| 31 | |
| 32 | // Upload causes this program to periodically upload approved counters |
| 33 | // from the local telemetry database to telemetry.go.dev. |
| 34 | // |
| 35 | // This option has no effect unless the user has given consent |
| 36 | // to enable data collection, for example by running |
| 37 | // cmd/gotelemetry or affirming the gopls dialog. |
| 38 | // |
| 39 | // (This feature is expected to be used only by gopls. |
| 40 | // Longer term, the go command may become the sole program |
| 41 | // responsible for uploading.) |
| 42 | Upload bool |
| 43 | |
| 44 | // TelemetryDir, if set, will specify an alternate telemetry |
| 45 | // directory to write data to. If not set, it uses the default |
| 46 | // directory. |
| 47 | // This field is intended to be used for isolating testing environments. |
| 48 | TelemetryDir string |
| 49 | |
| 50 | // UploadStartTime, if set, overrides the time used as the upload start time, |
| 51 | // which is the time used by the upload logic to determine whether counter |
| 52 | // file data should be uploaded. Only counter files that have expired before |
| 53 | // the start time are considered for upload. |
| 54 | // |
| 55 | // This field can be used to simulate a future upload that collects recently |
| 56 | // modified counters. |
| 57 | UploadStartTime time.Time |
| 58 | |
| 59 | // UploadURL, if set, overrides the URL used to receive uploaded reports. If |
| 60 | // unset, this URL defaults to https://telemetry.go.dev/upload. |
| 61 | UploadURL string |
| 62 | } |
| 63 | |
| 64 | // Start initializes telemetry using the specified configuration. |
| 65 | // |
| 66 | // Start opens the local telemetry database so that counter increment |
| 67 | // operations are durably recorded in the local file system. |
| 68 | // |
| 69 | // If [Config.Upload] is set, and the user has opted in to telemetry |
| 70 | // uploading, this process may attempt to upload approved counters |
| 71 | // to telemetry.go.dev. |
| 72 | // |
| 73 | // If [Config.ReportCrashes] is set, any fatal crash will be |
| 74 | // recorded by incrementing a counter named for the stack of the |
| 75 | // first running goroutine in the traceback. |
| 76 | // |
| 77 | // If either of these flags is set, Start re-executes the current |
| 78 | // executable as a child process, in a special mode in which it |
| 79 | // acts as a telemetry sidecar for the parent process (the application). |
| 80 | // In that mode, the call to Start will never return, so Start must |
| 81 | // be called immediately within main, even before such things as |
| 82 | // inspecting the command line. The application should avoid expensive |
| 83 | // steps or external side effects in init functions, as they will |
| 84 | // be executed twice (parent and child). |
| 85 | // |
| 86 | // Start returns a StartResult, which may be awaited via [StartResult.Wait] to |
| 87 | // wait for all work done by Start to complete. |
| 88 | func Start(config Config) *StartResult { |
| 89 | if config.TelemetryDir != "" { |
| 90 | telemetry.Default = telemetry.NewDir(config.TelemetryDir) |
| 91 | } |
| 92 | result := new(StartResult) |
| 93 | |
| 94 | mode, _ := telemetry.Default.Mode() |
| 95 | if mode == "off" { |
| 96 | // Telemetry is turned off. Crash reporting doesn't work without telemetry |
| 97 | // at least set to "local". The upload process runs in both "on" and "local" modes. |
| 98 | // In local mode the upload process builds local reports but does not do the upload. |
| 99 | return result |
| 100 | } |
| 101 | |
| 102 | counter.Open() |
| 103 | |
| 104 | if _, err := os.Stat(telemetry.Default.LocalDir()); err != nil { |
| 105 | // There was a problem statting LocalDir, which is needed for both |
| 106 | // crash monitoring and counter uploading. Most likely, there was an |
| 107 | // error creating telemetry.LocalDir in the counter.Open call above. |
| 108 | // Don't start the child. |
| 109 | return result |
| 110 | } |
| 111 | |
| 112 | var reportCrashes = config.ReportCrashes && crashmonitor.Supported() |
| 113 | |
| 114 | switch v := os.Getenv(telemetryChildVar); v { |
| 115 | case "": |
| 116 | // The subprocess started by parent has GO_TELEMETRY_CHILD=1. |
| 117 | childShouldUpload := config.Upload && acquireUploadToken() |
| 118 | if reportCrashes || childShouldUpload { |
| 119 | parent(reportCrashes, childShouldUpload, result) |
| 120 | } |
| 121 | case "1": |
| 122 | // golang/go#67211: be sure to set telemetryChildVar before running the |
| 123 | // child, because the child itself invokes the go command to download the |
| 124 | // upload config. If the telemetryChildVar variable is still set to "1", |
| 125 | // that delegated go command may think that it is itself a telemetry |
| 126 | // child. |
| 127 | // |
| 128 | // On the other hand, if telemetryChildVar were simply unset, then the |
| 129 | // delegated go commands would fork themselves recursively. Short-circuit |
| 130 | // this recursion. |
| 131 | os.Setenv(telemetryChildVar, "2") |
| 132 | upload := os.Getenv(telemetryUploadVar) == "1" |
| 133 | child(reportCrashes, upload, config.UploadStartTime, config.UploadURL) |
| 134 | os.Exit(0) |
| 135 | case "2": |
| 136 | // Do nothing: see note above. |
| 137 | default: |
| 138 | log.Fatalf("unexpected value for %q: %q", telemetryChildVar, v) |
| 139 | } |
| 140 | |
| 141 | return result |
| 142 | } |
| 143 | |
| 144 | // A StartResult is a handle to the result of a call to [Start]. Call |
| 145 | // [StartResult.Wait] to wait for the completion of all work done on behalf of |
| 146 | // Start. |
| 147 | type StartResult struct { |
| 148 | wg sync.WaitGroup |
| 149 | } |
| 150 | |
| 151 | // Wait waits for the completion of all work initiated by [Start]. |
| 152 | func (res *StartResult) Wait() { |
| 153 | if res == nil { |
| 154 | return |
| 155 | } |
| 156 | res.wg.Wait() |
| 157 | } |
| 158 | |
| 159 | var daemonize = func(cmd *exec.Cmd) {} |
| 160 | |
| 161 | // If telemetryChildVar is set to "1" in the environment, this is the telemetry |
| 162 | // child. |
| 163 | // |
| 164 | // If telemetryChildVar is set to "2", this is a child of the child, and no |
| 165 | // further forking should occur. |
| 166 | const telemetryChildVar = "GO_TELEMETRY_CHILD" |
| 167 | |
| 168 | // If telemetryUploadVar is set to "1" in the environment, the upload token has been |
| 169 | // acquired by the parent, and the child should attempt an upload. |
| 170 | const telemetryUploadVar = "GO_TELEMETRY_CHILD_UPLOAD" |
| 171 | |
| 172 | func parent(reportCrashes, upload bool, result *StartResult) { |
| 173 | // This process is the application (parent). |
| 174 | // Fork+exec the telemetry child. |
| 175 | exe, err := os.Executable() |
| 176 | if err != nil { |
| 177 | // There was an error getting os.Executable. It's possible |
| 178 | // for this to happen on AIX if os.Args[0] is not an absolute |
| 179 | // path and we can't find os.Args[0] in PATH. |
| 180 | log.Printf("failed to start telemetry sidecar: os.Executable: %v", err) |
| 181 | return |
| 182 | } |
| 183 | cmd := exec.Command(exe, "** telemetry **") // this unused arg is just for ps(1) |
| 184 | daemonize(cmd) |
| 185 | cmd.Env = append(os.Environ(), telemetryChildVar+"=1") |
| 186 | if upload { |
| 187 | cmd.Env = append(cmd.Env, telemetryUploadVar+"=1") |
| 188 | } |
| 189 | cmd.Dir = telemetry.Default.LocalDir() |
| 190 | |
| 191 | // The child process must write to a log file, not |
| 192 | // the stderr file it inherited from the parent, as |
| 193 | // the child may outlive the parent but should not prolong |
| 194 | // the life of any pipes created (by the grandparent) |
| 195 | // to gather the output of the parent. |
| 196 | // |
| 197 | // By default, we discard the child process's stderr, |
| 198 | // but in line with the uploader, log to a file in debug |
| 199 | // only if that directory was created by the user. |
| 200 | fd, err := os.Stat(telemetry.Default.DebugDir()) |
| 201 | if err != nil { |
| 202 | if !os.IsNotExist(err) { |
| 203 | log.Fatalf("failed to stat debug directory: %v", err) |
| 204 | } |
| 205 | } else if fd.IsDir() { |
| 206 | // local/debug exists and is a directory. Set stderr to a log file path |
| 207 | // in local/debug. |
| 208 | childLogPath := filepath.Join(telemetry.Default.DebugDir(), "sidecar.log") |
| 209 | childLog, err := os.OpenFile(childLogPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) |
| 210 | if err != nil { |
| 211 | log.Fatalf("opening sidecar log file for child: %v", err) |
| 212 | } |
| 213 | defer childLog.Close() |
| 214 | cmd.Stderr = childLog |
| 215 | } |
| 216 | |
| 217 | if reportCrashes { |
| 218 | pipe, err := cmd.StdinPipe() |
| 219 | if err != nil { |
| 220 | log.Fatalf("StdinPipe: %v", err) |
| 221 | } |
| 222 | |
| 223 | crashmonitor.Parent(pipe.(*os.File)) // (this conversion is safe) |
| 224 | } |
| 225 | |
| 226 | if err := cmd.Start(); err != nil { |
| 227 | log.Fatalf("can't start telemetry child process: %v", err) |
| 228 | } |
| 229 | result.wg.Add(1) |
| 230 | go func() { |
| 231 | cmd.Wait() // Release resources if cmd happens not to outlive this process. |
| 232 | result.wg.Done() |
| 233 | }() |
| 234 | } |
| 235 | |
| 236 | func child(reportCrashes, upload bool, uploadStartTime time.Time, uploadURL string) { |
| 237 | log.SetPrefix(fmt.Sprintf("telemetry-sidecar (pid %v): ", os.Getpid())) |
| 238 | |
| 239 | // Start crashmonitoring and uploading depending on what's requested |
| 240 | // and wait for the longer running child to complete before exiting: |
| 241 | // if we collected a crash before the upload finished, wait for the |
| 242 | // upload to finish before exiting |
| 243 | var g errgroup.Group |
| 244 | |
| 245 | if reportCrashes { |
| 246 | g.Go(func() error { |
| 247 | crashmonitor.Child() |
| 248 | return nil |
| 249 | }) |
| 250 | } |
| 251 | if upload { |
| 252 | g.Go(func() error { |
| 253 | uploaderChild(uploadStartTime, uploadURL) |
| 254 | return nil |
| 255 | }) |
| 256 | } |
| 257 | g.Wait() |
| 258 | } |
| 259 | |
| 260 | func uploaderChild(asof time.Time, uploadURL string) { |
| 261 | if err := upload.Run(upload.RunConfig{ |
| 262 | UploadURL: uploadURL, |
| 263 | LogWriter: os.Stderr, |
| 264 | StartTime: asof, |
| 265 | }); err != nil { |
| 266 | log.Printf("upload failed: %v", err) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // acquireUploadToken acquires a token permitting the caller to upload. |
| 271 | // To limit the frequency of uploads, only one token is issue per |
| 272 | // machine per time period. |
| 273 | // The boolean indicates whether the token was acquired. |
| 274 | func acquireUploadToken() bool { |
| 275 | if telemetry.Default.LocalDir() == "" { |
| 276 | // The telemetry dir wasn't initialized properly, probably because |
| 277 | // os.UserConfigDir did not complete successfully. In that case |
| 278 | // there are no counters to upload, so we should just do nothing. |
| 279 | return false |
| 280 | } |
| 281 | tokenfile := filepath.Join(telemetry.Default.LocalDir(), "upload.token") |
| 282 | const period = 24 * time.Hour |
| 283 | |
| 284 | // A process acquires a token by successfully creating a |
| 285 | // well-known file. If the file already exists and has an |
| 286 | // mtime age less then than the period, the process does |
| 287 | // not acquire the token. If the file is older than the |
| 288 | // period, the process is allowed to remove the file and |
| 289 | // try to re-create it. |
| 290 | fi, err := os.Stat(tokenfile) |
| 291 | if err == nil { |
| 292 | if time.Since(fi.ModTime()) < period { |
| 293 | return false |
| 294 | } |
| 295 | // There's a possible race here where two processes check the |
| 296 | // token file and see that it's older than the period, then the |
| 297 | // first one removes it and creates another, and then a second one |
| 298 | // removes the newly created file and creates yet another |
| 299 | // file. Then both processes would act as though they had the token. |
| 300 | // This is very rare, but it's also okay because we're only grabbing |
| 301 | // the token to do rate limiting, not for correctness. |
| 302 | _ = os.Remove(tokenfile) |
| 303 | } else if !os.IsNotExist(err) { |
| 304 | log.Printf("error acquiring upload taken: statting token file: %v", err) |
| 305 | return false |
| 306 | } |
| 307 | |
| 308 | f, err := os.OpenFile(tokenfile, os.O_CREATE|os.O_EXCL, 0666) |
| 309 | if err != nil { |
| 310 | if os.IsExist(err) { |
| 311 | return false |
| 312 | } |
| 313 | log.Printf("error acquiring upload token: creating token file: %v", err) |
| 314 | return false |
| 315 | } |
| 316 | _ = f.Close() |
| 317 | return true |
| 318 | } |