-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathleader_election.go
284 lines (242 loc) · 7.85 KB
/
leader_election.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package leaderelection
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/cenkalti/backoff"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/client-go/rest"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8s "k8s.io/client-go/kubernetes"
)
const (
defaultLeaseName = "leader-election-lease"
defaultLeaseDuration = 60 * time.Second
defaultRenewDeadline = 30 * time.Second
defaultRetryPeriod = 15 * time.Second
timeoutRunLeaderEngine = 15 * time.Second
defaultRandomizationFactor = 0.5
)
var (
GetAPIClient = func() (k8s.Interface, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to get in-cluster config, err: %v", err)
}
apiClient, err := k8s.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("failed to obtain K8s API client, err: %v", err)
}
return apiClient, nil
}
ErrNotRunning = fmt.Errorf("leader engine is not running")
)
var (
initialRetryDelay = 1 * time.Second
maxRetryDelay = 5 * time.Minute
)
func WithLeaseDuration(dur time.Duration) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.leaseDuration = dur
}
}
func WithRenewTime(dur time.Duration) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.renewDeadline = dur
}
}
func WithRetryPeriod(dur time.Duration) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.retryPeriod = dur
}
}
func WithHolderIdentity(identity string) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.holderIdentity = identity
}
}
func WithLeaseName(name string) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.leaseName = name
}
}
func WithLeaseNamespace(namespace string) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.leaseNamespace = namespace
}
}
func WithContext(ctx context.Context) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.parentCtx = ctx
}
}
func WithLogger(logger Logger) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.logger = logger
}
}
func WithErrorLogger(logger Logger) K8sLeaderEngineOption {
return func(le *K8sLeaderEngine) {
le.errorLogger = logger
}
}
func New(opts ...K8sLeaderEngineOption) (*K8sLeaderEngine, error) {
e := &K8sLeaderEngine{
leaseName: defaultLeaseName,
leaseDuration: defaultLeaseDuration,
renewDeadline: defaultRenewDeadline,
retryPeriod: defaultRetryPeriod,
logger: &defaultLogger{},
errorLogger: &defaultLogger{},
stopped: make(chan struct{}),
subscribers: make(map[string]LeaderEngineSubscriber),
}
for _, o := range opts {
o(e)
}
e.leaseNamespace = e.getResourceNamespace()
if e.parentCtx == nil {
e.parentCtx = context.Background()
}
e.ctx, e.ctxCancel = context.WithCancel(e.parentCtx)
err := doWithExpBackoff(e.initializeLeaderEngine, initialRetryDelay, maxRetryDelay)
if err != nil {
return nil, fmt.Errorf("failed to initialize leader engine, err: %v", err)
}
e.logger.Log("Initialized leader engine with lease name: %q, namespace: %q", e.leaseName, e.leaseNamespace)
return e, nil
}
// Start the leader engine and block until a leader is elected.
func (le *K8sLeaderEngine) Start() error {
if !le.isRunning.CompareAndSwap(false, true) {
return fmt.Errorf("leader engine is already started")
}
go le.runLeaderEngine()
timeout := time.After(timeoutRunLeaderEngine)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
leaderIdentity := le.GetLeader()
if leaderIdentity != "" {
le.logger.Log("Leader election started. Current leader is %q", leaderIdentity)
return nil
}
case <-timeout:
return fmt.Errorf("leader check timed out after %s. Stop the engine and try again", timeoutRunLeaderEngine)
}
}
}
// Stop the engine and wait until the goroutines have stopped
func (le *K8sLeaderEngine) Stop() error {
if !le.isRunning.CompareAndSwap(true, false) {
return fmt.Errorf("leader engine is not started or already stopped")
}
le.ctxCancel()
le.logger.Log("Leader election engine cancelled internal context, will wait until stopped signal is received")
<-le.stopped
le.logger.Log("Leader election engine stopped")
return nil
}
func (le *K8sLeaderEngine) Subscribe(subscriber LeaderEngineSubscriber) {
le.subscribersMu.Lock()
defer le.subscribersMu.Unlock()
subscriberName := subscriber.Name()
_, ok := le.subscribers[subscriberName]
if ok {
le.logger.Log("Already have a subscriber with name: %q, skipping", subscriber)
return
}
le.subscribers[subscriberName] = subscriber
}
func (le *K8sLeaderEngine) Unsubscribe(subscriber LeaderEngineSubscriber) error {
le.subscribersMu.Lock()
defer le.subscribersMu.Unlock()
subscriberName := subscriber.Name()
_, ok := le.subscribers[subscriberName]
if ok {
return fmt.Errorf("there is no subscriber with name: %q", subscriberName)
}
delete(le.subscribers, subscriberName)
return nil
}
func (le *K8sLeaderEngine) GetLeader() string {
le.leaderIdentityMutex.Lock()
defer le.leaderIdentityMutex.Unlock()
return le.currentLeaderIdentity
}
func (le *K8sLeaderEngine) IsLeader() bool {
return le.holderIdentity == le.GetLeader()
}
func (le *K8sLeaderEngine) initializeLeaderEngine() error {
var err error
if le.holderIdentity == "" {
le.holderIdentity, err = os.Hostname()
if err != nil {
return fmt.Errorf("failed to obtain hostname, err: %v", err)
}
}
le.logger.Log("Initializing leader engine with holder identity: %q", le.holderIdentity)
apiClient, err := GetAPIClient()
if err != nil {
return err
}
le.apiClient = apiClient
le.coreClient = apiClient.CoreV1()
le.coordinationClient = apiClient.CoordinationV1()
_, err = le.coordinationClient.Leases(le.leaseNamespace).Get(le.parentCtx, le.leaseName, metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
return fmt.Errorf("failed to obtain leases from namespace: %q, err: %v", le.leaseNamespace, err)
}
le.leaderElector, err = le.newLeaderElector(le.parentCtx)
if err != nil {
return fmt.Errorf("failed to initialize leader elector process, err: %v", err)
}
le.logger.Log("Leader election for %q is initialized", le.holderIdentity)
return nil
}
func (le *K8sLeaderEngine) runLeaderEngine() {
for {
le.logger.Log("Starting leader election process for %q under namespace: %q", le.holderIdentity, le.leaseNamespace)
le.leaderElector.Run(le.ctx)
select {
case <-le.ctx.Done():
le.logger.Log("Leader election engine is stopping")
le.stopped <- struct{}{}
return
default:
le.logger.Log("%q lost the leader lease", le.holderIdentity)
}
}
}
func (le *K8sLeaderEngine) getResourceNamespace() string {
namespace := os.Getenv("K8S_RESOURCE_NAMESPACE")
if namespace != "" {
return namespace
}
le.logger.Log("Environment variable K8S_RESOURCE_NAMESPACE is unset. Falling back to service account's namespace")
return le.getLocalResourceNamespace()
}
func (le *K8sLeaderEngine) getLocalResourceNamespace() string {
namespaceFilePath := filepath.Join(ServiceAccountMountPath, "namespace")
if _, err := os.Stat(namespaceFilePath); os.IsNotExist(err) {
le.logger.Log("Namespace file %q is not found. Will use 'default' namespace", namespaceFilePath)
return "default"
}
ns, err := os.ReadFile(namespaceFilePath)
if err != nil {
le.logger.Log("Failed to access namespace file: %q, err: %v. Will use 'default' namespace.", err)
return "default"
}
return string(ns)
}
func doWithExpBackoff(f func() error, initialInterval, timeout time.Duration) error {
b := backoff.NewExponentialBackOff()
b.RandomizationFactor = defaultRandomizationFactor
b.MaxElapsedTime = timeout
b.InitialInterval = initialInterval
return backoff.Retry(f, b)
}