-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
390 lines (336 loc) · 10.7 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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
)
type ConfigError struct {
missingEnv string
}
func (e *ConfigError) Error() string {
return fmt.Sprintf("config: missing required environment variable: '%s'", e.missingEnv)
}
type AwaitElection struct {
LockName string
LeaderIdentity string
StatusEndpoint string
LeaseDuration time.Duration
RetryPeriod time.Duration
LeaderExec func(ctx context.Context) error
EtcdClient *clientv3.Client
leaseID clientv3.LeaseID
ForceAcquire bool
currentLeader string
}
func NewAwaitElectionConfig(exec func(ctx context.Context) error) (*AwaitElection, error) {
lockName := os.Getenv("ETCD_AWAIT_ELECTION_LOCK_NAME")
if lockName == "" {
return nil, &ConfigError{missingEnv: "ETCD_AWAIT_ELECTION_LOCK_NAME"}
}
leaderIdentity := os.Getenv("ETCD_AWAIT_ELECTION_IDENTITY")
if leaderIdentity == "" {
return nil, &ConfigError{missingEnv: "ETCD_AWAIT_ELECTION_IDENTITY"}
}
statusEndpoint := os.Getenv("ETCD_AWAIT_ELECTION_STATUS_ENDPOINT")
leaseDuration := 15 * time.Second
if val, ok := os.LookupEnv("ETCD_AWAIT_ELECTION_LEASE_DURATION"); ok {
d, err := strconv.Atoi(val)
if err == nil {
leaseDuration = time.Duration(d) * time.Second
}
}
retryPeriod := 2 * time.Second
if val, ok := os.LookupEnv("ETCD_AWAIT_ELECTION_RETRY_PERIOD"); ok {
d, err := strconv.Atoi(val)
if err == nil {
retryPeriod = time.Duration(d) * time.Second
}
}
endpoints := os.Getenv("ETCD_AWAIT_ELECTION_ENDPOINTS")
if endpoints == "" {
return nil, &ConfigError{missingEnv: "ETCD_AWAIT_ELECTION_ENDPOINTS"}
}
endpointsList := strings.Split(endpoints, ",")
tlsConfig, err := getTLSConfig()
if err != nil {
return nil, err
}
etcdClient, err := clientv3.New(clientv3.Config{
Endpoints: endpointsList,
TLS: tlsConfig,
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, fmt.Errorf("failed to create etcd client: %w", err)
}
forceAcquire := false
if val, ok := os.LookupEnv("ETCD_AWAIT_ELECTION_FORCE_ACQUIRE"); ok {
forceAcquire, _ = strconv.ParseBool(val) // Ignore error, default will be false
}
return &AwaitElection{
LockName: lockName,
LeaderIdentity: leaderIdentity,
StatusEndpoint: statusEndpoint,
LeaseDuration: leaseDuration,
RetryPeriod: retryPeriod,
LeaderExec: exec,
EtcdClient: etcdClient,
ForceAcquire: forceAcquire,
}, nil
}
func getTLSConfig() (*tls.Config, error) {
certFile := os.Getenv("ETCD_AWAIT_ELECTION_CERT")
keyFile := os.Getenv("ETCD_AWAIT_ELECTION_KEY")
caFile := os.Getenv("ETCD_AWAIT_ELECTION_CACERT")
if certFile == "" || keyFile == "" || caFile == "" {
return nil, nil
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load client certificate: %w", err)
}
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("failed to read CA certificate: %w", err)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
return nil, fmt.Errorf("failed to add CA certificate to pool")
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}, nil
}
func (el *AwaitElection) createAndSaveNewLease(ctx context.Context) error {
lease, err := el.EtcdClient.Grant(ctx, int64(el.LeaseDuration.Seconds()))
if err != nil {
return fmt.Errorf("failed to create lease: %v", err)
}
el.leaseID = lease.ID
return nil
}
func (el *AwaitElection) keepLeaseAlive(ctx context.Context, cancel context.CancelFunc) {
ch, kaerr := el.EtcdClient.KeepAlive(ctx, el.leaseID)
if kaerr != nil {
log.Printf("Failed to set up lease keep-alive: %v", kaerr)
cancel() // Immediately cancel context if setting up keep-alive fails
el.revokeLease(ctx) // Immediately try to revoke lease if setting up keep-alive fails
return
}
for {
select {
case kaResp, ok := <-ch:
if !ok || kaResp == nil {
log.Printf("Lease keep-alive channel closed or response is nil, lease might be lost")
cancel() // Cancel context if keep-alive fails
el.revokeLease(ctx) // Revoke lease immediately if keep-alive fails
return
}
case <-time.After(el.RetryPeriod):
healthCtx, healthCancel := context.WithTimeout(ctx, 2*time.Second)
defer healthCancel()
_, err := el.EtcdClient.Get(healthCtx, "health")
if err != nil {
log.Printf("Failed to get etcd health: %v", err)
cancel()
el.revokeLease(ctx)
return
}
case <-ctx.Done():
log.Printf("Context canceled, stopping lease keep-alive")
return
}
}
}
func (el *AwaitElection) revokeLease(ctx context.Context) {
if _, err := el.EtcdClient.Revoke(ctx, el.leaseID); err != nil {
log.Printf("Failed to revoke lease: %v", err)
} else {
log.Printf("Lease revoked successfully")
}
}
func (el *AwaitElection) watchLeadership(ctx context.Context, cancel context.CancelFunc) {
watchChan := el.EtcdClient.Watch(ctx, el.LockName)
for watchResp := range watchChan {
for _, ev := range watchResp.Events {
if ev.Type == clientv3.EventTypeDelete {
log.Printf("Leadership key deleted, cancelling leadership")
cancel()
return
}
}
}
}
func (el *AwaitElection) acquireLeadership(ctx context.Context) error {
for {
if el.ForceAcquire {
// Delete the existing lock if force acquire is enabled
_, err := el.EtcdClient.Delete(ctx, el.LockName)
if err != nil {
log.Printf("Failed to delete existing lock: %v", err)
} else {
log.Printf("Existing lock deleted under force acquire policy")
}
} else {
resp, err := el.EtcdClient.Get(ctx, el.LockName)
if err != nil {
return fmt.Errorf("failed to get current leader: %v", err)
}
if len(resp.Kvs) > 0 && string(resp.Kvs[0].Value) == el.LeaderIdentity {
// Current node is already the leader, delete the existing lock to reacquire it
_, err := el.EtcdClient.Delete(ctx, el.LockName)
if err != nil {
log.Printf("Failed to delete existing lock: %v", err)
} else {
log.Printf("Existing lock owned by current node deleted to reacquire it")
}
}
}
lease, err := el.EtcdClient.Grant(ctx, int64(el.LeaseDuration.Seconds()))
if err != nil {
return fmt.Errorf("failed to create lease: %v", err)
}
el.leaseID = lease.ID
txn := el.EtcdClient.Txn(ctx).If(
clientv3.Compare(clientv3.CreateRevision(el.LockName), "=", 0),
).Then(
clientv3.OpPut(el.LockName, el.LeaderIdentity, clientv3.WithLease(lease.ID)),
).Else(
clientv3.OpGet(el.LockName),
)
txnResp, err := txn.Commit()
if err != nil {
return fmt.Errorf("failed to commit transaction: %v", err)
}
if txnResp.Succeeded {
// Leadership acquired
el.currentLeader = el.LeaderIdentity
log.Printf("Leadership acquired by %s", el.LeaderIdentity)
return nil
}
// There's a current leader, check who it is
resp, err := el.EtcdClient.Get(ctx, el.LockName)
if err != nil {
return fmt.Errorf("failed to get current leader: %v", err)
}
currentLeader := string(resp.Kvs[0].Value)
if currentLeader != el.currentLeader {
el.currentLeader = currentLeader
log.Printf("Current leader is %s, will continue trying", currentLeader)
}
// Wait and retry
time.Sleep(el.RetryPeriod)
}
}
func (el *AwaitElection) Run() error {
for {
mainCtx, cancel := context.WithCancel(context.Background())
// Start the status endpoint to serve HTTP requests
el.startStatusEndpoint(mainCtx)
// Attempt to acquire leadership
err := el.acquireLeadership(mainCtx)
if err != nil {
log.Fatalf("Failed to acquire leadership: %v", err)
cancel()
return err
}
// Keep lease alive in a separate goroutine
go el.keepLeaseAlive(mainCtx, cancel)
// Monitor leadership status in a separate goroutine
go el.watchLeadership(mainCtx, cancel)
// Execute the leader function
err = el.LeaderExec(mainCtx)
if err != nil {
log.Printf("Leader execution error: %v", err)
}
// Regardless of the command result, prepare to cancel context
cancel()
// Use a separate context for lease revocation to ensure it can complete
revokeCtx, revokeCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer revokeCancel()
el.revokeLease(revokeCtx)
// Retrieve exit code if the command failed
exitCode := 0
if exitErr, ok := err.(*exec.ExitError); ok {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
exitCode = status.ExitStatus()
}
}
// Log and exit with the command's exit status
log.Printf("Exiting process with code %d", exitCode)
syscall.Exit(exitCode)
}
}
func (el *AwaitElection) startStatusEndpoint(ctx context.Context) {
if el.StatusEndpoint == "" {
log.Printf("Status endpoint not configured")
return
}
serveMux := http.NewServeMux()
serveMux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
resp, err := el.EtcdClient.Get(ctx, el.LockName)
if err != nil || len(resp.Kvs) == 0 {
writer.Header().Set("Content-Type", "text/plain")
writer.WriteHeader(http.StatusOK)
writer.Write([]byte(fmt.Sprintf("{\"status\": \"ok\", \"phase\": \"awaiting\", \"leader\": \"unknown\"}\n")))
return
}
currentLeader := string(resp.Kvs[0].Value)
if currentLeader == el.LeaderIdentity {
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
writer.Write([]byte(fmt.Sprintf("{\"status\": \"ok\", \"phase\": \"running\", \"leader\": \"%s\"}\n", currentLeader)))
} else {
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
writer.Write([]byte(fmt.Sprintf("{\"status\": \"ok\", \"phase\": \"awaiting\", \"leader\": \"%s\"}\n", currentLeader)))
}
})
statusServer := http.Server{
Addr: el.StatusEndpoint,
Handler: serveMux,
BaseContext: func(listener net.Listener) context.Context {
return ctx
},
}
go func() {
log.Printf("Starting status endpoint on %s", el.StatusEndpoint)
if err := statusServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("Failed to start status server: %v", err)
}
}()
}
func Execute(ctx context.Context) error {
log.Printf("Starting command '%s' with arguments: '%v'", os.Args[1], os.Args[2:])
cmd := exec.CommandContext(ctx, os.Args[1], os.Args[2:]...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
return cmd.Run()
}
func main() {
log.Printf("Running etcd-await-election")
if len(os.Args) <= 1 {
log.Fatalf("Need at least one argument to run")
}
awaitElectionConfig, err := NewAwaitElectionConfig(Execute)
if err != nil {
log.Fatalf("Failed to create runner: %v", err)
}
err = awaitElectionConfig.Run()
if err != nil {
log.Fatalf("Failed to run: %v", err)
}
}