-
Notifications
You must be signed in to change notification settings - Fork 14
/
run.go
119 lines (101 loc) · 2.25 KB
/
run.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
package localproxy
import (
"context"
"errors"
"fmt"
"time"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/log"
)
// LocalProxy is the controller of kube-proxy and unbound running on the same server as CKE.
type LocalProxy struct {
Interval time.Duration
Storage cke.Storage
currentAP string
}
// Run starts the controller.
func (c *LocalProxy) Run(ctx context.Context) error {
tick := time.NewTicker(c.Interval)
defer tick.Stop()
for {
select {
case <-tick.C:
if err := c.runOnce(ctx); err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}
func (c *LocalProxy) runOnce(ctx context.Context) error {
inf := newInfrastructure(c.Storage)
defer inf.Close()
cluster, err := c.Storage.GetCluster(ctx)
if errors.Is(err, cke.ErrNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("failed to get cluster: %w", err)
}
st, err := getStatus(ctx, inf)
if err != nil {
log.Error("failed to get status", map[string]interface{}{
log.FnError: err,
})
//lint:ignore nilerr intentional
return nil
}
ap, ops := decideOps(cluster, c.currentAP, st)
if len(ops) == 0 {
return nil
}
c.currentAP = ap
for _, op := range ops {
if err := runOp(ctx, op, inf); err != nil {
log.Error("failed to run an operation", map[string]interface{}{
"op": op.Name(),
log.FnError: err,
})
}
}
return nil
}
func runOp(ctx context.Context, op cke.Operator, inf cke.Infrastructure) error {
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():
log.Info("interrupt the operation due to cancellation", map[string]interface{}{
"op": op.Name(),
})
return nil
default:
}
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(),
})
return err
}
log.Info("operation completed", map[string]interface{}{
"op": op.Name(),
})
return nil
}