Debian Codegraph @

debian/go/src/golang.org/x/telemetry/start_test.go

raw symbols SCIP
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_test
6
7 import (
8 "io"
9 "log"
10 "net/http"
11 "net/http/httptest"
12 "os"
13 "os/exec"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "golang.org/x/telemetry"
20 "golang.org/x/telemetry/counter"
21 "golang.org/x/telemetry/counter/countertest"
22 "golang.org/x/telemetry/internal/configtest"
23 ic "golang.org/x/telemetry/internal/counter"
24 "golang.org/x/telemetry/internal/regtest"
25 it "golang.org/x/telemetry/internal/telemetry"
26 "golang.org/x/telemetry/internal/testenv"
27 )
28
29 // These environment variables are used to coordinate the fork+exec subprocess
30 // started by TestStart.
31 const (
32 runStartEnv = "X_TELEMETRY_TEST_START"
33 telemetryDirEnv = "X_TELEMETRY_TEST_START_TELEMETRY_DIR"
34 uploadURLEnv = "X_TELEMETRY_TEST_START_UPLOAD_URL"
35 asofEnv = "X_TELEMETRY_TEST_START_ASOF"
36 )
37
38 func TestMain(m *testing.M) {
39 // TestStart can't use internal/regtest, because Start itself also uses
40 // fork+exec to start a subprocess, which does not interact well with the
41 // fork+exec trick used by regtest.RunProg.
42 if prog := os.Getenv(runStartEnv); prog != "" {
43 os.Exit(runProg(prog))
44 }
45 os.Exit(m.Run())
46 }
47
48 // runProg runs the given program.
49 // See the switch statement below.
50 func runProg(prog string) int {
51
52 mustGetEnv := func(envvar string) string {
53 v := os.Getenv(envvar)
54 if v == "" {
55 log.Fatalf("missing required environment var %q", envvar)
56 }
57 return v
58 }
59
60 // Get the fake time used by all programs.
61 asof, err := time.Parse("2006-01-02", mustGetEnv(asofEnv))
62 if err != nil {
63 log.Fatalf("parsing %s: %v", asofEnv, err)
64 }
65
66 // Set global state.
67 ic.CounterTime = func() time.Time { return asof } // must be done before Open
68 countertest.Open(mustGetEnv(telemetryDirEnv))
69
70 switch prog {
71 case "setmode":
72 // Use the modified time above for the asof time.
73 if err := it.Default.SetModeAsOf("on", asof); err != nil {
74 log.Fatalf("setting mode: %v", err)
75 }
76 case "inc":
77 // (CounterTime is already set above)
78 counter.Inc("teststart/counter")
79
80 case "start":
81 res := telemetry.Start(telemetry.Config{
82 // No need to set TelemetryDir since the Default dir is already set by countertest.Open.
83 Upload: true,
84 UploadURL: mustGetEnv(uploadURLEnv),
85 UploadStartTime: asof,
86 })
87 res.Wait()
88 default:
89 log.Fatalf("unknown program %q", prog)
90 }
91 return 0
92 }
93
94 func execProg(t *testing.T, telemetryDir, prog string, asof time.Time, env ...string) {
95 // Run the runStart function below, via a fork+exec trick.
96 exe, err := os.Executable()
97 if err != nil {
98 t.Error(err)
99 return
100 }
101 cmd := exec.Command(exe, "** TestStart **") // this unused arg is just for ps(1)
102 cmd.Stderr = os.Stderr
103 cmd.Env = os.Environ()
104 cmd.Env = append(cmd.Env, asofEnv+"="+asof.Format("2006-01-02"))
105 cmd.Env = append(cmd.Env, telemetryDirEnv+"="+telemetryDir)
106 cmd.Env = append(cmd.Env, runStartEnv+"="+prog) // see TestMain
107 cmd.Env = append(cmd.Env, env...)
108 out, err := cmd.Output()
109 if err != nil {
110 t.Errorf("program failed unexpectedly (%v)\n%s", err, out)
111 }
112 }
113
114 func TestStart(t *testing.T) {
115 testenv.SkipIfUnsupportedPlatform(t)
116 testenv.MustHaveExec(t)
117
118 // This test sets up a telemetry environment, and then runs a test program
119 // that increments a counter, and uploads via telemetry.Start.
120
121 telemetryDir := t.TempDir()
122
123 uploaded := false
124 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
125 uploaded = true
126 body, err := io.ReadAll(r.Body)
127 if err != nil {
128 t.Errorf("error reading body: %v", err)
129 } else {
130 if body := string(body); !strings.Contains(body, "teststart/counter") {
131 t.Errorf("upload does not contain \"teststart/counter\":\n%s", body)
132 }
133 }
134 }))
135 uploadEnv := []string{uploadURLEnv + "=" + server.URL}
136
137 uc := regtest.CreateTestUploadConfig(t, []string{"teststart/counter"}, nil)
138 uploadEnv = append(uploadEnv, configtest.LocalProxyEnv(t, uc, "v1.2.3")...)
139
140 // Script programs.
141 now := time.Now()
142 execProg(t, telemetryDir, "setmode", now.Add(-30*24*time.Hour)) // back-date telemetry acceptance
143 execProg(t, telemetryDir, "inc", now.Add(-8*24*time.Hour)) // increment the counter
144 execProg(t, telemetryDir, "start", now, uploadEnv...) // run start
145
146 if !uploaded {
147 t.Fatalf("no upload occurred on %v", os.Getpid())
148 }
149 }
150
151 func TestConcurrentStart(t *testing.T) {
152 testenv.SkipIfUnsupportedPlatform(t)
153 testenv.MustHaveExec(t)
154
155 telemetryDir := t.TempDir()
156
157 var uploadMu sync.Mutex
158 uploads := map[string]int{} // date -> uploads
159 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
160 key := r.URL.Path
161 if idx := strings.LastIndex(r.URL.Path, "/"); idx >= 0 {
162 key = r.URL.Path[idx+len("/"):]
163 }
164 uploadMu.Lock()
165 uploads[key]++
166 uploadMu.Unlock()
167 }))
168 uploadEnv := []string{uploadURLEnv + "=" + server.URL}
169
170 uc := regtest.CreateTestUploadConfig(t, []string{"teststart/counter"}, nil)
171 uploadEnv = append(uploadEnv, configtest.LocalProxyEnv(t, uc, "v1.2.3")...)
172
173 now := time.Now()
174 execProg(t, telemetryDir, "setmode", now.Add(-365*24*time.Hour)) // back-date telemetry acceptance
175 execProg(t, telemetryDir, "inc", now.Add(-8*24*time.Hour)) // increment the counter
176
177 // Populate three weeks of counters to upload.
178 for i := -28; i < -7; i++ { // Populate three weeks of counters to upload.
179 execProg(t, telemetryDir, "inc", now.Add(time.Duration(i)*24*time.Hour))
180 }
181
182 // Run start concurrently.
183 var wg sync.WaitGroup
184 for i := 0; i < 10; i++ {
185 wg.Add(1)
186 go func() {
187 defer wg.Done()
188 execProg(t, telemetryDir, "start", now, uploadEnv...)
189 }()
190 }
191 wg.Wait()
192
193 // Expect exactly three weeks to be uploaded.
194 if got, want := len(uploads), 3; got != want {
195 t.Errorf("got %d report dates, want %d", got, want)
196 }
197 for asof, n := range uploads {
198 if n != 1 {
199 t.Errorf("got %d reports for %s, want 1", n, asof)
200 }
201 }
202 }