-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmachinepool_controller_noderef.go
228 lines (197 loc) · 8.2 KB
/
machinepool_controller_noderef.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
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"fmt"
"time"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/controllers/noderefutil"
expv1 "sigs.k8s.io/cluster-api/exp/api/v1beta1"
"sigs.k8s.io/cluster-api/internal/util/taints"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/annotations"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
)
var errNoAvailableNodes = errors.New("cannot find nodes with matching ProviderIDs in ProviderIDList")
type getNodeReferencesResult struct {
references []corev1.ObjectReference
available int
ready int
}
func (r *MachinePoolReconciler) reconcileNodeRefs(ctx context.Context, s *scope) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
cluster := s.cluster
mp := s.machinePool
// Create a watch on the nodes in the Cluster.
if err := r.watchClusterNodes(ctx, cluster); err != nil {
return ctrl.Result{}, err
}
// Check that the MachinePool hasn't been deleted or in the process.
if !mp.DeletionTimestamp.IsZero() {
return ctrl.Result{}, nil
}
// Check that the Machine doesn't already have a NodeRefs.
// Return early if there is no work to do.
if mp.Status.Replicas == mp.Status.ReadyReplicas && len(mp.Status.NodeRefs) == int(mp.Status.ReadyReplicas) {
conditions.MarkTrue(mp, expv1.ReplicasReadyCondition)
return ctrl.Result{}, nil
}
// Check that the MachinePool has valid ProviderIDList.
if len(mp.Spec.ProviderIDList) == 0 && (mp.Spec.Replicas == nil || *mp.Spec.Replicas != 0) {
log.V(2).Info("MachinePool doesn't have any ProviderIDs yet")
return ctrl.Result{}, nil
}
clusterClient, err := r.ClusterCache.GetClient(ctx, util.ObjectKey(cluster))
if err != nil {
return ctrl.Result{}, err
}
if err = r.deleteRetiredNodes(ctx, clusterClient, mp.Status.NodeRefs, mp.Spec.ProviderIDList); err != nil {
return ctrl.Result{}, err
}
// Return early if nodeRefMap is nil.
if s.nodeRefMap == nil {
return ctrl.Result{}, errors.New("failed to get Node references")
}
// Get the Node references.
nodeRefsResult, err := r.getNodeReferences(ctx, mp.Spec.ProviderIDList, mp.Spec.MinReadySeconds, s.nodeRefMap)
if err != nil {
if err == errNoAvailableNodes {
log.Info("Cannot assign NodeRefs to MachinePool, no matching Nodes")
// No need to requeue here. Nodes emit an event that triggers reconciliation.
return ctrl.Result{}, nil
}
r.recorder.Event(mp, corev1.EventTypeWarning, "FailedSetNodeRef", err.Error())
return ctrl.Result{}, errors.Wrapf(err, "failed to get node references")
}
mp.Status.ReadyReplicas = int32(nodeRefsResult.ready)
mp.Status.AvailableReplicas = int32(nodeRefsResult.available)
mp.Status.UnavailableReplicas = mp.Status.Replicas - mp.Status.AvailableReplicas
mp.Status.NodeRefs = nodeRefsResult.references
log.Info("Set MachinePool's NodeRefs", "nodeRefs", mp.Status.NodeRefs)
r.recorder.Event(mp, corev1.EventTypeNormal, "SuccessfulSetNodeRefs", fmt.Sprintf("%+v", mp.Status.NodeRefs))
// Reconcile node annotations and taints.
err = r.patchNodes(ctx, clusterClient, nodeRefsResult.references, mp)
if err != nil {
return ctrl.Result{}, err
}
if mp.Status.Replicas != mp.Status.ReadyReplicas || len(nodeRefsResult.references) != int(mp.Status.ReadyReplicas) {
log.Info("Not enough ready replicas or node references", "nodeRefs", len(nodeRefsResult.references), "readyReplicas", mp.Status.ReadyReplicas, "replicas", mp.Status.Replicas)
conditions.MarkFalse(mp, expv1.ReplicasReadyCondition, expv1.WaitingForReplicasReadyReason, clusterv1.ConditionSeverityInfo, "")
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
// At this point, the required number of replicas are ready
conditions.MarkTrue(mp, expv1.ReplicasReadyCondition)
return ctrl.Result{}, nil
}
// deleteRetiredNodes deletes nodes that don't have a corresponding ProviderID in Spec.ProviderIDList.
// A MachinePool infrastructure provider indicates an instance in the set has been deleted by
// removing its ProviderID from the slice.
func (r *MachinePoolReconciler) deleteRetiredNodes(ctx context.Context, c client.Client, nodeRefs []corev1.ObjectReference, providerIDList []string) error {
log := ctrl.LoggerFrom(ctx, "providerIDList", len(providerIDList))
nodeRefsMap := make(map[string]*corev1.Node, len(nodeRefs))
for _, nodeRef := range nodeRefs {
node := &corev1.Node{}
if err := c.Get(ctx, client.ObjectKey{Name: nodeRef.Name}, node); err != nil {
log.Error(err, "Failed to get Node, skipping", "Node", klog.KRef("", nodeRef.Name))
continue
}
if node.Spec.ProviderID == "" {
log.V(2).Info("No ProviderID detected, skipping", "providerID", node.Spec.ProviderID)
continue
}
nodeRefsMap[node.Spec.ProviderID] = node
}
for _, providerID := range providerIDList {
if providerID == "" {
log.V(2).Info("No ProviderID detected, skipping", "providerID", providerID)
continue
}
delete(nodeRefsMap, providerID)
}
for _, node := range nodeRefsMap {
if err := c.Delete(ctx, node); err != nil && !apierrors.IsNotFound(err) {
return errors.Wrapf(err, "failed to delete Node")
}
}
return nil
}
func (r *MachinePoolReconciler) getNodeReferences(ctx context.Context, providerIDList []string, minReadySeconds *int32, nodeRefsMap map[string]*corev1.Node) (getNodeReferencesResult, error) {
log := ctrl.LoggerFrom(ctx, "providerIDList", len(providerIDList))
var ready, available int
var nodeRefs []corev1.ObjectReference
for _, providerID := range providerIDList {
if providerID == "" {
log.V(2).Info("No ProviderID detected, skipping", "providerID", providerID)
continue
}
if node, ok := nodeRefsMap[providerID]; ok {
if noderefutil.IsNodeReady(node) {
ready++
if noderefutil.IsNodeAvailable(node, *minReadySeconds, metav1.Now()) {
available++
}
}
nodeRefs = append(nodeRefs, corev1.ObjectReference{
APIVersion: corev1.SchemeGroupVersion.String(),
Kind: "Node",
Name: node.Name,
UID: node.UID,
})
}
}
if len(nodeRefs) == 0 && len(providerIDList) != 0 {
return getNodeReferencesResult{}, errNoAvailableNodes
}
return getNodeReferencesResult{nodeRefs, available, ready}, nil
}
// patchNodes patches the nodes with the cluster name and cluster namespace annotations.
func (r *MachinePoolReconciler) patchNodes(ctx context.Context, c client.Client, references []corev1.ObjectReference, mp *expv1.MachinePool) error {
log := ctrl.LoggerFrom(ctx)
for _, nodeRef := range references {
node := &corev1.Node{}
if err := c.Get(ctx, client.ObjectKey{Name: nodeRef.Name}, node); err != nil {
log.Error(err, "Failed to get Node, skipping setting annotations", "Node", klog.KRef("", nodeRef.Name))
continue
}
patchHelper, err := patch.NewHelper(node, c)
if err != nil {
return err
}
desired := map[string]string{
clusterv1.ClusterNameAnnotation: mp.Spec.ClusterName,
clusterv1.ClusterNamespaceAnnotation: mp.GetNamespace(),
clusterv1.OwnerKindAnnotation: mp.Kind,
clusterv1.OwnerNameAnnotation: mp.Name,
}
// Add annotations and drop NodeUninitializedTaint.
hasAnnotationChanges := annotations.AddAnnotations(node, desired)
hasTaintChanges := taints.RemoveNodeTaint(node, clusterv1.NodeUninitializedTaint)
// Patch the node if needed.
if hasAnnotationChanges || hasTaintChanges {
if err := patchHelper.Patch(ctx, node); err != nil {
log.Error(err, "Failed patch Node to set annotations and drop taints", "Node", klog.KObj(node))
return err
}
}
}
return nil
}