Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/counter/counter_test.go

raw symbols SCIP
1 // Copyright 2023 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 counter
6
7 // Builders at
8 // https://build.golang.org/?repo=golang.org%2fx%2ftelemetry
9
10 // there are troubles with tests in Windows. all open files have to
11 // be closed by the test so the test directory can be removed.
12 // Once defaultFile is closed, no more tests can be run as
13 // Open() will fault. (This is mysterious.)
14
15 import (
16 "bytes"
17 "encoding/hex"
18 "fmt"
19 "log"
20 "os"
21 "path/filepath"
22 "reflect"
23 "runtime"
24 "strings"
25 "sync"
26 "testing"
27 "time"
28
29 "golang.org/x/telemetry/internal/telemetry"
30 "golang.org/x/telemetry/internal/testenv"
31 )
32
33 func TestBasic(t *testing.T) {
34 testenv.SkipIfUnsupportedPlatform(t)
35
36 t.Logf("GOOS %s GOARCH %s", runtime.GOOS, runtime.GOARCH)
37 setup(t)
38 defer restore()
39 var f file
40 defer close(&f)
41 c := f.New("gophers")
42 c.Add(9)
43 f.rotate()
44 if f.err != nil {
45 t.Fatal(f.err)
46 }
47 current := f.current.Load()
48 if current == nil {
49 t.Fatal("no mapped file")
50 }
51 c.Add(0x90)
52
53 name := current.f.Name()
54 t.Logf("wrote %s:\n%s", name, hexDump(current.mapping.Data))
55
56 data, err := os.ReadFile(name)
57 if err != nil {
58 t.Fatal(err)
59 }
60 pf, err := Parse(name, data)
61 if err != nil {
62 t.Fatal(err)
63 }
64
65 want := map[string]uint64{"gophers": 0x99}
66 if !reflect.DeepEqual(pf.Count, want) {
67 t.Errorf("pf.Count = %v, want %v", pf.Count, want)
68 }
69 }
70
71 func TestMissingLocalDir(t *testing.T) {
72 testenv.SkipIfUnsupportedPlatform(t)
73 err := os.RemoveAll(telemetry.Default.LocalDir())
74 if err != nil {
75 t.Fatal(err)
76 }
77 TestBasic(t)
78 }
79
80 func TestParallel(t *testing.T) {
81 testenv.SkipIfUnsupportedPlatform(t)
82
83 t.Logf("GOOS %s GOARCH %s", runtime.GOOS, runtime.GOARCH)
84 setup(t)
85 defer restore()
86 var f file
87 defer close(&f)
88 c := f.New("manygophers")
89
90 var wg sync.WaitGroup
91 wg.Add(100)
92 for i := 0; i < 100; i++ {
93 go func() {
94 c.Inc()
95 wg.Done()
96 }()
97 }
98 wg.Wait()
99 f.rotate()
100 if f.err != nil {
101 t.Fatal(f.err)
102 }
103 current := f.current.Load()
104 if current == nil {
105 t.Fatal("no mapped file")
106 }
107 name := current.f.Name()
108 t.Logf("wrote %s:\n%s", name, hexDump(current.mapping.Data))
109
110 data, err := os.ReadFile(name)
111 if err != nil {
112 t.Fatal(err)
113 }
114 pf, err := Parse(name, data)
115 if err != nil {
116 t.Fatal(err)
117 }
118
119 want := map[string]uint64{"manygophers": 100}
120 if !reflect.DeepEqual(pf.Count, want) {
121 t.Errorf("pf.Count = %v, want %v", pf.Count, want)
122 }
123 }
124
125 // this is needed in Windows so that the generated testing.go file
126 // can clean up the temporary test directory
127 func close(f *file) {
128 mf := f.current.Load()
129 if mf == nil {
130 // telemetry might have been off
131 return
132 }
133 mf.close()
134 }
135
136 func TestLarge(t *testing.T) {
137 testenv.SkipIfUnsupportedPlatform(t)
138 t.Logf("GOOS %s GOARCH %s", runtime.GOOS, runtime.GOARCH)
139 setup(t)
140 defer restore()
141 var f file
142 defer close(&f)
143 f.rotate()
144 for i := int64(0); i < 10000; i++ {
145 c := f.New(fmt.Sprint("gophers", i))
146 c.Add(i*i + 1)
147 }
148 for i := int64(0); i < 10000; i++ {
149 c := f.New(fmt.Sprint("gophers", i))
150 c.Add(i / 2)
151 }
152 current := f.current.Load()
153 if current == nil {
154 t.Fatal("no mapped file")
155 }
156 name := current.f.Name()
157
158 data, err := os.ReadFile(name)
159 if err != nil {
160 t.Fatal(err)
161 }
162 pf, err := Parse(name, data)
163 if err != nil {
164 t.Fatal(err)
165 }
166
167 var errcnt int
168 for i := uint64(0); i < 10000; i++ {
169 key := fmt.Sprint("gophers", i)
170 want := 1 + i*i + i/2
171 if n := pf.Count[key]; n != want {
172 // print out the first few errors
173 t.Errorf("Count[%s] = %d, want %d", key, n, want)
174 errcnt++
175 if errcnt > 5 {
176 return
177 }
178 }
179 }
180 }
181
182 func TestRepeatedNew(t *testing.T) {
183 testenv.SkipIfUnsupportedPlatform(t)
184
185 t.Logf("GOOS %s GOARCH %s", runtime.GOOS, runtime.GOARCH)
186 setup(t)
187 defer restore()
188 var f file
189 defer close(&f)
190 f.rotate()
191 f.New("gophers")
192 c1ptr := f.lookup("gophers")
193 f.New("gophers")
194 c2ptr := f.lookup("gophers")
195 if c1ptr != c2ptr {
196 t.Errorf("c1ptr = %p, c2ptr = %p, want same", c1ptr, c2ptr)
197 }
198 }
199
200 func hexDump(data []byte) string {
201 lines := strings.SplitAfter(hex.Dump(data), "\n")
202 var keep []string
203 for len(lines) > 0 {
204 line := lines[0]
205 keep = append(keep, line)
206 lines = lines[1:]
207 const allZeros = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
208 if strings.Contains(line, allZeros) {
209 i := 0
210 for i < len(lines) && strings.Contains(lines[i], allZeros) {
211 i++
212 }
213 if i > 2 {
214 keep = append(keep, "*\n", lines[i-1])
215 lines = lines[i:]
216 }
217 }
218 }
219 return strings.Join(keep, "")
220 }
221
222 func TestNewFile(t *testing.T) {
223 testenv.SkipIfUnsupportedPlatform(t)
224
225 t.Logf("GOOS %s GOARCH %s", runtime.GOOS, runtime.GOARCH)
226 setup(t)
227 defer restore()
228 now := CounterTime().UTC()
229 year, month, day := now.Date()
230 // preserve time location as done in (*file).filename.
231 testStartTime := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
232
233 // test that completely new files have dates well in the future
234 // Try 20 times to get 20 different random numbers.
235 for i := 0; i < 20; i++ {
236 var f file
237 c := f.New("gophers")
238 // shouldn't see a file yet
239 fi, err := os.ReadDir(telemetry.Default.LocalDir())
240 if err != nil {
241 t.Fatal(err)
242 }
243 if len(fi) != 0 {
244 t.Fatalf("len(fi) = %d, want 0", len(fi))
245 }
246 c.Add(9)
247 // still shouldn't see a file
248 fi, err = os.ReadDir(telemetry.Default.LocalDir())
249 if err != nil {
250 close(&f)
251 t.Fatal(err)
252 }
253 if len(fi) != 0 {
254 close(&f)
255 t.Fatalf("len(fi) = %d, want 0", len(fi))
256 }
257 f.rotate()
258 // now we should see a count file and a weekends file
259 fi, _ = os.ReadDir(telemetry.Default.LocalDir())
260 if len(fi) != 2 {
261 close(&f)
262 t.Fatalf("len(fi) = %d, want 2", len(fi))
263 }
264 var countFile, weekendsFile string
265 for _, f := range fi {
266 switch f.Name() {
267 case "weekends":
268 weekendsFile = f.Name()
269 // while we're here, check that is ok
270 buf, err := os.ReadFile(filepath.Join(telemetry.Default.LocalDir(), weekendsFile))
271 if err != nil {
272 t.Fatal(err)
273 }
274 buf = bytes.TrimSpace(buf)
275 if len(buf) == 0 || buf[0] < '0' || buf[0] >= '7' {
276 t.Errorf("weekends file has bad data: %q", buf)
277 }
278 default:
279 countFile = f.Name()
280 }
281 }
282
283 buf, err := os.ReadFile(filepath.Join(telemetry.Default.LocalDir(), countFile))
284 if err != nil {
285 close(&f)
286 t.Fatal(err)
287 }
288 cf, err := Parse(countFile, buf)
289 if err != nil {
290 close(&f)
291 t.Fatal(err)
292 }
293 timeEnd, err := time.Parse(time.RFC3339, cf.Meta["TimeEnd"])
294 if err != nil {
295 close(&f)
296 t.Fatal(err)
297 }
298 days := (timeEnd.Sub(testStartTime)) / (24 * time.Hour)
299 if days <= 0 || days > 7 {
300 timeBegin, _ := time.Parse(time.RFC3339, cf.Meta["TimeBegin"])
301 t.Logf("testStartTime: %v file: %v TimeBegin: %v TimeEnd: %v", testStartTime, fi[0].Name(), timeBegin, timeEnd)
302 t.Errorf("%d: days = %d, want 7 < days <= 14", i, days)
303 }
304 close(&f)
305 // remove the file for the next iteration of the loop
306 os.Remove(filepath.Join(telemetry.Default.LocalDir(), countFile))
307 os.Remove(filepath.Join(telemetry.Default.LocalDir(), weekendsFile))
308 }
309 }
310
311 func TestWeekends(t *testing.T) {
312 testenv.SkipIfUnsupportedPlatform(t)
313
314 setup(t)
315 // get all the 49 combinations of today and when the week ends
316 for i := 0; i < 7; i++ {
317 CounterTime = future(i)
318 for index := range "0123456" {
319 os.WriteFile(filepath.Join(telemetry.Default.LocalDir(), "weekends"), []byte{byte(index + '0')}, 0666)
320 var f file
321 c := f.New("gophers")
322 c.Add(7)
323 f.rotate1()
324 fis, err := os.ReadDir(telemetry.Default.LocalDir())
325 if err != nil {
326 t.Fatal(err)
327 }
328 weekends := time.Weekday(-1)
329 var begins, ends time.Time
330 for _, fi := range fis {
331 // ignore errors for brevity: something else will fail
332 if fi.Name() == "weekends" {
333 buf, _ := os.ReadFile(filepath.Join(telemetry.Default.LocalDir(), fi.Name()))
334 buf = bytes.TrimSpace(buf)
335 weekends = time.Weekday(buf[0] - '0')
336 } else if strings.HasSuffix(fi.Name(), ".count") {
337 buf, _ := os.ReadFile(filepath.Join(telemetry.Default.LocalDir(), fi.Name()))
338 parsed, _ := Parse(fi.Name(), buf)
339 begins, _ = time.Parse(time.RFC3339, parsed.Meta["TimeBegin"])
340 ends, _ = time.Parse(time.RFC3339, parsed.Meta["TimeEnd"])
341 }
342 }
343 if weekends < 0 {
344 for _, f := range fis {
345 t.Errorf("in %s, weekends is %d", f.Name(), weekends)
346 }
347 continue
348 }
349 delta := int(ends.Sub(begins) / (24 * time.Hour))
350 // if we're an old user, we should have a <=7 day report
351 // if we're a new user, we should have a <=7+7 day report
352 more := 0
353 if delta <= 0+more || delta > 7+more {
354 t.Errorf("delta %d, expected %d<delta<=%d",
355 delta, more, more+7)
356 }
357 if weekends != ends.Weekday() {
358 t.Errorf("weekends %s unexpecteledy not end day %s", weekends, ends.Weekday())
359 }
360 // needed for Windows
361 close(&f)
362 // remove files for the next iteration of the loop
363 for _, f := range fis {
364 os.Remove(filepath.Join(telemetry.Default.LocalDir(), f.Name()))
365 }
366 }
367 }
368 }
369
370 func future(days int) func() time.Time {
371 return func() time.Time {
372 return time.Now().UTC().AddDate(0, 0, days)
373 }
374 }
375
376 func TestStack(t *testing.T) {
377 testenv.SkipIfUnsupportedPlatform(t)
378 t.Logf("GOOS %s GOARCH %s", runtime.GOOS, runtime.GOARCH)
379 setup(t)
380 defer restore()
381 var f file
382 defer close(&f)
383 f.rotate()
384
385 c := f.NewStack("foo", 5)
386 c.Inc()
387 c.Inc()
388 names := c.Names()
389 if len(names) != 2 {
390 t.Fatalf("got %d names, want 2", len(names))
391 }
392 // each name should be 4 lines, and the two names should
393 // differ only in the second line.
394 n0 := strings.Split(names[0], "\n")
395 n1 := strings.Split(names[1], "\n")
396 if len(n0) != 4 || len(n1) != 4 {
397 t.Errorf("got %d and %d lines, want 4 (%q,%q)", len(n0), len(n1), n0, n1)
398 }
399 for i := 0; i < 4 && i < len(n0) && i < len(n1); i++ {
400 if i == 1 {
401 continue
402 }
403 if n0[i] != n1[i] {
404 t.Errorf("line %d differs:\n%s\n%s", i, n0[i], n1[i])
405 }
406 }
407 // check that ReadStack gives the same results
408 mp, err := ReadStack(c)
409 if len(mp) != 2 {
410 t.Errorf("ReadStack returned %d values, expected 2", len(mp))
411 }
412 for k, v := range mp {
413 if v != 1 {
414 t.Errorf("got %d for %q, expected 1", v, k)
415 }
416 }
417
418 oldnames := make(map[string]bool)
419 for _, nm := range names {
420 oldnames[nm] = true
421 }
422 for i := 0; i < 2; i++ {
423 fn(t, 4, c)
424 }
425 newnames := make(map[string]bool)
426 for _, nm := range c.Names() {
427 if !oldnames[nm] {
428 newnames[nm] = true
429 }
430 }
431 // expect 5 new names, one for each level of recursion
432 if len(newnames) != 5 {
433 t.Errorf("got %d new names, want 5", len(newnames))
434 }
435 // make sure the new names contain compression
436 for k := range newnames {
437 if !strings.Contains(k, "\"") {
438 t.Errorf("new name %q does not contain \"", k)
439 }
440 }
441 // look inside. old names should have a count of 1, new ones 2
442 for _, ct := range c.Counters() {
443 if ct == nil {
444 t.Fatal("nil counter")
445 }
446 _, err := Read(ct)
447 if err != nil {
448 t.Errorf("failed to read known counter %v", err)
449 }
450 if ct.ptr.count == nil {
451 t.Errorf("%q has nil ptr.count", ct.Name())
452 continue
453 }
454 if oldnames[ct.Name()] && ct.ptr.count.Load() != 1 {
455 t.Errorf("old name %q has count %d, want 1", ct.Name(), ct.ptr.count.Load())
456 }
457 if newnames[ct.Name()] && ct.ptr.count.Load() != 2 {
458 t.Errorf("new name %q has count %d, want 2", ct.Name(), ct.ptr.count.Load())
459 }
460 }
461 // check that Parse expands compressed counter names
462 current := f.current.Load()
463 if current == nil {
464 t.Fatal("no mapped file")
465 }
466 data := current.mapping.Data
467 fname := "2023-01-01.v1.count" // bogus file name required by Parse.
468 theFile, err := Parse(fname, data)
469 if err != nil {
470 t.Fatal(err)
471 }
472 // We know what lines should appear in the stack counter names,
473 // although line numbers outside our control might change.
474 // A less fragile test would just check that " doesn't appear
475 known := map[string]bool{
476 "foo": true,
477 "golang.org/x/telemetry/internal/counter.fn": true,
478 "golang.org/x/telemetry/internal/counter.TestStack": true,
479 "runtime.goexit": true,
480 "testing.tRunner": true,
481 }
482 counts := theFile.Count
483 for k := range counts {
484 ll := strings.Split(k, "\n")
485 for _, line := range ll {
486 ix := strings.LastIndex(line, ":")
487 if ix < 0 {
488 continue // foo, for instance
489 }
490 line = line[:ix]
491 if !known[line] {
492 t.Errorf("unexpected line %q", line)
493 }
494 }
495 }
496 }
497
498 // fn calls itself n times recursively while incrementing the stack counter.
499 func fn(t *testing.T, n int, c *StackCounter) {
500 c.Inc()
501 if n > 0 {
502 fn(t, n-1, c)
503 }
504 }
505
506 func setup(t *testing.T) {
507 log.SetFlags(log.Lshortfile)
508 telemetry.Default = telemetry.NewDir(t.TempDir()) // new dir for each test
509 os.MkdirAll(telemetry.Default.LocalDir(), 0777)
510 os.MkdirAll(telemetry.Default.UploadDir(), 0777)
511 }
512
513 func restore() {
514 CounterTime = func() time.Time { return time.Now().UTC() }
515 }
516
517 func (f *file) New(name string) *Counter {
518 return &Counter{name: name, file: f}
519 }
520
521 func (f *file) NewStack(name string, depth int) *StackCounter {
522 return &StackCounter{name: name, depth: depth, file: f}
523 }