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