-
Notifications
You must be signed in to change notification settings - Fork 15
/
control.go
316 lines (281 loc) · 6.3 KB
/
control.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
package server
import (
"context"
"errors"
"os"
"time"
"github.com/coreos/etcd/clientv3/concurrency"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/log"
"github.com/cybozu-go/well"
)
var (
errCommandFailure = errors.New("command failed")
)
// Controller manage operations
type Controller struct {
session *concurrency.Session
interval time.Duration
timeout time.Duration
addon Integrator
}
// NewController construct controller instance
func NewController(s *concurrency.Session, interval, timeout time.Duration, addon Integrator) Controller {
return Controller{s, interval, timeout, addon}
}
// Run execute procedures with leader elections
func (c Controller) Run(ctx context.Context) error {
hostname, err := os.Hostname()
if err != nil {
return err
}
e := concurrency.NewElection(c.session, cke.KeyLeader)
RETRY:
select {
case <-c.session.Done():
return errors.New("session has been orphaned")
default:
}
err = e.Campaign(ctx, hostname)
if err != nil {
return err
}
leaderKey := e.Key()
log.Info("I am the leader", map[string]interface{}{
"session": c.session.Lease(),
})
err = c.runLoop(ctx, leaderKey)
ctxWithTimeout, cancel := context.WithTimeout(context.Background(), c.timeout)
err2 := e.Resign(ctxWithTimeout)
cancel()
if err2 != nil {
return err2
}
if err == cke.ErrNoLeader {
log.Warn("lost the leadership", nil)
goto RETRY
}
return err
}
func (c Controller) runLoop(ctx context.Context, leaderKey string) error {
err := c.checkLastOp(ctx, leaderKey)
if err != nil {
return err
}
watchChan := make(chan struct{})
var addonChan chan struct{}
env := well.NewEnvironment(ctx)
if c.addon != nil {
addonChan = make(chan struct{}, 1)
env.Go(func(ctx context.Context) error {
return c.addon.StartWatch(ctx, addonChan)
})
}
env.Go(func(ctx context.Context) error {
return startWatcher(ctx, c.session.Client(), watchChan)
})
env.Stop()
<-watchChan
defer func() {
env.Cancel(nil)
env.Wait()
}()
ticker := time.NewTicker(c.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
default:
}
err := c.runOnce(ctx, leaderKey, ticker.C, watchChan, addonChan)
if err != nil {
return err
}
}
}
func (c Controller) checkLastOp(ctx context.Context, leaderKey string) error {
storage := cke.Storage{
Client: c.session.Client(),
}
records, err := storage.GetRecords(ctx, 1)
if err != nil {
return err
}
if len(records) == 0 {
return nil
}
r := records[0]
if r.Status == cke.StatusCancelled || r.Status == cke.StatusCompleted {
return nil
}
log.Warn("cancel the orphaned operation", map[string]interface{}{
"id": r.ID,
"op": r.Operation,
})
r.Cancel()
return storage.UpdateRecord(ctx, leaderKey, r)
}
func (c Controller) runOnce(ctx context.Context, leaderKey string, tick <-chan time.Time, watchChan, addonChan <-chan struct{}) error {
wait := false
defer func() {
if !wait {
return
}
select {
case <-watchChan:
case <-addonChan:
case <-ctx.Done():
case <-tick:
}
}()
storage := cke.Storage{
Client: c.session.Client(),
}
cluster, err := storage.GetCluster(ctx)
switch err {
case cke.ErrNotFound:
wait = true
if c.addon != nil {
return c.addon.Do(ctx, leaderKey)
}
return nil
case nil:
default:
return err
}
err = cluster.Validate()
if err != nil {
log.Error("invalid cluster configuration", map[string]interface{}{
log.FnError: err,
})
wait = true
return nil
}
inf, err := cke.NewInfrastructure(ctx, cluster, storage)
if err != nil {
wait = true
log.Error("failed to initialize infrastructure", map[string]interface{}{
log.FnError: err,
})
if c.addon != nil {
return c.addon.Do(ctx, leaderKey)
}
return nil
}
defer inf.Close()
// prepare service account signing
_, err = storage.GetServiceAccountCert(ctx)
switch err {
case nil:
case cke.ErrNotFound:
crt, key, err := cke.KubernetesCA{}.IssueForServiceAccount(ctx, inf)
if err != nil {
return err
}
err = storage.PutServiceAccountData(ctx, leaderKey, crt, key)
if err != nil {
return err
}
default:
return err
}
status, err := c.GetClusterStatus(ctx, cluster, inf)
if err != nil {
wait = true
log.Warn("failed to get cluster status", map[string]interface{}{
log.FnError: err,
})
return nil
}
ops := DecideOps(cluster, status)
if len(ops) == 0 {
wait = true
if c.addon != nil {
return c.addon.Do(ctx, leaderKey)
}
return nil
}
for _, op := range ops {
err := runOp(ctx, op, leaderKey, storage, inf)
switch err {
case nil:
case errCommandFailure:
wait = true
return nil
default:
return err
}
}
return nil
}
func runOp(ctx context.Context, op cke.Operator, leaderKey string, storage cke.Storage, inf cke.Infrastructure) error {
// register operation record
id, err := storage.NextRecordID(ctx)
if err != nil {
return err
}
record := cke.NewRecord(id, op.Name())
err = storage.RegisterRecord(ctx, leaderKey, record)
if err != nil {
return err
}
log.Info("begin new operation", map[string]interface{}{
"op": op.Name(),
})
for {
commander := op.NextCommand()
if commander == nil {
break
}
// check the context before proceed
select {
case <-ctx.Done():
record.Cancel()
err = storage.UpdateRecord(ctx, leaderKey, record)
if err != nil {
return err
}
log.Info("interrupt the operation due to cancellation", map[string]interface{}{
"op": op.Name(),
})
return nil
default:
}
record.SetCommand(commander.Command())
err = storage.UpdateRecord(ctx, leaderKey, record)
if err != nil {
return err
}
log.Info("execute a command", map[string]interface{}{
"op": op.Name(),
"command": commander.Command().String(),
})
err = commander.Run(ctx, inf)
if err == nil {
continue
}
log.Error("command failed", map[string]interface{}{
log.FnError: err,
"op": op.Name(),
"command": commander.Command().String(),
})
record.SetError(err)
err2 := storage.UpdateRecord(ctx, leaderKey, record)
if err2 != nil {
return err2
}
// return errCommandFailure instead of err as command failure need to be
// handled gracefully.
return errCommandFailure
}
record.Complete()
err = storage.UpdateRecord(ctx, leaderKey, record)
if err != nil {
return err
}
log.Info("operation completed", map[string]interface{}{
"op": op.Name(),
})
return nil
}