-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
164 lines (137 loc) · 3.93 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"context"
"github.com/caitlinelfring/go-env-default"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"log"
"net/http"
"os"
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/leaderelection"
"github.com/gin-gonic/gin"
)
const (
leaseName = "k8s-leader-example"
lockName = "k8s-leader-example"
leaseNamespace = "default"
)
func main() {
leaseDuration := env.GetIntDefault("LEASE_DURATION", 15)
renewalDeadline := env.GetInt64Default("RENEWAL_DEADLINE", 10)
retryPeriod := env.GetIntDefault("RETRY_PERIOD", 5)
clientset := getKubeClient()
updatePodLabel(clientset)
leaderElectionConfig := leaderelection.LeaderElectionConfig{
// Create a leaderElectionConfig for leader election
Lock: &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{
Name: lockName,
Namespace: leaseNamespace,
},
Client: clientset.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{
Identity: os.Getenv("HOSTNAME"),
},
},
LeaseDuration: time.Duration(leaseDuration) * time.Second,
RenewDeadline: time.Duration(renewalDeadline) * time.Second,
RetryPeriod: time.Duration(retryPeriod) * time.Second,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: onStartedLeading,
OnStoppedLeading: onStoppedLeading,
},
ReleaseOnCancel: true,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
// Start the leader election
leaderelection.RunOrDie(ctx, leaderElectionConfig)
}()
r := gin.Default()
r.GET("/", rootPage())
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
cancel()
wg.Wait()
}
func rootPage() func(c *gin.Context) {
return func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hostname": os.Getenv("HOSTNAME"),
})
}
}
func updatePodLabel(clientset kubernetes.Interface) {
// Retrieve the pod
hostname := os.Getenv("HOSTNAME")
pod, err := clientset.CoreV1().Pods(metav1.NamespaceDefault).Get(context.TODO(), hostname, metav1.GetOptions{})
if err != nil {
log.Fatal(err)
}
// Update the pod label
existingLabels := pod.ObjectMeta.Labels
existingLabels["pod"] = os.Getenv("HOSTNAME")
pod.ObjectMeta.Labels = existingLabels
// Update the pod
updatedPod, err := clientset.CoreV1().Pods(metav1.NamespaceDefault).Update(context.TODO(), pod, metav1.UpdateOptions{})
if err != nil {
log.Fatal(err)
}
log.Printf("Updated pod label: %s\n", updatedPod.Labels["pod"])
}
func onStartedLeading(ctx context.Context) {
log.Println("Became leader: ", os.Getenv("HOSTNAME"))
clientset := getKubeClient()
updateServiceSelectorToCurrentPod(clientset)
go func() {
for {
select {
case <-ctx.Done():
log.Println("Stopped leader loop")
return
default:
// Perform leader tasks here
log.Println("Performing leader tasks...")
time.Sleep(1 * time.Second)
}
}
}()
}
func updateServiceSelectorToCurrentPod(clientset kubernetes.Interface) {
service, err := clientset.CoreV1().Services(leaseNamespace).Get(context.TODO(), leaseName, metav1.GetOptions{})
if err != nil {
log.Fatal(err)
}
// Get the existing selector labels
existingLabels := service.Spec.Selector
existingLabels["pod"] = os.Getenv("HOSTNAME")
service.Spec.Selector = existingLabels
// Update the Service
updatedService, err := clientset.CoreV1().Services(leaseNamespace).Update(context.TODO(), service, metav1.UpdateOptions{})
if err != nil {
log.Fatal(err)
}
log.Printf("Updated Service: %s\n", updatedService.Name)
}
func getKubeClient() *kubernetes.Clientset {
// Create a Kubernetes client using the current context
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
return clientset
}
func onStoppedLeading() {
log.Println("Stopped being leader")
}