This repository has been archived by the owner on Nov 30, 2023. It is now read-only.
/
create.go
463 lines (388 loc) · 14.4 KB
/
create.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
463
package azureconfig
import (
"context"
"fmt"
"net"
"strings"
"time"
"github.com/giantswarm/apiextensions/v6/pkg/annotation"
providerv1alpha1 "github.com/giantswarm/apiextensions/v6/pkg/apis/provider/v1alpha1"
"github.com/giantswarm/microerror"
"github.com/giantswarm/operatorkit/v7/pkg/controller/context/reconciliationcanceledcontext"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
capz "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1"
capi "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
localannotation "github.com/giantswarm/azure-operator/v6/pkg/annotation"
"github.com/giantswarm/azure-operator/v6/pkg/label"
"github.com/giantswarm/azure-operator/v6/service/controller/key"
"github.com/giantswarm/azure-operator/v6/service/network"
)
const (
dockerVolumeSizeGB = 50
kubeletVolumeSizeGB = 100
// DNS domain for dns searches in pods.
kubeletClusterDomain = "cluster.local"
kubeDNSIPLastOctet = 10
ProviderAzure = "azure"
)
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
azureCluster, err := key.ToAzureCluster(obj)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "finding required cluster api types")
var cluster capi.Cluster
{
nsName := types.NamespacedName{
Name: key.ClusterName(&azureCluster),
Namespace: azureCluster.Namespace,
}
err = r.ctrlClient.Get(ctx, nsName, &cluster)
if apierrors.IsNotFound(err) {
r.logger.Debugf(ctx, "referenced Cluster CR (%q) not found", nsName.String())
r.logger.Debugf(ctx, "cancelling reconciliation")
reconciliationcanceledcontext.SetCanceled(ctx)
return nil
} else if err != nil {
return microerror.Mask(err)
}
}
var masterMachines []capz.AzureMachine
var workerMachines []capz.AzureMachine
{
azureMachineList := &capz.AzureMachineList{}
{
err := r.ctrlClient.List(
ctx,
azureMachineList,
client.InNamespace(cluster.Namespace),
client.MatchingLabels{capi.ClusterLabelName: key.ClusterName(&cluster)},
)
if err != nil {
return microerror.Mask(err)
}
}
for i, m := range azureMachineList.Items {
if key.IsControlPlaneMachine(&azureMachineList.Items[i]) {
masterMachines = append(masterMachines, m)
} else {
workerMachines = append(workerMachines, m)
}
}
if len(masterMachines) < 1 {
r.logger.Debugf(ctx, "no control plane AzureMachines found for cluster %q", key.ClusterName(&cluster))
r.logger.Debugf(ctx, "cancelling reconciliation")
reconciliationcanceledcontext.SetCanceled(ctx)
return nil
}
}
r.logger.Debugf(ctx, "found required cluster api types")
r.logger.Debugf(ctx, "building azureconfig from cluster api crs")
var mappedAzureConfig providerv1alpha1.AzureConfig
{
mappedAzureConfig, err = r.buildAzureConfig(ctx, cluster, azureCluster, masterMachines, workerMachines)
if err != nil {
return microerror.Mask(err)
}
}
r.logger.Debugf(ctx, "built azureconfig from cluster api crs")
r.logger.Debugf(ctx, "finding existing azureconfig")
var presentAzureConfig providerv1alpha1.AzureConfig
{
nsName := types.NamespacedName{
Name: key.ClusterName(&cluster),
Namespace: metav1.NamespaceDefault,
}
err = r.ctrlClient.Get(ctx, nsName, &presentAzureConfig)
if apierrors.IsNotFound(err) {
r.logger.Debugf(ctx, "did not found existing azureconfig")
r.logger.Debugf(ctx, "creating azureconfig")
err = r.ctrlClient.Create(ctx, &mappedAzureConfig)
if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "created azureconfig")
presentAzureConfig = mappedAzureConfig
} else if err != nil {
return microerror.Mask(err)
}
}
r.logger.Debugf(ctx, "finding if existing azureconfig needs update")
{
// Ensure that availability zones are kept as-is.
mappedAzureConfig.Spec.Azure.AvailabilityZones = presentAzureConfig.Spec.Azure.AvailabilityZones
// Ensure that present network allocations are kept as-is.
mappedAzureConfig.Spec.Azure.VirtualNetwork = presentAzureConfig.Spec.Azure.VirtualNetwork
// Were there any changes that requires CR update?
changed := false
if !azureConfigsEqual(mappedAzureConfig, presentAzureConfig) {
// Copy Spec section as-is. This should always match desired state.
presentAzureConfig.Spec = mappedAzureConfig.Spec
changed = true
}
// Copy mapped labels if missing or changed, but don't touch labels
// that we don't manage.
for k, v := range mappedAzureConfig.Labels {
old, exists := presentAzureConfig.Labels[k]
if old != v || !exists {
presentAzureConfig.Labels[k] = v
changed = true
}
}
// Ensure External IP address annotation is up to date.
if presentAzureConfig.Annotations == nil {
presentAzureConfig.Annotations = make(map[string]string)
}
presentAzureConfig.Annotations[localannotation.WorkersEgressExternalPublicIP] = mappedAzureConfig.Annotations[localannotation.WorkersEgressExternalPublicIP]
if changed {
r.logger.Debugf(ctx, "existing azureconfig needs update")
err = r.ctrlClient.Update(ctx, &presentAzureConfig)
if apierrors.IsConflict(err) {
r.logger.Debugf(ctx, "conflict trying to save object in k8s API concurrently")
r.logger.Debugf(ctx, "canceling resource")
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "existing azureconfig updated")
} else {
r.logger.Debugf(ctx, "no update for existing azureconfig needed")
}
}
r.logger.Debugf(ctx, "finding if existing azureconfig needs status update")
{
nsName := types.NamespacedName{
Name: key.ClusterName(&azureCluster),
Namespace: metav1.NamespaceDefault,
}
err = r.ctrlClient.Get(ctx, nsName, &presentAzureConfig)
if err != nil {
return microerror.Mask(err)
}
updateStatus := false
if len(presentAzureConfig.Status.Cluster.Conditions) == 0 {
c := providerv1alpha1.StatusClusterCondition{
Status: "True",
Type: "Creating",
}
presentAzureConfig.Status.Cluster.Conditions = append(presentAzureConfig.Status.Cluster.Conditions, c)
r.logger.Debugf(ctx, "cluster condition status needs update")
updateStatus = true
}
if len(presentAzureConfig.Status.Cluster.Versions) == 0 {
v := providerv1alpha1.StatusClusterVersion{
LastTransitionTime: metav1.Time{Time: time.Now()},
Semver: key.OperatorVersion(&presentAzureConfig),
}
presentAzureConfig.Status.Cluster.Versions = append(presentAzureConfig.Status.Cluster.Versions, v)
r.logger.Debugf(ctx, "cluster version status needs update")
updateStatus = true
}
if updateStatus {
err = r.ctrlClient.Status().Update(ctx, &presentAzureConfig)
if apierrors.IsConflict(err) {
r.logger.Debugf(ctx, "conflict trying to save object in k8s API concurrently")
r.logger.Debugf(ctx, "canceling resource")
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.Debugf(ctx, "status updated")
} else {
r.logger.Debugf(ctx, "no status update for existing azureconfig needed")
}
}
return nil
}
func (r *Resource) buildAzureConfig(ctx context.Context, cluster capi.Cluster, azureCluster capz.AzureCluster, masters, workers []capz.AzureMachine) (providerv1alpha1.AzureConfig, error) {
var err error
azureConfig := providerv1alpha1.AzureConfig{}
azureConfig.Labels = make(map[string]string)
azureConfig.Annotations = make(map[string]string)
{
azureConfig.ObjectMeta.Name = key.ClusterName(&cluster)
azureConfig.ObjectMeta.Namespace = metav1.NamespaceDefault
}
{
cluster, err := r.newCluster(cluster, azureCluster, workers)
if err != nil {
return providerv1alpha1.AzureConfig{}, microerror.Mask(err)
}
cluster.Kubernetes.CloudProvider = ProviderAzure
azureConfig.Spec.Cluster = cluster
}
{
azureConfig.Annotations[annotation.ClusterDescription] = cluster.Annotations[annotation.ClusterDescription]
if azureCluster.Annotations[localannotation.WorkersEgressExternalPublicIP] != "" {
azureConfig.Annotations[localannotation.WorkersEgressExternalPublicIP] = azureCluster.Annotations[localannotation.WorkersEgressExternalPublicIP]
}
}
{
azureConfig.Labels[label.Cluster] = key.ClusterName(&cluster)
azureConfig.Labels[capi.ClusterLabelName] = key.ClusterName(&cluster)
azureConfig.Labels[label.Organization] = key.OrganizationID(&cluster)
azureConfig.Labels[label.ReleaseVersion] = key.ReleaseVersion(&cluster)
azureConfig.Labels[label.OperatorVersion] = key.OperatorVersion(&azureCluster)
}
{
azureConfig.Spec.Azure.AvailabilityZones, err = getAvailabilityZones(masters, workers)
if err != nil {
return providerv1alpha1.AzureConfig{}, microerror.Mask(err)
}
}
var (
// hostDNSZone is created by stripping 3 first components from
// API domain are e.g.
// api.eggs2.k8s.gollum.azure.giantswarm.io becomes
// gollum.azure.giantswarm.io.
hostDNSZone = strings.Join(strings.Split(azureConfig.Spec.Cluster.Kubernetes.API.Domain, ".")[3:], ".")
hostResourceGroup = r.managementClusterResourceGroup
)
azureConfig.Spec.Azure.DNSZones.API.Name = hostDNSZone
azureConfig.Spec.Azure.DNSZones.API.ResourceGroup = hostResourceGroup
azureConfig.Spec.Azure.DNSZones.Etcd.Name = hostDNSZone
azureConfig.Spec.Azure.DNSZones.Etcd.ResourceGroup = hostResourceGroup
azureConfig.Spec.Azure.DNSZones.Ingress.Name = hostDNSZone
azureConfig.Spec.Azure.DNSZones.Ingress.ResourceGroup = hostResourceGroup
if len(azureCluster.Spec.NetworkSpec.Vnet.CIDRBlocks) > 0 && azureCluster.Spec.NetworkSpec.Vnet.CIDRBlocks[0] != "" {
_, vnet, err := net.ParseCIDR(azureCluster.Spec.NetworkSpec.Vnet.CIDRBlocks[0])
if err != nil {
return providerv1alpha1.AzureConfig{}, microerror.Mask(err)
}
// Ensure cidrblock is the desired size.
ones, _ := vnet.Mask.Size()
if ones != r.vnetMaskSize {
return providerv1alpha1.AzureConfig{}, microerror.Maskf(invalidSubnetMaskError, "azureCluster.Spec.NetworkSpec.Vnet.CIDRBlocks[0] has mask /%d, but only /%d is supported.", ones, r.vnetMaskSize)
}
azureNetwork, err := network.Compute(*vnet)
if err != nil {
return providerv1alpha1.AzureConfig{}, microerror.Mask(err)
}
azureConfig.Spec.Azure.VirtualNetwork.CIDR = vnet.String()
azureConfig.Spec.Azure.VirtualNetwork.CalicoSubnetCIDR = azureNetwork.Calico.String()
azureConfig.Spec.Azure.VirtualNetwork.MasterSubnetCIDR = azureNetwork.Master.String()
azureConfig.Spec.Azure.VirtualNetwork.WorkerSubnetCIDR = azureNetwork.Worker.String()
}
{
var masterNodes []providerv1alpha1.AzureConfigSpecAzureNode
for _, m := range masters {
n := providerv1alpha1.AzureConfigSpecAzureNode{
VMSize: m.Spec.VMSize,
DockerVolumeSizeGB: dockerVolumeSizeGB,
KubeletVolumeSizeGB: kubeletVolumeSizeGB,
}
masterNodes = append(masterNodes, n)
}
var workerNodes []providerv1alpha1.AzureConfigSpecAzureNode
for _, m := range workers {
n := providerv1alpha1.AzureConfigSpecAzureNode{
VMSize: m.Spec.VMSize,
DockerVolumeSizeGB: dockerVolumeSizeGB,
KubeletVolumeSizeGB: kubeletVolumeSizeGB,
}
workerNodes = append(workerNodes, n)
}
azureConfig.Spec.Azure.Masters = masterNodes
azureConfig.Spec.Azure.Workers = workerNodes
}
{
credentialSecret, err := r.clientFactory.GetCredentialSecret(ctx, cluster.ObjectMeta)
if err != nil {
return providerv1alpha1.AzureConfig{}, microerror.Mask(err)
}
azureConfig.Spec.Azure.CredentialSecret = *credentialSecret
}
return azureConfig, nil
}
func (r *Resource) newCluster(cluster capi.Cluster, azureCluster capz.AzureCluster, workers []capz.AzureMachine) (providerv1alpha1.Cluster, error) {
commonCluster := providerv1alpha1.Cluster{}
{
commonCluster.Calico.CIDR = r.calico.CIDRSize
commonCluster.Calico.MTU = r.calico.MTU
commonCluster.Calico.Subnet = r.calico.Subnet
}
{
commonCluster.ID = key.ClusterName(&cluster)
}
{
commonCluster.Customer.ID = key.OrganizationID(&cluster)
}
{
etcdServerDomain, err := newEtcdServerDomain(azureCluster)
if err != nil {
return providerv1alpha1.Cluster{}, microerror.Mask(err)
}
commonCluster.Etcd.Domain = etcdServerDomain
commonCluster.Etcd.Prefix = r.etcdPrefix
commonCluster.Etcd.Port = 2379
}
{
apiServerDomain, err := newAPIServerDomain(azureCluster)
if err != nil {
return providerv1alpha1.Cluster{}, microerror.Mask(err)
}
apiServerIPRange := r.clusterIPRange
if apiServerIPRange == "" {
return providerv1alpha1.Cluster{}, microerror.Maskf(executionFailedError, "Kubernetes IP range must not be empty")
}
commonCluster.Kubernetes.API.ClusterIPRange = apiServerIPRange // TODO rename (HOST_SUBNET_RANGE in k8s-vm)
commonCluster.Kubernetes.API.Domain = apiServerDomain
commonCluster.Kubernetes.API.SecurePort = r.apiServerSecurePort
}
{
_, ipNet, err := net.ParseCIDR(commonCluster.Kubernetes.API.ClusterIPRange)
ip := ipNet.IP
if err != nil {
return providerv1alpha1.Cluster{}, microerror.Mask(err)
}
ip[3] = kubeDNSIPLastOctet
commonCluster.Kubernetes.DNS.IP = ip.String()
}
{
kubeletDomain, err := newKubeletDomain(azureCluster)
if err != nil {
return providerv1alpha1.Cluster{}, microerror.Mask(err)
}
// We ingore the error here. It happens because AzureCluster or AzureConfig don't know about MachinePoolID.
kubeletLabels, _ := key.KubeletLabelsNodePool(&azureCluster)
commonCluster.Kubernetes.Kubelet.Domain = kubeletDomain
commonCluster.Kubernetes.Kubelet.Labels = kubeletLabels
}
{
commonCluster.Kubernetes.Domain = kubeletClusterDomain
}
{
// The AzureConfig field containing the list of SSH keys is not used any more,
// but is a mandatory field so we set it to an empty slice.
commonCluster.Kubernetes.SSH.UserList = []providerv1alpha1.ClusterKubernetesSSHUser{}
}
{
commonCluster.Masters = newSpecClusterMasterNodes()
commonCluster.Workers = newSpecClusterWorkerNodes(len(workers))
}
{
commonCluster.Scaling.Max = len(workers)
commonCluster.Scaling.Min = len(workers)
}
return commonCluster, nil
}
func newSpecClusterMasterNodes() []providerv1alpha1.ClusterNode {
// Return one master node with empty ID. I don't expect it to be used
// anywhere.
masterNodes := make([]providerv1alpha1.ClusterNode, 1)
masterNodes[0].ID = "master-0"
return masterNodes
}
func newSpecClusterWorkerNodes(numWorkers int) []providerv1alpha1.ClusterNode {
var workerNodes []providerv1alpha1.ClusterNode
for i := 0; i < numWorkers; i++ {
n := providerv1alpha1.ClusterNode{
ID: fmt.Sprintf("node-%d", i),
}
workerNodes = append(workerNodes, n)
}
return workerNodes
}