-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
kubeadmconfig_controller.go
838 lines (729 loc) · 33.9 KB
/
kubeadmconfig_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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
/*
Copyright 2019 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"
"strconv"
"time"
"github.com/go-logr/logr"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/utils/pointer"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3"
bootstrapv1 "sigs.k8s.io/cluster-api/bootstrap/kubeadm/api/v1alpha3"
"sigs.k8s.io/cluster-api/bootstrap/kubeadm/internal/cloudinit"
"sigs.k8s.io/cluster-api/bootstrap/kubeadm/internal/locking"
kubeadmv1beta1 "sigs.k8s.io/cluster-api/bootstrap/kubeadm/types/v1beta1"
bsutil "sigs.k8s.io/cluster-api/bootstrap/util"
"sigs.k8s.io/cluster-api/controllers/remote"
capierrors "sigs.k8s.io/cluster-api/errors"
expv1 "sigs.k8s.io/cluster-api/exp/api/v1alpha3"
"sigs.k8s.io/cluster-api/feature"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/annotations"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
"sigs.k8s.io/cluster-api/util/predicates"
"sigs.k8s.io/cluster-api/util/secret"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/source"
)
// InitLocker is a lock that is used around kubeadm init
type InitLocker interface {
Lock(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) bool
Unlock(ctx context.Context, cluster *clusterv1.Cluster) bool
}
// +kubebuilder:rbac:groups=bootstrap.cluster.x-k8s.io,resources=kubeadmconfigs;kubeadmconfigs/status,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=clusters;clusters/status;machines;machines/status,verbs=get;list;watch
// +kubebuilder:rbac:groups=exp.cluster.x-k8s.io,resources=machinepools;machinepools/status,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=secrets;events;configmaps,verbs=get;list;watch;create;update;patch;delete
// KubeadmConfigReconciler reconciles a KubeadmConfig object
type KubeadmConfigReconciler struct {
Client client.Client
Log logr.Logger
KubeadmInitLock InitLocker
scheme *runtime.Scheme
remoteClientGetter remote.ClusterClientGetter
}
type Scope struct {
logr.Logger
Config *bootstrapv1.KubeadmConfig
ConfigOwner *bsutil.ConfigOwner
Cluster *clusterv1.Cluster
}
// SetupWithManager sets up the reconciler with the Manager.
func (r *KubeadmConfigReconciler) SetupWithManager(mgr ctrl.Manager, option controller.Options) error {
if r.KubeadmInitLock == nil {
r.KubeadmInitLock = locking.NewControlPlaneInitMutex(ctrl.Log.WithName("init-locker"), mgr.GetClient())
}
if r.remoteClientGetter == nil {
r.remoteClientGetter = remote.NewClusterClient
}
r.scheme = mgr.GetScheme()
b := ctrl.NewControllerManagedBy(mgr).
For(&bootstrapv1.KubeadmConfig{}).
WithOptions(option).
WithEventFilter(predicates.ResourceNotPaused(r.Log)).
Watches(
&source.Kind{Type: &clusterv1.Machine{}},
&handler.EnqueueRequestsFromMapFunc{
ToRequests: handler.ToRequestsFunc(r.MachineToBootstrapMapFunc),
},
)
if feature.Gates.Enabled(feature.MachinePool) {
b = b.Watches(
&source.Kind{Type: &expv1.MachinePool{}},
&handler.EnqueueRequestsFromMapFunc{
ToRequests: handler.ToRequestsFunc(r.MachinePoolToBootstrapMapFunc),
},
)
}
c, err := b.Build(r)
if err != nil {
return errors.Wrap(err, "failed setting up with a controller manager")
}
err = c.Watch(
&source.Kind{Type: &clusterv1.Cluster{}},
&handler.EnqueueRequestsFromMapFunc{
ToRequests: handler.ToRequestsFunc(r.ClusterToKubeadmConfigs),
},
predicates.ClusterUnpausedAndInfrastructureReady(r.Log),
)
if err != nil {
return errors.Wrap(err, "failed adding Watch for Clusters to controller manager")
}
return nil
}
// Reconcile handles KubeadmConfig events.
func (r *KubeadmConfigReconciler) Reconcile(req ctrl.Request) (_ ctrl.Result, rerr error) {
ctx := context.Background()
log := r.Log.WithValues("kubeadmconfig", req.NamespacedName)
// Lookup the kubeadm config
config := &bootstrapv1.KubeadmConfig{}
if err := r.Client.Get(ctx, req.NamespacedName, config); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
log.Error(err, "Failed to get config")
return ctrl.Result{}, err
}
// Look up the owner of this KubeConfig if there is one
configOwner, err := bsutil.GetConfigOwner(ctx, r.Client, config)
if apierrors.IsNotFound(err) {
// Could not find the owner yet, this is not an error and will rereconcile when the owner gets set.
return ctrl.Result{}, nil
}
if err != nil {
log.Error(err, "Failed to get owner")
return ctrl.Result{}, err
}
if configOwner == nil {
return ctrl.Result{}, nil
}
log = log.WithValues("kind", configOwner.GetKind(), "version", configOwner.GetResourceVersion(), "name", configOwner.GetName())
// Lookup the cluster the config owner is associated with
cluster, err := util.GetClusterByName(ctx, r.Client, configOwner.GetNamespace(), configOwner.ClusterName())
if err != nil {
if errors.Cause(err) == util.ErrNoCluster {
log.Info(fmt.Sprintf("%s does not belong to a cluster yet, waiting until it's part of a cluster", configOwner.GetKind()))
return ctrl.Result{}, nil
}
if apierrors.IsNotFound(err) {
log.Info("Cluster does not exist yet, waiting until it is created")
return ctrl.Result{}, nil
}
log.Error(err, "Could not get cluster with metadata")
return ctrl.Result{}, err
}
if annotations.IsPaused(cluster, config) {
log.Info("Reconciliation is paused for this object")
return ctrl.Result{}, nil
}
scope := &Scope{
Logger: log,
Config: config,
ConfigOwner: configOwner,
Cluster: cluster,
}
// Initialize the patch helper.
patchHelper, err := patch.NewHelper(config, r.Client)
if err != nil {
return ctrl.Result{}, err
}
// Attempt to Patch the KubeadmConfig object and status after each reconciliation if no error occurs.
defer func() {
// always update the readyCondition; the summary is represented using the "1 of x completed" notation.
conditions.SetSummary(config,
conditions.WithConditions(
bootstrapv1.DataSecretAvailableCondition,
bootstrapv1.CertificatesAvailableCondition,
),
conditions.WithStepCounter(),
)
// Patch ObservedGeneration only if the reconciliation completed successfully
patchOpts := []patch.Option{}
if rerr == nil {
patchOpts = append(patchOpts, patch.WithStatusObservedGeneration{})
}
if err := patchHelper.Patch(ctx, config, patchOpts...); err != nil {
log.Error(rerr, "Failed to patch config")
if rerr == nil {
rerr = err
}
}
}()
switch {
// Wait for the infrastructure to be ready.
case !cluster.Status.InfrastructureReady:
log.Info("Cluster infrastructure is not ready, waiting")
conditions.MarkFalse(config, bootstrapv1.DataSecretAvailableCondition, bootstrapv1.WaitingForClusterInfrastructureReason, clusterv1.ConditionSeverityInfo, "")
return ctrl.Result{}, nil
// Migrate plaintext data to secret.
case config.Status.BootstrapData != nil && config.Status.DataSecretName == nil:
if err := r.storeBootstrapData(ctx, scope, config.Status.BootstrapData); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
// Reconcile status for machines that already have a secret reference, but our status isn't up to date.
// This case solves the pivoting scenario (or a backup restore) which doesn't preserve the status subresource on objects.
case configOwner.DataSecretName() != nil && (!config.Status.Ready || config.Status.DataSecretName == nil):
config.Status.Ready = true
config.Status.DataSecretName = configOwner.DataSecretName()
conditions.MarkTrue(config, bootstrapv1.DataSecretAvailableCondition)
return ctrl.Result{}, nil
// Status is ready means a config has been generated.
case config.Status.Ready:
// If the BootstrapToken has been generated for a join and the infrastructure is not ready.
// This indicates the token in the join config has not been consumed and it may need a refresh.
if (config.Spec.JoinConfiguration != nil && config.Spec.JoinConfiguration.Discovery.BootstrapToken != nil) && !configOwner.IsInfrastructureReady() {
token := config.Spec.JoinConfiguration.Discovery.BootstrapToken.Token
remoteClient, err := r.remoteClientGetter(ctx, r.Client, util.ObjectKey(cluster), r.scheme)
if err != nil {
log.Error(err, "Error creating remote cluster client")
return ctrl.Result{}, err
}
log.Info("Refreshing token until the infrastructure has a chance to consume it")
err = refreshToken(remoteClient, token)
if err != nil {
// It would be nice to re-create the bootstrap token if the error was "not found", but we have no way to update the Machine's bootstrap data
return ctrl.Result{}, errors.Wrapf(err, "failed to refresh bootstrap token")
}
// NB: this may not be sufficient to keep the token live if we don't see it before it expires, but when we generate a config we will set the status to "ready" which should generate an update event
return ctrl.Result{
RequeueAfter: DefaultTokenTTL / 2,
}, nil
}
// In any other case just return as the config is already generated and need not be generated again.
return ctrl.Result{}, nil
}
if !cluster.Status.ControlPlaneInitialized {
return r.handleClusterNotInitialized(ctx, scope)
}
// Every other case it's a join scenario
// Nb. in this case ClusterConfiguration and InitConfiguration should not be defined by users, but in case of misconfigurations, CABPK simply ignore them
// Unlock any locks that might have been set during init process
r.KubeadmInitLock.Unlock(ctx, cluster)
// if the JoinConfiguration is missing, create a default one
if config.Spec.JoinConfiguration == nil {
log.Info("Creating default JoinConfiguration")
config.Spec.JoinConfiguration = &kubeadmv1beta1.JoinConfiguration{}
}
// it's a control plane join
if configOwner.IsControlPlaneMachine() {
return r.joinControlplane(ctx, scope)
}
// It's a worker join
return r.joinWorker(ctx, scope)
}
func (r *KubeadmConfigReconciler) handleClusterNotInitialized(ctx context.Context, scope *Scope) (_ ctrl.Result, reterr error) {
// initialize the DataSecretAvailableCondition if missing.
// this is required in order to avoid the condition's LastTransitionTime to flicker in case of errors surfacing
// using the DataSecretGeneratedFailedReason
if conditions.GetReason(scope.Config, bootstrapv1.DataSecretAvailableCondition) != bootstrapv1.DataSecretGenerationFailedReason {
conditions.MarkFalse(scope.Config, bootstrapv1.DataSecretAvailableCondition, bootstrapv1.WaitingForControlPlaneAvailableReason, clusterv1.ConditionSeverityInfo, "")
}
// if it's NOT a control plane machine, requeue
if !scope.ConfigOwner.IsControlPlaneMachine() {
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
// if the machine has not ClusterConfiguration and InitConfiguration, requeue
if scope.Config.Spec.InitConfiguration == nil && scope.Config.Spec.ClusterConfiguration == nil {
scope.Info("Control plane is not ready, requeing joining control planes until ready.")
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
machine := &clusterv1.Machine{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(scope.ConfigOwner.Object, machine); err != nil {
return ctrl.Result{}, errors.Wrapf(err, "cannot convert %s to Machine", scope.ConfigOwner.GetKind())
}
// acquire the init lock so that only the first machine configured
// as control plane get processed here
// if not the first, requeue
if !r.KubeadmInitLock.Lock(ctx, scope.Cluster, machine) {
scope.Info("A control plane is already being initialized, requeing until control plane is ready")
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
defer func() {
if reterr != nil {
if !r.KubeadmInitLock.Unlock(ctx, scope.Cluster) {
reterr = kerrors.NewAggregate([]error{reterr, errors.New("failed to unlock the kubeadm init lock")})
}
}
}()
scope.Info("Creating BootstrapData for the init control plane")
// Nb. in this case JoinConfiguration should not be defined by users, but in case of misconfigurations, CABPK simply ignore it
// get both of ClusterConfiguration and InitConfiguration strings to pass to the cloud init control plane generator
// kubeadm allows one of these values to be empty; CABPK replace missing values with an empty config, so the cloud init generation
// should not handle special cases.
if scope.Config.Spec.InitConfiguration == nil {
scope.Config.Spec.InitConfiguration = &kubeadmv1beta1.InitConfiguration{
TypeMeta: metav1.TypeMeta{
APIVersion: "kubeadm.k8s.io/v1beta1",
Kind: "InitConfiguration",
},
}
}
initdata, err := kubeadmv1beta1.ConfigurationToYAML(scope.Config.Spec.InitConfiguration)
if err != nil {
scope.Error(err, "Failed to marshal init configuration")
return ctrl.Result{}, err
}
if scope.Config.Spec.ClusterConfiguration == nil {
scope.Config.Spec.ClusterConfiguration = &kubeadmv1beta1.ClusterConfiguration{
TypeMeta: metav1.TypeMeta{
APIVersion: "kubeadm.k8s.io/v1beta1",
Kind: "ClusterConfiguration",
},
}
}
// injects into config.ClusterConfiguration values from top level object
r.reconcileTopLevelObjectSettings(scope.Cluster, machine, scope.Config)
clusterdata, err := kubeadmv1beta1.ConfigurationToYAML(scope.Config.Spec.ClusterConfiguration)
if err != nil {
scope.Error(err, "Failed to marshal cluster configuration")
return ctrl.Result{}, err
}
certificates := secret.NewCertificatesForInitialControlPlane(scope.Config.Spec.ClusterConfiguration)
err = certificates.LookupOrGenerate(
ctx,
r.Client,
util.ObjectKey(scope.Cluster),
*metav1.NewControllerRef(scope.Config, bootstrapv1.GroupVersion.WithKind("KubeadmConfig")),
)
if err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.CertificatesAvailableCondition, bootstrapv1.CertificatesGenerationFailedReason, clusterv1.ConditionSeverityWarning, err.Error())
return ctrl.Result{}, err
}
conditions.MarkTrue(scope.Config, bootstrapv1.CertificatesAvailableCondition)
verbosityFlag := ""
if scope.Config.Spec.Verbosity != nil {
verbosityFlag = fmt.Sprintf("--v %s", strconv.Itoa(int(*scope.Config.Spec.Verbosity)))
}
files, err := r.resolveFiles(ctx, scope.Config, certificates.AsFiles()...)
if err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.DataSecretAvailableCondition, bootstrapv1.DataSecretGenerationFailedReason, clusterv1.ConditionSeverityWarning, err.Error())
return ctrl.Result{}, err
}
cloudInitData, err := cloudinit.NewInitControlPlane(&cloudinit.ControlPlaneInput{
BaseUserData: cloudinit.BaseUserData{
AdditionalFiles: files,
NTP: scope.Config.Spec.NTP,
PreKubeadmCommands: scope.Config.Spec.PreKubeadmCommands,
PostKubeadmCommands: scope.Config.Spec.PostKubeadmCommands,
Users: scope.Config.Spec.Users,
Mounts: scope.Config.Spec.Mounts,
DiskSetup: scope.Config.Spec.DiskSetup,
KubeadmVerbosity: verbosityFlag,
},
InitConfiguration: initdata,
ClusterConfiguration: clusterdata,
Certificates: certificates,
})
if err != nil {
scope.Error(err, "Failed to generate cloud init for bootstrap control plane")
return ctrl.Result{}, err
}
if err := r.storeBootstrapData(ctx, scope, cloudInitData); err != nil {
scope.Error(err, "Failed to store bootstrap data")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *KubeadmConfigReconciler) joinWorker(ctx context.Context, scope *Scope) (ctrl.Result, error) {
certificates := secret.NewCertificatesForWorker(scope.Config.Spec.JoinConfiguration.CACertPath)
err := certificates.Lookup(
ctx,
r.Client,
util.ObjectKey(scope.Cluster),
)
if err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.CertificatesAvailableCondition, bootstrapv1.CertificatesCorruptedReason, clusterv1.ConditionSeverityError, err.Error())
return ctrl.Result{}, err
}
if err := certificates.EnsureAllExist(); err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.CertificatesAvailableCondition, bootstrapv1.CertificatesCorruptedReason, clusterv1.ConditionSeverityError, err.Error())
return ctrl.Result{}, err
}
conditions.MarkTrue(scope.Config, bootstrapv1.CertificatesAvailableCondition)
// ensure that joinConfiguration.Discovery is properly set for joining node on the current cluster
if err := r.reconcileDiscovery(ctx, scope.Cluster, scope.Config, certificates); err != nil {
if requeueErr, ok := errors.Cause(err).(capierrors.HasRequeueAfterError); ok {
scope.Info(err.Error())
return ctrl.Result{RequeueAfter: requeueErr.GetRequeueAfter()}, nil
}
return ctrl.Result{}, err
}
joinData, err := kubeadmv1beta1.ConfigurationToYAML(scope.Config.Spec.JoinConfiguration)
if err != nil {
scope.Error(err, "Failed to marshal join configuration")
return ctrl.Result{}, err
}
if scope.Config.Spec.JoinConfiguration.ControlPlane != nil {
return ctrl.Result{}, errors.New("Machine is a Worker, but JoinConfiguration.ControlPlane is set in the KubeadmConfig object")
}
scope.Info("Creating BootstrapData for the worker node")
verbosityFlag := ""
if scope.Config.Spec.Verbosity != nil {
verbosityFlag = fmt.Sprintf("--v %s", strconv.Itoa(int(*scope.Config.Spec.Verbosity)))
}
files, err := r.resolveFiles(ctx, scope.Config)
if err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.DataSecretAvailableCondition, bootstrapv1.DataSecretGenerationFailedReason, clusterv1.ConditionSeverityWarning, err.Error())
return ctrl.Result{}, err
}
cloudJoinData, err := cloudinit.NewNode(&cloudinit.NodeInput{
BaseUserData: cloudinit.BaseUserData{
AdditionalFiles: files,
NTP: scope.Config.Spec.NTP,
PreKubeadmCommands: scope.Config.Spec.PreKubeadmCommands,
PostKubeadmCommands: scope.Config.Spec.PostKubeadmCommands,
Users: scope.Config.Spec.Users,
Mounts: scope.Config.Spec.Mounts,
DiskSetup: scope.Config.Spec.DiskSetup,
KubeadmVerbosity: verbosityFlag,
UseExperimentalRetry: scope.Config.Spec.UseExperimentalRetryJoin,
},
JoinConfiguration: joinData,
})
if err != nil {
scope.Error(err, "Failed to create a worker join configuration")
return ctrl.Result{}, err
}
if err := r.storeBootstrapData(ctx, scope, cloudJoinData); err != nil {
scope.Error(err, "Failed to store bootstrap data")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *KubeadmConfigReconciler) joinControlplane(ctx context.Context, scope *Scope) (ctrl.Result, error) {
if !scope.ConfigOwner.IsControlPlaneMachine() {
return ctrl.Result{}, fmt.Errorf("%s is not a valid control plane kind, only Machine is supported", scope.ConfigOwner.GetKind())
}
if scope.Config.Spec.JoinConfiguration.ControlPlane == nil {
scope.Config.Spec.JoinConfiguration.ControlPlane = &kubeadmv1beta1.JoinControlPlane{}
}
certificates := secret.NewCertificatesForJoiningControlPlane()
err := certificates.Lookup(
ctx,
r.Client,
util.ObjectKey(scope.Cluster),
)
if err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.CertificatesAvailableCondition, bootstrapv1.CertificatesCorruptedReason, clusterv1.ConditionSeverityError, err.Error())
return ctrl.Result{}, err
}
if err := certificates.EnsureAllExist(); err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.CertificatesAvailableCondition, bootstrapv1.CertificatesCorruptedReason, clusterv1.ConditionSeverityError, err.Error())
return ctrl.Result{}, err
}
conditions.MarkTrue(scope.Config, bootstrapv1.CertificatesAvailableCondition)
// ensure that joinConfiguration.Discovery is properly set for joining node on the current cluster
if err := r.reconcileDiscovery(ctx, scope.Cluster, scope.Config, certificates); err != nil {
if requeueErr, ok := errors.Cause(err).(capierrors.HasRequeueAfterError); ok {
scope.Info(err.Error())
return ctrl.Result{RequeueAfter: requeueErr.GetRequeueAfter()}, nil
}
return ctrl.Result{}, err
}
joinData, err := kubeadmv1beta1.ConfigurationToYAML(scope.Config.Spec.JoinConfiguration)
if err != nil {
scope.Error(err, "Failed to marshal join configuration")
return ctrl.Result{}, err
}
scope.Info("Creating BootstrapData for the join control plane")
verbosityFlag := ""
if scope.Config.Spec.Verbosity != nil {
verbosityFlag = fmt.Sprintf("--v %s", strconv.Itoa(int(*scope.Config.Spec.Verbosity)))
}
files, err := r.resolveFiles(ctx, scope.Config, certificates.AsFiles()...)
if err != nil {
conditions.MarkFalse(scope.Config, bootstrapv1.DataSecretAvailableCondition, bootstrapv1.DataSecretGenerationFailedReason, clusterv1.ConditionSeverityWarning, err.Error())
return ctrl.Result{}, err
}
cloudJoinData, err := cloudinit.NewJoinControlPlane(&cloudinit.ControlPlaneJoinInput{
JoinConfiguration: joinData,
Certificates: certificates,
BaseUserData: cloudinit.BaseUserData{
AdditionalFiles: files,
NTP: scope.Config.Spec.NTP,
PreKubeadmCommands: scope.Config.Spec.PreKubeadmCommands,
PostKubeadmCommands: scope.Config.Spec.PostKubeadmCommands,
Users: scope.Config.Spec.Users,
Mounts: scope.Config.Spec.Mounts,
DiskSetup: scope.Config.Spec.DiskSetup,
KubeadmVerbosity: verbosityFlag,
UseExperimentalRetry: scope.Config.Spec.UseExperimentalRetryJoin,
},
})
if err != nil {
scope.Error(err, "Failed to create a control plane join configuration")
return ctrl.Result{}, err
}
if err := r.storeBootstrapData(ctx, scope, cloudJoinData); err != nil {
scope.Error(err, "Failed to store bootstrap data")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// resolveFiles maps .Spec.Files into cloudinit.Files, resolving any object references
// along the way.
func (r *KubeadmConfigReconciler) resolveFiles(ctx context.Context, cfg *bootstrapv1.KubeadmConfig, merge ...bootstrapv1.File) ([]bootstrapv1.File, error) {
collected := append(cfg.Spec.Files, merge...)
for i := range collected {
in := collected[i]
if in.ContentFrom != nil {
data, err := r.resolveSecretFileContent(ctx, cfg.Namespace, in)
if err != nil {
return nil, errors.Wrapf(err, "failed to resolve file source")
}
in.ContentFrom = nil
in.Content = string(data)
collected[i] = in
}
}
return collected, nil
}
// resolveSecretFileContent returns file content fetched from a referenced secret object.
func (r *KubeadmConfigReconciler) resolveSecretFileContent(ctx context.Context, ns string, source bootstrapv1.File) ([]byte, error) {
secret := &corev1.Secret{}
key := types.NamespacedName{Namespace: ns, Name: source.ContentFrom.Secret.Name}
if err := r.Client.Get(ctx, key, secret); err != nil {
if apierrors.IsNotFound(err) {
return nil, errors.Wrapf(err, "secret not found: %s", key)
}
return nil, errors.Wrapf(err, "failed to retrieve Secret %q", key)
}
data, ok := secret.Data[source.ContentFrom.Secret.Key]
if !ok {
return nil, errors.Errorf("secret references non-existent secret key: %q", source.ContentFrom.Secret.Key)
}
return data, nil
}
// ClusterToKubeadmConfigs is a handler.ToRequestsFunc to be used to enqeue
// requests for reconciliation of KubeadmConfigs.
func (r *KubeadmConfigReconciler) ClusterToKubeadmConfigs(o handler.MapObject) []ctrl.Request {
result := []ctrl.Request{}
c, ok := o.Object.(*clusterv1.Cluster)
if !ok {
r.Log.Error(errors.Errorf("expected a Cluster but got a %T", o.Object), "failed to get Machine for Cluster")
return nil
}
selectors := []client.ListOption{
client.InNamespace(c.Namespace),
client.MatchingLabels{
clusterv1.ClusterLabelName: c.Name,
},
}
machineList := &clusterv1.MachineList{}
if err := r.Client.List(context.Background(), machineList, selectors...); err != nil {
r.Log.Error(err, "failed to list Machines", "Cluster", c.Name, "Namespace", c.Namespace)
return nil
}
for _, m := range machineList.Items {
if m.Spec.Bootstrap.ConfigRef != nil &&
m.Spec.Bootstrap.ConfigRef.GroupVersionKind().GroupKind() == bootstrapv1.GroupVersion.WithKind("KubeadmConfig").GroupKind() {
name := client.ObjectKey{Namespace: m.Namespace, Name: m.Spec.Bootstrap.ConfigRef.Name}
result = append(result, ctrl.Request{NamespacedName: name})
}
}
return result
}
// MachineToBootstrapMapFunc is a handler.ToRequestsFunc to be used to enqeue
// request for reconciliation of KubeadmConfig.
func (r *KubeadmConfigReconciler) MachineToBootstrapMapFunc(o handler.MapObject) []ctrl.Request {
result := []ctrl.Request{}
m, ok := o.Object.(*clusterv1.Machine)
if !ok {
return nil
}
if m.Spec.Bootstrap.ConfigRef != nil && m.Spec.Bootstrap.ConfigRef.GroupVersionKind() == bootstrapv1.GroupVersion.WithKind("KubeadmConfig") {
name := client.ObjectKey{Namespace: m.Namespace, Name: m.Spec.Bootstrap.ConfigRef.Name}
result = append(result, ctrl.Request{NamespacedName: name})
}
return result
}
// MachinePoolToBootstrapMapFunc is a handler.ToRequestsFunc to be used to enqueue
// request for reconciliation of KubeadmConfig.
func (r *KubeadmConfigReconciler) MachinePoolToBootstrapMapFunc(o handler.MapObject) []ctrl.Request {
result := []ctrl.Request{}
m, ok := o.Object.(*expv1.MachinePool)
if !ok {
return nil
}
configRef := m.Spec.Template.Spec.Bootstrap.ConfigRef
if configRef != nil && configRef.GroupVersionKind().GroupKind() == bootstrapv1.GroupVersion.WithKind("KubeadmConfig").GroupKind() {
name := client.ObjectKey{Namespace: m.Namespace, Name: configRef.Name}
result = append(result, ctrl.Request{NamespacedName: name})
}
return result
}
// reconcileDiscovery ensures that config.JoinConfiguration.Discovery is properly set for the joining node.
// The implementation func respect user provided discovery configurations, but in case some of them are missing, a valid BootstrapToken object
// is automatically injected into config.JoinConfiguration.Discovery.
// This allows to simplify configuration UX, by providing the option to delegate to CABPK the configuration of kubeadm join discovery.
func (r *KubeadmConfigReconciler) reconcileDiscovery(ctx context.Context, cluster *clusterv1.Cluster, config *bootstrapv1.KubeadmConfig, certificates secret.Certificates) error {
log := r.Log.WithValues("kubeadmconfig", fmt.Sprintf("%s/%s", config.Namespace, config.Name))
// if config already contains a file discovery configuration, respect it without further validations
if config.Spec.JoinConfiguration.Discovery.File != nil {
return nil
}
// otherwise it is necessary to ensure token discovery is properly configured
if config.Spec.JoinConfiguration.Discovery.BootstrapToken == nil {
config.Spec.JoinConfiguration.Discovery.BootstrapToken = &kubeadmv1beta1.BootstrapTokenDiscovery{}
}
// calculate the ca cert hashes if they are not already set
if len(config.Spec.JoinConfiguration.Discovery.BootstrapToken.CACertHashes) == 0 {
hashes, err := certificates.GetByPurpose(secret.ClusterCA).Hashes()
if err != nil {
log.Error(err, "Unable to generate Cluster CA certificate hashes")
return err
}
config.Spec.JoinConfiguration.Discovery.BootstrapToken.CACertHashes = hashes
}
// if BootstrapToken already contains an APIServerEndpoint, respect it; otherwise inject the APIServerEndpoint endpoint defined in cluster status
apiServerEndpoint := config.Spec.JoinConfiguration.Discovery.BootstrapToken.APIServerEndpoint
if apiServerEndpoint == "" {
if cluster.Spec.ControlPlaneEndpoint.IsZero() {
return errors.Wrap(&capierrors.RequeueAfterError{RequeueAfter: 10 * time.Second}, "Waiting for Cluster Controller to set Cluster.Spec.ControlPlaneEndpoint")
}
apiServerEndpoint = cluster.Spec.ControlPlaneEndpoint.String()
config.Spec.JoinConfiguration.Discovery.BootstrapToken.APIServerEndpoint = apiServerEndpoint
log.Info("Altering JoinConfiguration.Discovery.BootstrapToken", "APIServerEndpoint", apiServerEndpoint)
}
// if BootstrapToken already contains a token, respect it; otherwise create a new bootstrap token for the node to join
if config.Spec.JoinConfiguration.Discovery.BootstrapToken.Token == "" {
remoteClient, err := r.remoteClientGetter(ctx, r.Client, util.ObjectKey(cluster), r.scheme)
if err != nil {
return err
}
token, err := createToken(remoteClient)
if err != nil {
return errors.Wrapf(err, "failed to create new bootstrap token")
}
config.Spec.JoinConfiguration.Discovery.BootstrapToken.Token = token
log.Info("Altering JoinConfiguration.Discovery.BootstrapToken", "Token", token)
}
// If the BootstrapToken does not contain any CACertHashes then force skip CA Verification
if len(config.Spec.JoinConfiguration.Discovery.BootstrapToken.CACertHashes) == 0 {
log.Info("No CAs were provided. Falling back to insecure discover method by skipping CA Cert validation")
config.Spec.JoinConfiguration.Discovery.BootstrapToken.UnsafeSkipCAVerification = true
}
return nil
}
// reconcileTopLevelObjectSettings injects into config.ClusterConfiguration values from top level objects like cluster and machine.
// The implementation func respect user provided config values, but in case some of them are missing, values from top level objects are used.
func (r *KubeadmConfigReconciler) reconcileTopLevelObjectSettings(cluster *clusterv1.Cluster, machine *clusterv1.Machine, config *bootstrapv1.KubeadmConfig) {
log := r.Log.WithValues("kubeadmconfig", fmt.Sprintf("%s/%s", config.Namespace, config.Name))
// If there is no ControlPlaneEndpoint defined in ClusterConfiguration but
// there is a ControlPlaneEndpoint defined at Cluster level (e.g. the load balancer endpoint),
// then use Cluster's ControlPlaneEndpoint as a control plane endpoint for the Kubernetes cluster.
if config.Spec.ClusterConfiguration.ControlPlaneEndpoint == "" && !cluster.Spec.ControlPlaneEndpoint.IsZero() {
config.Spec.ClusterConfiguration.ControlPlaneEndpoint = cluster.Spec.ControlPlaneEndpoint.String()
log.Info("Altering ClusterConfiguration", "ControlPlaneEndpoint", config.Spec.ClusterConfiguration.ControlPlaneEndpoint)
}
// If there are no ClusterName defined in ClusterConfiguration, use Cluster.Name
if config.Spec.ClusterConfiguration.ClusterName == "" {
config.Spec.ClusterConfiguration.ClusterName = cluster.Name
log.Info("Altering ClusterConfiguration", "ClusterName", config.Spec.ClusterConfiguration.ClusterName)
}
// If there are no Network settings defined in ClusterConfiguration, use ClusterNetwork settings, if defined
if cluster.Spec.ClusterNetwork != nil {
if config.Spec.ClusterConfiguration.Networking.DNSDomain == "" && cluster.Spec.ClusterNetwork.ServiceDomain != "" {
config.Spec.ClusterConfiguration.Networking.DNSDomain = cluster.Spec.ClusterNetwork.ServiceDomain
log.Info("Altering ClusterConfiguration", "DNSDomain", config.Spec.ClusterConfiguration.Networking.DNSDomain)
}
if config.Spec.ClusterConfiguration.Networking.ServiceSubnet == "" &&
cluster.Spec.ClusterNetwork.Services != nil &&
len(cluster.Spec.ClusterNetwork.Services.CIDRBlocks) > 0 {
config.Spec.ClusterConfiguration.Networking.ServiceSubnet = cluster.Spec.ClusterNetwork.Services.String()
log.Info("Altering ClusterConfiguration", "ServiceSubnet", config.Spec.ClusterConfiguration.Networking.ServiceSubnet)
}
if config.Spec.ClusterConfiguration.Networking.PodSubnet == "" &&
cluster.Spec.ClusterNetwork.Pods != nil &&
len(cluster.Spec.ClusterNetwork.Pods.CIDRBlocks) > 0 {
config.Spec.ClusterConfiguration.Networking.PodSubnet = cluster.Spec.ClusterNetwork.Pods.String()
log.Info("Altering ClusterConfiguration", "PodSubnet", config.Spec.ClusterConfiguration.Networking.PodSubnet)
}
}
// If there are no KubernetesVersion settings defined in ClusterConfiguration, use Version from machine, if defined
if config.Spec.ClusterConfiguration.KubernetesVersion == "" && machine.Spec.Version != nil {
config.Spec.ClusterConfiguration.KubernetesVersion = *machine.Spec.Version
log.Info("Altering ClusterConfiguration", "KubernetesVersion", config.Spec.ClusterConfiguration.KubernetesVersion)
}
}
// storeBootstrapData creates a new secret with the data passed in as input,
// sets the reference in the configuration status and ready to true.
func (r *KubeadmConfigReconciler) storeBootstrapData(ctx context.Context, scope *Scope, data []byte) error {
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: scope.Config.Name,
Namespace: scope.Config.Namespace,
Labels: map[string]string{
clusterv1.ClusterLabelName: scope.Cluster.Name,
},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: bootstrapv1.GroupVersion.String(),
Kind: "KubeadmConfig",
Name: scope.Config.Name,
UID: scope.Config.UID,
Controller: pointer.BoolPtr(true),
},
},
},
Data: map[string][]byte{
"value": data,
},
Type: clusterv1.ClusterSecretType,
}
// as secret creation and scope.Config status patch are not atomic operations
// it is possible that secret creation happens but the config.Status patches are not applied
if err := r.Client.Create(ctx, secret); err != nil {
if !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "failed to create bootstrap data secret for KubeadmConfig %s/%s", scope.Config.Namespace, scope.Config.Name)
}
r.Log.Info("bootstrap data secret for KubeadmConfig already exists", "secret", secret.Name, "KubeadmConfig", scope.Config.Name)
}
scope.Config.Status.DataSecretName = pointer.StringPtr(secret.Name)
scope.Config.Status.Ready = true
conditions.MarkTrue(scope.Config, bootstrapv1.DataSecretAvailableCondition)
return nil
}