Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/upload/run_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 upload_test
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "net/http"
12 "net/http/httptest"
13 "os"
14 "path/filepath"
15 "regexp"
16 "runtime"
17 "strings"
18 "testing"
19 "time"
20
21 "golang.org/x/telemetry/counter"
22 "golang.org/x/telemetry/internal/configtest"
23 "golang.org/x/telemetry/internal/regtest"
24 "golang.org/x/telemetry/internal/telemetry"
25 "golang.org/x/telemetry/internal/testenv"
26 "golang.org/x/telemetry/internal/upload"
27 )
28
29 // runConfig sets up an upload environment for the provided test, with a
30 // fake proxy allowing the given counters, and a fake upload server.
31 //
32 // The returned RunConfig is ready to pass to Run to upload the given
33 // directory. The second return is a function to fetch all uploaded reports.
34 //
35 // For convenience, runConfig also sets the mode in telemetryDir to "on",
36 // back-dated to a time in the past. Callers that want to run the upload with a
37 // different mode can reset as necessary.
38 //
39 // All associated resources are cleaned up with t.Clean.
40 func runConfig(t *testing.T, telemetryDir string, counters, stackCounters []string) (upload.RunConfig, func() [][]byte) {
41 t.Helper()
42
43 if err := telemetry.NewDir(telemetryDir).SetModeAsOf("on", time.Now().Add(-365*24*time.Hour)); err != nil {
44 t.Fatal(err)
45 }
46
47 srv, uploaded := upload.CreateTestUploadServer(t)
48 uc := upload.CreateTestUploadConfig(t, counters, stackCounters)
49 env := configtest.LocalProxyEnv(t, uc, "v1.2.3")
50
51 return upload.RunConfig{
52 TelemetryDir: telemetryDir,
53 UploadURL: srv.URL,
54 LogWriter: testWriter{t},
55 Env: env,
56 }, uploaded
57 }
58
59 // testWriter is an io.Writer wrapping t.Log.
60 type testWriter struct {
61 t *testing.T
62 }
63
64 func (w testWriter) Write(p []byte) (n int, err error) {
65 w.t.Log(strings.TrimSuffix(string(p), "\n")) // trim newlines added by logging
66 return len(p), nil
67 }
68
69 func TestRun_Basic(t *testing.T) {
70 // Check the correctness of a single upload to the local server.
71
72 testenv.SkipIfUnsupportedPlatform(t)
73
74 prog := regtest.NewProgram(t, "prog", func() int {
75 counter.Inc("knownCounter")
76 counter.Inc("unknownCounter")
77 counter.NewStack("aStack", 4).Inc()
78 return 0
79 })
80
81 // produce a counter file (timestamped with "today")
82 telemetryDir := t.TempDir()
83 if out, err := regtest.RunProgAsOf(t, telemetryDir, time.Now().Add(-8*24*time.Hour), prog); err != nil {
84 t.Fatalf("failed to run program: %s", out)
85 }
86
87 // Running the program should produce a counter file.
88 checkTelemetryFiles(t, telemetryDir, telemetryFiles{counterFiles: 1})
89
90 // Aside: writing the "debug" file here reproduces a scenario observed in the
91 // past where the "debug" directory could not be read.
92 // (there is no issue to reference for additional context, unfortunately)
93 logName := filepath.Join(telemetryDir, "debug")
94 err := os.WriteFile(logName, nil, 0666) // must be done before calling Run
95 if err != nil {
96 t.Fatal(err)
97 }
98
99 // Run the upload.
100 cfg, getUploads := runConfig(t, telemetryDir, []string{"knownCounter", "aStack"}, nil)
101 if err := upload.Run(cfg); err != nil {
102 t.Fatal(err)
103 }
104
105 // The upload process should have deleted the counter file, and produced both
106 // a local and uploaded report.
107 checkTelemetryFiles(t, telemetryDir, telemetryFiles{localReports: 1, uploadedReports: 1})
108
109 // Check that the uploaded report matches our expectations exactly.
110 uploads := getUploads()
111 if len(uploads) != 1 {
112 t.Fatalf("got %d uploads, want 1", len(uploads))
113 }
114 var got telemetry.Report
115 if err := json.Unmarshal(uploads[0], &got); err != nil {
116 t.Fatal(err)
117 }
118 if got.Week == "" {
119 t.Errorf("Uploaded report missing Week field:\n%s", uploads[0])
120 }
121 if len(got.Programs) != 1 {
122 t.Fatalf("got %d uploaded programs, want 1", len(got.Programs))
123 }
124 gotProgram := got.Programs[0]
125 want := telemetry.Report{
126 Week: got.Week, // volatile
127 X: got.X, // volatile
128 Programs: []*telemetry.ProgramReport{{
129 Program: "upload.test",
130 Version: "",
131 GoVersion: gotProgram.GoVersion, // easiest to read this from the report
132 GOOS: runtime.GOOS,
133 GOARCH: runtime.GOARCH,
134 Counters: map[string]int64{
135 "knownCounter": 1,
136 },
137 Stacks: map[string]int64{},
138 }},
139 Config: "v1.2.3",
140 }
141 gotFormatted, err := json.MarshalIndent(got, "", "\t")
142 if err != nil {
143 t.Fatal(err)
144 }
145 wantFormatted, err := json.MarshalIndent(want, "", "\t")
146 if err != nil {
147 t.Fatal(err)
148 }
149 if got, want := string(gotFormatted), string(wantFormatted); got != want {
150 t.Errorf("Mismatching uploaded report:\ngot:\n%s\nwant:\n%s", got, want)
151 }
152 }
153
154 type telemetryFiles struct {
155 counterFiles int
156 localReports int
157 unuploadedReports int
158 uploadedReports int
159 // Other files like mode or weekends are intentionally omitted, because they
160 // are less interesting internal details.
161 }
162
163 // checkTelemetryFiles checks that the state of telemetryDir matches the
164 // desired telemetryFiles.
165 func checkTelemetryFiles(t *testing.T, telemetryDir string, want telemetryFiles) {
166 t.Helper()
167
168 dir := telemetry.NewDir(telemetryDir)
169
170 countFiles := func(dir, pattern string) int {
171 count := 0
172 fis, err := os.ReadDir(dir)
173 if err != nil {
174 return 0 // missing directory
175 }
176 re, err := regexp.Compile(pattern)
177 if err != nil {
178 t.Fatal(err)
179 }
180 for _, fi := range fis {
181 if re.MatchString(fi.Name()) {
182 count++
183 }
184 }
185 return count
186 }
187 got := telemetryFiles{
188 counterFiles: countFiles(dir.LocalDir(), `\.v1\.count`),
189 localReports: countFiles(dir.LocalDir(), `^local\..*\.json$`),
190 unuploadedReports: countFiles(dir.LocalDir(), `^[0-9].*\.json$`),
191 uploadedReports: countFiles(dir.UploadDir(), `^[0-9].*\.json$`),
192 }
193 if got != want {
194 t.Errorf("got telemetry files %+v, want %+v", got, want)
195 }
196 }
197
198 func TestRun_Retries(t *testing.T) {
199 // Check that the Run handles upload server status codes appropriately,
200 // and that retries behave as expected.
201
202 testenv.SkipIfUnsupportedPlatform(t)
203
204 prog := regtest.NewIncProgram(t, "prog", "counter")
205
206 tests := []struct {
207 initialStatus int
208 initialFiles telemetryFiles
209 filesAfterRetry telemetryFiles
210 }{
211 {
212 http.StatusOK,
213 telemetryFiles{localReports: 1, uploadedReports: 1},
214 telemetryFiles{localReports: 1, uploadedReports: 1},
215 },
216 {
217 http.StatusBadRequest,
218 telemetryFiles{localReports: 1},
219 telemetryFiles{localReports: 1},
220 },
221 {
222 http.StatusInternalServerError,
223 telemetryFiles{localReports: 1, unuploadedReports: 1},
224 telemetryFiles{localReports: 1, uploadedReports: 1},
225 },
226 }
227
228 for _, test := range tests {
229 t.Run(fmt.Sprint(test.initialStatus), func(t *testing.T) {
230 telemetryDir := t.TempDir()
231 if out, err := regtest.RunProgAsOf(t, telemetryDir, time.Now().Add(-8*24*time.Hour), prog); err != nil {
232 t.Fatalf("failed to run program: %s", out)
233 }
234
235 // Start an upload server that returns the given status code.
236 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
237 w.WriteHeader(test.initialStatus)
238 }))
239 t.Cleanup(srv.Close)
240
241 // Enable uploads.
242 dir := telemetry.NewDir(telemetryDir)
243 if err := dir.SetModeAsOf("on", time.Now().Add(-365*24*time.Hour)); err != nil {
244 t.Fatal(err)
245 }
246
247 // Write the proxy.
248 uc := upload.CreateTestUploadConfig(t, []string{"counter"}, nil)
249 env := configtest.LocalProxyEnv(t, uc, "v1.2.3")
250
251 // Run the upload.
252 badCfg := upload.RunConfig{
253 TelemetryDir: telemetryDir,
254 UploadURL: srv.URL,
255 Env: env,
256 }
257 if err := upload.Run(badCfg); err != nil {
258 t.Fatal(err)
259 }
260
261 // Check that the upload left the telemetry directory in the desired state.
262 checkTelemetryFiles(t, telemetryDir, test.initialFiles)
263
264 // Now re-run the upload with a succeeding upload server.
265 goodCfg, _ := runConfig(t, telemetryDir, []string{"counter"}, nil)
266 if err := upload.Run(goodCfg); err != nil {
267 t.Fatal(err)
268 }
269
270 // Check files after retrying.
271 checkTelemetryFiles(t, telemetryDir, test.filesAfterRetry)
272 })
273 }
274 }
275
276 func TestRun_MultipleUploads(t *testing.T) {
277 // This test checks that [upload.Run] produces multiple reports when counters
278 // span more than a week.
279
280 testenv.SkipIfUnsupportedPlatform(t)
281
282 // This program is run at two different dates.
283 prog := regtest.NewIncProgram(t, "prog", "counter1")
284
285 // Create two counter files to upload, at least a week apart.
286 telemetryDir := t.TempDir()
287 asof1 := time.Now().Add(-15 * 24 * time.Hour)
288 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof1, prog); err != nil {
289 t.Fatalf("failed to run program: %s", out)
290 }
291 asof2 := time.Now().Add(-8 * 24 * time.Hour)
292 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof2, prog); err != nil {
293 t.Fatalf("failed to run program: %s", out)
294 }
295
296 cfg, getUploads := runConfig(t, telemetryDir, []string{"counter1", "counter2"}, nil)
297 if err := upload.Run(cfg); err != nil {
298 t.Fatal(err)
299 }
300
301 uploads := getUploads()
302 if got, want := len(uploads), 2; got != want {
303 t.Fatalf("got %d uploads, want %d", got, want)
304 }
305 for _, upload := range uploads {
306 report := string(upload)
307 if !strings.Contains(report, "counter1") {
308 t.Errorf("Didn't get an upload for counter1. Report:\n%s", report)
309 }
310 }
311 }
312
313 func TestRun_EmptyUpload(t *testing.T) {
314 // This test verifies that an empty counter file does not cause uploads of
315 // another week's reports to fail.
316
317 testenv.SkipIfUnsupportedPlatform(t)
318
319 // prog1 runs in week 1, and increments no counter.
320 prog1 := regtest.NewIncProgram(t, "prog1")
321 // prog2 runs in week 2.
322 prog2 := regtest.NewIncProgram(t, "prog2", "week2")
323
324 telemetryDir := t.TempDir()
325
326 // Create two counter files to upload, at least a week apart.
327 // Week 1 has no counters, which in the past caused the both uploads to fail.
328 asof1 := time.Now().Add(-15 * 24 * time.Hour)
329 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof1, prog1); err != nil {
330 t.Fatalf("failed to run program: %s", out)
331 }
332 asof2 := time.Now().Add(-8 * 24 * time.Hour)
333 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof2, prog2); err != nil {
334 t.Fatalf("failed to run program: %s", out)
335 }
336
337 cfg, getUploads := runConfig(t, telemetryDir, []string{"week1", "week2"}, nil)
338 if err := upload.Run(cfg); err != nil {
339 t.Fatal(err)
340 }
341
342 // Check that we got one upload, for week 2.
343 uploads := getUploads()
344 if got, want := len(uploads), 1; got != want {
345 t.Fatalf("got %d uploads, want %d", got, want)
346 }
347 for _, upload := range uploads {
348 report := string(upload)
349 if !strings.Contains(report, "week2") {
350 t.Errorf("Didn't get an upload for week2. Report:\n%s", report)
351 }
352 }
353 }
354
355 func TestRun_MissingDate(t *testing.T) {
356 // This test verifies that a counter file with corrupt metadata does not
357 // prevent the uploader from uploading another week's reports.
358
359 testenv.SkipIfUnsupportedPlatform(t)
360
361 prog := regtest.NewIncProgram(t, "prog", "counter")
362
363 telemetryDir := t.TempDir()
364
365 // Create two counter files to upload, a week apart.
366 asof1 := time.Now().Add(-15 * 24 * time.Hour)
367 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof1, prog); err != nil {
368 t.Fatalf("failed to run program: %s", out)
369 }
370
371 // Corrupt the week 1 counter file.
372 {
373 localDir := telemetry.NewDir(telemetryDir).LocalDir()
374 fis, err := os.ReadDir(localDir)
375 if err != nil {
376 t.Fatal(err)
377 }
378 var countFiles []string
379 for _, fi := range fis {
380 if strings.HasSuffix(fi.Name(), ".v1.count") {
381 countFiles = append(countFiles, filepath.Join(localDir, fi.Name()))
382 }
383 }
384 if len(countFiles) != 1 {
385 t.Fatalf("after first RunProgAsOf, found %d count files, want 1", len(countFiles))
386 }
387 countFile := countFiles[0]
388 data, err := os.ReadFile(countFile)
389 if err != nil {
390 t.Fatal(err)
391 }
392 // Importantly, the byte replacement here has the same length.
393 // If not, the entire file (and not just metadata) would be corrupt, due to
394 // the header length mismatch.
395 corrupted := bytes.Replace(data, []byte(`TimeBegin:`), []byte(`TimxBegin:`), 1)
396 if err := os.WriteFile(countFile, corrupted, 0666); err != nil {
397 t.Fatal(err)
398 }
399 }
400
401 asof2 := time.Now().Add(-8 * 24 * time.Hour)
402 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof2, prog); err != nil {
403 t.Fatalf("failed to run program: %s", out)
404 }
405
406 cfg, getUploads := runConfig(t, telemetryDir, []string{"counter"}, nil)
407 if err := upload.Run(cfg); err != nil {
408 t.Fatal(err)
409 }
410
411 // Check that we got one upload, for week 2.
412 uploads := getUploads()
413 if got, want := len(uploads), 1; got != want {
414 t.Fatalf("got %d uploads, want %d", got, want)
415 }
416 report := string(uploads[0])
417 if !strings.Contains(report, "counter") {
418 t.Errorf("Didn't get an upload for counter. Report:\n%s", report)
419 }
420 }
421
422 func TestRun_ModeHandling(t *testing.T) {
423 // This test verifies that the uploader honors the telemetry mode, as well as
424 // its asof date.
425
426 testenv.SkipIfUnsupportedPlatform(t)
427
428 prog := regtest.NewIncProgram(t, "prog1", "counter")
429
430 tests := []struct {
431 mode string
432 wantUploads int
433 }{
434 {"off", 0},
435 {"local", 0},
436 {"on", 1}, // only the second week is uploadable
437 }
438 for _, test := range tests {
439 t.Run(test.mode, func(t *testing.T) {
440 telemetryDir := t.TempDir()
441 // Create two counter files to upload, at least a week apart.
442 now := time.Now()
443 asof1 := now.Add(-15 * 24 * time.Hour)
444 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof1, prog); err != nil {
445 t.Fatalf("failed to run program: %s", out)
446 }
447 asof2 := now.Add(-8 * 24 * time.Hour)
448 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof2, prog); err != nil {
449 t.Fatalf("failed to run program: %s", out)
450 }
451
452 cfg, getUploads := runConfig(t, telemetryDir, []string{"counter"}, nil)
453
454 // Enable telemetry as of 10 days ago. This should prevent the first week
455 // from being uploaded, but not the second.
456 if err := telemetry.NewDir(telemetryDir).SetModeAsOf(test.mode, now.Add(-10*24*time.Hour)); err != nil {
457 t.Fatal(err)
458 }
459
460 if err := upload.Run(cfg); err != nil {
461 t.Fatal(err)
462 }
463
464 uploads := getUploads()
465 if gotUploads := len(uploads); gotUploads != test.wantUploads {
466 t.Fatalf("got %d uploads, want %d", gotUploads, test.wantUploads)
467 }
468 })
469 }
470 }
471 func TestRun_DebugLog(t *testing.T) {
472 // This test verifies that the uploader honors the telemetry mode, as well as
473 // its asof date.
474
475 testenv.SkipIfUnsupportedPlatform(t)
476
477 prog := regtest.NewIncProgram(t, "prog1", "counter")
478
479 tests := []struct {
480 name string
481 setup func(t *testing.T) (telemetryDir string, err error)
482 wantDebugLogs int
483 wantUploads int
484 }{
485 {
486 name: "valid",
487 setup: func(t *testing.T) (string, error) {
488 userConfigDir := "user config" // test use of space in the name
489 if runtime.GOOS == "windows" {
490 userConfigDir = "userconfig" // windows doesn't allow space in dir name
491 }
492 telemetryDir := filepath.Join(t.TempDir(), userConfigDir)
493 return telemetryDir, os.MkdirAll(filepath.Join(telemetryDir, "debug"), 0755)
494 },
495 wantDebugLogs: 1,
496 wantUploads: 1,
497 },
498 {
499 name: "nodebug",
500 setup: func(t *testing.T) (string, error) {
501 return t.TempDir(), nil
502 },
503 wantUploads: 1,
504 },
505 {
506 name: "not a directory", // debug log setup error shouldn't prevent uploading.
507 setup: func(t *testing.T) (string, error) {
508 telemetryDir := t.TempDir()
509 return telemetryDir, os.WriteFile(filepath.Join(telemetryDir, "debug"), nil, 0666)
510 },
511 wantUploads: 1,
512 },
513 }
514 for _, test := range tests {
515 t.Run(test.name, func(t *testing.T) {
516 telemetryDir, err := test.setup(t)
517 if err != nil {
518 t.Fatalf("failed to configure the telemetry and debug directories: %v", err)
519 }
520 now := time.Now()
521 asof := now.Add(-8 * 24 * time.Hour)
522 if out, err := regtest.RunProgAsOf(t, telemetryDir, asof, prog); err != nil {
523 t.Fatalf("failed to run program: %s", out)
524 }
525
526 cfg, getUploads := runConfig(t, telemetryDir, []string{"counter"}, nil)
527 if err := upload.Run(cfg); err != nil {
528 t.Fatal(err)
529 }
530
531 uploads := getUploads()
532 if gotUploads := len(uploads); gotUploads != test.wantUploads {
533 t.Errorf("got %d uploads, want %d", gotUploads, test.wantUploads)
534 }
535 debugLogs := getDebugLogs(t, filepath.Join(telemetryDir, "debug"))
536 if gotDebugLogs := len(debugLogs); gotDebugLogs != test.wantDebugLogs {
537 t.Fatalf("got %d debug logs, want %d", gotDebugLogs, test.wantDebugLogs)
538 }
539 })
540 }
541 }
542
543 func getDebugLogs(t *testing.T, debugDir string) []string {
544 t.Helper()
545 if stat, err := os.Stat(debugDir); err != nil || !stat.IsDir() {
546 return nil
547 }
548 files, err := os.ReadDir(debugDir)
549 if err != nil {
550 return nil
551 }
552 var ret []string
553 for _, f := range files {
554 if !strings.HasSuffix(f.Name(), ".log") {
555 t.Logf("Ignoring %v", f.Name())
556 continue
557 }
558 contents, err := os.ReadFile(filepath.Join(debugDir, f.Name()))
559 if err != nil || !bytes.Contains(contents, []byte("mode on")) {
560 t.Logf("Ignoring %v - unreadable or unexpected contents (err: %v)", f.Name(), err)
561 continue
562 }
563 ret = append(ret, f.Name())
564 }
565 return ret
566 }