Skip to content

Commit

Permalink
🌱 Make using leader elector with client timeout non-breaking
Browse files Browse the repository at this point in the history
This change is a follow-up to the one that introduces the usage of the
leader-elector with client timeout. That change was breaking because it
introduces a new option and always assumed it was set. This change makes
us only use that option if its actually set.
  • Loading branch information
alvaroaleman authored and vincepri committed Dec 2, 2024
1 parent 4bc3811 commit 2a0ce59
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions pkg/leaderelection/leader_election.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"time"

"k8s.io/apimachinery/pkg/util/uuid"
coordinationv1client "k8s.io/client-go/kubernetes/typed/coordination/v1"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/leaderelection/resourcelock"

Expand All @@ -49,7 +51,10 @@ type Options struct {
// will use for holding the leader lock.
LeaderElectionID string

// RenewDeadline is the renew deadline for this leader election client
// RenewDeadline is the renew deadline for this leader election client.
// Must be set to ensure the resource lock has an appropriate client timeout.
// Without that, a single slow response from the API server can result
// in losing leadership.
RenewDeadline time.Duration
}

Expand Down Expand Up @@ -91,15 +96,37 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op
// Construct clients for leader election
rest.AddUserAgent(config, "leader-election")

return resourcelock.NewFromKubeconfig(options.LeaderElectionResourceLock,
if options.RenewDeadline != 0 {
return resourcelock.NewFromKubeconfig(options.LeaderElectionResourceLock,
options.LeaderElectionNamespace,
options.LeaderElectionID,
resourcelock.ResourceLockConfig{
Identity: id,
EventRecorder: recorderProvider.GetEventRecorderFor(id),
},
config,
options.RenewDeadline,
)
}

corev1Client, err := corev1client.NewForConfig(config)
if err != nil {
return nil, err
}

coordinationClient, err := coordinationv1client.NewForConfig(config)
if err != nil {
return nil, err
}
return resourcelock.New(options.LeaderElectionResourceLock,
options.LeaderElectionNamespace,
options.LeaderElectionID,
corev1Client,
coordinationClient,
resourcelock.ResourceLockConfig{
Identity: id,
EventRecorder: recorderProvider.GetEventRecorderFor(id),
},
config,
options.RenewDeadline,
)
}

Expand Down

0 comments on commit 2a0ce59

Please sign in to comment.