-
Notifications
You must be signed in to change notification settings - Fork 84
/
ibmvpcmachine_controller.go
231 lines (199 loc) · 8.54 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
/*
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/IBM/vpc-go-sdk/vpcv1"
"github.com/go-logr/logr"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
"k8s.io/utils/pointer"
capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
infrav1beta1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1"
"sigs.k8s.io/cluster-api-provider-ibmcloud/cloud/scope"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/endpoints"
)
// 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 := &infrav1beta1.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 := &infrav1beta1.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{}, errors.Errorf("failed to create scope: %+v", err)
}
// Always close the scope when exiting this function, so we can persist any IBMVPCMachine changes.
defer func() {
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(machineScope)
}
// SetupWithManager creates a new IBMVPCMachine controller for a manager.
func (r *IBMVPCMachineReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&infrav1beta1.IBMVPCMachine{}).
Complete(r)
}
func (r *IBMVPCMachineReconciler) reconcileNormal(machineScope *scope.MachineScope) (ctrl.Result, error) {
controllerutil.AddFinalizer(machineScope.IBMVPCMachine, infrav1beta1.MachineFinalizer)
// Make sure bootstrap data is available and populated.
if machineScope.Machine.Spec.Bootstrap.DataSecretName == nil {
machineScope.Info("Bootstrap data secret reference is not yet available")
return ctrl.Result{}, nil
}
if machineScope.IBMVPCCluster.Status.Subnet.ID != nil {
machineScope.IBMVPCMachine.Spec.PrimaryNetworkInterface = infrav1beta1.NetworkInterface{
Subnet: *machineScope.IBMVPCCluster.Status.Subnet.ID,
}
}
instance, err := r.getOrCreate(machineScope)
if err != nil {
return ctrl.Result{}, errors.Wrapf(err, "failed to reconcile VSI for IBMVPCMachine %s/%s", machineScope.IBMVPCMachine.Namespace, machineScope.IBMVPCMachine.Name)
}
if instance != nil {
machineScope.IBMVPCMachine.Status.InstanceID = *instance.ID
machineScope.IBMVPCMachine.Status.Addresses = []corev1.NodeAddress{
{
Type: corev1.NodeInternalIP,
Address: *instance.PrimaryNetworkInterface.PrimaryIP.Address,
},
}
_, ok := machineScope.IBMVPCMachine.Labels[capiv1beta1.MachineControlPlaneLabelName]
machineScope.IBMVPCMachine.Spec.ProviderID = pointer.StringPtr(fmt.Sprintf("ibmvpc://%s/%s", machineScope.Machine.Spec.ClusterName, machineScope.IBMVPCMachine.Name))
if ok {
if machineScope.IBMVPCCluster.Spec.ControlPlaneLoadBalancer == nil {
options := &vpcv1.AddInstanceNetworkInterfaceFloatingIPOptions{}
options.SetID(*machineScope.IBMVPCCluster.Status.VPCEndpoint.FIPID)
options.SetInstanceID(*instance.ID)
options.SetNetworkInterfaceID(*instance.PrimaryNetworkInterface.ID)
floatingIP, _, err :=
machineScope.IBMVPCClient.AddInstanceNetworkInterfaceFloatingIP(options)
if err != nil {
return ctrl.Result{}, errors.Wrapf(err, "failed to bind floating IP to control plane %s/%s", machineScope.IBMVPCMachine.Namespace, machineScope.IBMVPCMachine.Name)
}
machineScope.IBMVPCMachine.Status.Addresses = append(machineScope.IBMVPCMachine.Status.Addresses, corev1.NodeAddress{
Type: corev1.NodeExternalIP,
Address: *floatingIP.Address,
})
} else {
if instance.PrimaryNetworkInterface.PrimaryIP.Address == nil || *instance.PrimaryNetworkInterface.PrimaryIP.Address == "0.0.0.0" {
return ctrl.Result{}, errors.Wrapf(err, "invalid primary ip address")
}
internalIP := instance.PrimaryNetworkInterface.PrimaryIP.Address
port := int64(6443)
poolMember, err := machineScope.CreateVPCLoadBalancerPoolMember(internalIP, port)
if err != nil {
return ctrl.Result{}, errors.Wrapf(err, "failed to bind port %d to control plane %s/%s", port, machineScope.IBMVPCMachine.Namespace, machineScope.IBMVPCMachine.Name)
}
if poolMember != nil && *poolMember.ProvisioningStatus != string(infrav1beta1.VPCLoadBalancerStateActive) {
return ctrl.Result{RequeueAfter: 1 * time.Minute}, nil
}
}
}
machineScope.IBMVPCMachine.Status.Ready = true
}
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.MachineControlPlaneLabelName]; ok && scope.IBMVPCCluster.Spec.ControlPlaneLoadBalancer != nil {
if err := scope.DeleteVPCLoadBalancerPoolMember(); err != nil {
return ctrl.Result{}, errors.Wrap(err, "failed to delete loadBalancer pool member")
}
}
if err := scope.DeleteMachine(); err != nil {
scope.Info("error deleting IBMVPCMachine")
return ctrl.Result{}, errors.Wrapf(err, "error deleting IBMVPCMachine %s/%s", scope.IBMVPCMachine.Namespace, scope.IBMVPCMachine.Spec.Name)
}
defer func() {
if reterr == nil {
// VSI is deleted so remove the finalizer.
controllerutil.RemoveFinalizer(scope.IBMVPCMachine, infrav1beta1.MachineFinalizer)
}
}()
return ctrl.Result{}, nil
}