-
Notifications
You must be signed in to change notification settings - Fork 77
/
ibmpowervscluster_controller.go
462 lines (390 loc) · 18.3 KB
/
ibmpowervscluster_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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
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"
"strings"
"time"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/tools/record"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/predicates"
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/cloud/services/powervs"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/endpoints"
genUtil "sigs.k8s.io/cluster-api-provider-ibmcloud/util"
)
// IBMPowerVSClusterReconciler reconciles a IBMPowerVSCluster object.
type IBMPowerVSClusterReconciler struct {
client.Client
Recorder record.EventRecorder
ServiceEndpoint []endpoints.ServiceEndpoint
Scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=ibmpowervsclusters,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=ibmpowervsclusters/status,verbs=get;update;patch
// Reconcile implements controller runtime Reconciler interface and handles reconcileation logic for IBMPowerVSCluster.
func (r *IBMPowerVSClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
log := ctrl.LoggerFrom(ctx)
// Fetch the IBMPowerVSCluster instance.
ibmCluster := &infrav1beta2.IBMPowerVSCluster{}
err := r.Get(ctx, req.NamespacedName, ibmCluster)
if err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
// Fetch the Cluster.
cluster, err := util.GetOwnerCluster(ctx, r.Client, ibmCluster.ObjectMeta)
if err != nil {
return ctrl.Result{}, err
}
if cluster == nil {
log.Info("Cluster Controller has not yet set OwnerRef")
return ctrl.Result{}, nil
}
log = log.WithValues("cluster", klog.KObj(cluster))
// Create the scope.
clusterScope, err := scope.NewPowerVSClusterScope(scope.PowerVSClusterScopeParams{
Client: r.Client,
Logger: log,
Cluster: cluster,
IBMPowerVSCluster: ibmCluster,
ServiceEndpoint: r.ServiceEndpoint,
})
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed to create scope: %w", err)
}
// Always close the scope when exiting this function so we can persist any IBMPowerVSCluster changes.
defer func() {
if err := clusterScope.Close(); err != nil && reterr == nil {
reterr = err
}
}()
// Handle deleted clusters.
if !ibmCluster.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, clusterScope)
}
return r.reconcile(clusterScope)
}
func (r *IBMPowerVSClusterReconciler) reconcile(clusterScope *scope.PowerVSClusterScope) (ctrl.Result, error) { //nolint:gocyclo
if controllerutil.AddFinalizer(clusterScope.IBMPowerVSCluster, infrav1beta2.IBMPowerVSClusterFinalizer) {
return ctrl.Result{}, nil
}
// check for annotation set for cluster resource and decide on proceeding with infra creation.
// do not proceed further if "powervs.cluster.x-k8s.io/create-infra=true" annotation is not set.
if !genUtil.CheckCreateInfraAnnotation(*clusterScope.IBMPowerVSCluster) {
clusterScope.IBMPowerVSCluster.Status.Ready = true
return ctrl.Result{}, nil
}
// validate PER availability for the PowerVS zone, proceed further only if PowerVS zone support PER.
// more information about PER can be found here: https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-per
if err := clusterScope.IsPowerVSZoneSupportsPER(); err != nil {
clusterScope.Error(err, "error checking PER capability for PowerVS zone")
return reconcile.Result{}, err
}
// reconcile service resource group
clusterScope.Info("Reconciling resource group")
if err := clusterScope.ReconcileResourceGroup(); err != nil {
clusterScope.Error(err, "failed to reconcile resource group")
return reconcile.Result{}, err
}
powerVSCluster := clusterScope.IBMPowerVSCluster
// reconcile PowerVS service instance
clusterScope.Info("Reconciling PowerVS service instance")
if requeue, err := clusterScope.ReconcilePowerVSServiceInstance(); err != nil {
clusterScope.Error(err, "failed to reconcile PowerVS service instance")
conditions.MarkFalse(powerVSCluster, infrav1beta2.ServiceInstanceReadyCondition, infrav1beta2.ServiceInstanceReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
} else if requeue {
clusterScope.Info("PowerVS service instance creation is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.ServiceInstanceReadyCondition)
clusterScope.IBMPowerVSClient.WithClients(powervs.ServiceOptions{CloudInstanceID: clusterScope.GetServiceInstanceID()})
// reconcile network
clusterScope.Info("Reconciling network")
if requeue, err := clusterScope.ReconcileNetwork(); err != nil {
clusterScope.Error(err, "failed to reconcile PowerVS network")
conditions.MarkFalse(powerVSCluster, infrav1beta2.NetworkReadyCondition, infrav1beta2.NetworkReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
} else if requeue {
clusterScope.Info("PowerVS network creation is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.NetworkReadyCondition)
// reconcile VPC
clusterScope.Info("Reconciling VPC")
if requeue, err := clusterScope.ReconcileVPC(); err != nil {
clusterScope.Error(err, "failed to reconcile VPC")
conditions.MarkFalse(powerVSCluster, infrav1beta2.VPCReadyCondition, infrav1beta2.VPCReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
} else if requeue {
clusterScope.Info("VPC creation is pending, requeuing")
return reconcile.Result{RequeueAfter: 15 * time.Second}, nil
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.VPCReadyCondition)
// reconcile VPC Subnet
clusterScope.Info("Reconciling VPC subnets")
if requeue, err := clusterScope.ReconcileVPCSubnet(); err != nil {
clusterScope.Error(err, "failed to reconcile VPC subnet")
conditions.MarkFalse(powerVSCluster, infrav1beta2.VPCSubnetReadyCondition, infrav1beta2.VPCSubnetReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
} else if requeue {
clusterScope.Info("VPC subnet creation is pending, requeuing")
return reconcile.Result{RequeueAfter: 15 * time.Second}, nil
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.VPCSubnetReadyCondition)
// reconcile Transit Gateway
clusterScope.Info("Reconciling Transit Gateway")
if requeue, err := clusterScope.ReconcileTransitGateway(); err != nil {
clusterScope.Error(err, "failed to reconcile transit gateway")
conditions.MarkFalse(powerVSCluster, infrav1beta2.TransitGatewayReadyCondition, infrav1beta2.TransitGatewayReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
} else if requeue {
clusterScope.Info("Transit gateway creation is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.TransitGatewayReadyCondition)
// reconcile LoadBalancer
clusterScope.Info("Reconciling VPC load balancers")
if requeue, err := clusterScope.ReconcileLoadBalancer(); err != nil {
clusterScope.Error(err, "failed to reconcile VPC load balancer")
conditions.MarkFalse(powerVSCluster, infrav1beta2.LoadBalancerReadyCondition, infrav1beta2.LoadBalancerReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
} else if requeue {
clusterScope.Info("VPC load balancer creation is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
// reconcile COSInstance
if clusterScope.IBMPowerVSCluster.Spec.Ignition != nil {
clusterScope.Info("Reconciling COS service instance")
if err := clusterScope.ReconcileCOSInstance(); err != nil {
conditions.MarkFalse(powerVSCluster, infrav1beta2.COSInstanceReadyCondition, infrav1beta2.COSInstanceReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error())
return reconcile.Result{}, err
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.COSInstanceReadyCondition)
}
// update cluster object with loadbalancer host
loadBalancer := clusterScope.PublicLoadBalancer()
if loadBalancer == nil {
return reconcile.Result{}, fmt.Errorf("failed to fetch public loadbalancer")
}
if clusterScope.GetLoadBalancerState(loadBalancer.Name) == nil || *clusterScope.GetLoadBalancerState(loadBalancer.Name) != infrav1beta2.VPCLoadBalancerStateActive {
clusterScope.Info("LoadBalancer state is not active")
return reconcile.Result{RequeueAfter: time.Minute}, nil
}
clusterScope.Info("Getting load balancer host")
hostName := clusterScope.GetLoadBalancerHostName(loadBalancer.Name)
if hostName == nil || *hostName == "" {
clusterScope.Info("LoadBalancer hostname is not yet available, requeuing")
return reconcile.Result{RequeueAfter: time.Minute}, nil
}
conditions.MarkTrue(powerVSCluster, infrav1beta2.LoadBalancerReadyCondition)
clusterScope.IBMPowerVSCluster.Spec.ControlPlaneEndpoint.Host = *clusterScope.GetLoadBalancerHostName(loadBalancer.Name)
clusterScope.IBMPowerVSCluster.Spec.ControlPlaneEndpoint.Port = clusterScope.APIServerPort()
clusterScope.IBMPowerVSCluster.Status.Ready = true
return ctrl.Result{}, nil
}
func (r *IBMPowerVSClusterReconciler) reconcileDelete(ctx context.Context, clusterScope *scope.PowerVSClusterScope) (ctrl.Result, error) {
cluster := clusterScope.IBMPowerVSCluster
if result, err := r.deleteIBMPowerVSImage(ctx, clusterScope); err != nil || !result.IsZero() {
return result, err
}
// check for annotation set for cluster resource and decide on proceeding with infra deletion.
if !genUtil.CheckCreateInfraAnnotation(*clusterScope.IBMPowerVSCluster) {
controllerutil.RemoveFinalizer(cluster, infrav1beta2.IBMPowerVSClusterFinalizer)
return ctrl.Result{}, nil
}
clusterScope.Info("Reconciling IBMPowerVSCluster delete")
allErrs := []error{}
clusterScope.IBMPowerVSClient.WithClients(powervs.ServiceOptions{CloudInstanceID: clusterScope.GetServiceInstanceID()})
clusterScope.Info("Deleting Transit Gateway")
if requeue, err := clusterScope.DeleteTransitGateway(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete transit gateway"))
} else if requeue {
clusterScope.Info("Transit gateway deletion is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
clusterScope.Info("Deleting VPC load balancer")
if requeue, err := clusterScope.DeleteLoadBalancer(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete VPC load balancer"))
} else if requeue {
clusterScope.Info("VPC load balancer deletion is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
clusterScope.Info("Deleting VPC subnet")
if requeue, err := clusterScope.DeleteVPCSubnet(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete VPC subnet"))
} else if requeue {
clusterScope.Info("VPC subnet deletion is pending, requeuing")
return reconcile.Result{RequeueAfter: 15 * time.Second}, nil
}
clusterScope.Info("Deleting VPC")
if requeue, err := clusterScope.DeleteVPC(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete VPC"))
} else if requeue {
clusterScope.Info("VPC deletion is pending, requeuing")
return reconcile.Result{RequeueAfter: 15 * time.Second}, nil
}
clusterScope.Info("Deleting DHCP server")
if err := clusterScope.DeleteDHCPServer(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete DHCP server"))
}
clusterScope.Info("Deleting Power VS service instance")
if requeue, err := clusterScope.DeleteServiceInstance(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete Power VS service instance"))
} else if requeue {
clusterScope.Info("PowerVS service instance deletion is pending, requeuing")
return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil
}
if clusterScope.IBMPowerVSCluster.Spec.Ignition != nil {
clusterScope.Info("Deleting COS service instance")
if err := clusterScope.DeleteCOSInstance(); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "failed to delete COS service instance"))
}
}
if len(allErrs) > 0 {
return ctrl.Result{}, kerrors.NewAggregate(allErrs)
}
clusterScope.Info("IBMPowerVSCluster deletion completed")
controllerutil.RemoveFinalizer(cluster, infrav1beta2.IBMPowerVSClusterFinalizer)
return ctrl.Result{}, nil
}
func (r *IBMPowerVSClusterReconciler) deleteIBMPowerVSImage(ctx context.Context, clusterScope *scope.PowerVSClusterScope) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
cluster := clusterScope.IBMPowerVSCluster
descendants, err := r.listDescendants(ctx, cluster)
if err != nil {
log.Error(err, "Failed to list descendants")
return reconcile.Result{}, err
}
// since we are avoiding using cache for IBMPowerVSCluster the Type meta of the retrieved object will be empty
// explicitly setting here to filter children
if gvk := cluster.GetObjectKind().GroupVersionKind(); gvk.Empty() {
gvk, err := r.GroupVersionKindFor(cluster)
if err != nil {
log.Error(err, "Failed to get GVK of cluster")
return reconcile.Result{}, err
}
cluster.SetGroupVersionKind(gvk)
}
children, err := descendants.filterOwnedDescendants(cluster)
if err != nil {
log.Error(err, "Failed to extract direct descendants")
return reconcile.Result{}, err
}
if len(children) > 0 {
log.Info("Cluster still has children - deleting them first", "count", len(children))
var errs []error
for _, child := range children {
if !child.GetDeletionTimestamp().IsZero() {
// Don't handle deleted child.
continue
}
gvk := child.GetObjectKind().GroupVersionKind().String()
log.Info("Deleting child object", "gvk", gvk, "name", child.GetName())
if err := r.Client.Delete(ctx, child); err != nil {
err = fmt.Errorf("error deleting cluster %s/%s: failed to delete %s %s: %w", cluster.Namespace, cluster.Name, gvk, child.GetName(), err)
log.Error(err, "Error deleting resource", "gvk", gvk, "name", child.GetName())
errs = append(errs, err)
}
}
if len(errs) > 0 {
return ctrl.Result{}, kerrors.NewAggregate(errs)
}
}
if descendantCount := descendants.length(); descendantCount > 0 {
indirect := descendantCount - len(children)
log.Info("Cluster still has descendants - need to requeue", "descendants", descendants.descendantNames(), "indirect descendants count", indirect)
// Requeue so we can check the next time to see if there are still any descendants left.
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
return ctrl.Result{}, nil
}
type clusterDescendants struct {
ibmPowerVSImages infrav1beta2.IBMPowerVSImageList
}
// length returns the number of descendants.
func (c *clusterDescendants) length() int {
return len(c.ibmPowerVSImages.Items)
}
func (c *clusterDescendants) descendantNames() string {
descendants := make([]string, 0)
ibmPowerVSImageNames := make([]string, len(c.ibmPowerVSImages.Items))
for i, ibmPowerVSImage := range c.ibmPowerVSImages.Items {
ibmPowerVSImageNames[i] = ibmPowerVSImage.Name
}
if len(ibmPowerVSImageNames) > 0 {
descendants = append(descendants, "IBM Powervs Images: "+strings.Join(ibmPowerVSImageNames, ","))
}
return strings.Join(descendants, ";")
}
// listDescendants returns a list of all IBMPowerVSImages for the cluster.
func (r *IBMPowerVSClusterReconciler) listDescendants(ctx context.Context, cluster *infrav1beta2.IBMPowerVSCluster) (clusterDescendants, error) {
var descendants clusterDescendants
listOptions := []client.ListOption{
client.InNamespace(cluster.Namespace),
client.MatchingLabels(map[string]string{capiv1beta1.ClusterNameLabel: cluster.Name}),
}
if err := r.Client.List(ctx, &descendants.ibmPowerVSImages, listOptions...); err != nil {
return descendants, fmt.Errorf("failed to list IBMPowerVSImages for cluster %s/%s: %w", cluster.Namespace, cluster.Name, err)
}
return descendants, nil
}
// filterOwnedDescendants returns an array of runtime.Objects containing only those descendants that have the cluster
// as an owner reference.
func (c clusterDescendants) filterOwnedDescendants(cluster *infrav1beta2.IBMPowerVSCluster) ([]client.Object, error) {
var ownedDescendants []client.Object
eachFunc := func(o runtime.Object) error {
obj := o.(client.Object)
acc, err := meta.Accessor(obj)
if err != nil {
return nil //nolint:nilerr // We don't want to exit the EachListItem loop, just continue
}
if util.IsOwnedByObject(acc, cluster) {
ownedDescendants = append(ownedDescendants, obj)
}
return nil
}
lists := []client.ObjectList{
&c.ibmPowerVSImages,
}
for _, list := range lists {
if err := meta.EachListItem(list, eachFunc); err != nil {
return nil, fmt.Errorf("error finding owned descendants of cluster %s/%s: %w", cluster.Namespace, cluster.Name, err)
}
}
return ownedDescendants, nil
}
// SetupWithManager creates a new IBMPowerVSCluster controller for a manager.
func (r *IBMPowerVSClusterReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&infrav1beta2.IBMPowerVSCluster{}).
WithEventFilter(predicates.ResourceIsNotExternallyManaged(ctrl.LoggerFrom(context.TODO()))).
Complete(r)
}