From 36cb2cea5e291548443ce1eb3ccadf917e211bcc Mon Sep 17 00:00:00 2001 From: Mikhail Mazurskiy Date: Wed, 12 May 2021 12:13:02 +1000 Subject: [PATCH] Use rand from apimachinery to avoid seeding rng every time --- pkg/common/common.go | 7 +++---- pkg/config/initoptions.go | 2 +- pkg/inventory/inventory.go | 4 +--- test/e2e/common_test.go | 4 +--- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/pkg/common/common.go b/pkg/common/common.go index 372dbb8..2a9c190 100644 --- a/pkg/common/common.go +++ b/pkg/common/common.go @@ -5,8 +5,8 @@ package common import ( "fmt" - "math/rand" + "k8s.io/apimachinery/pkg/util/rand" cmdutil "k8s.io/kubectl/pkg/cmd/util" ) @@ -44,9 +44,8 @@ const ( ) // RandomStr returns an eight-digit (with leading zeros) string of a -// random number seeded with the parameter. -func RandomStr(seed int64) string { - rand.Seed(seed) +// random number. +func RandomStr() string { randomInt := rand.Intn(maxRandInt) // nolint:gosec return fmt.Sprintf("%08d", randomInt) } diff --git a/pkg/config/initoptions.go b/pkg/config/initoptions.go index bb02cec..8f2cdca 100644 --- a/pkg/config/initoptions.go +++ b/pkg/config/initoptions.go @@ -221,7 +221,7 @@ func fileExists(path string) bool { func (i *InitOptions) fillInValues() string { now := time.Now() nowStr := now.Format("2006-01-02 15:04:05 MST") - randomSuffix := common.RandomStr(now.UTC().UnixNano()) + randomSuffix := common.RandomStr() manifestStr := i.Template klog.V(4).Infof("namespace/inventory-id: %s/%s", i.Namespace, i.InventoryID) manifestStr = strings.ReplaceAll(manifestStr, "", nowStr) diff --git a/pkg/inventory/inventory.go b/pkg/inventory/inventory.go index e420ce6..28b84f2 100644 --- a/pkg/inventory/inventory.go +++ b/pkg/inventory/inventory.go @@ -14,7 +14,6 @@ package inventory import ( "fmt" "strings" - "time" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -174,8 +173,7 @@ func fixLegacyInventoryName(obj *unstructured.Unstructured) error { name := accessor.GetName() if obj.GetName() == legacyInvName || name == legacyInvName { klog.V(4).Infof("renaming legacy inventory name") - seed := time.Now().UTC().UnixNano() - randomSuffix := common.RandomStr(seed) + randomSuffix := common.RandomStr() return addSuffixToName(obj, randomSuffix) } return nil diff --git a/test/e2e/common_test.go b/test/e2e/common_test.go index 3468008..d6e2408 100644 --- a/test/e2e/common_test.go +++ b/test/e2e/common_test.go @@ -6,7 +6,6 @@ package e2e import ( "fmt" "strings" - "time" . "github.com/onsi/gomega" appsv1 "k8s.io/api/apps/v1" @@ -22,8 +21,7 @@ import ( ) func randomString(prefix string) string { - seed := time.Now().UTC().UnixNano() - randomSuffix := common.RandomStr(seed) + randomSuffix := common.RandomStr() return fmt.Sprintf("%s%s", prefix, randomSuffix) }