-
Notifications
You must be signed in to change notification settings - Fork 0
/
cordonfieldssyncer.go
303 lines (279 loc) · 8.6 KB
/
cordonfieldssyncer.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
package nodesyncer
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/kubectl"
nodehelper "github.com/rancher/rancher/pkg/node"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
const (
drainTokenPrefix = "drain-node-"
description = "token for drain"
)
var nodeMapLock = sync.Mutex{}
var toIgnoreErrs = []string{"--ignore-daemonsets", "--delete-local-data", "--force", "did not complete within"}
func (m *nodesSyncer) syncCordonFields(key string, obj *v3.Node) (runtime.Object, error) {
if obj == nil || obj.DeletionTimestamp != nil || obj.Spec.DesiredNodeUnschedulable == "" {
return nil, nil
}
if obj.Spec.DesiredNodeUnschedulable != "true" && obj.Spec.DesiredNodeUnschedulable != "false" {
return nil, nil
}
node, err := nodehelper.GetNodeForMachine(obj, m.nodeLister)
if err != nil || node == nil || node.DeletionTimestamp != nil {
return nil, err
}
desiredValue := convert.ToBool(obj.Spec.DesiredNodeUnschedulable)
if node.Spec.Unschedulable != desiredValue {
toUpdate := node.DeepCopy()
toUpdate.Spec.Unschedulable = desiredValue
if _, err := m.nodeClient.Update(toUpdate); err != nil {
return nil, err
}
}
nodeCopy := obj.DeepCopy()
if !desiredValue {
removeDrainCondition(nodeCopy)
}
nodeCopy.Spec.DesiredNodeUnschedulable = ""
_, err = m.machines.Update(nodeCopy)
if err != nil {
return nil, err
}
return nil, nil
}
func (d *NodeDrain) drainNode(key string, obj *v3.Node) (runtime.Object, error) {
if obj == nil || obj.DeletionTimestamp != nil || obj.Spec.DesiredNodeUnschedulable == "" {
return nil, nil
}
if obj.Spec.DesiredNodeUnschedulable != "drain" && obj.Spec.DesiredNodeUnschedulable != "stopDrain" {
return nil, nil
}
if obj.Spec.DesiredNodeUnschedulable == "drain" {
nodeMapLock.Lock()
if _, ok := d.nodesToContext[obj.Name]; ok {
nodeMapLock.Unlock()
return nil, nil
}
ctx, cancel := context.WithCancel(d.ctx)
d.nodesToContext[obj.Name] = cancel
go d.drain(ctx, obj, cancel)
nodeMapLock.Unlock()
} else if obj.Spec.DesiredNodeUnschedulable == "stopDrain" {
nodeMapLock.Lock()
cancelFunc, ok := d.nodesToContext[obj.Name]
nodeMapLock.Unlock()
if ok {
cancelFunc()
}
return nil, d.resetDesiredNodeUnschedulable(obj)
}
return nil, nil
}
func (d *NodeDrain) updateNode(node *v3.Node, updateFunc func(node *v3.Node, originalErr error, kubeErr error), originalErr error, kubeErr error) (*v3.Node, error) {
updatedObj, err := d.machines.Update(node)
if err != nil && errors.IsConflict(err) {
// retrying twelve times, if conflict error still exists, give up
for i := 0; i < 12; i++ {
latestObj, err := d.machines.Get(node.Name, metav1.GetOptions{})
if err != nil {
logrus.Warnf("nodeDrain: error fetching node %s", node.Spec.RequestedHostname)
return nil, err
}
updateFunc(latestObj, originalErr, kubeErr)
updatedObj, err = d.machines.Update(latestObj)
if err != nil && errors.IsConflict(err) {
logrus.Debugf("nodeDrain: conflict error, will retry again %s", node.Spec.RequestedHostname)
time.Sleep(5 * time.Millisecond)
continue
}
return updatedObj, err
}
}
return updatedObj, err
}
func (d *NodeDrain) drain(ctx context.Context, obj *v3.Node, cancel context.CancelFunc) {
defer deleteFromContextMap(d.nodesToContext, obj.Name)
for {
select {
case <-ctx.Done():
return
default:
}
stopped := false
nodeName := obj.Spec.RequestedHostname
updatedObj, err := v3.NodeConditionDrained.DoUntilTrue(obj, func() (runtime.Object, error) {
kubeConfig, err := d.getKubeConfig()
if err != nil {
logrus.Errorf("nodeDrain: error getting kubeConfig for node %s", obj.Name)
return obj, fmt.Errorf("error getting kubeConfig for node %s", obj.Name)
}
nodeCopy := obj.DeepCopy()
setConditionDraining(nodeCopy, nil, nil)
nodeObj, err := d.updateNode(nodeCopy, setConditionDraining, nil, nil)
if err != nil {
return obj, err
}
logrus.Infof("Draining node %s in %s", nodeName, obj.Namespace)
_, msg, err := kubectl.Drain(ctx, kubeConfig, nodeName, getFlags(nodeObj.Spec.NodeDrainInput))
if err != nil {
if ctx.Err() == context.Canceled {
stopped = true
logrus.Infof(fmt.Sprintf("Stopped draining %s in %s", nodeName, obj.Namespace))
return nodeObj, nil
}
errMsg := filterErrorMsg(msg, nodeName)
return nodeObj, fmt.Errorf("%s", errMsg)
}
return nodeObj, nil
})
kubeErr := err
if err != nil {
ignore, timeoutErr := ignoreErr(err.Error())
if ignore {
kubeErr = nil
if timeoutErr {
err = fmt.Errorf(fmt.Sprintf("Drain failed: drain did not complete within %vs",
obj.Spec.NodeDrainInput.Timeout))
}
}
}
if !stopped {
nodeCopy := updatedObj.(*v3.Node).DeepCopy()
setConditionComplete(nodeCopy, err, kubeErr)
_, updateErr := d.updateNode(nodeCopy, setConditionComplete, err, kubeErr)
if kubeErr != nil || updateErr != nil {
logrus.Errorf("nodeDrain: [%s] in cluster [%s] : %v %v", nodeName, d.clusterName, err, updateErr)
d.machines.Controller().Enqueue("", fmt.Sprintf("%s/%s", d.clusterName, obj.Name))
}
cancel()
}
}
}
func (d *NodeDrain) resetDesiredNodeUnschedulable(obj *v3.Node) error {
nodeCopy := obj.DeepCopy()
removeDrainCondition(nodeCopy)
nodeCopy.Spec.DesiredNodeUnschedulable = ""
if _, err := d.machines.Update(nodeCopy); err != nil {
return err
}
return nil
}
func (d *NodeDrain) getKubeConfig() (*clientcmdapi.Config, error) {
cluster, err := d.clusterLister.Get("", d.clusterName)
if err != nil {
return nil, err
}
user, err := d.systemAccountManager.GetSystemUser(cluster.Name)
if err != nil {
return nil, err
}
token, err := d.userManager.EnsureToken(drainTokenPrefix+user.Name, description, user.Name)
if err != nil {
return nil, err
}
kubeConfig := d.kubeConfigGetter.KubeConfig(d.clusterName, token)
for k := range kubeConfig.Clusters {
kubeConfig.Clusters[k].InsecureSkipTLSVerify = true
}
return kubeConfig, nil
}
func getFlags(input *v3.NodeDrainInput) []string {
return []string{
fmt.Sprintf("--delete-local-data=%v", input.DeleteLocalData),
fmt.Sprintf("--force=%v", input.Force),
fmt.Sprintf("--grace-period=%v", input.GracePeriod),
fmt.Sprintf("--ignore-daemonsets=%v", input.IgnoreDaemonSets),
fmt.Sprintf("--timeout=%s", convert.ToString(input.Timeout)+"s")}
}
func filterErrorMsg(msg string, nodeName string) string {
upd := []string{}
lines := strings.Split(msg, "\n")
for _, line := range lines[1:] {
if strings.HasPrefix(line, "WARNING") || strings.HasPrefix(line, nodeName) {
continue
}
if strings.Contains(line, "aborting") {
continue
}
if strings.HasPrefix(line, "There are pending nodes ") {
// for only one node in our case
continue
}
if strings.HasPrefix(line, "There are pending pods ") {
// already considered error
continue
}
if strings.HasPrefix(line, "error") && strings.Contains(line, "unable to drain node") {
// actual reason at end
continue
}
if strings.HasPrefix(line, "pod") && strings.Contains(line, "evicted") {
// evicted successfully
continue
}
upd = append(upd, line)
}
return strings.Join(upd, "\n")
}
func removeDrainCondition(obj *v3.Node) {
exists := false
for _, condition := range obj.Status.Conditions {
if condition.Type == "Drained" {
exists = true
break
}
}
if exists {
var conditions []v3.NodeCondition
for _, condition := range obj.Status.Conditions {
if condition.Type == "Drained" {
continue
}
conditions = append(conditions, condition)
}
obj.Status.Conditions = conditions
}
}
func deleteFromContextMap(data map[string]context.CancelFunc, id string) {
nodeMapLock.Lock()
delete(data, id)
nodeMapLock.Unlock()
}
func ignoreErr(msg string) (bool, bool) {
for _, val := range toIgnoreErrs {
if strings.Contains(msg, val) {
// check if timeout error
if !strings.HasPrefix(val, "--") {
return true, true
}
return true, false
}
}
return false, false
}
func setConditionDraining(node *v3.Node, err error, kubeErr error) {
v3.NodeConditionDrained.Unknown(node)
v3.NodeConditionDrained.Reason(node, "")
v3.NodeConditionDrained.Message(node, "")
}
func setConditionComplete(node *v3.Node, err error, kubeErr error) {
if err == nil {
v3.NodeConditionDrained.True(node)
} else {
v3.NodeConditionDrained.False(node)
v3.NodeConditionDrained.ReasonAndMessageFromError(node, err)
}
if kubeErr == nil {
node.Spec.DesiredNodeUnschedulable = ""
}
}