forked from CRASH-Tech/proxmox-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leaderElection.go
80 lines (69 loc) · 1.93 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
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"context"
"os"
"time"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
)
func getNewLock(lockname, podname, namespace string) *resourcelock.LeaseLock {
return &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{
Name: lockname,
Namespace: namespace,
},
Client: config.KubernetesClient.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{
Identity: podname,
},
}
}
func setLeaderLabel(isLeader bool) {
pod, err := config.KubernetesClient.CoreV1().Pods(namespace).Get(context.TODO(), hostname, metav1.GetOptions{})
if err != nil {
log.Fatal(err)
}
existingLabels := pod.ObjectMeta.Labels
if isLeader {
existingLabels["leader"] = "true"
} else {
existingLabels["leader"] = "false"
}
pod.ObjectMeta.Labels = existingLabels
updatedPod, err := config.KubernetesClient.CoreV1().Pods(namespace).Update(context.TODO(), pod, metav1.UpdateOptions{})
if err != nil {
log.Fatal(err)
}
log.Infof("Updated pod label: %s\n", updatedPod.Labels["leader"])
}
func runLeaderElection(lock *resourcelock.LeaseLock, ctx context.Context, id string) {
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: lock,
ReleaseOnCancel: true,
LeaseDuration: 15 * time.Second,
RenewDeadline: 10 * time.Second,
RetryPeriod: 2 * time.Second,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(c context.Context) {
mutex.Unlock()
setLeaderLabel(true)
worker()
},
OnStoppedLeading: func() {
log.Warn("We are no longer the leader, terminating...")
mutex.Lock()
setLeaderLabel(false)
os.Exit(0)
},
OnNewLeader: func(current_id string) {
if current_id == id {
log.Info("We are still the leading!")
return
}
log.Warnf("New leader is %s", current_id)
},
},
})
}