-
Notifications
You must be signed in to change notification settings - Fork 5
/
capi.go
1298 lines (1118 loc) · 36 KB
/
capi.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 capi
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
osruntime "runtime"
"strings"
"time"
"context"
"encoding/base64"
"encoding/json"
"github.com/aws/aws-sdk-go/aws/session"
cfn "github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/christianh814/gokp/cmd/kind"
"github.com/christianh814/gokp/cmd/utils"
"github.com/rwtodd/Go.Sed/sed"
log "github.com/sirupsen/logrus"
"sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/cloudformation/bootstrap"
cloudformation "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/cloudformation/service"
creds "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/credentials"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
capiclient "sigs.k8s.io/cluster-api/cmd/clusterctl/client"
kcpv1 "sigs.k8s.io/cluster-api/controlplane/kubeadm/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/yaml"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
"k8s.io/client-go/discovery/cached/memory"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
corev1 "k8s.io/api/core/v1"
coreV1Types "k8s.io/client-go/kubernetes/typed/core/v1"
infrav1 "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1"
)
var CNIurl string = "https://docs.projectcalico.org/v3.20/manifests/calico.yaml"
var azureCNIurl string = "https://raw.githubusercontent.com/kubernetes-sigs/cluster-api-provider-azure/main/templates/addons/calico.yaml"
var decUnstructured = yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
var KubernetesVersion string = "v1.23.3"
func CreateAzureK8sInstance(kindkconfig string, clusterName *string, workdir string, azureCredsMap map[string]string, capicfg string, createHaCluster bool) (bool, error) {
log.Info("Started creating Azure cluster")
log.Info(kindkconfig)
var secretsClient coreV1Types.SecretInterface
// Set up variables
var cpMachineCount int64
var workerMachineCount int64
log.Info("Setting up credentials.")
for k := range azureCredsMap {
os.Setenv(k, azureCredsMap[k])
}
os.Setenv("AZURE_CLUSTER_IDENTITY_SECRET_NAME", "cluster-identity-secret")
os.Setenv("AZURE_CLUSTER_IDENTITY_SECRET_NAMESPACE", "default")
os.Setenv("CLUSTER_IDENTITY_NAME", "cluster-identity")
clusterInstallConfig, err := clientcmd.BuildConfigFromFlags("", kindkconfig)
if err != nil {
return false, err
}
clientset, err := kubernetes.NewForConfig(clusterInstallConfig)
if err != nil {
return false, err
}
secretsClient = clientset.CoreV1().Secrets("default")
spClientSecret := os.Getenv("AZURE_CLIENT_SECRET")
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "cluster-identity-secret",
Namespace: "default",
},
Type: corev1.SecretTypeOpaque,
Data: map[string][]byte{"clientSecret": []byte(spClientSecret)},
}
_, err = secretsClient.Create(context.TODO(), secret, metav1.CreateOptions{})
if err != nil {
return false, err
}
log.Info("Created service principal secret")
// init Azure provider into the Kind instance
log.Info("Initializing Azure provider")
c, err := capiclient.New("")
if err != nil {
return false, err
}
_, err = c.Init(capiclient.InitOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
InfrastructureProviders: []string{"azure"},
LogUsageInstructions: false,
})
if err != nil {
return false, err
}
// Check to see if it's rolled out, if not then wait 20 seconds and check again. Stop after 15x
counter := 0
for runs := 15; counter <= runs; counter++ {
capaClient := clientset.AppsV1().Deployments("capz-system")
if counter > runs {
return false, errors.New("CAPI Controller took too long to roll out")
}
capaDeployment, err := capaClient.Get(context.TODO(), "capz-controller-manager", metav1.GetOptions{})
if err != nil {
return false, err
}
availableReplicas := capaDeployment.Status.AvailableReplicas
if availableReplicas > int32(0) {
time.Sleep(20 * time.Second)
break
}
time.Sleep(20 * time.Second)
}
log.Info("Creating azureidentity")
dynamic := dynamic.NewForConfigOrDie(clusterInstallConfig)
identity := &infrav1.AzureClusterIdentity{
TypeMeta: metav1.TypeMeta{
Kind: "AzureClusterIdentity",
APIVersion: "infrastructure.cluster.x-k8s.io/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "cluster-identity",
},
Spec: infrav1.AzureClusterIdentitySpec{
Type: infrav1.ServicePrincipal,
ClientID: os.Getenv("AZURE_CLIENT_ID"),
ClientSecret: corev1.SecretReference{Name: "cluster-identity-secret"},
TenantID: os.Getenv("AZURE_TENANT_ID"),
AllowedNamespaces: &infrav1.AllowedNamespaces{
NamespaceList: []string{"default"},
},
},
}
resourceId := schema.GroupVersionResource{
Group: "infrastructure.cluster.x-k8s.io",
Version: "v1beta1",
Resource: "azureclusteridentities",
}
//identity_json, err := json.Marshal(identity)
if err != nil {
return false, err
}
identity_temp, err := runtime.DefaultUnstructuredConverter.ToUnstructured(identity)
if err != nil {
return false, err
}
identity_uns := &unstructured.Unstructured{
Object: identity_temp,
}
_, err = dynamic.Resource(resourceId).Namespace("default").Create(context.TODO(), identity_uns, metav1.CreateOptions{})
if err != nil {
return false, err
}
log.Info("Created azureidentity")
// Generate cluster YAML for CAPI on KIND and apply it
newClient, err := capiclient.New("")
if err != nil {
return false, err
}
// Set up options to write out the install YAML
// TODO: Make Kubernetes version an option
if createHaCluster {
// If HA was requested we create it
cpMachineCount = 3
workerMachineCount = 3
//
} else {
// If HA was NOT requested we create a small cluster
cpMachineCount = 1
workerMachineCount = 2
}
cto := capiclient.GetClusterTemplateOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
ClusterName: *clusterName,
ControlPlaneMachineCount: &cpMachineCount,
WorkerMachineCount: &workerMachineCount,
KubernetesVersion: KubernetesVersion,
TargetNamespace: "default",
}
// Load up the config with the options
installYaml, err := newClient.GetClusterTemplate(cto)
if err != nil {
return false, err
}
// Write the install file out
installClusterYaml := workdir + "/" + "install-cluster.yaml"
err = utils.WriteYamlOutput(installYaml, installClusterYaml)
if err != nil {
return false, err
}
// Apply the YAML to the KIND instance so that the cluster gets installed on AWS
log.Info("Preflight complete, installing cluster")
err = utils.SplitYamls(workdir+"/"+"capi-install-yamls-output", installClusterYaml, "---")
if err != nil {
return false, err
}
// get a list of those files
yamlFiles, err := filepath.Glob(workdir + "/" + "capi-install-yamls-output" + "/" + "*.yaml")
if err != nil {
return false, err
}
for _, yamlFile := range yamlFiles {
err = DoSSA(context.TODO(), clusterInstallConfig, yamlFile)
if err != nil {
log.Warn("Unable to read YAML: ", err)
//return false, err
}
}
// use clientcmd to apply the configuration
log.Info("Submitted cluster config")
// First, wait for the infra to appear
_, err = waitForAWSInfra(clusterInstallConfig, *clusterName)
if err != nil {
return false, err
}
// Then, wait for the CP to appear
_, err = waitForCP(clusterInstallConfig, *clusterName, createHaCluster)
if err != nil {
return false, err
}
log.Info("Control Plane Nodes are Online, saving Kubeconfig")
// Write out CAPI kubeconfig and save it
clusterKubeconfig, err := c.GetKubeconfig(capiclient.GetKubeconfigOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
WorkloadClusterName: *clusterName,
})
if err != nil {
return false, err
}
clusterkcfg, err := os.Create(capicfg)
if err != nil {
return false, err
}
clusterkcfg.WriteString(clusterKubeconfig)
clusterkcfg.Close()
//Apply the CNI solution. For now we use Calico
// TODO: This should be something that is an end user can choose
// Set up the Capi CFG connection
capiInstallConfig, err := clientcmd.BuildConfigFromFlags("", capicfg)
if err != nil {
return false, err
}
// Download the CNI YAML
cniYaml := workdir + "/" + "cni.yaml"
_, err = utils.DownloadFile(cniYaml, azureCNIurl)
if err != nil {
return false, err
}
// Split the CNI yaml into individual files
err = utils.SplitYamls(workdir+"/"+"cni-output", cniYaml, "---")
if err != nil {
return false, err
}
// get a list of those files
cniyamlFiles, err := filepath.Glob(workdir + "/" + "cni-output" + "/" + "*.yaml")
if err != nil {
return false, err
}
for _, cniyamlFile := range cniyamlFiles {
err = DoSSA(context.TODO(), capiInstallConfig, cniyamlFile)
if err != nil {
if !strings.Contains(err.Error(), "is missing in") {
return false, err
}
//log.Warn("Unable to read YAML: ", err)
}
}
// Wait until Nodes are READY
log.Info("Waiting for worker nodes to come online")
// HACK: We sleep to give time for the CNI to rollout
// TODO: Wait until CNI Deployment is done
time.Sleep(time.Minute)
_, err = waitForReadyNodes(capiInstallConfig)
if err != nil {
return false, err
}
// Unexport Azure settings
for k := range azureCredsMap {
os.Unsetenv(k)
}
os.Unsetenv("AZURE_CLUSTER_IDENTITY_SECRET_NAME")
os.Unsetenv("AZURE_CLUSTER_IDENTITY_SECRET_NAMESPACE")
os.Unsetenv("CLUSTER_IDENTITY_NAME")
os.Unsetenv("AZURE_CLIENT_SECRET")
// If we're here, that means everything turned out okay
log.Info("Successfully created Azure Kubernetes Cluster")
return true, nil
}
// CreateAwsK8sInstance creates a Kubernetes cluster on AWS using CAPI and CAPI-AWS
func CreateAwsK8sInstance(kindkconfig string, clusterName *string, workdir string, awscreds map[string]string, capicfg string, createHaCluster bool, skipCloudFormation bool) (bool, error) {
// Export AWS settings as Env vars
for k := range awscreds {
os.Setenv(k, awscreds[k])
}
// Set up variables
var cpMachineCount int64
var workerMachineCount int64
// Boostrapping Cloud Formation stack on AWS only if needed
if !skipCloudFormation {
log.Info("Boostrapping Cloud Formation stack on AWS")
template := bootstrap.NewTemplate()
sess, err := session.NewSession()
if err != nil {
return false, err
}
cfnSvc := cloudformation.NewService(cfn.New(sess))
// tag things based on the clustername
tags := map[string]string{
"gokp-cluster": *clusterName,
}
err = cfnSvc.ReconcileBootstrapStack(template.Spec.StackName, *template.RenderCloudFormation(), tags)
if err != nil {
return false, err
}
} else {
log.Info("Skipping CloudFormation Creation")
}
//Encode credentials
awsCreds, err := creds.NewAWSCredentialFromDefaultChain(awscreds["AWS_REGION"])
if err != nil {
return false, err
}
b64creds, err := awsCreds.RenderBase64EncodedAWSDefaultProfile()
os.Setenv("AWS_B64ENCODED_CREDENTIALS", b64creds)
if err != nil {
return false, err
}
// init AWS provider into the Kind instance
log.Info("Initializing AWS provider")
c, err := capiclient.New("")
if err != nil {
return false, err
}
_, err = c.Init(capiclient.InitOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
InfrastructureProviders: []string{"aws"},
LogUsageInstructions: false,
})
if err != nil {
return false, err
}
// Generate cluster YAML for CAPI on KIND and apply it
newClient, err := capiclient.New("")
if err != nil {
return false, err
}
// Set up options to write out the install YAML
// TODO: Make Kubernetes version an option
if createHaCluster {
// If HA was requested we create it
cpMachineCount = 3
workerMachineCount = 3
//
} else {
// If HA was NOT requested we create a small cluster
cpMachineCount = 1
workerMachineCount = 2
}
cto := capiclient.GetClusterTemplateOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
ClusterName: *clusterName,
ControlPlaneMachineCount: &cpMachineCount,
WorkerMachineCount: &workerMachineCount,
KubernetesVersion: KubernetesVersion,
TargetNamespace: "default",
}
// Load up the config with the options
installYaml, err := newClient.GetClusterTemplate(cto)
if err != nil {
return false, err
}
// Write the install file out
installClusterYaml := workdir + "/" + "install-cluster.yaml"
err = utils.WriteYamlOutput(installYaml, installClusterYaml)
if err != nil {
return false, err
}
// Apply the YAML to the KIND instance so that the cluster gets installed on AWS
log.Info("Preflight complete, installing cluster")
// use clientcmd to apply the configuration
clusterInstallConfig, err := clientcmd.BuildConfigFromFlags("", kindkconfig)
if err != nil {
return false, err
}
// Wait for the deployment to rollout
// We want to wait for "capa-controller-manager" deployment in the "capa-system" ns to
// rollout before we proceed.
// TODO: We probably want a generic "watch/rollout" function for things
// Create clientset to check the status
clientset, err := kubernetes.NewForConfig(clusterInstallConfig)
if err != nil {
return false, err
}
// Check to see if it's rolled out, if not then wait 5 seconds and check again. Stop after 10x
counter := 0
for runs := 10; counter <= runs; counter++ {
capaClient := clientset.AppsV1().Deployments("capa-system")
if counter > runs {
return false, errors.New("CAPI Controller took too long to roll out")
}
capaDeployment, err := capaClient.Get(context.TODO(), "capa-controller-manager", metav1.GetOptions{})
if err != nil {
return false, err
}
availableReplicas := capaDeployment.Status.AvailableReplicas
if availableReplicas > int32(0) {
time.Sleep(5 * time.Second)
break
}
time.Sleep(5 * time.Second)
}
// Apply the config now that the capa controller is rolled out
// Split the one yaml CAPI gives you into individual files
err = utils.SplitYamls(workdir+"/"+"capi-install-yamls-output", installClusterYaml, "---")
if err != nil {
return false, err
}
// get a list of those files
yamlFiles, err := filepath.Glob(workdir + "/" + "capi-install-yamls-output" + "/" + "*.yaml")
if err != nil {
return false, err
}
for _, yamlFile := range yamlFiles {
err = DoSSA(context.TODO(), clusterInstallConfig, yamlFile)
if err != nil {
log.Warn("Unable to read YAML: ", err)
//return false, err
}
}
// Wait for the controlplane to have 3 nodes and that they are initialized
// First, wait for the infra to appear
_, err = waitForAWSInfra(clusterInstallConfig, *clusterName)
if err != nil {
return false, err
}
// Then, wait for the CP to appear
_, err = waitForCP(clusterInstallConfig, *clusterName, createHaCluster)
if err != nil {
return false, err
}
log.Info("Control Plane Nodes are Online, saving Kubeconfig")
// Write out CAPI kubeconfig and save it
clusterKubeconfig, err := c.GetKubeconfig(capiclient.GetKubeconfigOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
WorkloadClusterName: *clusterName,
})
if err != nil {
return false, err
}
clusterkcfg, err := os.Create(capicfg)
if err != nil {
return false, err
}
clusterkcfg.WriteString(clusterKubeconfig)
clusterkcfg.Close()
//Apply the CNI solution. For now we use Calico
// TODO: This should be something that is an end user can choose
// Set up the Capi CFG connection
capiInstallConfig, err := clientcmd.BuildConfigFromFlags("", capicfg)
if err != nil {
return false, err
}
// Download the CNI YAML
cniYaml := workdir + "/" + "cni.yaml"
_, err = utils.DownloadFile(cniYaml, CNIurl)
if err != nil {
return false, err
}
// Split the CNI yaml into individual files
err = utils.SplitYamls(workdir+"/"+"cni-output", cniYaml, "---")
if err != nil {
return false, err
}
// get a list of those files
cniyamlFiles, err := filepath.Glob(workdir + "/" + "cni-output" + "/" + "*.yaml")
if err != nil {
return false, err
}
for _, cniyamlFile := range cniyamlFiles {
err = DoSSA(context.TODO(), capiInstallConfig, cniyamlFile)
if err != nil {
if !strings.Contains(err.Error(), "is missing in") {
return false, err
}
//log.Warn("Unable to read YAML: ", err)
}
}
// Wait until Nodes are READY
log.Info("Waiting for worker nodes to come online")
// HACK: We sleep to give time for the CNI to rollout
// TODO: Wait until CNI Deployment is done
time.Sleep(time.Minute)
_, err = waitForReadyNodes(capiInstallConfig)
if err != nil {
return false, err
}
// Unexport AWS settings
for k := range awscreds {
os.Unsetenv(k)
}
// If we're here, that means everything turned out okay
log.Info("Successfully created Azure Kubernetes Cluster")
return true, nil
}
// CreateDevelK8sInstance creates a K8S cluster on Docker
func CreateDevelK8sInstance(kindkconfig string, clusterName *string, workdir string, capicfg string, createHaCluster bool) (bool, error) {
log.Info("Initializing Docker provider")
var cpMachineCount int64
var workerMachineCount int64
c, err := capiclient.New("")
if err != nil {
return false, err
}
_, err = c.Init(capiclient.InitOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
InfrastructureProviders: []string{"docker"},
LogUsageInstructions: false,
})
if err != nil {
return false, err
}
// Generate cluster YAML for CAPI on KIND and apply it
newClient, err := capiclient.New("")
if err != nil {
return false, err
}
// Set up options to write out the install YAML
// TODO: Make Kubernetes version an option
if createHaCluster {
// If HA was requested we create it
cpMachineCount = 3
workerMachineCount = 3
//
} else {
// If HA was NOT requested we create a small cluster
cpMachineCount = 1
workerMachineCount = 2
}
cto := capiclient.GetClusterTemplateOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
ClusterName: *clusterName,
ControlPlaneMachineCount: &cpMachineCount,
WorkerMachineCount: &workerMachineCount,
KubernetesVersion: KubernetesVersion,
TargetNamespace: "default",
ProviderRepositorySource: &capiclient.ProviderRepositorySourceOptions{Flavor: "development"},
}
// Load up the config with the options
installYaml, err := newClient.GetClusterTemplate(cto)
if err != nil {
return false, err
}
// Write the install file out
installClusterYaml := workdir + "/" + "install-cluster.yaml"
err = utils.WriteYamlOutput(installYaml, installClusterYaml)
if err != nil {
return false, err
}
// Apply the YAML to the KIND instance so that the cluster gets installed on AWS
log.Info("Preflight complete, installing cluster")
// use clientcmd to apply the configuration
clusterInstallConfig, err := clientcmd.BuildConfigFromFlags("", kindkconfig)
if err != nil {
return false, err
}
// Wait for the deployment to rollout
// We want to wait for "capa-controller-manager" deployment in the "capa-system" ns to
// rollout before we proceed.
// TODO: We probably want a generic "watch/rollout" function for things
// Create clientset to check the status
clientset, err := kubernetes.NewForConfig(clusterInstallConfig)
if err != nil {
return false, err
}
// Check to see if it's rolled out, if not then wait 5 seconds and check again. Stop after 10x
counter := 0
for runs := 10; counter <= runs; counter++ {
capaClient := clientset.AppsV1().Deployments("capd-system")
if counter > runs {
return false, errors.New("CAPI Controller took too long to roll out")
}
capdDeployment, err := capaClient.Get(context.TODO(), "capd-controller-manager", metav1.GetOptions{})
if err != nil {
return false, err
}
availableReplicas := capdDeployment.Status.AvailableReplicas
if availableReplicas > int32(0) {
time.Sleep(5 * time.Second)
break
}
time.Sleep(5 * time.Second)
}
// Apply the config now that the capa controller is rolled out
// Split the one yaml CAPI gives you into individual files
err = utils.SplitYamls(workdir+"/"+"capi-install-yamls-output", installClusterYaml, "---")
if err != nil {
return false, err
}
// get a list of those files
yamlFiles, err := filepath.Glob(workdir + "/" + "capi-install-yamls-output" + "/" + "*.yaml")
if err != nil {
return false, err
}
for _, yamlFile := range yamlFiles {
err = DoSSA(context.TODO(), clusterInstallConfig, yamlFile)
if err != nil {
log.Warn("Unable to read YAML: ", err)
//return false, err
}
}
// Wait for the controlplane to have 3 nodes and that they are initialized
// First, wait for the infra to appear. This function is badly named
// but it should still work even for capd
_, err = waitForAWSInfra(clusterInstallConfig, *clusterName)
if err != nil {
return false, err
}
// Then, wait for the CP to appear
_, err = waitForCP(clusterInstallConfig, *clusterName, createHaCluster)
if err != nil {
return false, err
}
log.Info("Control Plane Nodes are Online, saving Kubeconfig")
// Write out CAPI kubeconfig and save it
var clusterKubeconfig string
if osruntime.GOOS == "darwin" {
// HACK: If we are on a mac we have to modify the file first
dirtyKK, err := kind.GetKindKubeconfig(*clusterName, false)
if err != nil {
return false, err
}
// Let's try this sed thing
engine, err := sed.New(strings.NewReader(`s/0.0.0.0/127.0.0.1/g s/certificate-authority-data:.*/insecure-skip-tls-verify: true/g`))
if err != nil {
return false, err
}
// set clusterKubeconfig
clusterKubeconfig, err = engine.RunString(dirtyKK)
if err != nil {
return false, err
}
} else {
// If we are on Linux we'll get it the "regular" way
clusterKubeconfig, err = c.GetKubeconfig(capiclient.GetKubeconfigOptions{
Kubeconfig: capiclient.Kubeconfig{Path: kindkconfig},
WorkloadClusterName: *clusterName,
})
if err != nil {
return false, err
}
}
clusterkcfg, err := os.Create(capicfg)
if err != nil {
return false, err
}
clusterkcfg.WriteString(clusterKubeconfig)
clusterkcfg.Close()
//Apply the CNI solution. For now we use Calico
// TODO: This should be something that is an end user can choose
// Set up the Capi CFG connection
capiInstallConfig, err := clientcmd.BuildConfigFromFlags("", capicfg)
if err != nil {
return false, err
}
// Download the CNI YAML
cniYaml := workdir + "/" + "cni.yaml"
_, err = utils.DownloadFile(cniYaml, CNIurl)
if err != nil {
return false, err
}
// Split the CNI yaml into individual files
err = utils.SplitYamls(workdir+"/"+"cni-output", cniYaml, "---")
if err != nil {
return false, err
}
// get a list of those files
cniyamlFiles, err := filepath.Glob(workdir + "/" + "cni-output" + "/" + "*.yaml")
if err != nil {
return false, err
}
for _, cniyamlFile := range cniyamlFiles {
err = DoSSA(context.TODO(), capiInstallConfig, cniyamlFile)
if err != nil {
if !strings.Contains(err.Error(), "is missing in") {
return false, err
}
//log.Warn("Unable to read YAML: ", err)
}
}
// Wait until Nodes are READY
log.Info("Waiting for worker nodes to come online")
// HACK: We sleep to give time for the CNI to rollout
// TODO: Wait until CNI Deployment is done
time.Sleep(time.Minute)
_, err = waitForReadyNodes(capiInstallConfig)
if err != nil {
return false, err
}
// if we're here we must be okay
return true, nil
}
// DoSSA does service side apply with the given YAML
func DoSSA(ctx context.Context, cfg *rest.Config, yaml string) error {
// Read yaml into a slice of byte
yml, err := ioutil.ReadFile(yaml)
if err != nil {
log.Fatal(err)
}
// get the RESTMapper for the GVR
dc, err := discovery.NewDiscoveryClientForConfig(cfg)
if err != nil {
return err
}
mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(dc))
// create dymanic client
dyn, err := dynamic.NewForConfig(cfg)
if err != nil {
return err
}
// read YAML manifest into unstructured.Unstructured
obj := &unstructured.Unstructured{}
_, gvk, err := decUnstructured.Decode(yml, nil, obj)
if err != nil {
return err
}
// Get the GVR
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return err
}
// Get the REST interface for the GVR
var dr dynamic.ResourceInterface
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
// namespaced resources should specify the namespace
dr = dyn.Resource(mapping.Resource).Namespace(obj.GetNamespace())
} else {
// for cluster-wide resources
dr = dyn.Resource(mapping.Resource)
}
// Create object into JSON
data, err := json.Marshal(obj)
if err != nil {
return err
}
// Create or Update the obj with service side apply
// types.ApplyPatchType indicates service side apply
// FieldManager specifies the field owner ID.
_, err = dr.Patch(ctx, obj.GetName(), types.ApplyPatchType, data, metav1.PatchOptions{
FieldManager: "gokp-bootstrapper",
})
return err
}
// waitForAWSInfra waits until the infrastructure is provisioned
// TODO: probably should use https://pkg.go.dev/k8s.io/client-go/tools/watch
func waitForAWSInfra(restConfig *rest.Config, clustername string) (bool, error) {
// We need to load the scheme since it's not part of the core API
log.Info("Waiting for Infrastructure")
scheme := runtime.NewScheme()
err := clusterv1.AddToScheme(scheme)
if err != nil {
return false, err
}
c, err := client.New(restConfig, client.Options{
Scheme: scheme,
})
if err != nil {
return false, err
}
// wait up until 40 minutes
counter := 0
for runs := 20; counter <= runs; counter++ {
if counter > runs {
return false, errors.New("aws infra did not come up after 40 minutes")
}
// get the current status, wait for "Provisioned"
cluster := &clusterv1.Cluster{}
if err := c.Get(context.TODO(), client.ObjectKey{Namespace: "default", Name: clustername}, cluster); err != nil {
return false, err
}
if cluster.Status.Phase == "Provisioned" {
break
}
time.Sleep(time.Minute)
}
return true, nil
}
// waitForCP waits until the CP to come up
// TODO: probably should use https://pkg.go.dev/k8s.io/client-go/tools/watch
func waitForCP(restConfig *rest.Config, clustername string, createHaCluster bool) (bool, error) {
log.Info("Waiting for the Control Plane to appear")
// Set the vars we need
cpname := clustername + "-control-plane"
var expectedCPReplicas int32
if createHaCluster {
expectedCPReplicas = 3
} else {
expectedCPReplicas = 1
}
// We need to load the scheme since it's not part of the core API
scheme := runtime.NewScheme()
_ = kcpv1.AddToScheme(scheme)
c, err := client.New(restConfig, client.Options{
Scheme: scheme,
})
if err != nil {
return false, err
}
// wait up until 20 minutes
counter := 0
for runs := 20; counter <= runs; counter++ {
if counter > runs {
return false, errors.New("control-plane did not come up after 10 minutes")
}
// get the current status, wait for 3 CP nodes
kcp := &kcpv1.KubeadmControlPlane{}
if err := c.Get(context.TODO(), client.ObjectKey{Namespace: "default", Name: cpname}, kcp); err != nil {
return false, err
}
if kcp.Status.Replicas == expectedCPReplicas {
break
}
time.Sleep(time.Minute)
}
return true, nil
}
// waitForReadyNodes waits until all nodes are in a ready state
// TODO: probably should use https://pkg.go.dev/k8s.io/client-go/tools/watch
func waitForReadyNodes(cfg *rest.Config) (bool, error) {
nodesClientSet, err := kubernetes.NewForConfig(cfg)
if err != nil {
return false, err
}
// Get All nodes
nodesClient, err := nodesClientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return false, err
}
// Let's range over all nodes and wait until they're ready
for _, node := range nodesClient.Items {
// We are going to range over the conditions
for _, i := range node.Status.Conditions {
// we only care about if the Kublet is ready
if i.Reason == "KubeletReady" {
// set a counter so we don't run forever
c := 0