-
Notifications
You must be signed in to change notification settings - Fork 453
/
create.go
1195 lines (1010 loc) · 40.6 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package cluster
import (
"context"
"errors"
"fmt"
"math/big"
"net/netip"
"net/url"
"os"
"path/filepath"
stdruntime "runtime"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/google/uuid"
"github.com/hashicorp/go-getter/v2"
"github.com/siderolabs/go-blockdevice/blockdevice/encryption"
"github.com/siderolabs/go-kubeconfig"
"github.com/siderolabs/go-pointer"
"github.com/siderolabs/go-procfs/procfs"
sideronet "github.com/siderolabs/net"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/client-go/tools/clientcmd"
"github.com/siderolabs/talos/cmd/talosctl/cmd/mgmt/cluster/internal/firewallpatch"
"github.com/siderolabs/talos/cmd/talosctl/pkg/mgmt/helpers"
"github.com/siderolabs/talos/pkg/cli"
"github.com/siderolabs/talos/pkg/cluster/check"
"github.com/siderolabs/talos/pkg/images"
clientconfig "github.com/siderolabs/talos/pkg/machinery/client/config"
"github.com/siderolabs/talos/pkg/machinery/config"
"github.com/siderolabs/talos/pkg/machinery/config/bundle"
"github.com/siderolabs/talos/pkg/machinery/config/configpatcher"
"github.com/siderolabs/talos/pkg/machinery/config/encoder"
"github.com/siderolabs/talos/pkg/machinery/config/generate"
"github.com/siderolabs/talos/pkg/machinery/config/machine"
"github.com/siderolabs/talos/pkg/machinery/config/types/v1alpha1"
"github.com/siderolabs/talos/pkg/machinery/constants"
"github.com/siderolabs/talos/pkg/machinery/nethelpers"
"github.com/siderolabs/talos/pkg/machinery/version"
"github.com/siderolabs/talos/pkg/provision"
"github.com/siderolabs/talos/pkg/provision/access"
"github.com/siderolabs/talos/pkg/provision/providers"
)
const (
// gatewayOffset is the offset from the network address of the IP address of the network gateway.
gatewayOffset = 1
// nodesOffset is the offset from the network address of the beginning of the IP addresses to be used for nodes.
nodesOffset = 2
// vipOffset is the offset from the network address of the CIDR to use for allocating the Virtual (shared) IP address, if enabled.
vipOffset = 50
inputDirFlag = "input-dir"
// these flags are considered gen options.
nodeInstallImageFlag = "install-image"
configDebugFlag = "with-debug"
dnsDomainFlag = "dns-domain"
withClusterDiscoveryFlag = "with-cluster-discovery"
registryMirrorFlag = "registry-mirror"
registryInsecureFlag = "registry-insecure-skip-verify"
networkIPv4Flag = "ipv4"
networkIPv6Flag = "ipv6"
networkMTUFlag = "mtu"
networkCIDRFlag = "cidr"
nameserversFlag = "nameservers"
clusterDiskSizeFlag = "disk"
clusterDiskPreallocateFlag = "disk-preallocate"
clusterDisksFlag = "user-disk"
customCNIUrlFlag = "custom-cni-url"
talosVersionFlag = "talos-version"
encryptStatePartitionFlag = "encrypt-state"
encryptEphemeralPartitionFlag = "encrypt-ephemeral"
useVIPFlag = "use-vip"
enableKubeSpanFlag = "with-kubespan"
bootloaderEnabledFlag = "with-bootloader"
forceEndpointFlag = "endpoint"
controlPlanePortFlag = "control-plane-port"
kubePrismFlag = "kubeprism-port"
tpm2EnabledFlag = "with-tpm2"
diskEncryptionKeyTypesFlag = "disk-encryption-key-types"
firewallFlag = "with-firewall"
)
var (
talosconfig string
nodeImage string
nodeInstallImage string
registryMirrors []string
registryInsecure []string
kubernetesVersion string
nodeVmlinuzPath string
nodeInitramfsPath string
nodeISOPath string
nodeDiskImagePath string
nodeIPXEBootScript string
applyConfigEnabled bool
bootloaderEnabled bool
uefiEnabled bool
tpm2Enabled bool
extraUEFISearchPaths []string
configDebug bool
networkCIDR string
networkMTU int
networkIPv4 bool
networkIPv6 bool
wireguardCIDR string
nameservers []string
dnsDomain string
workers int
controlplanes int
controlPlaneCpus string
workersCpus string
controlPlaneMemory int
workersMemory int
clusterDiskSize int
clusterDiskPreallocate bool
clusterDisks []string
extraDisks int
extraDiskSize int
targetArch string
clusterWait bool
clusterWaitTimeout time.Duration
forceInitNodeAsEndpoint bool
forceEndpoint string
inputDir string
cniBinPath []string
cniConfDir string
cniCacheDir string
cniBundleURL string
ports string
dockerHostIP string
withInitNode bool
customCNIUrl string
crashdumpOnFailure bool
skipKubeconfig bool
skipInjectingConfig bool
talosVersion string
encryptStatePartition bool
encryptEphemeralPartition bool
useVIP bool
enableKubeSpan bool
enableClusterDiscovery bool
configPatch []string
configPatchControlPlane []string
configPatchWorker []string
badRTC bool
extraBootKernelArgs string
dockerDisableIPv6 bool
controlPlanePort int
kubePrismPort int
dhcpSkipHostname bool
skipBootPhaseFinishedCheck bool
networkChaos bool
jitter time.Duration
latency time.Duration
packetLoss float64
packetReorder float64
packetCorrupt float64
bandwidth int
diskEncryptionKeyTypes []string
withFirewall string
withUUIDHostnames bool
)
// createCmd represents the cluster up command.
var createCmd = &cobra.Command{
Use: "create",
Short: "Creates a local docker-based or QEMU-based kubernetes cluster",
Long: ``,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return cli.WithContext(context.Background(), func(ctx context.Context) error {
return create(ctx, cmd.Flags())
})
},
}
func downloadBootAssets(ctx context.Context) error {
// download & cache images if provides as URLs
for _, downloadableImage := range []*string{
&nodeVmlinuzPath,
&nodeInitramfsPath,
&nodeISOPath,
&nodeDiskImagePath,
} {
if *downloadableImage == "" {
continue
}
u, err := url.Parse(*downloadableImage)
if err != nil || !(u.Scheme == "http" || u.Scheme == "https") {
// not a URL
continue
}
defaultStateDir, err := clientconfig.GetTalosDirectory()
if err != nil {
return err
}
cacheDir := filepath.Join(defaultStateDir, "cache")
if os.MkdirAll(cacheDir, 0o755) != nil {
return err
}
destPath := strings.ReplaceAll(
strings.ReplaceAll(u.String(), "/", "-"),
":", "-")
_, err = os.Stat(filepath.Join(cacheDir, destPath))
if err == nil {
*downloadableImage = filepath.Join(cacheDir, destPath)
// already cached
continue
}
fmt.Fprintf(os.Stderr, "downloading asset from %q to %q\n", u.String(), filepath.Join(cacheDir, destPath))
client := getter.Client{
Getters: []getter.Getter{
&getter.HttpGetter{
HeadFirstTimeout: 30 * time.Minute,
ReadTimeout: 30 * time.Minute,
},
},
}
_, err = client.Get(ctx, &getter.Request{
Src: u.String(),
Dst: filepath.Join(cacheDir, destPath),
GetMode: getter.ModeFile,
})
if err != nil {
// clean up the destination on failure
os.Remove(filepath.Join(cacheDir, destPath)) //nolint:errcheck
return err
}
*downloadableImage = filepath.Join(cacheDir, destPath)
}
return nil
}
//nolint:gocyclo,cyclop
func create(ctx context.Context, flags *pflag.FlagSet) error {
if err := downloadBootAssets(ctx); err != nil {
return err
}
if controlplanes < 1 {
return errors.New("number of controlplanes can't be less than 1")
}
controlPlaneNanoCPUs, err := parseCPUShare(controlPlaneCpus)
if err != nil {
return fmt.Errorf("error parsing --cpus: %s", err)
}
workerNanoCPUs, err := parseCPUShare(workersCpus)
if err != nil {
return fmt.Errorf("error parsing --cpus-workers: %s", err)
}
controlPlaneMemory := int64(controlPlaneMemory) * 1024 * 1024
workerMemory := int64(workersMemory) * 1024 * 1024
// Validate CIDR range and allocate IPs
fmt.Fprintln(os.Stderr, "validating CIDR and reserving IPs")
cidr4, err := netip.ParsePrefix(networkCIDR)
if err != nil {
return fmt.Errorf("error validating cidr block: %w", err)
}
if !cidr4.Addr().Is4() {
return errors.New("--cidr is expected to be IPV4 CIDR")
}
// use ULA IPv6 network fd00::/8, add 'TAL' in hex to build /32 network, add IPv4 CIDR to build /64 unique network
cidr6, err := netip.ParsePrefix(
fmt.Sprintf(
"fd74:616c:%02x%02x:%02x%02x::/64",
cidr4.Addr().As4()[0], cidr4.Addr().As4()[1], cidr4.Addr().As4()[2], cidr4.Addr().As4()[3],
),
)
if err != nil {
return fmt.Errorf("error validating cidr IPv6 block: %w", err)
}
var cidrs []netip.Prefix
if networkIPv4 {
cidrs = append(cidrs, cidr4)
}
if networkIPv6 {
cidrs = append(cidrs, cidr6)
}
if len(cidrs) == 0 {
return errors.New("neither IPv4 nor IPv6 network was enabled")
}
// Gateway addr at 1st IP in range, ex. 192.168.0.1
gatewayIPs := make([]netip.Addr, len(cidrs))
for j := range gatewayIPs {
gatewayIPs[j], err = sideronet.NthIPInNetwork(cidrs[j], gatewayOffset)
if err != nil {
return err
}
}
// Set starting ip at 2nd ip in range, ex: 192.168.0.2
ips := make([][]netip.Addr, len(cidrs))
for j := range cidrs {
ips[j] = make([]netip.Addr, controlplanes+workers)
for i := range ips[j] {
ips[j][i], err = sideronet.NthIPInNetwork(cidrs[j], nodesOffset+i)
if err != nil {
return err
}
}
}
// Parse nameservers
nameserverIPs := make([]netip.Addr, len(nameservers))
for i := range nameserverIPs {
nameserverIPs[i], err = netip.ParseAddr(nameservers[i])
if err != nil {
return fmt.Errorf("failed parsing nameserver IP %q: %w", nameservers[i], err)
}
}
// Virtual (shared) IP at the vipOffset IP in range, ex. 192.168.0.50
var vip netip.Addr
if useVIP {
vip, err = sideronet.NthIPInNetwork(cidrs[0], vipOffset)
if err != nil {
return err
}
}
// Validate network chaos flags
if !networkChaos {
if jitter != 0 || latency != 0 || packetLoss != 0 || packetReorder != 0 || packetCorrupt != 0 || bandwidth != 0 {
return errors.New("network chaos flags can only be used with --with-network-chaos")
}
}
provisioner, err := providers.Factory(ctx, provisionerName)
if err != nil {
return err
}
defer provisioner.Close() //nolint:errcheck
// Craft cluster and node requests
request := provision.ClusterRequest{
Name: clusterName,
Network: provision.NetworkRequest{
Name: clusterName,
CIDRs: cidrs,
GatewayAddrs: gatewayIPs,
MTU: networkMTU,
Nameservers: nameserverIPs,
LoadBalancerPorts: []int{controlPlanePort},
CNI: provision.CNIConfig{
BinPath: cniBinPath,
ConfDir: cniConfDir,
CacheDir: cniCacheDir,
BundleURL: cniBundleURL,
},
DHCPSkipHostname: dhcpSkipHostname,
DockerDisableIPv6: dockerDisableIPv6,
NetworkChaos: networkChaos,
Jitter: jitter,
Latency: latency,
PacketLoss: packetLoss,
PacketReorder: packetReorder,
PacketCorrupt: packetCorrupt,
Bandwidth: bandwidth,
},
Image: nodeImage,
KernelPath: nodeVmlinuzPath,
InitramfsPath: nodeInitramfsPath,
ISOPath: nodeISOPath,
IPXEBootScript: nodeIPXEBootScript,
DiskImagePath: nodeDiskImagePath,
SelfExecutable: os.Args[0],
StateDirectory: stateDir,
}
provisionOptions := []provision.Option{
provision.WithDockerPortsHostIP(dockerHostIP),
provision.WithBootlader(bootloaderEnabled),
provision.WithUEFI(uefiEnabled),
provision.WithTPM2(tpm2Enabled),
provision.WithExtraUEFISearchPaths(extraUEFISearchPaths),
provision.WithTargetArch(targetArch),
}
var configBundleOpts []bundle.Option
if ports != "" {
if provisionerName != "docker" {
return errors.New("exposed-ports flag only supported with docker provisioner")
}
portList := strings.Split(ports, ",")
provisionOptions = append(provisionOptions, provision.WithDockerPorts(portList))
}
disks, err := getDisks()
if err != nil {
return err
}
if inputDir != "" {
definedGenFlag := checkForDefinedGenFlag(flags)
if definedGenFlag != "" {
return fmt.Errorf("flag --%s is not supported with generated configs(--%s)", definedGenFlag, inputDirFlag)
}
configBundleOpts = append(configBundleOpts, bundle.WithExistingConfigs(inputDir))
} else {
genOptions := []generate.Option{
generate.WithInstallImage(nodeInstallImage),
generate.WithDebug(configDebug),
generate.WithDNSDomain(dnsDomain),
generate.WithClusterDiscovery(enableClusterDiscovery),
}
for _, registryMirror := range registryMirrors {
components := strings.SplitN(registryMirror, "=", 2)
if len(components) != 2 {
return fmt.Errorf("invalid registry mirror spec: %q", registryMirror)
}
genOptions = append(genOptions, generate.WithRegistryMirror(components[0], components[1]))
}
for _, registryHost := range registryInsecure {
genOptions = append(genOptions, generate.WithRegistryInsecureSkipVerify(registryHost))
}
genOptions = append(genOptions, provisioner.GenOptions(request.Network)...)
if customCNIUrl != "" {
genOptions = append(genOptions, generate.WithClusterCNIConfig(&v1alpha1.CNIConfig{
CNIName: constants.CustomCNI,
CNIUrls: []string{customCNIUrl},
}))
}
if len(disks) > 1 {
// convert provision disks to machine disks
machineDisks := make([]*v1alpha1.MachineDisk, len(disks)-1)
for i, disk := range disks[1:] {
machineDisks[i] = &v1alpha1.MachineDisk{
DeviceName: provisioner.UserDiskName(i + 1),
DiskPartitions: disk.Partitions,
}
}
genOptions = append(genOptions, generate.WithUserDisks(machineDisks))
}
if talosVersion == "" {
if provisionerName == "docker" {
parts := strings.Split(nodeImage, ":")
talosVersion = parts[len(parts)-1]
} else {
parts := strings.Split(nodeInstallImage, ":")
talosVersion = parts[len(parts)-1]
}
}
if talosVersion != "latest" {
var versionContract *config.VersionContract
versionContract, err = config.ParseContractFromVersion(talosVersion)
if err != nil {
return fmt.Errorf("error parsing Talos version %q: %w", talosVersion, err)
}
genOptions = append(genOptions, generate.WithVersionContract(versionContract))
}
if encryptStatePartition || encryptEphemeralPartition {
diskEncryptionConfig := &v1alpha1.SystemDiskEncryptionConfig{}
var keys []*v1alpha1.EncryptionKey
for i, key := range diskEncryptionKeyTypes {
switch key {
case "uuid":
keys = append(keys, &v1alpha1.EncryptionKey{
KeyNodeID: &v1alpha1.EncryptionKeyNodeID{},
KeySlot: i,
})
case "kms":
var ip netip.Addr
// get bridge IP
ip, err = sideronet.NthIPInNetwork(cidr4, 1)
if err != nil {
return err
}
port := 4050
keys = append(keys, &v1alpha1.EncryptionKey{
KeyKMS: &v1alpha1.EncryptionKeyKMS{
KMSEndpoint: "grpc://" + nethelpers.JoinHostPort(ip.String(), port),
},
KeySlot: i,
})
provisionOptions = append(provisionOptions, provision.WithKMS(nethelpers.JoinHostPort("0.0.0.0", port)))
case "tpm":
keys = append(keys, &v1alpha1.EncryptionKey{
KeyTPM: &v1alpha1.EncryptionKeyTPM{},
KeySlot: i,
})
default:
return fmt.Errorf("unknown key type %q", key)
}
}
if len(keys) == 0 {
return errors.New("no disk encryption key types enabled")
}
if encryptStatePartition {
diskEncryptionConfig.StatePartition = &v1alpha1.EncryptionConfig{
EncryptionProvider: encryption.LUKS2,
EncryptionKeys: keys,
}
}
if encryptEphemeralPartition {
diskEncryptionConfig.EphemeralPartition = &v1alpha1.EncryptionConfig{
EncryptionProvider: encryption.LUKS2,
EncryptionKeys: keys,
}
}
genOptions = append(genOptions, generate.WithSystemDiskEncryption(diskEncryptionConfig))
}
if useVIP {
genOptions = append(genOptions,
generate.WithNetworkOptions(
v1alpha1.WithNetworkInterfaceVirtualIP(provisioner.GetFirstInterface(), vip.String()),
),
)
}
if enableKubeSpan {
genOptions = append(genOptions,
generate.WithNetworkOptions(
v1alpha1.WithKubeSpan(),
),
)
}
if !bootloaderEnabled {
// disable kexec, as this would effectively use the bootloader
genOptions = append(genOptions,
generate.WithSysctls(map[string]string{
"kernel.kexec_load_disabled": "1",
}),
)
}
if controlPlanePort != constants.DefaultControlPlanePort {
genOptions = append(genOptions,
generate.WithLocalAPIServerPort(controlPlanePort),
)
}
if kubePrismPort != constants.DefaultKubePrismPort {
genOptions = append(genOptions,
generate.WithKubePrismPort(kubePrismPort),
)
}
defaultInternalLB, defaultEndpoint := provisioner.GetLoadBalancers(request.Network)
if defaultInternalLB == "" {
// provisioner doesn't provide internal LB, so use first controlplane node
defaultInternalLB = ips[0][0].String()
}
if useVIP {
defaultInternalLB = vip.String()
}
var endpointList []string
switch {
case defaultEndpoint != "":
if forceEndpoint == "" {
forceEndpoint = defaultEndpoint
}
fallthrough
case forceEndpoint != "":
endpointList = []string{forceEndpoint}
// using non-default endpoints, provision additional cert SANs and fix endpoint list
provisionOptions = append(provisionOptions, provision.WithEndpoint(forceEndpoint))
genOptions = append(genOptions, generate.WithAdditionalSubjectAltNames(endpointList))
case forceInitNodeAsEndpoint:
endpointList = []string{ips[0][0].String()}
default:
// use control plane nodes as endpoints, client-side load-balancing
for i := 0; i < controlplanes; i++ {
endpointList = append(endpointList, ips[0][i].String())
}
}
genOptions = append(genOptions, generate.WithEndpointList(endpointList))
configBundleOpts = append(configBundleOpts,
bundle.WithInputOptions(
&bundle.InputOptions{
ClusterName: clusterName,
Endpoint: fmt.Sprintf("https://%s", nethelpers.JoinHostPort(defaultInternalLB, controlPlanePort)),
KubeVersion: strings.TrimPrefix(kubernetesVersion, "v"),
GenOptions: genOptions,
}),
)
}
addConfigPatch := func(configPatches []string, configOpt func([]configpatcher.Patch) bundle.Option) error {
var patches []configpatcher.Patch
patches, err = configpatcher.LoadPatches(configPatches)
if err != nil {
return fmt.Errorf("error parsing config JSON patch: %w", err)
}
configBundleOpts = append(configBundleOpts, configOpt(patches))
return nil
}
if err = addConfigPatch(configPatch, bundle.WithPatch); err != nil {
return err
}
if err = addConfigPatch(configPatchControlPlane, bundle.WithPatchControlPlane); err != nil {
return err
}
if err = addConfigPatch(configPatchWorker, bundle.WithPatchWorker); err != nil {
return err
}
if withFirewall != "" {
var defaultAction nethelpers.DefaultAction
defaultAction, err = nethelpers.DefaultActionString(withFirewall)
if err != nil {
return err
}
var controlplaneIPs []netip.Addr
for i := range ips {
controlplaneIPs = append(controlplaneIPs, ips[i][:controlplanes]...)
}
configBundleOpts = append(configBundleOpts,
bundle.WithPatchControlPlane([]configpatcher.Patch{firewallpatch.ControlPlane(defaultAction, cidrs, gatewayIPs, controlplaneIPs)}),
bundle.WithPatchWorker([]configpatcher.Patch{firewallpatch.Worker(defaultAction, cidrs, gatewayIPs)}),
)
}
configBundle, err := bundle.NewBundle(configBundleOpts...)
if err != nil {
return err
}
bundleTalosconfig := configBundle.TalosConfig()
if bundleTalosconfig == nil {
if clusterWait {
return errors.New("no talosconfig in the config bundle: cannot wait for cluster")
}
if applyConfigEnabled {
return errors.New("no talosconfig in the config bundle: cannot apply config")
}
}
if skipInjectingConfig {
types := []machine.Type{machine.TypeControlPlane, machine.TypeWorker}
if withInitNode {
types = append([]machine.Type{machine.TypeInit}, types...)
}
if err = configBundle.Write(".", encoder.CommentsAll, types...); err != nil {
return err
}
}
// Wireguard configuration.
var wireguardConfigBundle *helpers.WireguardConfigBundle
if wireguardCIDR != "" {
wireguardConfigBundle, err = helpers.NewWireguardConfigBundle(ips[0], wireguardCIDR, 51111, controlplanes)
if err != nil {
return err
}
}
var extraKernelArgs *procfs.Cmdline
if extraBootKernelArgs != "" {
extraKernelArgs = procfs.NewCmdline(extraBootKernelArgs)
}
// Add talosconfig to provision options, so we'll have it to parse there
provisionOptions = append(provisionOptions, provision.WithTalosConfig(configBundle.TalosConfig()))
// Create the controlplane nodes.
for i := 0; i < controlplanes; i++ {
var cfg config.Provider
nodeIPs := make([]netip.Addr, len(cidrs))
for j := range nodeIPs {
nodeIPs[j] = ips[j][i]
}
nodeUUID := uuid.New()
nodeReq := provision.NodeRequest{
Name: nodeName(clusterName, "controlplane", i+1, nodeUUID),
Type: machine.TypeControlPlane,
IPs: nodeIPs,
Memory: controlPlaneMemory,
NanoCPUs: controlPlaneNanoCPUs,
Disks: disks,
SkipInjectingConfig: skipInjectingConfig,
BadRTC: badRTC,
ExtraKernelArgs: extraKernelArgs,
UUID: pointer.To(nodeUUID),
}
if i == 0 {
nodeReq.Ports = []string{"50000:50000/tcp", fmt.Sprintf("%d:%d/tcp", controlPlanePort, controlPlanePort)}
}
if withInitNode && i == 0 {
cfg = configBundle.Init()
nodeReq.Type = machine.TypeInit
} else {
cfg = configBundle.ControlPlane()
}
if wireguardConfigBundle != nil {
cfg, err = wireguardConfigBundle.PatchConfig(nodeIPs[0], cfg)
if err != nil {
return err
}
}
nodeReq.Config = cfg
request.Nodes = append(request.Nodes, nodeReq)
}
// append extra disks
for i := 0; i < extraDisks; i++ {
disks = append(disks, &provision.Disk{
Size: uint64(extraDiskSize) * 1024 * 1024,
SkipPreallocate: !clusterDiskPreallocate,
})
}
for i := 1; i <= workers; i++ {
cfg := configBundle.Worker()
nodeIPs := make([]netip.Addr, len(cidrs))
for j := range nodeIPs {
nodeIPs[j] = ips[j][controlplanes+i-1]
}
if wireguardConfigBundle != nil {
cfg, err = wireguardConfigBundle.PatchConfig(nodeIPs[0], cfg)
if err != nil {
return err
}
}
nodeUUID := uuid.New()
request.Nodes = append(request.Nodes,
provision.NodeRequest{
Name: nodeName(clusterName, "worker", i, nodeUUID),
Type: machine.TypeWorker,
IPs: nodeIPs,
Memory: workerMemory,
NanoCPUs: workerNanoCPUs,
Disks: disks,
Config: cfg,
SkipInjectingConfig: skipInjectingConfig,
BadRTC: badRTC,
ExtraKernelArgs: extraKernelArgs,
UUID: pointer.To(nodeUUID),
})
}
cluster, err := provisioner.Create(ctx, request, provisionOptions...)
if err != nil {
return err
}
// No talosconfig in the bundle - skip the operations below
if bundleTalosconfig == nil {
return nil
}
// Create and save the talosctl configuration file.
if err = saveConfig(bundleTalosconfig); err != nil {
return err
}
clusterAccess := access.NewAdapter(cluster, provisionOptions...)
defer clusterAccess.Close() //nolint:errcheck
if applyConfigEnabled {
err = clusterAccess.ApplyConfig(ctx, request.Nodes, os.Stdout)
if err != nil {
return err
}
}
if err = postCreate(ctx, clusterAccess); err != nil {
if crashdumpOnFailure {
provisioner.CrashDump(ctx, cluster, os.Stderr)
}
return err
}
return showCluster(cluster)
}
func nodeName(clusterName, role string, index int, uuid uuid.UUID) string {
if withUUIDHostnames {
return fmt.Sprintf("machine-%s", uuid)
}
return fmt.Sprintf("%s-%s-%d", clusterName, role, index)
}
func postCreate(ctx context.Context, clusterAccess *access.Adapter) error {
if !withInitNode {
if err := clusterAccess.Bootstrap(ctx, os.Stdout); err != nil {
return fmt.Errorf("bootstrap error: %w", err)
}
}
if !clusterWait {
return nil
}
// Run cluster readiness checks
checkCtx, checkCtxCancel := context.WithTimeout(ctx, clusterWaitTimeout)
defer checkCtxCancel()
checks := check.DefaultClusterChecks()
if skipBootPhaseFinishedCheck {
checks = check.PreBootSequenceChecks()
}
checks = append(checks, check.ExtraClusterChecks()...)
if err := check.Wait(checkCtx, clusterAccess, checks, check.StderrReporter()); err != nil {
return err
}
if !skipKubeconfig {
if err := mergeKubeconfig(ctx, clusterAccess); err != nil {
return err
}
}
return nil
}
func saveConfig(talosConfigObj *clientconfig.Config) (err error) {
c, err := clientconfig.Open(talosconfig)
if err != nil {
return fmt.Errorf("error opening talos config: %w", err)
}
renames := c.Merge(talosConfigObj)
for _, rename := range renames {
fmt.Fprintf(os.Stderr, "renamed talosconfig context %s\n", rename.String())
}
return c.Save(talosconfig)
}
func mergeKubeconfig(ctx context.Context, clusterAccess *access.Adapter) error {
kubeconfigPath, err := kubeconfig.SinglePath()
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "\nmerging kubeconfig into %q\n", kubeconfigPath)
k8sconfig, err := clusterAccess.Kubeconfig(ctx)
if err != nil {
return fmt.Errorf("error fetching kubeconfig: %w", err)
}
kubeConfig, err := clientcmd.Load(k8sconfig)
if err != nil {
return fmt.Errorf("error parsing kubeconfig: %w", err)
}
if clusterAccess.ForceEndpoint != "" {
for name := range kubeConfig.Clusters {
kubeConfig.Clusters[name].Server = fmt.Sprintf("https://%s", nethelpers.JoinHostPort(clusterAccess.ForceEndpoint, controlPlanePort))
}
}
_, err = os.Stat(kubeconfigPath)
if err != nil {
if !os.IsNotExist(err) {
return err
}
return clientcmd.WriteToFile(*kubeConfig, kubeconfigPath)
}
merger, err := kubeconfig.Load(kubeconfigPath)
if err != nil {
return fmt.Errorf("error loading existing kubeconfig: %w", err)
}
err = merger.Merge(kubeConfig, kubeconfig.MergeOptions{
ActivateContext: true,
OutputWriter: os.Stdout,
ConflictHandler: func(component kubeconfig.ConfigComponent, name string) (kubeconfig.ConflictDecision, error) {
return kubeconfig.RenameDecision, nil
},
})
if err != nil {
return fmt.Errorf("error merging kubeconfig: %w", err)
}
return merger.Write(kubeconfigPath)
}
func parseCPUShare(cpus string) (int64, error) {
cpu, ok := new(big.Rat).SetString(cpus)
if !ok {
return 0, fmt.Errorf("failed to parsing as a rational number: %s", cpus)
}
nano := cpu.Mul(cpu, big.NewRat(1e9, 1))
if !nano.IsInt() {
return 0, errors.New("value is too precise")
}
return nano.Num().Int64(), nil
}
func getDisks() ([]*provision.Disk, error) {
// should have at least a single primary disk