-
Notifications
You must be signed in to change notification settings - Fork 8
/
vspheremachine_controller.go
227 lines (187 loc) · 8.6 KB
/
vspheremachine_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
/*
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/pkg/errors"
"github.com/spectrocloud/cluster-api-provider-vsphere-static-ip/pkg/ipam"
"github.com/spectrocloud/cluster-api-provider-vsphere-static-ip/pkg/ipam/factory"
_ "github.com/spectrocloud/cluster-api-provider-vsphere-static-ip/pkg/ipam/metal3io"
"github.com/spectrocloud/cluster-api-provider-vsphere-static-ip/pkg/util"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
infrav1 "sigs.k8s.io/cluster-api-provider-vsphere/api/v1alpha4"
capi "sigs.k8s.io/cluster-api/api/v1alpha4"
clusterutilv1 "sigs.k8s.io/cluster-api/util"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// VSphereMachineReconciler reconciles a VSphereMachine object
type VSphereMachineReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=kubeadmcontrolplanes,verbs=get;list;watch
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=vspheremachinetemplates,verbs=get;list;watch
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=vspheremachines,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=vspheremachines/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=machines;machines/status,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=clusters;clusters/status,verbs=get;list;watch
// +kubebuilder:rbac:groups=ipam.metal3.io,resources=ippools,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups=ipam.metal3.io,resources=ippools/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=ipam.metal3.io,resources=ipclaims,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=ipam.metal3.io,resources=ipclaims/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=ipam.metal3.io,resources=ipaddresses,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=ipam.metal3.io,resources=ipaddresses/status,verbs=get;update;patch
func (r *VSphereMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("vspheremachine", req.NamespacedName)
var res *ctrl.Result
var err error
vsphereMachine := &infrav1.VSphereMachine{}
if err := r.Get(ctx, req.NamespacedName, vsphereMachine); err != nil {
return ctrl.Result{}, util.IgnoreNotFound(err)
}
//handle the case where gvk is empty
if vsphereMachine.GroupVersionKind().Empty() {
log.V(0).Info("setting the missing gvk for vsphereMachine")
vsphereMachine.Kind = "VSphereMachine"
vsphereMachine.APIVersion = infrav1.GroupVersion.String()
}
// fetch the capi machine.
machine, err := clusterutilv1.GetOwnerMachine(ctx, r.Client, vsphereMachine.ObjectMeta)
if err != nil {
return ctrl.Result{}, err
}
if machine == nil {
log.V(0).Info("waiting for machine controller to set ownerRef on VSphereMachine")
return ctrl.Result{}, nil
}
// fetch the capi cluster
cluster, err := clusterutilv1.GetClusterFromMetadata(ctx, r.Client, machine.ObjectMeta)
if err != nil {
log.V(0).Info("machine is missing cluster label or cluster does not exist")
return ctrl.Result{}, nil
}
res, err = r.reconcileVSphereMachineIPAddress(cluster, vsphereMachine)
if err != nil {
log.Error(err, "failed to reconcile VSphereMachine IP")
}
if res == nil {
res = &ctrl.Result{}
}
return *res, err
}
func (r *VSphereMachineReconciler) reconcileVSphereMachineIPAddress(cluster *capi.Cluster, vSphereMachine *infrav1.VSphereMachine) (*ctrl.Result, error) {
if vSphereMachine == nil {
r.Log.V(0).Info("invalid VSphereMachine, skipping reconcile IPAddress")
return &ctrl.Result{}, nil
}
log := r.Log.WithValues("vsphereMachine", vSphereMachine.Name, "namespace", vSphereMachine.Namespace)
devices := vSphereMachine.Spec.VirtualMachineCloneSpec.Network.Devices
log.V(0).Info("reconcile IP address for VSphereMachine")
if len(devices) == 0 {
log.V(0).Info("no network device found for VSphereMachine")
return &ctrl.Result{}, nil
}
if util.IsMachineIPAllocationDHCP(devices) {
log.V(0).Info("VSphereMachine has allocation type DHCP")
return &ctrl.Result{}, nil
}
dataPatch := client.MergeFrom(vSphereMachine.DeepCopy())
newIpamFunc, ok := factory.IpamFactory[ipam.IpamTypeMetal3io]
if !ok {
log.V(0).Info("ipam type not supported")
return &ctrl.Result{}, nil
}
ipamFunc := newIpamFunc(r.Client, log)
for i := range devices {
if util.IsDeviceIPAllocationDHCP(devices[i]) || len(devices[i].IPAddrs) > 0 {
continue
}
poolMatchLabels, err := r.getIPPoolMatchLabels(r.Client, vSphereMachine)
if err != nil {
log.Error(err, "failed to get IPPool match labels")
return &ctrl.Result{}, nil
}
ipPool, err := ipamFunc.GetAvailableIPPool(poolMatchLabels, cluster.ObjectMeta)
if err != nil {
log.Error(err, "failed to get an available IPPool")
return &ctrl.Result{}, nil
}
if ipPool == nil {
log.V(0).Info("waiting for IPPool to be available")
return &ctrl.Result{}, nil
}
ipName := util.GetFormattedClaimName(vSphereMachine.Name, i)
ip, err := ipamFunc.GetIP(ipName, ipPool)
if err != nil {
return &ctrl.Result{}, errors.Wrapf(err, "failed to get allocated IP address for VSphereMachine %s", vSphereMachine.Name)
}
if ip == nil {
if _, err := ipamFunc.AllocateIP(ipName, ipPool, vSphereMachine); err != nil {
return &ctrl.Result{}, errors.Wrapf(err, "failed to allocate IP address for VSphereMachine: %s", vSphereMachine.Name)
}
log.V(0).Info("waiting for IP address to be available for the VSphereMachine")
return &ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
if err := util.ValidateIP(ip); err != nil {
return &ctrl.Result{}, errors.Wrapf(err, "invalid IP address retrieved for VSphereMachine: %s", vSphereMachine.Name)
}
log.V(0).Info("static IP selected for VSphereMachine", "IPAddressName", ip.GetName())
//capv expects static-ip in the CIDR format
ipCidr := fmt.Sprintf("%s/%d", util.GetAddress(ip), util.GetMask(ip))
log.V(0).Info("assigning IP address to VSphereMachine", "IPAddress", util.GetAddress(ip))
devices[i].IPAddrs = []string{ipCidr}
gateway := util.GetGateway(ip)
//TODO: handle ipv6
//gateway4 is required if DHCP4 is disabled, gateway6 is required if DHCP6 is disabled
devices[i].Gateway4 = gateway
//if configured, the values of nameservers and searchDomains from the IPPool
//will override the default values set from the VSphereMachineTemplate
nameservers := util.GetDNSServers(ipPool)
if len(nameservers) > 0 {
devices[i].Nameservers = nameservers
}
searchDomains := util.GetSearchDomains(ipPool)
if len(searchDomains) > 0 {
devices[i].SearchDomains = searchDomains
}
}
if err := r.Patch(context.TODO(), vSphereMachine, dataPatch); err != nil {
return &ctrl.Result{}, errors.Wrapf(err, "failed to patch VSphereMachine %s", vSphereMachine.Name)
}
log.V(0).Info("successfully reconciled IP address for VSphereMachine")
return &ctrl.Result{}, nil
}
func (r *VSphereMachineReconciler) getIPPoolMatchLabels(cli client.Client, vSphereMachine *infrav1.VSphereMachine) (map[string]string, error) {
//match labels for the IPPool are retrieved from the VSphereMachineTemplate
vmTemplateName, ok := vSphereMachine.GetAnnotations()[capi.TemplateClonedFromNameAnnotation]
if !ok {
return nil, fmt.Errorf("VSphereMachine %s has no value set in the 'cloned-from-name' annotation", vSphereMachine.Name)
}
vsphereMachineTemplate := &infrav1.VSphereMachineTemplate{}
key := types.NamespacedName{Namespace: vSphereMachine.Namespace, Name: vmTemplateName}
if err := cli.Get(context.Background(), key, vsphereMachineTemplate); err != nil {
return nil, fmt.Errorf("failed to get VSphereMachineTemplate %s", vmTemplateName)
}
return vsphereMachineTemplate.GetLabels(), nil
}
func (r *VSphereMachineReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&infrav1.VSphereMachine{}).
Complete(r)
}