-
Notifications
You must be signed in to change notification settings - Fork 14
/
reboot_decide.go
273 lines (247 loc) · 8.46 KB
/
reboot_decide.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
package op
import (
"context"
"fmt"
"strings"
"time"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/log"
"github.com/cybozu-go/well"
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
)
// enumeratePods enumerates Pods on a specified node.
// It calls podHandler for each Pods not owned by Job nor DaemonSet and calls jobPodHandler for each running Pods owned by a Job.
// If those handlers returns error, this function returns the error immediately.
// Note: This function does not distinguish API errors and state evaluation returned from subfunction.
func enumeratePods(ctx context.Context, cs *kubernetes.Clientset, node string,
podHandler func(pod *corev1.Pod) error, jobPodHandler func(pod *corev1.Pod) error) error {
podList, err := cs.CoreV1().Pods(corev1.NamespaceAll).List(ctx, metav1.ListOptions{
FieldSelector: fields.SelectorFromSet(fields.Set{"spec.nodeName": node}).String(),
})
if err != nil {
return err
}
for i := range podList.Items {
pod := &podList.Items[i]
owner := metav1.GetControllerOf(pod)
if owner != nil {
switch owner.Kind {
case "DaemonSet":
continue
case "Job":
switch pod.Status.Phase {
case corev1.PodPending:
case corev1.PodSucceeded:
case corev1.PodFailed:
default:
err = jobPodHandler(pod)
if err != nil {
return err
}
}
continue
}
}
err = podHandler(pod)
if err != nil {
return err
}
}
return nil
}
// checkJobPodNotExist checks running Pods on the specified Node.
// It returns an error if a running Pod exists.
func checkJobPodNotExist(ctx context.Context, cs *kubernetes.Clientset, node string) error {
return enumeratePods(ctx, cs, node, func(_ *corev1.Pod) error {
return nil
}, func(pod *corev1.Pod) error {
return fmt.Errorf("job-managed pod exists: %s/%s, phase=%s", pod.Namespace, pod.Name, pod.Status.Phase)
})
}
// evictOrDeleteNodePod evicts or delete Pods on the specified Node.
// It first tries eviction. If the eviction failed and the Pod's namespace is not protected, it deletes the Pod.
// If a running Job Pod exists, this function returns an error.
func evictOrDeleteNodePod(ctx context.Context, cs *kubernetes.Clientset, node string, protected map[string]bool) error {
return enumeratePods(ctx, cs, node, func(pod *corev1.Pod) error {
err := cs.CoreV1().Pods(pod.Namespace).EvictV1(ctx, &policyv1.Eviction{
ObjectMeta: metav1.ObjectMeta{Name: pod.Name, Namespace: pod.Namespace},
})
switch {
case err == nil:
log.Info("start evicting pod", map[string]interface{}{
"namespace": pod.Namespace,
"name": pod.Name,
})
case apierrors.IsNotFound(err):
// already evicted or deleted.
case !apierrors.IsTooManyRequests(err):
// not a PDB related error
return fmt.Errorf("failed to evict pod %s/%s: %w", pod.Namespace, pod.Name, err)
case !protected[pod.Namespace]:
log.Warn("failed to evict non-protected pod due to PDB", map[string]interface{}{
"namespace": pod.Namespace,
"name": pod.Name,
log.FnError: err,
})
err := cs.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return err
}
log.Warn("deleted non-protected pod", map[string]interface{}{
"namespace": pod.Namespace,
"name": pod.Name,
})
default:
return fmt.Errorf("failed to evict pod %s/%s due to PDB: %w", pod.Namespace, pod.Name, err)
}
return nil
}, func(pod *corev1.Pod) error {
return fmt.Errorf("job-managed pod exists: %s/%s, phase=%s", pod.Namespace, pod.Name, pod.Status.Phase)
})
}
// checkPodDeletion checks whether the evicted or deleted Pods are eventually deleted.
// If those pods still exist, this function returns an error.
func checkPodDeletion(ctx context.Context, cs *kubernetes.Clientset, node string) error {
return enumeratePods(ctx, cs, node, func(pod *corev1.Pod) error {
return fmt.Errorf("pod exists: %s/%s, phase=%s", pod.Namespace, pod.Name, pod.Status.Phase)
}, func(pod *corev1.Pod) error {
// This should not happen... or rare case?
return fmt.Errorf("job-managed pod exists: %s/%s, phase=%s", pod.Namespace, pod.Name, pod.Status.Phase)
})
}
// chooseDrainedNodes chooses nodes to be newly drained.
// For now, this function does not check "drainability".
func ChooseDrainedNodes(c *cke.Cluster, apiServers map[string]bool, rqEntries []*cke.RebootQueueEntry) []*cke.RebootQueueEntry {
maxConcurrentReboots := cke.DefaultMaxConcurrentReboots
if c.Reboot.MaxConcurrentReboots != nil {
maxConcurrentReboots = *c.Reboot.MaxConcurrentReboots
}
now := time.Now()
apiServerInProgress := false
var apiServerDrainable *cke.RebootQueueEntry
workerInProgress := []*cke.RebootQueueEntry{}
workerDrainable := []*cke.RebootQueueEntry{}
for _, entry := range rqEntries {
if !entry.ClusterMember(c) {
continue
}
switch entry.Status {
case cke.RebootStatusDraining, cke.RebootStatusRebooting:
if apiServers[entry.Node] {
apiServerInProgress = true
} else {
workerInProgress = append(workerInProgress, entry)
}
case cke.RebootStatusQueued:
if entry.DrainBackOffExpire.After(now) {
continue
}
if apiServers[entry.Node] {
if apiServerDrainable == nil {
apiServerDrainable = entry
}
} else {
workerDrainable = append(workerDrainable, entry)
}
}
}
// rules:
// - API Servers are rebooted one by one.
// - It is VERY important.
// - API Servers are rebooted with lower priority than worker nodes.
// - API Servers are not rebooted simultaneously with worker nodes.
if apiServerInProgress {
return nil
}
if len(workerInProgress) == 0 && len(workerDrainable) == 0 {
if apiServerDrainable != nil {
return []*cke.RebootQueueEntry{apiServerDrainable}
} else {
return nil
}
}
if len(workerInProgress) >= maxConcurrentReboots {
return nil
} else if len(workerInProgress)+len(workerDrainable) <= maxConcurrentReboots {
return workerDrainable
} else {
return workerDrainable[:maxConcurrentReboots-len(workerInProgress)]
}
}
func CheckDrainCompletion(ctx context.Context, inf cke.Infrastructure, apiserver *cke.Node, c *cke.Cluster, rqEntries []*cke.RebootQueueEntry) ([]*cke.RebootQueueEntry, []*cke.RebootQueueEntry, error) {
evictionTimeoutSeconds := cke.DefaultRebootEvictionTimeoutSeconds
if c.Reboot.EvictionTimeoutSeconds != nil {
evictionTimeoutSeconds = *c.Reboot.EvictionTimeoutSeconds
}
cs, err := inf.K8sClient(ctx, apiserver)
if err != nil {
return nil, nil, err
}
t := time.Now().Add(time.Duration(-evictionTimeoutSeconds) * time.Second)
var completed []*cke.RebootQueueEntry
var timedout []*cke.RebootQueueEntry
for _, entry := range rqEntries {
if !entry.ClusterMember(c) {
continue
}
if entry.Status != cke.RebootStatusDraining {
continue
}
err := checkPodDeletion(ctx, cs, entry.Node)
if err == nil {
completed = append(completed, entry)
} else if entry.LastTransitionTime.Before(t) {
timedout = append(timedout, entry)
}
}
return completed, timedout, nil
}
func CheckRebootDequeue(ctx context.Context, c *cke.Cluster, rqEntries []*cke.RebootQueueEntry) []*cke.RebootQueueEntry {
dequeued := []*cke.RebootQueueEntry{}
for _, entry := range rqEntries {
switch {
case !entry.ClusterMember(c):
case entry.Status == cke.RebootStatusCancelled:
case entry.Status == cke.RebootStatusRebooting && rebootCompleted(ctx, c, entry):
default:
continue
}
dequeued = append(dequeued, entry)
}
return dequeued
}
func rebootCompleted(ctx context.Context, c *cke.Cluster, entry *cke.RebootQueueEntry) bool {
if c.Reboot.CommandTimeoutSeconds != nil && *c.Reboot.CommandTimeoutSeconds != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Second*time.Duration(*c.Reboot.CommandTimeoutSeconds))
defer cancel()
}
result := false
env := well.NewEnvironment(ctx)
env.Go(func(ctx context.Context) error {
args := append(c.Reboot.BootCheckCommand[1:], entry.Node, fmt.Sprintf("%d", entry.LastTransitionTime.Unix()))
command := well.CommandContext(ctx, c.Reboot.BootCheckCommand[0], args...)
stdout, err := command.Output()
if err != nil {
return err
}
if strings.TrimSuffix(string(stdout), "\n") == "true" {
result = true
}
return nil
})
env.Stop()
err := env.Wait()
if err != nil {
log.Warn("failed to check boot", map[string]interface{}{
"name": entry.Node,
})
return false
}
return result
}