This repository has been archived by the owner on Dec 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
os.go
1630 lines (1488 loc) · 49.9 KB
/
os.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
package os
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"path/filepath"
"regexp"
"strings"
"text/template"
"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/crds"
"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/sudo"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/envcfg"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/manifest"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/object"
"github.com/weaveworks/cluster-api-provider-existinginfra/pkg/utilities/version"
"github.com/weaveworks/libgitops/pkg/serializer"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/api/apps/v1beta2"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1"
"sigs.k8s.io/yaml"
)
// TODO replace wksctl with a more generic term
const (
LocalCluster = "wks.weave.works/local-cluster"
Created = "wks.weave.works/is-created"
PemDestDir = "/etc/pki/weaveworks/wksctl/pem"
ConfigDestDir = "/etc/pki/weaveworks/wksctl"
sealedSecretVersion = "v0.11.0"
sealedSecretKeySecretName = "sealed-secrets-key"
fluxSecretTemplate = `apiVersion: v1
{{ if .SecretValue }}
data:
identity: {{.SecretValue}}
{{ end }}
kind: Secret
metadata:
name: flux-git-deploy
namespace: {{.Namespace}}
type: Opaque`
connectionSecretTemplate = `apiVersion: v1
data:
config: {{.SecretValue}}
kind: Secret
metadata:
name: connection-info
namespace: {{.Namespace}}
type: Opaque`
)
// OS represents an operating system and exposes the operations required to
// install Kubernetes on a machine setup with that OS.
type OS struct {
Name string
Runner plan.Runner
PkgType resource.PkgType
}
type CRDFile struct {
Fname string
Data []byte
}
// Retrieve all CRD definitions needed for cluster API
func GetCRDs(fs http.FileSystem) ([]CRDFile, error) {
log.Info("Getting CRDs")
crddir, err := fs.Open(".")
if err != nil {
return nil, errors.Wrap(err, "failed to list cluster API CRDs")
}
log.Info("Opened CRDs")
crdFiles := make([]CRDFile, 0)
for {
entry, err := crddir.Readdir(1)
if err != nil && err != io.EOF {
return nil, errors.Wrap(err, "failed to open cluster API CRD directory")
}
if entry == nil {
break
}
if entry[0].IsDir() || !strings.HasPrefix(entry[0].Name(), "cluster") {
continue
}
fname := entry[0].Name()
crd, err := fs.Open(fname)
if err != nil {
return nil, errors.Wrap(err, "failed to open cluster API CRD")
}
data, err := ioutil.ReadAll(crd)
if err != nil {
return nil, errors.Wrap(err, "failed to read cluster API CRD")
}
crdFiles = append(crdFiles, CRDFile{fname, data})
}
log.Info("Got CRDs")
return crdFiles, nil
}
// GitParams are all SeedNodeParams related to the user's Git(Hub) repo
type GitParams struct {
GitURL string
GitBranch string
GitPath string
GitDeployKeyPath string
}
// AuthParams are parameters used to configure authn and authz for the cluster
type AuthParams struct {
PEMSecretResources map[string]*SecretResourceSpec
AuthConfigMap *v1.ConfigMap
AuthConfigManifest []byte
}
// ControllerParams are all SeedNodeParams related to the WKS controller
type ControllerParams struct {
// ImageOverride will override the WKS controller image if set. It will do so
// whether the controller manifest comes from a git repository or is the
// built-in one.
ImageOverride string
// ImageBuiltin is the WKS controller image to use when generating the WKS
// controller manifest from in-memory data.
ImageBuiltin string
// Namespace in which the controller runs
Namespace string
}
// MachineInfo holds connection information (key, ips, ports) about a machine
type MachineInfo struct {
SSHUser string `json:"sshUser"`
SSHKey string `json:"sshKey"`
PublicIP string `json:"publicIP"`
PublicPort string `json:"publicPort"`
PrivateIP string `json:"privateIP"`
PrivatePort string `json:"privatePort"`
}
// SeedNodeParams groups required inputs to configure a "seed" Kubernetes node.
type SeedNodeParams struct {
PublicIP string
PrivateIP string
ServicesCIDRBlocks []string
PodsCIDRBlocks []string
ExistingInfraCluster existinginfrav1.ExistingInfraCluster
ClusterManifest string
MachinesManifest string
ConnectionInfo []MachineInfo
// BootstrapToken is the token used by kubeadm init and kubeadm join
// to safely form new clusters.
BootstrapToken *kubeadmapi.BootstrapTokenString
KubeletConfig config.KubeletConfig
Controller ControllerParams
GitData GitParams
AuthInfo *AuthParams
SealedSecretKey string
SealedSecretCert string
ConfigDirectory string
Namespace string
ImageRepository string
ControlPlaneEndpoint string
AdditionalSANs []string
AddonNamespaces map[string]string
}
// Validate generally validates this SeedNodeParams struct, e.g. ensures it
// contains mandatory values, that these are well-formed, etc.
func (params SeedNodeParams) Validate() error {
if len(params.KubeletConfig.NodeIP) == 0 {
return errors.New("empty kubelet node IP")
}
if len(params.PublicIP) == 0 {
return errors.New("empty API server public IP")
}
if len(params.PrivateIP) == 0 {
return errors.New("empty API server private IP")
}
return nil
}
// SetupSeedNode installs Kubernetes on this machine, and store the provided
// manifests in the API server, so that the rest of the cluster can then be
// set up by the WKS controller.
func SetupSeedNode(ctx context.Context, o *OS, params SeedNodeParams) error {
p, err := CreateSeedNodeSetupPlan(ctx, o, params)
if err != nil {
return err
}
return ApplyPlan(ctx, o, p)
}
// CreateSeedNodeSetupPlan constructs the seed node plan used to setup the initial node
// prior to turning control over to wks-controller
func CreateSeedNodeSetupPlan(ctx context.Context, o *OS, params SeedNodeParams) (*plan.Plan, error) {
if err := params.Validate(); err != nil {
return nil, err
}
log.Info("Validated params")
cfg, err := envcfg.GetEnvSpecificConfig(ctx, o.PkgType, params.Namespace, params.KubeletConfig.CloudProvider, o.Runner)
if err != nil {
return nil, err
}
log.Info("Got environment config")
// Get cluster
cluster := params.ExistingInfraCluster
log.Infof("Got cluster")
kubernetesVersion := getKubernetesVersion(&cluster)
log.Info("Got Kubernetes version")
// Get configuration file resources from config map manifests referenced by the cluster spec
configMapManifests, configMaps, configFileResources, err := createConfigFileResourcesFromClusterSpec(&cluster.Spec, params.Namespace)
if err != nil {
return nil, err
}
log.Info("Extracted config maps")
b := plan.NewBuilder()
baseRes := recipe.BuildBasePlan(o.PkgType)
b.AddResource("install:base", baseRes)
configRes := recipe.BuildConfigPlan(configFileResources)
b.AddResource("install:config", configRes, plan.DependOn("install:base"))
log.Info("Built config plan")
criRes := recipe.BuildCRIPlan(ctx, &cluster.Spec.CRI, cfg, o.PkgType)
b.AddResource("install:cri", criRes, plan.DependOn("install:config"))
log.Info("Built cri plan")
k8sRes := recipe.BuildK8SPlan(kubernetesVersion, params.KubeletConfig.NodeIP, cfg.SELinuxInstalled, cfg.SetSELinuxPermissive, cfg.DisableSwap, cfg.LockYUMPkgs, o.PkgType, params.KubeletConfig.CloudProvider, params.KubeletConfig.ExtraArguments)
b.AddResource("install:k8s", k8sRes, plan.DependOn("install:cri"))
log.Info("Built k8s plan")
apiServerArgs := GetAPIServerArgs(&cluster.Spec)
if params.AuthInfo != nil {
addAuthArgs(apiServerArgs, params.AuthInfo.PEMSecretResources, &cluster.Spec)
}
// Backwards-compatibility: fall back if not specified
controlPlaneEndpoint := params.ControlPlaneEndpoint
if controlPlaneEndpoint == "" {
// TODO: dynamically inject the API server's port.
controlPlaneEndpoint = params.PrivateIP + ":6443"
}
log.Info("Got control plane endpoint")
kubeadmInitResource :=
&resource.KubeadmInit{
PublicIP: params.PublicIP,
PrivateIP: params.PrivateIP,
KubeletConfig: ¶ms.KubeletConfig,
ConntrackMax: cfg.ConntrackMax,
UseIPTables: cfg.UseIPTables,
SSHKey: params.ConnectionInfo[0].SSHKey,
BootstrapToken: params.BootstrapToken,
ControlPlaneEndpoint: controlPlaneEndpoint,
IgnorePreflightErrors: cfg.IgnorePreflightErrors,
KubernetesVersion: kubernetesVersion,
CloudProvider: params.KubeletConfig.CloudProvider,
ImageRepository: params.ImageRepository,
AdditionalSANs: params.AdditionalSANs,
Namespace: object.String(params.Namespace),
NodeName: cfg.HostnameOverride,
ExtraAPIServerArgs: apiServerArgs,
// kubeadm currently accepts a single subnet for services and pods
// ref: https://godoc.org/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1#Networking
// this should be ensured in the validation step in pkg.specs.validation.validateCIDRBlocks()
ServiceCIDRBlock: params.ServicesCIDRBlocks[0],
PodCIDRBlock: params.PodsCIDRBlocks[0],
}
b.AddResource("kubeadm:init", kubeadmInitResource, plan.DependOn("install:k8s"))
log.Info("Got init resource")
// TODO(damien): Add a CNI section in cluster.yaml once we support more than one CNI plugin.
// const cni = "weave-net"
var manifest string
fetchRsc := &resource.Run{Script: object.String("kubectl version | base64 | tr -d '\n'"), Output: &manifest}
b.AddResource("fetch:cni", fetchRsc, plan.DependOn("kubeadm:init"))
cniRsc := &resource.KubectlApply{ManifestURL: plan.ParamString("https://cloud.weave.works/k8s/net?k8s-version=%s",
&manifest)}
if len(params.PodsCIDRBlocks) > 0 && params.PodsCIDRBlocks[0] != "" {
cniRsc = &resource.KubectlApply{
ManifestURL: plan.ParamString("https://cloud.weave.works/k8s/net?k8s-version=%s&env.IPALLOC_RANGE=%s",
&manifest, ¶ms.PodsCIDRBlocks[0])}
}
b.AddResource("install:cni", cniRsc, plan.DependOn("fetch:cni"))
log.Info("Got cni resource")
// Add resources to apply the cluster API's CRDs so that Kubernetes
// understands objects like Cluster, Machine, etc.
crdIDs, err := AddClusterAPICRDs(b, crds.CRDs)
if err != nil {
return nil, err
}
kubectlApplyDeps := append([]string{"kubeadm:init"}, crdIDs...)
// If we're pulling data out of GitHub, we install sealed secrets and any auth secrets stored in sealed secrets
configDeps := kubectlApplyDeps
if params.AuthInfo != nil {
configDeps, err = addSealedSecretResourcesIfNecessary(b, kubectlApplyDeps, params.AuthInfo.PEMSecretResources, sealedSecretVersion, params.SealedSecretKey, params.SealedSecretCert, params.Namespace)
if err != nil {
return nil, err
}
}
// Set plan as an annotation on node, just like controller does
seedNodePlan, err := seedNodeSetupPlan(ctx, o, params, &cluster.Spec, configMaps, kubernetesVersion)
if err != nil {
return nil, err
}
log.Info("Got seed node plan")
b.AddResource("node:plan", &resource.KubectlAnnotateSingleNode{Key: recipe.PlanKey, Value: seedNodePlan.ToState().ToJSON()}, plan.DependOn("kubeadm:init"))
if params.AuthInfo != nil {
addAuthConfigMapIfNecessary(configMapManifests, params.AuthInfo.AuthConfigManifest)
}
if params.AuthInfo != nil {
addAuthConfigMapIfNecessary(configMapManifests, params.AuthInfo.AuthConfigManifest)
}
// Add config maps to system so controller can use them
configMapPlan := recipe.BuildConfigMapPlan(configMapManifests, params.Namespace)
log.Info("Got config map plan")
b.AddResource("install:configmaps", configMapPlan, plan.DependOn(configDeps[0], configDeps[1:]...))
applyClstrRsc := &resource.KubectlApply{Manifest: []byte(params.ClusterManifest), Namespace: object.String(params.Namespace), Filename: object.String("clustermanifest")}
b.AddResource("kubectl:apply:cluster", applyClstrRsc, plan.DependOn("install:configmaps", kubectlApplyDeps...))
mManRsc := &resource.KubectlApply{Manifest: []byte(params.MachinesManifest), Filename: object.String("machinesmanifest"), Namespace: object.String(params.Namespace)}
b.AddResource("kubectl:apply:machines", mManRsc, plan.DependOn(kubectlApplyDeps[0], kubectlApplyDeps[1:]...))
dep := addSealedSecretWaitIfNecessary(b, params.SealedSecretKey, params.SealedSecretCert)
connManifest, err := createConnectionSecret(params.Namespace, params.ConnectionInfo)
if err != nil {
return nil, err
}
b.AddResource("install:connection:info",
&resource.KubectlApply{
Manifest: connManifest,
Filename: object.String("connectionmanifest")},
plan.DependOn(dep))
{
capiCtlrManifest, err := capiControllerManifest(params.Controller, params.Namespace)
if err != nil {
return nil, err
}
ctlrRsc := &resource.KubectlApply{Manifest: capiCtlrManifest, Filename: object.String("capi_controller.yaml")}
b.AddResource("install:capi", ctlrRsc, plan.DependOn("kubectl:apply:cluster", "install:connection:info"))
}
// Create a config map tracking cluster parameters and node creation
cmap, err := CreateClusterConfigMap(¶ms.ExistingInfraCluster, params.Namespace, params.PrivateIP)
if err != nil {
return nil, err
}
cmapManifest, err := yaml.Marshal(cmap)
if err != nil {
return nil, err
}
cmapRes := &resource.KubectlApply{Manifest: cmapManifest, Filename: object.String("clusterconfigmap")}
b.AddResource("kubectl:apply:cluster-config-map", cmapRes, plan.DependOn(dep))
wksCtlrManifest, err := WksControllerManifest(params.Controller.ImageOverride, params.Namespace)
if err != nil {
return nil, err
}
ctlrRsc := &resource.KubectlApply{Manifest: wksCtlrManifest, Filename: object.String("wks_controller.yaml")}
b.AddResource("install:wks", ctlrRsc, plan.DependOn("kubectl:apply:cluster", "kubectl:apply:cluster-config-map"))
if err := ConfigureFlux(b, params); err != nil {
return nil, errors.Wrap(err, "Failed to configure flux")
}
return CreatePlan(b)
}
func CreateClusterConfigMap(eic *existinginfrav1.ExistingInfraCluster, namespace, seedNodeIP string) (*v1.ConfigMap, error) {
configMap := &v1.ConfigMap{}
configMap.TypeMeta.APIVersion = "v1"
configMap.TypeMeta.Kind = "ConfigMap"
configMap.Name = eic.Name
configMap.Namespace = namespace
if configMap.Data == nil {
configMap.Data = map[string]string{}
}
specBytes, err := json.Marshal(eic.Spec)
if err != nil {
return nil, err
}
hash := sha256.Sum256(specBytes)
configMap.Data["spec"] = base64.StdEncoding.EncodeToString(hash[:])
machineList := []string{seedNodeIP}
machineListBytes, err := json.Marshal(machineList)
if err != nil {
return nil, err
}
configMap.Data["machines"] = string(machineListBytes)
return configMap, nil
}
func addSealedSecretWaitIfNecessary(b *plan.Builder, key, cert string) string {
if key != "" && cert != "" {
b.AddResource("wait:sealed-secrets-controller",
&resource.KubectlWait{WaitNamespace: "kube-system", WaitType: "pods", WaitSelector: "name=sealed-secrets-controller",
WaitCondition: "condition=Ready", WaitTimeout: "300s"},
plan.DependOn("kubectl:apply:machines"))
return "wait:sealed-secrets-controller"
}
return "kubectl:apply:machines"
}
func addSealedSecretResourcesIfNecessary(b *plan.Builder, kubectlApplyDeps []string, pemSecretResources map[string]*SecretResourceSpec, sealedSecretVersion, key, cert, ns string) ([]string, error) {
log.Info("sealedSecretResources...")
if key != "" && cert != "" {
keyManifest, err := createSealedSecretKeySecretManifest(key, cert)
if err != nil {
return nil, err
}
crdManifest := sealedSecretCRDManifest()
controllerManifest := sealedSecretControllerManifest()
sealedSecretRsc := recipe.BuildSealedSecretPlan([]byte(sealedSecretVersion), crdManifest,
keyManifest, controllerManifest)
b.AddResource("install:sealed-secrets", sealedSecretRsc, plan.DependOn(kubectlApplyDeps[0], kubectlApplyDeps[1:]...))
log.Info("sealedSecretResources -- created sealed secret plan...")
// Now that the cluster is up, if auth is configured, create a secret containing the data for use by the machine actuator
for _, resourceSpec := range pemSecretResources {
b.AddResource(fmt.Sprintf("install:pem-secret-%s", resourceSpec.SecretName), resourceSpec.Resource, plan.DependOn("install:sealed-secrets"))
}
log.Info("sealedSecretResources -- created pem resources...")
return []string{"install:sealed-secrets"}, nil
}
return kubectlApplyDeps, nil
}
func createSealedSecretKeySecretManifest(privateKey, cert string) ([]byte, error) {
secret := &v1.Secret{
TypeMeta: metav1.TypeMeta{Kind: "Secret", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{Name: sealedSecretKeySecretName, Namespace: "kube-system"},
Type: v1.SecretTypeOpaque,
}
secret.Data = map[string][]byte{}
secret.StringData = map[string]string{}
secret.StringData[v1.TLSPrivateKeyKey] = privateKey
secret.StringData[v1.TLSCertKey] = cert
return yaml.Marshal(secret)
}
func ApplyPlan(ctx context.Context, o *OS, p *plan.Plan) error {
err := p.Undo(ctx, o.Runner, plan.EmptyState)
if err != nil {
log.Infof("Pre-plan cleanup failed:\n%s\n", err)
return err
}
_, err = p.Apply(ctx, o.Runner, plan.EmptyDiff())
if err != nil {
log.Errorf("Apply of Plan failed:\n%s\n", err)
return err
}
return err
}
func addAuthConfigMapIfNecessary(configMapManifests map[string][]byte, authConfigManifest []byte) {
if authConfigManifest != nil {
configMapManifests["auth-config"] = authConfigManifest
}
}
func capiControllerManifest(controller ControllerParams, namespace string) ([]byte, error) {
return getManifest(capiControllerManifestString, namespace)
}
// func controllerRoleBinding(namespace string) ([]byte, error) {
// t, err := template.New("crb").Parse(wksControllerRoleBinding)
// if err != nil {
// return nil, err
// }
// var populated bytes.Buffer
// if err = t.Execute(&populated, struct {
// ControllerNamespace string
// }{
// namespace,
// }); err != nil {
// return nil, err
// }
// return populated.Bytes(), nil
// }
func WksControllerManifest(imageOverride, namespace string) ([]byte, error) {
content, err := getManifest(wksControllerManifestString, namespace)
if err != nil {
return nil, err
}
content, err = UpdateControllerImage(content, version.ImageTag)
if err != nil {
return nil, errors.Wrap(err, "failed to update controller image with build version")
}
return UpdateControllerImage(content, imageOverride)
}
func sealedSecretCRDManifest() []byte {
return sealedSecretCRDManifestString
}
func sealedSecretControllerManifest() []byte {
return sealedSecretControllerManifestString
}
func getManifest(manifestString, namespace string) ([]byte, error) {
return manifest.WithNamespace(serializer.FromBytes([]byte(manifestString)), namespace)
}
const deployment = "Deployment"
// updateControllerImage replaces the controller image in the manifest and
// returns the updated manifest
func UpdateControllerImage(manifest []byte, controllerImageOverride string) ([]byte, error) {
if controllerImageOverride == "" {
return manifest, nil
}
fullOverride := strings.Contains(controllerImageOverride, ":")
d := &v1beta2.Deployment{}
if err := yaml.Unmarshal(manifest, d); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal WKS controller's manifest")
}
if d.Kind != deployment {
return nil, fmt.Errorf("invalid kind for WKS controller's manifest: expected %q but got %q", deployment, d.Kind)
}
var updatedController bool
for i := 0; i < len(d.Spec.Template.Spec.Containers); i++ {
if d.Spec.Template.Spec.Containers[i].Name == "controller" {
currentImage := d.Spec.Template.Spec.Containers[i].Image
if !fullOverride {
controllerImageOverride = currentImage[0:strings.Index(currentImage, ":")+1] + controllerImageOverride
}
d.Spec.Template.Spec.Containers[i].Image = controllerImageOverride
env := d.Spec.Template.Spec.Containers[i].Env
found := false
for _, entry := range env {
if entry.Name == "EXISTINGINFRA_CONTROLLER_IMAGE" {
entry.Value = controllerImageOverride
found = true
}
}
if !found {
env = append(env, v1.EnvVar{Name: "EXISTINGINFRA_CONTROLLER_IMAGE", Value: controllerImageOverride})
}
d.Spec.Template.Spec.Containers[i].Env = env
updatedController = true
}
}
if !updatedController {
return nil, errors.New("failed to update WKS controller's manifest: container not found")
}
return yaml.Marshal(d)
}
func getKubernetesVersion(cluster *existinginfrav1.ExistingInfraCluster) string {
return cluster.Spec.KubernetesVersion
}
// Sets the pod CIDR block in the weave-net manifest
func SetWeaveNetPodCIDRBlock(manifests [][]byte, podsCIDRBlock string) ([][]byte, error) {
// Weave-Net has a container named weave in its daemonset
containerName := "weave"
// The pod CIDR block is set via the IPALLOC_RANGE env var
podCIDRBlock := &v1.EnvVar{
Name: "IPALLOC_RANGE",
Value: podsCIDRBlock,
}
manifestList := &v1.List{}
err := yaml.Unmarshal(manifests[0], manifestList)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal weave-net manifest")
}
// Find and parse the DaemonSet included in the manifest list into an object
idx, daemonSet, err := FindDaemonSet(manifestList)
if err != nil {
return nil, errors.New("failed to find daemonset in weave-net manifest")
}
err = InjectEnvVarToContainer(daemonSet.Spec.Template.Spec.Containers, containerName, *podCIDRBlock)
if err != nil {
return nil, errors.Wrap(err, "failed to inject env var to weave container")
}
manifestList.Items[idx] = runtime.RawExtension{Object: daemonSet}
manifests[0], err = yaml.Marshal(manifestList)
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal weave-net manifest list")
}
return manifests, nil
}
// Finds container in the list by name, adds an env var, fails if env var exists with different value
func InjectEnvVarToContainer(
containers []v1.Container, name string, newEnvVar v1.EnvVar) error {
var targetContainer v1.Container
containerFound := false
var idx int
var container v1.Container
for idx, container = range containers {
if container.Name == name {
targetContainer = container
containerFound = true
break
}
}
if !containerFound {
return errors.New(fmt.Sprintf("did not find container %s in manifest", name))
}
for _, envVar := range targetContainer.Env {
if envVar.Name == newEnvVar.Name {
if envVar.Value != newEnvVar.Value {
return errors.New(
fmt.Sprintf("manifest already contains env var %s, and cannot overwrite", newEnvVar.Name))
}
return nil
}
}
envVars := targetContainer.Env
envVars = append(envVars, newEnvVar) // to satisfy linter
targetContainer.Env = envVars
containers[idx] = targetContainer
return nil
}
// Returns a daemonset manifest from a list
func FindDaemonSet(manifest *v1.List) (int, *appsv1.DaemonSet, error) {
if manifest == nil {
return -1, nil, errors.New("manifest is nil")
}
daemonSet := &appsv1.DaemonSet{}
var err error
var idx int
var item runtime.RawExtension
for idx, item = range manifest.Items {
err := yaml.Unmarshal(item.Raw, daemonSet)
if err == nil && daemonSet.Kind == "DaemonSet" {
break
}
}
if err != nil {
return -1, nil, errors.Wrap(err, "failed to unmarshal manifest list")
}
if daemonSet.Kind != "DaemonSet" {
return -1, nil, errors.New("daemonset not found in manifest list")
}
return idx, daemonSet, nil
}
func CreateConfigFileResourcesFromConfigMaps(fileSpecs []existinginfrav1.FileSpec, configMaps map[string]*v1.ConfigMap) ([]*resource.File, error) {
log.Info("Getting resources from config maps")
fileResources := make([]*resource.File, len(fileSpecs))
for idx, file := range fileSpecs {
source := &file.Source
fileResource := &resource.File{Destination: file.Destination}
log.Info("Getting file contents")
fileContents, ok := configMaps[source.ConfigMap].Data[source.Key]
if ok {
log.Info("Got file contents")
fileResource.Content = fileContents
fileResources[idx] = fileResource
continue
}
log.Infof("Failed to get file contents")
// if not in Data, check BinaryData
binaryContents, ok := configMaps[source.ConfigMap].BinaryData[source.Key]
if !ok {
return nil, fmt.Errorf("No config data for filespec: %v", file)
}
fileResource.Content = string(binaryContents)
fileResources[idx] = fileResource
}
return fileResources, nil
}
func CreateConfigFileResourcesFromFileSpecs(fileSpecs []existinginfrav1.FileSpec) ([]*resource.File, error) {
fileResources := make([]*resource.File, len(fileSpecs))
for idx, file := range fileSpecs {
source := &file.Source
fileResource := &resource.File{Destination: file.Destination}
fileResource.Content = source.Contents
fileResources[idx] = fileResource
}
return fileResources, nil
}
// NodeParams groups required inputs to configure a Kubernetes node.
type NodeParams struct {
IsMaster bool // true if this node is a master, false else.
MasterIP string
MasterPort int
Token string // kubeadm's --token
DiscoveryTokenCaCertHash string // kubeadm's --discovery-token-ca-cert-hash
CertificateKey string // kubeadm's --certificate-key
KubeletConfig config.KubeletConfig
KubernetesVersion string
CRI existinginfrav1.ContainerRuntime
ConfigFileSpecs []existinginfrav1.FileSpec
ProviderConfigMaps map[string]*v1.ConfigMap
AuthConfigMap *v1.ConfigMap
Secrets map[string]resource.SecretData // kind of auth -> names/values as-in v1.Secret
Namespace string
ControlPlaneEndpoint string // used instead of MasterIP if existed
AddonNamespaces map[string]string
}
// Validate generally validates this NodeParams struct, e.g. ensures it
// contains mandatory values, that these are well-formed, etc.
func (params NodeParams) Validate() error {
if len(params.KubeletConfig.NodeIP) == 0 {
return errors.New("empty kubelet node IP")
}
return nil
}
// SetupNode installs Kubernetes on this machine and configures it based on the
// manifests stored during the initialization of the cluster, when
// SetupSeedNode was called.
func (o OS) SetupNode(ctx context.Context, p *plan.Plan) error {
// We don't know the state of the machine so undo at the beginning
//nolint:errcheck
p.Undo(ctx, o.Runner, plan.EmptyState) // TODO: Implement error checking
_, err := p.Apply(ctx, o.Runner, plan.EmptyDiff())
if err != nil {
log.Errorf("Apply of Plan failed:\n%s\n", err)
}
return err
}
// CreateNodeSetupPlan creates the plan that will be used to set up a node.
func (o OS) CreateNodeSetupPlan(ctx context.Context, params NodeParams) (*plan.Plan, error) {
log.Info("Creating node setup plan")
if err := params.Validate(); err != nil {
return nil, err
}
log.Info("Validated parameters")
cfg, err := envcfg.GetEnvSpecificConfig(ctx, o.PkgType, params.Namespace, params.KubeletConfig.CloudProvider, o.Runner)
if err != nil {
return nil, err
}
log.Info("Got env config")
configFileResources, err := CreateConfigFileResourcesFromConfigMaps(params.ConfigFileSpecs, params.ProviderConfigMaps)
if err != nil {
return nil, err
}
log.Info("Created config file resources")
b := plan.NewBuilder()
baseRsrc := recipe.BuildBasePlan(o.PkgType)
b.AddResource("install:base", baseRsrc)
authConfigMap := params.AuthConfigMap
if authConfigMap != nil && params.IsMaster {
for _, authType := range []string{"authentication", "authorization"} {
if err := addAuthConfigResources(b, authConfigMap, params.Secrets[authType], authType); err != nil {
return nil, err
}
}
}
log.Info("Built base plan")
configRes := recipe.BuildConfigPlan(configFileResources)
b.AddResource("install:config", configRes, plan.DependOn("install:base"))
log.Info("Built config plan")
instCriRsrc := recipe.BuildCRIPlan(ctx, ¶ms.CRI, cfg, o.PkgType)
b.AddResource("install.cri", instCriRsrc, plan.DependOn("install:config"))
log.Info("Built cri plan")
instK8sRsrc := recipe.BuildK8SPlan(params.KubernetesVersion, params.KubeletConfig.NodeIP, cfg.SELinuxInstalled, cfg.SetSELinuxPermissive, cfg.DisableSwap, cfg.LockYUMPkgs, o.PkgType, params.KubeletConfig.CloudProvider, params.KubeletConfig.ExtraArguments)
log.Info("Built k8s plan")
b.AddResource("install:k8s", instK8sRsrc, plan.DependOn("install.cri"))
kadmPJRsrc := recipe.BuildKubeadmPrejoinPlan(params.KubernetesVersion, cfg.UseIPTables)
b.AddResource("kubeadm:prejoin", kadmPJRsrc, plan.DependOn("install:k8s"))
log.Info("Built join plan")
kadmJoinRsrc := &resource.KubeadmJoin{
IsMaster: params.IsMaster,
NodeIP: params.KubeletConfig.NodeIP,
NodeName: cfg.HostnameOverride,
MasterIP: params.MasterIP,
MasterPort: params.MasterPort,
Token: params.Token,
DiscoveryTokenCaCertHash: params.DiscoveryTokenCaCertHash,
CertificateKey: params.CertificateKey,
IgnorePreflightErrors: cfg.IgnorePreflightErrors,
KubernetesVersion: params.KubernetesVersion,
}
b.AddResource("kubeadm:join", kadmJoinRsrc, plan.DependOn("kubeadm:prejoin"))
return CreatePlan(b)
}
func addAuthConfigResources(b *plan.Builder, authConfigMap *v1.ConfigMap, secretData resource.SecretData, authType string) error {
secretName := authConfigMap.Data[authType+"-secret-name"]
if secretName != "" {
authPemRsrc, err := resource.NewKubeSecretResource(secretName, secretData, filepath.Join(PemDestDir, secretName),
func(s string) string {
return s + ".pem"
})
if err != nil {
return err
}
b.AddResource("install:"+authType+"-pem-files", authPemRsrc, plan.DependOn("install:base"))
b.AddResource("install:"+authType+"-config", &resource.File{Content: authConfigMap.Data[authType+"-config"], Destination: filepath.Join(ConfigDestDir, secretName+".yaml")})
}
return nil
}
func addAuthArgs(apiServerArgs map[string]string, pemSecretResources map[string]*SecretResourceSpec, providerSpec *existinginfrav1.ClusterSpec) {
authnResourceSpec := pemSecretResources["authentication"]
if authnResourceSpec != nil {
StoreIfNotEmpty(apiServerArgs, "authentication-token-webhook-config-file", filepath.Join(ConfigDestDir, authnResourceSpec.SecretName+".yaml"))
StoreIfNotEmpty(apiServerArgs, "authentication-token-webhook-cache-ttl", providerSpec.Authentication.CacheTTL)
}
authzResourceSpec := pemSecretResources["authorization"]
if authzResourceSpec != nil {
apiServerArgs["authorization-mode"] = "Webhook"
StoreIfNotEmpty(apiServerArgs, "authorization-webhook-config-file", filepath.Join(ConfigDestDir, authzResourceSpec.SecretName+".yaml"))
StoreIfNotEmpty(apiServerArgs, "authorization-webhook-cache-unauthorized-ttl", providerSpec.Authorization.CacheUnauthorizedTTL)
StoreIfNotEmpty(apiServerArgs, "authorization-webhook-cache-authorized-ttl", providerSpec.Authorization.CacheAuthorizedTTL)
}
}
const (
CentOS = "centos"
Ubuntu = "ubuntu"
RHEL = "rhel"
)
// Identify uses the provided SSH client to identify the operating system of
// the machine it is configured to talk to.
func Identify(ctx context.Context, sshClient plan.Runner) (*OS, error) {
osID, err := fetchOSID(ctx, sshClient)
if err != nil {
return nil, err
}
switch osID {
case CentOS:
return &OS{Name: osID, Runner: &sudo.Runner{Runner: sshClient}, PkgType: resource.PkgTypeRPM}, nil
case RHEL:
return &OS{Name: osID, Runner: &sudo.Runner{Runner: sshClient}, PkgType: resource.PkgTypeRHEL}, nil
case Ubuntu:
return &OS{Name: osID, Runner: &sudo.Runner{Runner: sshClient}, PkgType: resource.PkgTypeDeb}, nil
default:
return nil, fmt.Errorf("unknown operating system %q", osID)
}
}
var osIDRegexp = regexp.MustCompile("(?m)^ID=(.+)")
const (
numExpectedMatches = 2
idxOSID = 1
)
func fetchOSID(ctx context.Context, sshClient plan.Runner) (string, error) {
stdOut, err := sshClient.RunCommand(ctx, "cat /etc/*release", nil)
if err != nil {
return "", errors.Wrap(err, "failed to fetch operating system ID")
}
matches := osIDRegexp.FindStringSubmatch(stdOut)
if len(matches) != numExpectedMatches {
return "", errors.New("failed to identify operating system")
}
return strings.Trim(matches[idxOSID], ` "`), nil
}
// CreatePlan generates a plan from a plan builder
func CreatePlan(b *plan.Builder) (*plan.Plan, error) {
p, err := b.Plan()
if err != nil {
log.Infof("Plan creation failed:\n%s\n", err)
return nil, err
}
return &p, nil
}
type SecretResourceSpec struct {
SecretName string
Decrypted resource.SecretData
Resource plan.Resource
}
func StoreIfNotEmpty(vals map[string]string, key, value string) {
if value != "" {
vals[key] = value
}
}
func GetAPIServerArgs(providerSpec *existinginfrav1.ClusterSpec) map[string]string {
result := map[string]string{}
// Also add any explicit api server arguments from the generic section
for _, arg := range providerSpec.APIServer.ExtraArguments {
result[arg.Name] = arg.Value
}
return result
}
func AddClusterAPICRDs(b *plan.Builder, fs http.FileSystem) ([]string, error) {
crds, err := GetCRDs(fs)
if err != nil {
return nil, errors.Wrap(err, "failed to list cluster API CRDs")
}
crdIDs := make([]string, 0)
for _, crdFile := range crds {
id := fmt.Sprintf("kubectl:apply:%s", crdFile.Fname)
crdIDs = append(crdIDs, id)
rsrc := &resource.KubectlApply{Filename: object.String(crdFile.Fname), Manifest: crdFile.Data, WaitCondition: "condition=Established"}
b.AddResource(id, rsrc, plan.DependOn("install:cni"))
}
return crdIDs, nil
}
func seedNodeSetupPlan(ctx context.Context, o *OS, params SeedNodeParams, providerSpec *existinginfrav1.ClusterSpec, providerConfigMaps map[string]*v1.ConfigMap, kubernetesVersion string) (*plan.Plan, error) {
nodeParams := NodeParams{
IsMaster: true,
MasterIP: params.PrivateIP,
MasterPort: 6443, // See TODO in machine_actuator.go
KubeletConfig: params.KubeletConfig,
KubernetesVersion: kubernetesVersion,
CRI: providerSpec.CRI,
ConfigFileSpecs: providerSpec.OS.Files,
ProviderConfigMaps: providerConfigMaps,
Namespace: params.Namespace,
ControlPlaneEndpoint: providerSpec.ControlPlaneEndpoint,
}
if params.AuthInfo != nil {
nodeParams.AuthConfigMap = params.AuthInfo.AuthConfigMap
secrets := map[string]resource.SecretData{}
for k, v := range params.AuthInfo.PEMSecretResources {
secrets[k] = v.Decrypted
}
}
return o.CreateNodeSetupPlan(ctx, nodeParams)
}
// processDeployKey adds the encoded deploy key to the set of parameters used to configure flux
func processDeployKey(params map[string]string, gitDeployKeyPath string) error {
if gitDeployKeyPath == "" {
return nil
}
b64Key, err := readAndBase64EncodeKey(gitDeployKeyPath)