/
leaderElection.go
68 lines (61 loc) · 1.79 KB
/
leaderElection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright Contributors to the Open Cluster Management project
package clustersync
import (
"context"
"time"
"github.com/stolostron/search-indexer/pkg/config"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
klog "k8s.io/klog/v2"
)
var leader string
func getNewLock(client *kubernetes.Clientset, lockname, podName, podNamespace string) *resourcelock.LeaseLock {
return &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{
Name: lockname,
Namespace: podNamespace,
},
Client: client.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{
Identity: podName,
},
}
}
func runLeaderElection(ctx context.Context, lock *resourcelock.LeaseLock, runLeaderTasks func(context.Context)) {
for {
select {
case <-ctx.Done():
klog.Info("Exit leader election.")
return
default:
klog.V(1).Info("Attempting to become leader.")
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: lock,
ReleaseOnCancel: true, // Releases the lock on context cancel.
LeaseDuration: 15 * time.Second,
RenewDeadline: 10 * time.Second,
RetryPeriod: 2 * time.Second,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(c context.Context) {
klog.Info("I'm the leader! Starting leader activities.")
leader = config.Cfg.PodName
runLeaderTasks(c)
},
OnStoppedLeading: func() {
if leader == config.Cfg.PodName {
klog.Info("I'm no longer the leader.")
}
},
OnNewLeader: func(currentId string) {
if currentId != config.Cfg.PodName {
klog.Infof("Leader is %s", currentId)
leader = currentId
}
},
},
})
}
}
}