forked from open-cluster-management-io/sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_controller.go
More file actions
170 lines (141 loc) · 4.6 KB
/
Copy pathbase_controller.go
File metadata and controls
170 lines (141 loc) · 4.6 KB
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
package factory
import (
"context"
"fmt"
"sync"
"time"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
)
var defaultCacheSyncTimeout = 10 * time.Minute
// baseController represents generic Kubernetes controller boiler-plate
type baseController struct {
name string
cachesToSync []cache.InformerSynced
sync func(ctx context.Context, controllerContext SyncContext, key string) error
syncContext SyncContext
resyncEvery time.Duration
cacheSyncTimeout time.Duration
}
var _ Controller = &baseController{}
func (c baseController) Name() string {
return c.name
}
func waitForNamedCacheSync(ctx context.Context, controllerName string, stopCh <-chan struct{}, cacheSyncs ...cache.InformerSynced) error {
logger := klog.FromContext(ctx)
logger.Info("Waiting for caches to sync")
if !cache.WaitForCacheSync(stopCh, cacheSyncs...) {
return fmt.Errorf("unable to sync caches for %s", controllerName)
}
logger.Info("Caches are synced")
return nil
}
func (c *baseController) SyncContext() SyncContext {
return c.syncContext
}
func (c *baseController) Run(ctx context.Context, workers int) {
logger := klog.FromContext(ctx).WithName(c.name)
ctx = klog.NewContext(ctx, logger)
// give caches 10 minutes to sync
cacheSyncCtx, cacheSyncCancel := context.WithTimeout(ctx, c.cacheSyncTimeout)
defer cacheSyncCancel()
err := waitForNamedCacheSync(ctx, c.name, cacheSyncCtx.Done(), c.cachesToSync...)
if err != nil {
select {
case <-ctx.Done():
// Exit gracefully because the controller was requested to stop.
return
default:
// If caches did not sync after 10 minutes, it has taken oddly long and
// we should provide feedback. Since the control loops will never start,
// it is safer to exit with a good message than to continue with a dead loop.
// TODO: Consider making this behavior configurable.
klog.Exit(err)
}
}
var workerWg sync.WaitGroup
defer func() {
defer logger.Info("All workers have been terminated")
workerWg.Wait()
}()
// queueContext is used to track and initiate queue shutdown
queueContext, queueContextCancel := context.WithCancel(ctx)
for i := 1; i <= workers; i++ {
logger.Info("Starting worker of controller ...", "worker-ID", i)
workerWg.Add(1)
go func() {
defer func() {
logger.Info("Shutting down worker of controller ...")
workerWg.Done()
}()
c.runWorker(queueContext)
}()
}
// runPeriodicalResync is independent from queue
if c.resyncEvery > 0 {
workerWg.Add(1)
go func() {
defer workerWg.Done()
c.runPeriodicalResync(ctx, c.resyncEvery)
}()
}
// Handle controller shutdown
<-ctx.Done() // wait for controller context to be cancelled
c.syncContext.Queue().ShutDown() // shutdown the controller queue first
queueContextCancel() // cancel the queue context, which tell workers to initiate shutdown
// Wait for all workers to finish their job.
// at this point the Run() can hang and caller have to implement the logic that will kill
// this controller (SIGKILL).
logger.Info("Shutting down ...")
}
func (c *baseController) Sync(ctx context.Context, syncCtx SyncContext, key string) error {
return c.sync(ctx, syncCtx, key)
}
func (c *baseController) runPeriodicalResync(ctx context.Context, interval time.Duration) {
if interval == 0 {
return
}
go wait.UntilWithContext(ctx, func(ctx context.Context) {
c.syncContext.Queue().Add(DefaultQueueKey)
}, interval)
}
// runWorker runs a single worker
// The worker is asked to terminate when the passed context is cancelled and is given terminationGraceDuration time
// to complete its shutdown.
func (c *baseController) runWorker(queueCtx context.Context) {
wait.UntilWithContext(
queueCtx,
func(queueCtx context.Context) {
for {
select {
case <-queueCtx.Done():
return
default:
c.processNextWorkItem(queueCtx)
}
}
},
1*time.Second)
}
func (c *baseController) processNextWorkItem(queueCtx context.Context) {
logger := klog.FromContext(queueCtx)
key, quit := c.syncContext.Queue().Get()
if quit {
return
}
defer c.syncContext.Queue().Done(key)
syncCtx := c.syncContext.(syncContext)
queueKey := key
if err := c.sync(queueCtx, syncCtx, queueKey); err != nil {
if logger.V(4).Enabled() || key != DefaultQueueKey {
utilruntime.HandleErrorWithContext(queueCtx, err, "controller failed to sync", "key", key)
} else {
utilruntime.HandleErrorWithContext(queueCtx, err, "reconciliation failed")
}
c.syncContext.Queue().AddRateLimited(key)
return
}
c.syncContext.Queue().Forget(key)
}