From 8b692f593103d24d1de0d85ef89ec5b3f3e9cd5a Mon Sep 17 00:00:00 2001 From: Zeling Feng Date: Wed, 2 Dec 2020 19:09:17 -0800 Subject: 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 --- pkg/test/testutil/testutil.go | 11 +++++++++++ 1 file changed, 11 insertions(+) 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 + "-" } -- cgit v1.2.3