| 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 |
// countertest provides testing utilities for counters. |
| 6 |
// This package cannot be used except for testing. |
| 7 |
package countertest |
| 8 |
|
| 9 |
import ( |
| 10 |
"sync" |
| 11 |
"testing" |
| 12 |
|
| 13 |
"golang.org/x/telemetry/counter" |
| 14 |
ic "golang.org/x/telemetry/internal/counter" |
| 15 |
"golang.org/x/telemetry/internal/telemetry" |
| 16 |
) |
| 17 |
|
| 18 |
var ( |
| 19 |
openedMu sync.Mutex |
| 20 |
opened bool |
| 21 |
) |
| 22 |
|
| 23 |
// SupportedPlatform reports if this platform supports Open() |
| 24 |
const SupportedPlatform = !telemetry.DisabledOnPlatform |
| 25 |
|
| 26 |
func isOpen() bool { |
| 27 |
openedMu.Lock() |
| 28 |
defer openedMu.Unlock() |
| 29 |
return opened |
| 30 |
} |
| 31 |
|
| 32 |
// Open enables telemetry data writing to disk. |
| 33 |
// This is supposed to be called once during the program execution |
| 34 |
// (i.e. typically in TestMain), and must not be used with |
| 35 |
// golang.org/x/telemetry/counter.Open. |
| 36 |
func Open(telemetryDir string) { |
| 37 |
openedMu.Lock() |
| 38 |
defer openedMu.Unlock() |
| 39 |
if opened { |
| 40 |
panic("Open was called more than once") |
| 41 |
} |
| 42 |
telemetry.Default = telemetry.NewDir(telemetryDir) |
| 43 |
|
| 44 |
// TODO(rfindley): reinstate test coverage with counter rotation enabled. |
| 45 |
// Before the [counter.Open] and [counter.OpenAndRotate] APIs were split, |
| 46 |
// this called counter.Open (which rotated!). |
| 47 |
counter.Open() |
| 48 |
opened = true |
| 49 |
} |
| 50 |
|
| 51 |
// ReadCounter reads the given counter. |
| 52 |
func ReadCounter(c *counter.Counter) (count uint64, _ error) { |
| 53 |
return ic.Read(c) |
| 54 |
} |
| 55 |
|
| 56 |
// ReadStackCounter reads the given StackCounter. |
| 57 |
func ReadStackCounter(c *counter.StackCounter) (stackCounts map[string]uint64, _ error) { |
| 58 |
return ic.ReadStack(c) |
| 59 |
} |
| 60 |
|
| 61 |
// ReadFile reads the counters and stack counters from the given file. |
| 62 |
func ReadFile(name string) (counters, stackCounters map[string]uint64, _ error) { |
| 63 |
return ic.ReadFile(name) |
| 64 |
} |
| 65 |
|
| 66 |
func init() { |
| 67 |
// Extra safety check. |
| 68 |
if !testing.Testing() { |
| 69 |
panic("use of this package is disallowed in non-testing code") |
| 70 |
} |
| 71 |
} |