Skip to content

Commit

Permalink
leaderelection: configure all timeouts via environment variables
Browse files Browse the repository at this point in the history
Signed-off-by: Silvio Moioli <[email protected]>
  • Loading branch information
moio committed May 31, 2023
1 parent 39a4707 commit fb22944
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions pkg/leader/leader.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"time"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/leaderelection"
Expand All @@ -13,6 +14,13 @@ import (

type Callback func(cb context.Context)

const defaultLeaseDuration = 45 * time.Second
const defaultRenewDeadline = 30 * time.Second
const defaultRetryPeriod = 2 * time.Second

const developmentLeaseDuration = 45 * time.Hour
const developmentRenewDeadline = 30 * time.Hour

func RunOrDie(ctx context.Context, namespace, name string, client kubernetes.Interface, cb Callback) {
if namespace == "" {
namespace = "kube-system"
Expand Down Expand Up @@ -43,16 +51,37 @@ func run(ctx context.Context, namespace, name string, client kubernetes.Interfac
logrus.Fatalf("error creating leader lock for %s: %v", name, err)
}

t := time.Second
if dl := os.Getenv("CATTLE_DEV_MODE"); dl != "" {
t = time.Hour
leaseDuration := defaultLeaseDuration
renewDeadline := defaultRenewDeadline
retryPeriod := defaultRetryPeriod
if d := os.Getenv("CATTLE_DEV_MODE"); d != "" {
leaseDuration = developmentLeaseDuration
renewDeadline = developmentRenewDeadline
}
if d := os.Getenv("CATTLE_ELECTION_LEASE_DURATION"); d != "" {
leaseDuration, err = time.ParseDuration(d)
if err != nil {
return errors.Wrapf(err, "CATTLE_ELECTION_LEASE_DURATION is not a valid duration")
}
}
if d := os.Getenv("CATTLE_ELECTION_RENEW_DEADLINE"); d != "" {
renewDeadline, err = time.ParseDuration(d)
if err != nil {
return errors.Wrapf(err, "CATTLE_ELECTION_RENEW_DEADLINE is not a valid duration")
}
}
if d := os.Getenv("CATTLE_ELECTION_RETRY_PERIOD"); d != "" {
retryPeriod, err = time.ParseDuration(d)
if err != nil {
return errors.Wrapf(err, "CATTLE_ELECTION_RETRY_PERIOD is not a valid duration")
}
}

leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: rl,
LeaseDuration: 45 * t,
RenewDeadline: 30 * t,
RetryPeriod: 2 * time.Second,
LeaseDuration: leaseDuration,
RenewDeadline: renewDeadline,
RetryPeriod: retryPeriod,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
go cb(ctx)
Expand Down

0 comments on commit fb22944

Please sign in to comment.