This repository has been archived by the owner on Dec 7, 2023. It is now read-only.
/
existinginframachine_controller.go
1541 lines (1405 loc) · 53.4 KB
/
existinginframachine_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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2020 Weaveworks.
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"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/go-logr/logr"
gerrors "github.com/pkg/errors"
log "github.com/sirupsen/logrus"
existinginfrav1 "github.com/weaveworks/cluster-api-provider-existinginfra/apis/cluster.weave.works/v1alpha3"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/apis/wksprovider/machine/config"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/apis/wksprovider/machine/os"
machineutil "github.com/weaveworks/cluster-api-provider-existinginfra/pkg/cluster/machine"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/kubernetes/drain"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/plan"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/plan/recipe"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/plan/resource"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/plan/runners/ssh"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/specs"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/encoding"
bootstraputils "github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/kubeadm"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/object"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/version"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
bootstrapapi "k8s.io/cluster-bootstrap/token/api"
"k8s.io/kubernetes/cmd/kubeadm/app/phases/copycerts"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/patch"
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/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"sigs.k8s.io/yaml"
)
const (
masterLabel string = "node-role.kubernetes.io/master"
originalMasterLabel string = "wks.weave.works/original-master"
controllerName string = "wks-controller"
controllerNamespace string = "weavek8sops"
controllerSecret string = "wks-controller-secrets"
bootstrapTokenID string = "bootstrapTokenID"
)
// ExistingInfraMachineReconciler is responsible for managing this cluster's machines, and
// ensuring their state converge towards their definitions.
type ExistingInfraMachineReconciler struct {
Client client.Client
Log logr.Logger
Scheme *runtime.Scheme
clientSet *kubernetes.Clientset
controllerNamespace string
eventRecorder record.EventRecorder
verbose bool
}
// +kubebuilder:rbac:groups=cluster.weave.works,resources=existinginframachines,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cluster.weave.works,resources=existinginframachines/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;patch
func (a *ExistingInfraMachineReconciler) Reconcile(req ctrl.Request) (_ ctrl.Result, reterr error) {
ctx := context.TODO() // upstream will add this eventually
contextLog := log.WithField("name", req.NamespacedName)
// request only contains the name of the object, so fetch it from the api-server
eim := &existinginfrav1.ExistingInfraMachine{}
err := a.Client.Get(ctx, req.NamespacedName, eim)
if err != nil {
if apierrs.IsNotFound(err) { // isn't there; give in
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
// Get Machine via OwnerReferences
machine, err := util.GetOwnerMachine(ctx, a.Client, eim.ObjectMeta)
if err != nil {
return ctrl.Result{}, err
}
if machine == nil {
contextLog.Info("Machine Controller has not yet set ownerReferences")
return ctrl.Result{}, nil
}
contextLog = contextLog.WithField("machine", machine.Name)
// Get Cluster via label "cluster.x-k8s.io/cluster-name"
cluster, err := util.GetClusterFromMetadata(ctx, a.Client, machine.ObjectMeta)
if err != nil {
contextLog.Info("Machine is missing cluster label or cluster does not exist")
return ctrl.Result{}, nil
}
if util.IsPaused(cluster, eim) {
contextLog.Info("ExistingInfraMachine or linked Cluster is marked as paused. Won't reconcile")
return ctrl.Result{}, nil
}
contextLog = contextLog.WithField("cluster", cluster.Name)
// Now go from the Cluster to the ExistingInfraCluster
if cluster.Spec.InfrastructureRef == nil || cluster.Spec.InfrastructureRef.Name == "" {
contextLog.Info("Cluster is missing infrastructureRef")
return ctrl.Result{}, nil
}
eic := &existinginfrav1.ExistingInfraCluster{}
if err := a.Client.Get(ctx, client.ObjectKey{
Namespace: eim.Namespace,
Name: cluster.Spec.InfrastructureRef.Name,
}, eic); err != nil {
contextLog.Infof("ExistingInfraCluster is not available yet - %v", err)
return ctrl.Result{}, nil
}
// Initialize the patch helper
patchHelper, err := patch.NewHelper(eim, a.Client)
if err != nil {
return ctrl.Result{}, err
}
// Attempt to Patch the ExistingInfraMachine object and status after each reconciliation.
defer func() {
if err := patchHelper.Patch(ctx, eim); err != nil {
contextLog.Errorf("failed to patch ExistingInfraMachine: %v", err)
if reterr == nil {
reterr = err
}
}
}()
// Object still there but with deletion timestamp => run our finalizer
if !eim.ObjectMeta.DeletionTimestamp.IsZero() {
err := a.delete(ctx, eic, machine, eim)
if err != nil {
contextLog.Errorf("failed to delete machine: %v", err)
}
controllerutil.RemoveFinalizer(eim, existinginfrav1.ExistingInfraMachineFinalizer)
return ctrl.Result{}, err
}
reschedule, err := a.update(ctx, eic, machine, eim)
if err != nil {
contextLog.Errorf("failed to update machine: %v", err)
}
if reschedule {
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
return ctrl.Result{}, err
}
func (a *ExistingInfraMachineReconciler) create(ctx context.Context, installer *os.OS, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine) error {
contextLog := log.WithFields(log.Fields{"machine": machine.Name, "cluster": c.Name})
contextLog.Info("creating machine...")
nodePlan, err := a.getNodePlan(ctx, c, machine, a.getMachineAddress(eim), installer)
if err != nil {
return err
}
if err := installer.SetupNode(ctx, nodePlan); err != nil {
return gerrors.Wrapf(err, "failed to set up machine %s", machine.Name)
}
addr := a.getMachineAddress(eim)
node, err := a.findNodeByPrivateAddress(ctx, addr)
if err != nil {
return gerrors.Wrapf(err, "failed to find node by address: %s", addr)
}
if err = a.setNodeAnnotation(ctx, node.Name, recipe.PlanKey, nodePlan.ToState().ToJSON()); err != nil {
return err
}
if err = a.setNodeProviderIDIfNecessary(ctx, node); err != nil {
return err
}
// CAPI machine controller requires providerID
eim.Spec.ProviderID = generateProviderID(node.Name)
eim.Status.Ready = true
a.recordEvent(machine, corev1.EventTypeNormal, "Create", "created machine %s", machine.Name)
return nil
}
func (a *ExistingInfraMachineReconciler) getClusterConfigMap(ctx context.Context, eic *existinginfrav1.ExistingInfraCluster) (*v1.ConfigMap, error) {
var configMap v1.ConfigMap
if err := a.Client.Get(ctx, client.ObjectKey{Namespace: a.controllerNamespace, Name: eic.Name}, &configMap); err != nil {
if kerrors.IsNotFound(err) {
return nil, errors.New("No cluster config map found")
}
log.Infof("Failed to retrieve config map")
return nil, err
}
return &configMap, nil
}
func (a *ExistingInfraMachineReconciler) connectTo(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, m *existinginfrav1.ExistingInfraMachine) (*os.OS, io.Closer, error) {
privateAddress := a.getMachineAddress(m)
info, err := a.getMachineInfo(ctx, privateAddress)
if err != nil {
return nil, nil, err
}
sshKey, err := getSSHKey(info)
if err != nil {
return nil, nil, err
}
sshClient, err := ssh.NewClient(ssh.ClientParams{
User: info.SSHUser,
Host: privateAddress,
Port: m.Spec.Private.Port,
PrivateKey: sshKey,
PrintOutputs: a.verbose,
})
if err != nil {
return nil, nil, gerrors.Wrapf(err, "failed to create SSH client using %v", m.Spec.Private)
}
os, err := os.Identify(ctx, sshClient)
if err != nil {
return nil, nil, gerrors.Wrapf(err, "failed to identify machine %s's operating system", a.getMachineAddress(m))
}
return os, sshClient, nil
}
func (a *ExistingInfraMachineReconciler) getMachineInfo(ctx context.Context, privateAddress string) (os.MachineInfo, error) {
var secret corev1.Secret
err := a.Client.Get(ctx, client.ObjectKey{Namespace: a.controllerNamespace, Name: ConnectionSecretName}, &secret)
if err != nil {
return os.MachineInfo{}, gerrors.Wrap(err, "failed to get connection secret")
}
pool := secret.Data["config"]
var info []os.MachineInfo
if err := json.Unmarshal(pool, &info); err != nil {
return os.MachineInfo{}, gerrors.Wrap(err, "failed to unmarshal secret")
}
return a.getMachineInfoOrUseDefault(ctx, &info, privateAddress)
}
func (a *ExistingInfraMachineReconciler) getMachineInfoOrUseDefault(ctx context.Context, mi *[]os.MachineInfo, privateAddress string) (os.MachineInfo, error) {
type infoKey struct {
u string
p string
}
uniqInfos := make(map[infoKey]interface{})
for _, m := range *mi {
if m.PrivateIP == privateAddress {
return m, nil
}
uniqInfos[infoKey{u: m.SSHUser, p: m.SSHKey}] = nil
}
// if we don't find a user/key for this private IP and all of the entries are the same,
// return the first one
// TODO: Add an info for this private address
if len(uniqInfos) == 1 {
return (*mi)[0], nil
}
return os.MachineInfo{}, fmt.Errorf("No machine information found for: %s", privateAddress)
}
// kubeadmJoinSecrets groups the values available in the wks-controller-secrets
// Secret to provide to kubeadm join commands.
type kubeadmJoinSecrets struct {
// DiscoveryTokenCaCertHash is used to validate that the root CA public key
// of the cluster we are trying to join matches.
DiscoveryTokenCaCertHash string
// BootstrapTokenID is the ID of the token used by kubeadm init and kubeadm
// join to safely form new clusters.
BootstrapTokenID string
// CertificateKey is used by kubeadm --certificate-key to have other master
// nodes safely join the cluster.
CertificateKey string
}
func (a *ExistingInfraMachineReconciler) kubeadmJoinSecrets(ctx context.Context) (*kubeadmJoinSecrets, error) {
var secret corev1.Secret
err := a.Client.Get(ctx, client.ObjectKey{Namespace: a.controllerNamespace, Name: controllerSecret}, &secret)
if err != nil {
return nil, gerrors.Wrap(err, "failed to get WKS' secret")
}
return &kubeadmJoinSecrets{
DiscoveryTokenCaCertHash: string(secret.Data["discoveryTokenCaCertHash"]),
BootstrapTokenID: string(secret.Data[bootstrapTokenID]),
CertificateKey: string(secret.Data["certificateKey"]),
}, nil
}
func (a *ExistingInfraMachineReconciler) updateKubeadmJoinSecrets(ctx context.Context, id string, secret *corev1.Secret) error {
len := base64.StdEncoding.EncodedLen(len(id))
enc := make([]byte, len)
base64.StdEncoding.Encode(enc, []byte(id))
patch := []byte(fmt.Sprintf("{\"data\":{\"%s\":\"%s\"}}", bootstrapTokenID, enc))
err := a.Client.Patch(ctx, secret, client.RawPatch(types.StrategicMergePatchType, patch))
if err != nil {
log.Debugf("failed to patch wks secret %s %v", patch, err)
}
return err
}
func (a *ExistingInfraMachineReconciler) token(ctx context.Context, id string) (string, error) {
ns := "kube-system"
name := fmt.Sprintf("%s%s", bootstrapapi.BootstrapTokenSecretPrefix, id)
secret := &corev1.Secret{}
err := a.Client.Get(ctx, client.ObjectKey{Namespace: ns, Name: name}, secret)
if err != nil {
// The secret may have been removed if it expired so we will generate a new one
log.Infof("failed to find original bootstrap token %s/%s, generating a new one", ns, name)
newSecret, err := a.installNewBootstrapToken(ctx, ns)
if err != nil {
return "", gerrors.Wrapf(err, "failed to find old secret %s/%s or generate a new one", ns, name)
}
secret = newSecret
} else if bootstrapTokenHasExpired(secret) {
log.Infof("token %s/%s has expired, generating a new one", ns, name)
newSecret, err := a.installNewBootstrapToken(ctx, ns)
if err != nil {
return "", gerrors.Wrapf(err, "failed to replace expired secret %s/%s with a new one", ns, name)
}
secret = newSecret
}
tokenID, ok := secret.Data[bootstrapapi.BootstrapTokenIDKey]
if !ok {
return "", gerrors.Errorf("token-id not found %s/%s", ns, name)
}
tokenSecret, ok := secret.Data[bootstrapapi.BootstrapTokenSecretKey]
if !ok {
return "", gerrors.Errorf("token-secret not found %s/%s", ns, name)
}
return fmt.Sprintf("%s.%s", tokenID, tokenSecret), nil
}
func bootstrapTokenHasExpired(secret *corev1.Secret) bool {
// verify that the token hasn't expired
expiration, ok := secret.Data[bootstrapapi.BootstrapTokenExpirationKey]
if !ok {
log.Debugf("expiration not found for secret %s/%s", secret.ObjectMeta.Namespace, secret.ObjectMeta.Name)
return true
}
expirationTime, err := time.Parse(time.RFC3339, string(expiration))
if err != nil {
log.Debugf("failed to parse token expiration %s for secret %s/%s error %v", expiration, secret.ObjectMeta.Namespace, secret.ObjectMeta.Name, err)
return true
}
// if the token expires within 60 seconds, we need to generate a new one
return time.Until(expirationTime).Seconds() < 60
}
func (a *ExistingInfraMachineReconciler) installNewBootstrapToken(ctx context.Context, ns string) (*corev1.Secret, error) {
secret, err := bootstraputils.GenerateBootstrapSecret(ns)
if err != nil {
return nil, gerrors.Errorf("failed to create new bootstrap token %s/%s", ns, secret.ObjectMeta.Name)
}
err = a.Client.Create(ctx, secret)
if err != nil {
return nil, gerrors.Errorf("failed to install new bootstrap token %s/%s", ns, secret.ObjectMeta.Name)
}
tokenID, ok := secret.Data[bootstrapapi.BootstrapTokenIDKey]
if !ok {
return nil, gerrors.Errorf("token-id not found %s/%s", secret.ObjectMeta.Namespace, secret.ObjectMeta.Name)
}
if err := a.updateKubeadmJoinSecrets(ctx, string(tokenID), secret); err != nil {
return nil, gerrors.Errorf("Failed to update wks join token %s/%s", secret.ObjectMeta.Namespace, secret.ObjectMeta.Name)
}
return secret, nil
}
// Delete the machine. If no error is returned, it is assumed that all dependent resources have been cleaned up.
func (a *ExistingInfraMachineReconciler) delete(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine) error {
contextLog := log.WithFields(log.Fields{"machine": machine.Name, "cluster": c.Name})
contextLog.Info("deleting machine...")
addr := a.getMachineAddress(eim)
node, err := a.findNodeByPrivateAddress(ctx, addr)
if err != nil {
return gerrors.Wrapf(err, "failed to find node by address: %s", addr)
}
// Check if there's an adequate number of masters
isMaster := isMaster(node)
masters, err := a.getMasterNodes(ctx)
if err != nil {
return err
}
if isMaster && len(masters) == 1 {
return errors.New("there should be at least one master")
}
if err := drain.Drain(node, a.clientSet, drain.Params{
Force: true,
DeleteEmptyDirData: true,
IgnoreAllDaemonSets: true,
}); err != nil {
return err
}
//After deleting the k8s resource we need to reset the node so it can be readded later with a clean state.
//best effort attempt to clean up the machine after deleting it.
a.resetMachine(ctx, c, machine, eim)
if err := a.Client.Delete(ctx, node); err != nil {
return err
}
a.recordEvent(machine, corev1.EventTypeNormal, "Delete", "deleted machine %s", machine.Name)
return nil
}
func (a *ExistingInfraMachineReconciler) resetMachine(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine) {
installer, closer, err := a.connectTo(ctx, c, eim)
if err != nil {
log.Error(gerrors.Wrapf(err, "failed to establish connection to machine %s", machine.Name))
}
defer closer.Close()
b := plan.NewBuilder()
b.AddResource(
"kubeadm:reset",
&resource.Run{Script: object.String("kubeadm reset --force")},
)
p, err := b.Plan()
if err != nil {
log.Fatalf("%v", err)
}
if _, err := p.Apply(ctx, installer.Runner, plan.EmptyDiff()); err != nil {
log.Errorf("failed to completely reset machine: %v", err)
}
}
// Update the machine to the provided definition.
func (a *ExistingInfraMachineReconciler) update(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine) (bool, error) {
contextLog := log.WithFields(log.Fields{"machine": machine.Name, "cluster": c.Name})
contextLog.Info("updating machine...")
installer, closer, err := a.connectTo(ctx, c, eim)
if err != nil {
return false, gerrors.Wrapf(err, "failed to establish connection to machine %s", machine.Name)
}
defer closer.Close()
addr := a.getMachineAddress(eim)
node, err := a.findNodeByPrivateAddress(ctx, addr)
if err != nil {
if apierrs.IsNotFound(err) {
log.Infof("no existing node found for %s...", addr)
a.displayAllNodes(ctx)
log.Infof("creating %s...", addr)
// isn't there; try to create it
// Since ExistingInfra controller handles bootstrapping, add the
// finalizer here to ensure we cleanup on delete
if err := a.modifyEIM(ctx, eim, func(e *existinginfrav1.ExistingInfraMachine) {
controllerutil.AddFinalizer(eim, existinginfrav1.ExistingInfraMachineFinalizer)
}); err != nil {
return false, gerrors.Wrapf(err, "failed to add finalizer to: %s", eim.Spec.Private.Address)
}
return false, a.create(ctx, installer, c, machine, eim)
}
return false, gerrors.Wrapf(err, "failed to find node by address: %s", addr)
}
log.Infof("found existing node for %s...", addr)
contextLog = contextLog.WithFields(log.Fields{"node": node.Name})
if err = a.setNodeProviderIDIfNecessary(ctx, node); err != nil {
return false, err
}
isMaster := isMaster(node)
if isMaster {
// Check if the kubeadm-certs secret exists.
// If not, run the renewal plan to upload new certs:
// kubeadm init phase upload-certs --upload-certs
// and update wks-controller-secrets with the new certificate key and bootstrap token ID
// so that new control plane nodes can be added to the cluster.
exists, _ := a.kubeadmCertsExists(ctx)
if !exists {
log.Info("kubeadm-certs secret not found, regenerating...")
err = a.renewKubeadmCerts(ctx, installer)
if err != nil {
return false, err
}
}
if err := a.prepareForMasterUpdate(ctx, node); err != nil {
contextLog.Infof("skipping update for %s...", addr)
return false, err
}
}
nodePlan, err := a.getNodePlan(ctx, c, machine, a.getMachineAddress(eim), installer)
if err != nil {
return false, gerrors.Wrapf(err, "Failed to get node plan for machine %s", machine.Name)
}
planState := nodePlan.ToState()
currentPlan, found := node.Annotations[recipe.PlanKey]
if !found {
contextLog.Info("No plan annotation on Node; unable to update")
return false, nil
}
currentState, err := plan.NewStateFromJSON(strings.NewReader(currentPlan))
if err != nil {
return false, gerrors.Wrapf(err, "Failed to parse node plan for machine %s", machine.Name)
}
// check equality by re-serialising to JSON; this avoids any formatting differences, also
// type differences between deserialised State and State created from Plan.
planJSON := planState.ToJSON()
if currentState.ToJSON() == planJSON {
contextLog.Info("Machine and node have matching plans; nothing to do")
return false, nil
}
if diffedPlan, err := currentState.Diff(planState); err == nil {
contextLog.Info("........................ DIFF PLAN ........................")
fmt.Print(diffedPlan)
} else {
contextLog.Errorf("DIFF PLAN Error: %v", err)
}
contextLog.Infof("........................NEW UPDATE FOR: %s...........................", machine.Name)
upOrDowngrade := isUpOrDowngrade(machine, node)
contextLog.Infof("Is master: %t, is up or downgrade: %t", isMaster, upOrDowngrade)
if upOrDowngrade {
if err := checkForVersionJump(machine, node); err != nil {
return false, err
}
version := machineutil.GetKubernetesVersion(machine)
nodeStyleVersion := "v" + version
originalNeedsUpdate, err := a.checkIfOriginalMasterNotAtVersion(ctx, nodeStyleVersion)
if err != nil {
return false, err
}
contextLog.Infof("Original needs update: %t", originalNeedsUpdate)
masterNeedsUpdate, err := a.checkIfMasterNotAtVersion(ctx, nodeStyleVersion)
if err != nil {
return false, err
}
contextLog.Infof("Master needs update: %t", masterNeedsUpdate)
isOriginal, err := a.isOriginalMaster(ctx, node)
if err != nil {
return false, err
}
contextLog.Infof("Is original: %t", isOriginal)
if (!isOriginal && originalNeedsUpdate) || (!isMaster && masterNeedsUpdate) {
log.Info("Master nodes must be upgraded before worker nodes")
return true, nil
}
isController, err := a.isControllerNode(ctx, node)
if err != nil {
return false, err
}
contextLog.Infof("Is controller: %t", isController)
if isMaster {
switch {
case isController:
// If there is no error, this will end the run of this reconciliation since the controller will be migrated
if err := drain.Drain(node, a.clientSet, drain.Params{
Force: true,
DeleteEmptyDirData: true,
IgnoreAllDaemonSets: true,
}); err != nil {
return false, err
}
case isOriginal:
return false, a.kubeadmUpOrDowngrade(ctx, c, machine, eim, node, installer, version, planJSON, recipe.OriginalMaster)
default:
return false, a.kubeadmUpOrDowngrade(ctx, c, machine, eim, node, installer, version, planJSON, recipe.SecondaryMaster)
}
}
return false, a.kubeadmUpOrDowngrade(ctx, c, machine, eim, node, installer, version, planJSON, recipe.Worker)
}
isOriginal, err := a.isOriginalMaster(ctx, node)
if err != nil {
return false, err
}
log.Info("Is original control plane node: ", isOriginal)
log.Info("ControlPlaneEndpoint: ", c.Spec.ControlPlaneEndpoint)
if isOriginal && c.Spec.ControlPlaneEndpoint == "" {
return false, errors.New("cannot perform update of original control plane node without a control plane load balancer")
}
if err = a.performActualUpdate(ctx, installer, machine, node, nodePlan, c); err != nil {
return false, err
}
if err = a.setNodeAnnotation(ctx, node.Name, recipe.PlanKey, planJSON); err != nil {
return false, err
}
// CAPI machine controller requires providerID
eim.Spec.ProviderID = generateProviderID(node.Name)
eim.Status.Ready = true
a.recordEvent(machine, corev1.EventTypeNormal, "Update", "updated machine %s", machine.Name)
return false, nil
}
func (a *ExistingInfraMachineReconciler) displayAllNodes(ctx context.Context) {
var nodes corev1.NodeList
if err := a.Client.List(ctx, &nodes); err == nil {
nodeIPs := []string{}
for _, node := range nodes.Items {
nodeIPs = append(nodeIPs, getNodePrivateAddress(&node))
}
log.Infof("all existing nodes found: %+v", nodeIPs)
}
}
func (a *ExistingInfraMachineReconciler) renewKubeadmCerts(ctx context.Context, installer *os.OS) error {
// Renewal of kubeadm-certs is done in two steps, generating a certificate key
// which is passed to kubeadm upload certs plan
certificateKey, err := copycerts.CreateCertificateKey()
if err != nil {
return err
}
log.Debugf(fmt.Sprintf("uploading kubeadm certs with cert key: %s", certificateKey))
uploadCertsPlan, err := recipe.BuildUploadKubeadmCertsPlan(ctx, certificateKey)
if err != nil {
log.Errorf("failed to build upload kubeadm certs plan, err: %s", err)
return err
}
_, err = uploadCertsPlan.Apply(ctx, installer.Runner, plan.EmptyDiff())
if err != nil {
log.Errorf("Apply of Plan failed:\n%s\n", err)
return err
}
log.Infof("creating a new bootstrap token...")
bootstrapTokenSecret, err := a.installNewBootstrapToken(ctx, "kube-system")
if err != nil {
return gerrors.Errorf("failed to create new bootstrap token, err: %s", err)
}
tokenID, ok := bootstrapTokenSecret.Data[bootstrapapi.BootstrapTokenIDKey]
if !ok {
return gerrors.Errorf("token-id not found %s/%s", bootstrapTokenSecret.ObjectMeta.Namespace, bootstrapTokenSecret.ObjectMeta.Name)
}
// Base64 encode the certificate key and token ID
certificateKeyB64 := encoding.Base64Encode(certificateKey)
tokenIDB64 := encoding.Base64Encode(string(tokenID))
patch := []byte(fmt.Sprintf("{\"data\":{\"%s\":\"%s\", \"%s\":\"%s\"}}",
"certificateKey", certificateKeyB64, "bootstrapTokenID", tokenIDB64))
// Update wks-controller-secrets with new cert key and bootstrap token ID
secret := corev1.Secret{}
secretName := types.NamespacedName{
Name: controllerSecret,
Namespace: controllerNamespace,
}
err = a.Client.Get(ctx, secretName, &secret)
if err != nil {
log.Infof("failed to get %s in namespace %s %s %v", controllerSecret, controllerNamespace, patch, err)
return err
}
err = a.Client.Patch(ctx, &secret, client.RawPatch(types.StrategicMergePatchType, patch))
if err != nil {
log.Infof("failed to patch %s secret %s %v", controllerSecret, patch, err)
return err
}
return nil
}
// kubeadmUpOrDowngrade does upgrade or downgrade a machine.
// Parameter k8sversion specified here represents the version of both Kubernetes and Kubeadm.
func (a *ExistingInfraMachineReconciler) kubeadmUpOrDowngrade(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine, node *corev1.Node, installer *os.OS,
k8sVersion, planJSON string, ntype recipe.NodeType) error {
b := plan.NewBuilder()
upgradeRes, err := recipe.BuildUpgradePlan(installer.PkgType, k8sVersion, ntype)
if err != nil {
return err
}
b.AddResource("upgrade:k8s", upgradeRes)
p, err := b.Plan()
if err != nil {
return err
}
if err := installer.SetupNode(ctx, &p); err != nil {
log.Infof("Failed to upgrade node %s: %v", node.Name, err)
return err
}
log.Infof("About to uncordon node %s...", node.Name)
if err := a.uncordon(ctx, node); err != nil {
log.Info("Failed to uncordon...")
return err
}
log.Info("Finished with uncordon...")
if err = a.setNodeAnnotation(ctx, node.Name, recipe.PlanKey, planJSON); err != nil {
return err
}
a.recordEvent(machine, corev1.EventTypeNormal, "Update", "updated machine %s", machine.Name)
return nil
}
func (a *ExistingInfraMachineReconciler) prepareForMasterUpdate(ctx context.Context, node *corev1.Node) error {
// Check if it's safe to update a master
if err := a.checkMasterHAConstraint(ctx, node); err != nil {
return gerrors.Wrap(err, "Not enough available master nodes to allow master update")
}
return nil
}
func (a *ExistingInfraMachineReconciler) performActualUpdate(
ctx context.Context,
installer *os.OS,
machine *clusterv1.Machine,
node *corev1.Node,
nodePlan *plan.Plan,
cluster *existinginfrav1.ExistingInfraCluster) error {
if err := drain.Drain(node, a.clientSet, drain.Params{
Force: true,
DeleteEmptyDirData: true,
IgnoreAllDaemonSets: true,
}); err != nil {
return err
}
log.Info("repaving node...")
if err := installer.SetupNode(ctx, nodePlan); err != nil {
return gerrors.Wrapf(err, "failed to set up machine %s", machine.Name)
}
log.Info("uncordoning node...")
if err := a.uncordon(ctx, node); err != nil {
return err
}
log.Info("finished updating node...")
return nil
}
func (a *ExistingInfraMachineReconciler) getNodePlan(ctx context.Context, provider *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, machineAddress string, installer *os.OS) (*plan.Plan, error) {
namespace := a.controllerNamespace
secrets, err := a.kubeadmJoinSecrets(ctx)
if err != nil {
return nil, err
}
token, err := a.token(ctx, secrets.BootstrapTokenID)
if err != nil {
return nil, err
}
master, err := a.getControllerNode(ctx)
if err != nil {
return nil, err
}
masterIP, err := getInternalAddress(master)
if err != nil {
return nil, err
}
configMaps, err := a.getProviderConfigMaps(ctx, provider)
if err != nil {
return nil, err
}
authConfigMap, err := a.getAuthConfigMap(ctx)
if err != nil {
return nil, err
}
var authSecrets map[string]resource.SecretData
if authConfigMap != nil {
authSecrets, err = a.getAuthSecrets(ctx, authConfigMap)
if err != nil {
return nil, err
}
}
assetConfigMap, err := a.getAssetConfigMap(ctx, provider)
if err != nil {
return nil, err
}
assetDescriptions := map[string]bootstraputils.AssetDescription{}
err = json.Unmarshal([]byte(assetConfigMap.Data["assets"]), &assetDescriptions)
if err != nil {
return nil, err
}
kubernetesVersion := machineutil.GetKubernetesVersion(machine)
plan, err := installer.CreateNodeSetupPlan(ctx, os.NodeParams{
IsMaster: machine.Labels["set"] == "master",
MasterIP: masterIP,
MasterPort: 6443, // TODO: read this dynamically, from somewhere.
Token: token,
DiscoveryTokenCaCertHash: secrets.DiscoveryTokenCaCertHash,
CertificateKey: secrets.CertificateKey,
KubeletConfig: config.KubeletConfig{
NodeIP: machineAddress,
CloudProvider: provider.Spec.CloudProvider,
ExtraArguments: specs.TranslateServerArgumentsToStringMap(provider.Spec.KubeletArguments),
},
KubernetesVersion: kubernetesVersion,
CRI: provider.Spec.CRI,
CNI: provider.Spec.CNI,
ConfigFileSpecs: provider.Spec.OS.Files,
ProviderConfigMaps: configMaps,
AuthConfigMap: authConfigMap,
Secrets: authSecrets,
Namespace: namespace,
ControlPlaneEndpoint: provider.Spec.ControlPlaneEndpoint,
AssetDescriptions: assetDescriptions,
Flavor: provider.Spec.Flavor,
})
if err != nil {
return nil, gerrors.Wrapf(err, "failed to create machine plan for %s", machine.Name)
}
return plan, nil
}
func (a *ExistingInfraMachineReconciler) getAuthConfigMap(ctx context.Context) (*corev1.ConfigMap, error) {
return a.getConfigMap(ctx, "auth-config")
}
func (a *ExistingInfraMachineReconciler) getAssetConfigMap(ctx context.Context, eic *existinginfrav1.ExistingInfraCluster) (*corev1.ConfigMap, error) {
return a.getConfigMap(ctx, eic.Name+"-assets")
}
func (a *ExistingInfraMachineReconciler) getConfigMap(ctx context.Context, mapName string) (*corev1.ConfigMap, error) {
var maps corev1.ConfigMapList
err := a.Client.List(ctx, &maps, &client.ListOptions{Namespace: a.controllerNamespace})
if err != nil {
return nil, err
}
for _, cmap := range maps.Items {
if cmap.Name == mapName {
return &cmap, nil
}
}
return nil, nil
}
func (a *ExistingInfraMachineReconciler) getAuthSecrets(ctx context.Context, authConfigMap *corev1.ConfigMap) (map[string]resource.SecretData, error) {
authSecrets := map[string]resource.SecretData{}
for _, authType := range []string{"authentication", "authorization"} {
secretName := authConfigMap.Data[authType+"-secret-name"]
var secret corev1.Secret
err := a.Client.Get(ctx, client.ObjectKey{Namespace: a.controllerNamespace, Name: secretName}, &secret)
// TODO: retry several times like the old code did (?)
// TODO: check whether it is a not-found response
if err != nil {
// No secret present
continue
}
if secret.Data != nil {
authSecrets[authType] = secret.Data
}
}
return authSecrets, nil
}
func (a *ExistingInfraMachineReconciler) getProviderConfigMaps(ctx context.Context, provider *existinginfrav1.ExistingInfraCluster) (map[string]*corev1.ConfigMap, error) {
fileSpecs := provider.Spec.OS.Files
configMaps := map[string]*corev1.ConfigMap{}
for _, fileSpec := range fileSpecs {
mapName := fileSpec.Source.ConfigMap
if _, seen := configMaps[mapName]; !seen {
var configMap corev1.ConfigMap
err := a.Client.Get(ctx, client.ObjectKey{Namespace: a.controllerNamespace, Name: mapName}, &configMap)
if err != nil {
return nil, err
}
configMaps[mapName] = &configMap
}
}
return configMaps, nil
}
func isUpOrDowngrade(machine *clusterv1.Machine, node *corev1.Node) bool {
return machineVersion(machine) != nodeVersion(node)
}
func checkForVersionJump(machine *clusterv1.Machine, node *corev1.Node) error {
mVersion := machineVersion(machine)
nVersion := nodeVersion(node)
lt, err := version.LessThan(mVersion, nVersion)
if err != nil {
return err
}
if lt {
return fmt.Errorf("Downgrade not supported. Machine version: %s is less than node version: %s", mVersion, nVersion)
}
isVersionJump, err := version.Jump(nVersion, mVersion)
if err != nil {
return err
}
if isVersionJump {
return fmt.Errorf("Upgrades can only be performed between patch versions of a single minor version or between "+
"minor versions differing by no more than 1 - machine version: %s, node version: %s", mVersion, nVersion)
}
return nil
}
func (a *ExistingInfraMachineReconciler) checkIfMasterNotAtVersion(ctx context.Context, kubernetesVersion string) (bool, error) {
nodes, err := a.getMasterNodes(ctx)
if err != nil {
// If we can't read the nodes, return the error so we don't
// accidentally flush the sole master
return false, err
}
for _, master := range nodes {
if nodeVersion(master) != kubernetesVersion {
return true, nil
}
}
return false, nil
}
func (a *ExistingInfraMachineReconciler) checkIfOriginalMasterNotAtVersion(ctx context.Context, kubernetesVersion string) (bool, error) {
node, err := a.getOriginalMasterNode(ctx)
if err != nil {
// If we can't read the nodes, return the error so we don't
// accidentally flush the sole master
return false, err
}
return nodeVersion(node) != kubernetesVersion, nil
}
func (a *ExistingInfraMachineReconciler) getOriginalMasterNode(ctx context.Context) (*corev1.Node, error) {
nodes, err := a.getMasterNodes(ctx)
if err != nil {
return nil, err
}
for _, node := range nodes {
_, isOriginalMaster := node.Labels[originalMasterLabel]
if isOriginalMaster {
return node, nil
}
}
if len(nodes) == 0 {
return nil, errors.New("No master found")
}
// There is no master node which is labeled with originalMasterLabel
// So we just pick nodes[0] of the list, then label it.
originalMasterNode := nodes[0]
if _, exist := originalMasterNode.Labels[originalMasterLabel]; !exist {
if err := a.setNodeLabel(ctx, originalMasterNode.Name, originalMasterLabel, ""); err != nil {
return nil, err
}
}
return originalMasterNode, nil
}
func (a *ExistingInfraMachineReconciler) isOriginalMaster(ctx context.Context, node *corev1.Node) (bool, error) {
masterNode, err := a.getOriginalMasterNode(ctx)
if err != nil {
return false, err
}
return masterNode.Name == node.Name, nil
}
func machineVersion(machine *clusterv1.Machine) string {
return "v" + machineutil.GetKubernetesVersion(machine)
}
func nodeVersion(node *corev1.Node) string {
return node.Status.NodeInfo.KubeletVersion
}
func (a *ExistingInfraMachineReconciler) uncordon(ctx context.Context, node *corev1.Node) error {
contextLog := log.WithFields(log.Fields{"node": node.Name})
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
var result corev1.Node
getErr := a.Client.Get(ctx, client.ObjectKey{Name: node.Name}, &result)
if getErr != nil {
contextLog.Errorf("failed to read node info, can't reschedule: %v", getErr)
return getErr
}
result.Spec.Unschedulable = false
updateErr := a.Client.Update(ctx, &result)
if updateErr != nil {
contextLog.Errorf("failed to reschedule node: %v", updateErr)
return updateErr
}
return nil
})
if retryErr != nil {