diff --git a/main.go b/main.go index 93a4d0f19..e6f5563ad 100644 --- a/main.go +++ b/main.go @@ -31,10 +31,8 @@ package main import ( "context" - "crypto/md5" "flag" "fmt" - "io" "os" "strings" @@ -133,9 +131,7 @@ func main() { // hash the watched namespaces to allow for more than one operator deployment per namespace // same watched namespaces will return the same hash so only one operator will be active - h := md5.New() - io.WriteString(h, namespaces) - leaderElectionID := fmt.Sprintf("%s-%x", "controller-leader-election-helper", h.Sum(nil)) + leaderElectionID := fmt.Sprintf("%s-%x", "controller-leader-election-helper", util.GetMD5Hash(namespaces)) setupLog.Info("Using leader electrion id", "LeaderElectionID", leaderElectionID, "watched namespaces", namespaceList) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ diff --git a/pkg/util/util.go b/pkg/util/util.go index 02b5cb1a6..a070aaa7c 100644 --- a/pkg/util/util.go +++ b/pkg/util/util.go @@ -18,9 +18,11 @@ import ( "bytes" "compress/gzip" "context" + "crypto/md5" "crypto/tls" "crypto/x509" "encoding/base64" + "encoding/hex" "encoding/json" "fmt" "io" @@ -551,3 +553,9 @@ func RetryOnConflict(backoff wait.Backoff, fn func() error) error { func GetExternalPortForBroker(externalStartingPort, brokerId int32) int32 { return externalStartingPort + brokerId } + +// Generage MD5 hash for a given string +func GetMD5Hash(text string) string { + hash := md5.Sum([]byte(text)) + return hex.EncodeToString(hash[:]) +} diff --git a/pkg/util/util_test.go b/pkg/util/util_test.go index 502ae9b5b..3fd64f9f4 100644 --- a/pkg/util/util_test.go +++ b/pkg/util/util_test.go @@ -690,3 +690,29 @@ cruise.control.metrics.reporter.kubernetes.mode=true`, } } } + +func TestGetMD5Hash(t *testing.T) { + testCases := []struct { + testName string + input string + expected string + }{ + { + testName: "empty string", + input: "", + expected: "d41d8cd98f00b204e9800998ecf8427e", + }, + { + testName: "non-empty string", + input: "test", + expected: "098f6bcd4621d373cade4e832627b4f6", + }, + } + + for _, test := range testCases { + hash := GetMD5Hash(test.input) + if hash != test.expected { + t.Errorf("Expected: %s Got: %s", test.expected, hash) + } + } +}