Skip to content

Commit

Permalink
[INTERNAL] Create uniq leader ID per operator deployment (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
dobrerazvan authored Apr 16, 2024
1 parent aa25e15 commit bb519ee
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
8 changes: 7 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ package main
import (
"context"
"flag"
"fmt"
"os"
"strings"

Expand Down Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -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[:])
}
26 changes: 26 additions & 0 deletions pkg/util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit bb519ee

Please sign in to comment.