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
This commit is contained in:
Zeling Feng
2020-12-02 19:14:51 -08:00
committed by gVisor bot
parent ed8bdf461b
commit 8b692f5931
+11
View File
@@ -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 + "-"
}