mirror of
https://github.com/netbirdio/gvisor.git
synced 2026-05-22 17:12:49 -07:00
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:
@@ -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 + "-"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user