summaryrefslogtreecommitdiffhomepage
path: root/pkg/test/testutil
diff options
context:
space:
mode:
authorZeling Feng <zeling@google.com>2020-12-02 19:09:17 -0800
committergVisor bot <gvisor-bot@google.com>2020-12-02 19:14:51 -0800
commit8b692f593103d24d1de0d85ef89ec5b3f3e9cd5a (patch)
tree0a2a654e03189c9bf45d2bf7e4cf78a42a8c80a6 /pkg/test/testutil
parented8bdf461b5f8093957a11f526032d42938af7ca (diff)
Make testutil.RandomID safe for concurrent uses
testutil.RandomID was using Rand.Read which is not safe for concurrent use. It caused name conflicts in packetimpact tests when they are run in parallel. Adding a mutex to protect the Rand.Read operation. PiperOrigin-RevId: 345360062
Diffstat (limited to 'pkg/test/testutil')
-rw-r--r--pkg/test/testutil/testutil.go11
1 files changed, 11 insertions, 0 deletions
diff --git a/pkg/test/testutil/testutil.go b/pkg/test/testutil/testutil.go
index 976331230..757a689f6 100644
--- a/pkg/test/testutil/testutil.go
+++ b/pkg/test/testutil/testutil.go
@@ -248,14 +248,25 @@ func writeSpec(dir string, spec *specs.Spec) error {
// idRandomSrc is a pseudo random generator used to in RandomID.
var idRandomSrc = rand.New(rand.NewSource(time.Now().UnixNano()))
+// idRandomSrcMtx is the mutex protecting idRandomSrc.Read from being used
+// concurrently in differnt goroutines.
+var idRandomSrcMtx sync.Mutex
+
// RandomID returns 20 random bytes following the given prefix.
func RandomID(prefix string) string {
// Read 20 random bytes.
b := make([]byte, 20)
+ // Rand.Read is not safe for concurrent use. Packetimpact tests can be run in
+ // parallel now, so we have to protect the Read with a mutex. Otherwise we'll
+ // run into name conflicts.
+ // https://golang.org/pkg/math/rand/#Rand.Read
+ idRandomSrcMtx.Lock()
// "[Read] always returns len(p) and a nil error." --godoc
if _, err := idRandomSrc.Read(b); err != nil {
+ idRandomSrcMtx.Unlock()
panic("rand.Read failed: " + err.Error())
}
+ idRandomSrcMtx.Unlock()
if prefix != "" {
prefix = prefix + "-"
}