-
Notifications
You must be signed in to change notification settings - Fork 87
/
manager.go
59 lines (51 loc) · 1.09 KB
/
manager.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
package leader
import (
"context"
"sync"
"time"
"github.com/sirupsen/logrus"
"k8s.io/client-go/kubernetes"
)
type Manager struct {
sync.Mutex
leaderChan chan struct{}
leaderStarted bool
leaderCTX context.Context
namespace string
name string
k8s kubernetes.Interface
}
func NewManager(namespace, name string, k8s kubernetes.Interface) *Manager {
return &Manager{
leaderChan: make(chan struct{}),
namespace: namespace,
name: name,
k8s: k8s,
}
}
func (m *Manager) Start(ctx context.Context) {
m.Lock()
defer m.Unlock()
if m.leaderStarted {
return
}
m.leaderStarted = true
go RunOrDie(ctx, m.namespace, m.name, m.k8s, func(ctx context.Context) {
m.leaderCTX = ctx
close(m.leaderChan)
})
}
// OnLeader this function will be called when leadership is acquired.
func (m *Manager) OnLeader(f func(ctx context.Context) error) {
go func() {
<-m.leaderChan
for {
if err := f(m.leaderCTX); err != nil {
logrus.Errorf("failed to call leader func: %v", err)
time.Sleep(5 * time.Second)
continue
}
break
}
}()
}