Skip to content

Commit

Permalink
exit kube-ovn-controller on stopped leading (#1536)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangzujian committed May 17, 2022
1 parent 39e5f0a commit 24791f4
Showing 1 changed file with 3 additions and 28 deletions.
31 changes: 3 additions & 28 deletions pkg/controller/election.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,6 @@ func (c *Controller) leaderElection() {
}

func setupLeaderElection(config *leaderElectionConfig) *leaderelection.LeaderElector {
var elector *leaderelection.LeaderElector

// start a new context
ctx := context.Background()

var cancelContext context.CancelFunc

var newLeaderCtx = func(ctx context.Context) context.CancelFunc {
// allow to cancel the context in case we stop being the leader
leaderCtx, cancel := context.WithCancel(ctx)
go elector.Run(leaderCtx)
return cancel
}

var stopCh chan struct{}
callbacks := leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
Expand All @@ -81,11 +67,6 @@ func setupLeaderElection(config *leaderElectionConfig) *leaderelection.LeaderEle
klog.Info("I am not leader anymore")
close(stopCh)

// cancel the context
cancelContext()

cancelContext = newLeaderCtx(ctx)

if config.OnStoppedLeading != nil {
config.OnStoppedLeading()
}
Expand All @@ -101,12 +82,10 @@ func setupLeaderElection(config *leaderElectionConfig) *leaderelection.LeaderEle

broadcaster := record.NewBroadcaster()
hostname := os.Getenv(util.HostnameEnv)

recorder := broadcaster.NewRecorder(scheme.Scheme, apiv1.EventSource{
Component: ovnLeaderElector,
Host: hostname,
})

lock := resourcelock.ConfigMapLock{
ConfigMapMeta: metav1.ObjectMeta{Namespace: config.PodNamespace, Name: config.ElectionID},
Client: config.Client.CoreV1(),
Expand All @@ -115,21 +94,17 @@ func setupLeaderElection(config *leaderElectionConfig) *leaderelection.LeaderEle
EventRecorder: recorder,
},
}

var err error

elector, err = leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{
elector, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{
Lock: &lock,
LeaseDuration: 15 * time.Second,
RenewDeadline: 10 * time.Second,
RetryPeriod: 2 * time.Second,

Callbacks: callbacks,
Callbacks: callbacks,
})
if err != nil {
klog.Fatalf("unexpected error starting leader election: %v", err)
}

cancelContext = newLeaderCtx(ctx)
go elector.Run(context.Background())
return elector
}

0 comments on commit 24791f4

Please sign in to comment.