diff --git a/main.go b/main.go index 4aa93c4e9..e6f5563ad 100644 --- a/main.go +++ b/main.go @@ -32,6 +32,7 @@ package main import ( "context" "flag" + "fmt" "os" "strings" @@ -128,10 +129,15 @@ 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 + 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{ Scheme: scheme, LeaderElection: enableLeaderElection, - LeaderElectionID: "controller-leader-election-helper", + LeaderElectionID: leaderElectionID, WebhookServer: webhook.NewServer(webhook.Options{ Port: webhookServerPort, CertDir: webhookCertDir, 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) + } + } +}