-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathibmvpcmachine_controller.go
294 lines (252 loc) · 11.3 KB
/
ibmvpcmachine_controller.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
/*
Copyright 2021 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/go-logr/logr"
"github.com/IBM/vpc-go-sdk/vpcv1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/conditions"
infrav1beta2 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2"
"sigs.k8s.io/cluster-api-provider-ibmcloud/cloud/scope"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/endpoints"
capibmrecord "sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/record"
)
// IBMVPCMachineReconciler reconciles a IBMVPCMachine object.
type IBMVPCMachineReconciler struct {
client.Client
Log logr.Logger
Recorder record.EventRecorder
ServiceEndpoint []endpoints.ServiceEndpoint
Scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=ibmvpcmachines,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=ibmvpcmachines/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=machines;machines/status,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=secrets;,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=get;list;watch;create;update;patch
// Reconcile implements controller runtime Reconciler interface and handles reconcileation logic for IBMVPCMachine.
func (r *IBMVPCMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
log := r.Log.WithValues("ibmvpcmachine", req.NamespacedName)
// Fetch the IBMVPCMachine instance.
ibmVpcMachine := &infrav1beta2.IBMVPCMachine{}
err := r.Get(ctx, req.NamespacedName, ibmVpcMachine)
if err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
// Fetch the Machine.
machine, err := util.GetOwnerMachine(ctx, r.Client, ibmVpcMachine.ObjectMeta)
if err != nil {
return ctrl.Result{}, err
}
if machine == nil {
log.Info("Machine Controller has not yet set OwnerRef")
return ctrl.Result{}, nil
}
// Fetch the Cluster.
cluster, err := util.GetClusterFromMetadata(ctx, r.Client, ibmVpcMachine.ObjectMeta)
if err != nil {
log.Info("Machine is missing cluster label or cluster does not exist")
return ctrl.Result{}, nil
}
log = log.WithValues("cluster", cluster.Name)
ibmCluster := &infrav1beta2.IBMVPCCluster{}
ibmVpcClusterName := client.ObjectKey{
Namespace: ibmVpcMachine.Namespace,
Name: cluster.Spec.InfrastructureRef.Name,
}
if err := r.Client.Get(ctx, ibmVpcClusterName, ibmCluster); err != nil {
log.Info("IBMVPCCluster is not available yet")
return ctrl.Result{}, nil
}
// Create the machine scope.
machineScope, err := scope.NewMachineScope(scope.MachineScopeParams{
Client: r.Client,
Logger: log,
Cluster: cluster,
IBMVPCCluster: ibmCluster,
Machine: machine,
IBMVPCMachine: ibmVpcMachine,
ServiceEndpoint: r.ServiceEndpoint,
})
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to create scope: %w", err)
}
// Always close the scope when exiting this function, so we can persist any IBMVPCMachine changes.
defer func() {
if machineScope != nil {
if err := machineScope.Close(); err != nil && reterr == nil {
reterr = err
}
}
}()
// Handle deleted machines.
if !ibmVpcMachine.DeletionTimestamp.IsZero() {
return r.reconcileDelete(machineScope)
}
// Handle non-deleted machines.
return r.reconcileNormal(ctx, machineScope)
}
// SetupWithManager creates a new IBMVPCMachine controller for a manager.
func (r *IBMVPCMachineReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&infrav1beta2.IBMVPCMachine{}).
Complete(r)
}
func (r *IBMVPCMachineReconciler) reconcileNormal(ctx context.Context, machineScope *scope.MachineScope) (ctrl.Result, error) { //nolint:gocyclo
log := ctrl.LoggerFrom(ctx)
log.V(3).Info("Reconciling IBMVPCMachine")
if controllerutil.AddFinalizer(machineScope.IBMVPCMachine, infrav1beta2.MachineFinalizer) {
return ctrl.Result{}, nil
}
// Make sure bootstrap data is available and populated.
if machineScope.Machine.Spec.Bootstrap.DataSecretName == nil {
log.V(3).Info("Bootstrap data secret reference is not yet available")
return ctrl.Result{RequeueAfter: 1 * time.Minute}, nil
}
if machineScope.IBMVPCCluster.Status.Subnet.ID != nil {
machineScope.IBMVPCMachine.Spec.PrimaryNetworkInterface = infrav1beta2.NetworkInterface{
Subnet: *machineScope.IBMVPCCluster.Status.Subnet.ID,
}
}
instance, err := r.getOrCreate(machineScope)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to reconcile VSI for IBMVPCMachine %s/%s: %w", machineScope.IBMVPCMachine.Namespace, machineScope.IBMVPCMachine.Name, err)
}
machineRunning := false
if instance != nil {
// Attempt to tag the Instance.
if err := machineScope.TagResource(machineScope.IBMVPCCluster.Name, *instance.CRN); err != nil {
return ctrl.Result{}, fmt.Errorf("error failed to tag machine: %w", err)
}
// Set available status' for Machine.
machineScope.SetInstanceID(*instance.ID)
if err := machineScope.SetProviderID(instance.ID); err != nil {
return ctrl.Result{}, fmt.Errorf("error failed to set machine provider id: %w", err)
}
machineScope.SetAddresses(instance)
machineScope.SetInstanceStatus(*instance.Status)
// Depending on the state of the Machine, update status, conditions, etc.
switch machineScope.GetInstanceStatus() {
case vpcv1.InstanceStatusPendingConst:
machineScope.SetNotReady()
conditions.MarkFalse(machineScope.IBMVPCMachine, infrav1beta2.InstanceReadyCondition, infrav1beta2.InstanceNotReadyReason, capiv1beta1.ConditionSeverityWarning, "")
case vpcv1.InstanceStatusStoppedConst:
machineScope.SetNotReady()
conditions.MarkFalse(machineScope.IBMVPCMachine, infrav1beta2.InstanceReadyCondition, infrav1beta2.InstanceStoppedReason, capiv1beta1.ConditionSeverityError, "")
case vpcv1.InstanceStatusFailedConst:
msg := ""
healthReasonsLen := len(instance.HealthReasons)
if healthReasonsLen > 0 {
// Create a failure message using the last entry's Code and Message fields.
// TODO(cjschaef): Consider adding the MoreInfo field as well, as it contains a link to IBM Cloud docs.
msg = fmt.Sprintf("%s: %s", *instance.HealthReasons[healthReasonsLen-1].Code, *instance.HealthReasons[healthReasonsLen-1].Message)
}
machineScope.SetNotReady()
machineScope.SetFailureReason(infrav1beta2.UpdateMachineError)
machineScope.SetFailureMessage(msg)
conditions.MarkFalse(machineScope.IBMVPCMachine, infrav1beta2.InstanceReadyCondition, infrav1beta2.InstanceErroredReason, capiv1beta1.ConditionSeverityError, "%s", msg)
capibmrecord.Warnf(machineScope.IBMVPCMachine, "FailedBuildInstance", "Failed to build the instance - %s", msg)
return ctrl.Result{}, nil
case vpcv1.InstanceStatusRunningConst:
machineRunning = true
default:
machineScope.SetNotReady()
log.V(3).Info("unexpected vpc instance status", "instanceStatus", *instance.Status, "instanceID", machineScope.GetInstanceID())
conditions.MarkUnknown(machineScope.IBMVPCMachine, infrav1beta2.InstanceReadyCondition, "", "")
}
} else {
machineScope.SetNotReady()
conditions.MarkUnknown(machineScope.IBMVPCMachine, infrav1beta2.InstanceReadyCondition, infrav1beta2.InstanceStateUnknownReason, "")
}
// Check if the Machine is running.
if !machineRunning {
// Requeue after 1 minute if machine is not running.
return ctrl.Result{RequeueAfter: 1 * time.Minute}, nil
}
// Rely on defined VPC Load Balancer Pool Members first before falling back to hardcoded defaults.
if len(machineScope.IBMVPCMachine.Spec.LoadBalancerPoolMembers) > 0 {
needsRequeue := false
for _, poolMember := range machineScope.IBMVPCMachine.Spec.LoadBalancerPoolMembers {
requeue, err := machineScope.ReconcileVPCLoadBalancerPoolMember(poolMember)
if err != nil {
return ctrl.Result{}, fmt.Errorf("error failed to reconcile machine's pool member: %w", err)
} else if requeue {
needsRequeue = true
}
}
// If any VPC Load Balancer Pool Member needs reconciliation, requeue.
if needsRequeue {
return ctrl.Result{RequeueAfter: 1 * time.Minute}, nil
}
} else {
// Otherwise, default to previous Load Balancer Pool Member configuration.
_, ok := machineScope.IBMVPCMachine.Labels[capiv1beta1.MachineControlPlaneNameLabel]
if err = machineScope.SetProviderID(instance.ID); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to set provider id IBMVPCMachine %s/%s: %w", machineScope.IBMVPCMachine.Namespace, machineScope.IBMVPCMachine.Name, err)
}
if ok {
if instance.PrimaryNetworkInterface.PrimaryIP.Address == nil || *instance.PrimaryNetworkInterface.PrimaryIP.Address == "0.0.0.0" {
return ctrl.Result{}, fmt.Errorf("invalid primary ip address")
}
internalIP := instance.PrimaryNetworkInterface.PrimaryIP.Address
port := int64(machineScope.APIServerPort())
poolMember, err := machineScope.CreateVPCLoadBalancerPoolMember(internalIP, port)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to bind port %d to control plane %s/%s: %w", port, machineScope.IBMVPCMachine.Namespace, machineScope.IBMVPCMachine.Name, err)
}
if poolMember != nil && *poolMember.ProvisioningStatus != string(infrav1beta2.VPCLoadBalancerStateActive) {
return ctrl.Result{RequeueAfter: 1 * time.Minute}, nil
}
}
}
// With a running machine and all Load Balancer Pool Members reconciled, mark machine as ready.
machineScope.SetReady()
conditions.MarkTrue(machineScope.IBMVPCMachine, infrav1beta2.InstanceReadyCondition)
return ctrl.Result{}, nil
}
func (r *IBMVPCMachineReconciler) getOrCreate(scope *scope.MachineScope) (*vpcv1.Instance, error) {
instance, err := scope.CreateMachine()
return instance, err
}
func (r *IBMVPCMachineReconciler) reconcileDelete(scope *scope.MachineScope) (_ ctrl.Result, reterr error) {
scope.Info("Handling deleted IBMVPCMachine")
if _, ok := scope.IBMVPCMachine.Labels[capiv1beta1.MachineControlPlaneNameLabel]; ok {
if err := scope.DeleteVPCLoadBalancerPoolMember(); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to delete loadBalancer pool member: %w", err)
}
}
if err := scope.DeleteMachine(); err != nil {
scope.Info("error deleting IBMVPCMachine")
return ctrl.Result{}, fmt.Errorf("error deleting IBMVPCMachine %s/%s: %w", scope.IBMVPCMachine.Namespace, scope.IBMVPCMachine.Spec.Name, err)
}
defer func() {
if reterr == nil {
// VSI is deleted so remove the finalizer.
controllerutil.RemoveFinalizer(scope.IBMVPCMachine, infrav1beta2.MachineFinalizer)
}
}()
return ctrl.Result{}, nil
}