refactor machine name generation using secrets package

This commit is contained in:
Pavel Sviderski
2024-11-14 11:47:22 +10:00
parent 22bca16226
commit 2c62e1f6df
+4 -11
View File
@@ -1,9 +1,7 @@
package cluster package cluster
import ( import (
"crypto/rand"
"fmt" "fmt"
"math/big"
"uncloud/internal/secret" "uncloud/internal/secret"
) )
@@ -14,14 +12,9 @@ func NewMachineID() (string, error) {
// NewRandomMachineName generates a random machine name in the format "machine-xxxx". // NewRandomMachineName generates a random machine name in the format "machine-xxxx".
func NewRandomMachineName() (string, error) { func NewRandomMachineName() (string, error) {
const charset = "abcdefghijklmnopqrstuvwxyz0123456789" suffix, err := secret.RandomAlphaNumeric(4)
suffix := make([]byte, 4) if err != nil {
for i := range suffix { return "", fmt.Errorf("generate random suffix: %w", err)
randIdx, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
if err != nil {
return "", fmt.Errorf("get random number: %w", err)
}
suffix[i] = charset[randIdx.Int64()]
} }
return "machine-" + string(suffix), nil return "machine-" + suffix, nil
} }