-
Notifications
You must be signed in to change notification settings - Fork 6
/
cluster.go
1003 lines (935 loc) · 32.3 KB
/
cluster.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 cmd
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path"
"sort"
"strings"
"time"
"github.com/metal-stack/metal-lib/auth"
"gopkg.in/yaml.v3"
"github.com/fi-ts/cloud-go/api/client/cluster"
"github.com/fi-ts/cloud-go/api/models"
"github.com/fi-ts/cloudctl/cmd/helper"
"github.com/fi-ts/cloudctl/cmd/output"
"github.com/Masterminds/semver"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
clusterCmd = &cobra.Command{
Use: "cluster",
Short: "manage clusters",
Long: "TODO",
}
clusterCreateCmd = &cobra.Command{
Use: "create",
Short: "create a cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterCreate()
},
PreRun: bindPFlags,
}
clusterListCmd = &cobra.Command{
Use: "list",
Short: "list clusters",
Aliases: []string{"ls"},
RunE: func(cmd *cobra.Command, args []string) error {
return clusterList()
},
PreRun: bindPFlags,
}
clusterDeleteCmd = &cobra.Command{
Use: "delete <uid>",
Short: "delete a cluster",
Aliases: []string{"rm"},
RunE: func(cmd *cobra.Command, args []string) error {
return clusterDelete(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterDescribeCmd = &cobra.Command{
Use: "describe <uid>",
Short: "describe a cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterDescribe(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterKubeconfigCmd = &cobra.Command{
Use: "kubeconfig <uid>",
Short: "get cluster kubeconfig",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterKubeconfig(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterReconcileCmd = &cobra.Command{
Use: "reconcile <uid>",
Short: "trigger cluster reconciliation",
RunE: func(cmd *cobra.Command, args []string) error {
return reconcileCluster(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterUpdateCmd = &cobra.Command{
Use: "update <uid>",
Short: "update a cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return updateCluster(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterInputsCmd = &cobra.Command{
Use: "inputs",
Short: "get possible cluster inputs like k8s versions, etc.",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterInputs()
},
PreRun: bindPFlags,
}
clusterMachineCmd = &cobra.Command{
Use: "machine",
Aliases: []string{"machines"},
Short: "list and access machines in the cluster",
}
clusterMachineListCmd = &cobra.Command{
Use: "ls",
Aliases: []string{"list"},
Short: "list machines of the cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterMachines(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterMachineSSHCmd = &cobra.Command{
Use: "ssh <clusterid>",
Short: "ssh access a machine/firewall of the cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterMachineSSH(args, false)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterMachineConsoleCmd = &cobra.Command{
Use: "console <clusterid>",
Short: "console access a machine/firewall of the cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterMachineSSH(args, true)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
clusterLogsCmd = &cobra.Command{
Use: "logs",
Short: "get logs for the cluster",
RunE: func(cmd *cobra.Command, args []string) error {
return clusterLogs(args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return clusterListCompletion()
},
PreRun: bindPFlags,
}
)
func init() {
clusterCreateCmd.Flags().String("name", "", "name of the cluster, max 10 characters. [required]")
clusterCreateCmd.Flags().String("description", "", "description of the cluster. [optional]")
clusterCreateCmd.Flags().String("project", "", "project where this cluster should belong to. [required]")
clusterCreateCmd.Flags().String("partition", "", "partition of the cluster. [required]")
clusterCreateCmd.Flags().String("purpose", "evaluation", "purpose of the cluster, can be one of production|testing|development|evaluation. SLA is only given on production clusters. [optional]")
clusterCreateCmd.Flags().String("version", "", "kubernetes version of the cluster. defaults to latest available, check cluster inputs for possible values. [optional]")
clusterCreateCmd.Flags().String("machinetype", "", "machine type to use for the nodes. [optional]")
clusterCreateCmd.Flags().String("machineimage", "", "machine image to use for the nodes, must be in the form of <name>-<version> [optional]")
clusterCreateCmd.Flags().String("firewalltype", "", "machine type to use for the firewall. [optional]")
clusterCreateCmd.Flags().String("firewallimage", "", "machine image to use for the firewall. [optional]")
clusterCreateCmd.Flags().String("cri", "docker", "container runtime to use, only docker|containerd supported as alternative actually. [optional]")
clusterCreateCmd.Flags().Int32("minsize", 1, "minimal workers of the cluster.")
clusterCreateCmd.Flags().Int32("maxsize", 1, "maximal workers of the cluster.")
clusterCreateCmd.Flags().String("maxsurge", "1", "max number (e.g. 1) or percentage (e.g. 10%) of workers created during a update of the cluster.")
clusterCreateCmd.Flags().String("maxunavailable", "1", "max number (e.g. 1) or percentage (e.g. 10%) of workers that can be unavailable during a update of the cluster.")
clusterCreateCmd.Flags().StringSlice("labels", []string{}, "labels of the cluster")
clusterCreateCmd.Flags().StringSlice("external-networks", []string{"internet"}, "external networks of the cluster, can be internet,mpls")
clusterCreateCmd.Flags().BoolP("allowprivileged", "", false, "allow privileged containers the cluster.")
clusterCreateCmd.Flags().BoolP("defaultingress", "", false, "deploy a default ingress controller")
err := clusterCreateCmd.MarkFlagRequired("name")
if err != nil {
log.Fatal(err.Error())
}
err = clusterCreateCmd.MarkFlagRequired("project")
if err != nil {
log.Fatal(err.Error())
}
err = clusterCreateCmd.MarkFlagRequired("partition")
if err != nil {
log.Fatal(err.Error())
}
clusterCreateCmd.RegisterFlagCompletionFunc("project", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return projectListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("partition", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return partitionListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("external-networks", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return networkListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return versionListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("machinetype", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return machineTypeListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("machineimage", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return machineImageListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("firewalltype", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return firewallTypeListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("firewallimage", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return firewallImageListCompletion()
})
clusterCreateCmd.RegisterFlagCompletionFunc("purpose", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"production", "testing", "development", "evaluation"}, cobra.ShellCompDirectiveDefault
})
clusterCreateCmd.RegisterFlagCompletionFunc("cri", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"docker", "containerd"}, cobra.ShellCompDirectiveDefault
})
// Cluster list --------------------------------------------------------------------
clusterListCmd.Flags().String("project", "", "show clusters of given project")
clusterListCmd.Flags().String("partition", "", "show clusters in partition")
clusterListCmd.Flags().String("tenant", "", "show clusters of given tenant")
clusterListCmd.RegisterFlagCompletionFunc("project", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return projectListCompletion()
})
clusterListCmd.RegisterFlagCompletionFunc("partition", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return partitionListCompletion()
})
// Cluster update --------------------------------------------------------------------
clusterUpdateCmd.Flags().Int32("minsize", 0, "minimal workers of the cluster.")
clusterUpdateCmd.Flags().Int32("maxsize", 0, "maximal workers of the cluster.")
clusterUpdateCmd.Flags().String("version", "", "kubernetes version of the cluster.")
clusterUpdateCmd.Flags().String("firewalltype", "", "machine type to use for the firewall.")
clusterUpdateCmd.Flags().String("firewallimage", "", "machine image to use for the firewall.")
clusterUpdateCmd.Flags().String("machinetype", "", "machine type to use for the nodes.")
clusterUpdateCmd.Flags().String("machineimage", "", "machine image to use for the nodes, must be in the form of <name>-<version> ")
clusterUpdateCmd.Flags().StringSlice("addlabels", []string{}, "labels to add to the cluster")
clusterUpdateCmd.Flags().StringSlice("removelabels", []string{}, "labels to remove from the cluster")
clusterUpdateCmd.Flags().BoolP("allowprivileged", "", false, "allow privileged containers the cluster, please add --i-am-aware-of-dangerous-settings")
clusterUpdateCmd.Flags().BoolP("i-am-aware-of-dangerous-settings", "", false, "required when modify dangerous settings")
clusterUpdateCmd.Flags().String("purpose", "", "purpose of the cluster, can be one of production|testing|development|evaluation. SLA is only given on production clusters.")
clusterUpdateCmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return versionListCompletion()
})
clusterUpdateCmd.RegisterFlagCompletionFunc("firewalltype", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return firewallTypeListCompletion()
})
clusterUpdateCmd.RegisterFlagCompletionFunc("firewallimage", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return firewallImageListCompletion()
})
clusterUpdateCmd.RegisterFlagCompletionFunc("machinetype", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return machineTypeListCompletion()
})
clusterUpdateCmd.RegisterFlagCompletionFunc("machineimage", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return machineImageListCompletion()
})
clusterUpdateCmd.RegisterFlagCompletionFunc("purpose", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"production", "testing", "development", "evaluation"}, cobra.ShellCompDirectiveDefault
})
clusterMachineSSHCmd.Flags().String("machineid", "", "machine to connect to.")
clusterMachineSSHCmd.MarkFlagRequired("machineid")
clusterMachineSSHCmd.RegisterFlagCompletionFunc("machineid", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// FIXME howto implement flag based completion for a already given clusterid
fmt.Printf("args:%v\n", args)
return clusterMachineListCompletion("123")
})
clusterMachineConsoleCmd.Flags().String("machineid", "", "machine to connect to.")
clusterMachineConsoleCmd.MarkFlagRequired("machineid")
clusterMachineConsoleCmd.RegisterFlagCompletionFunc("machineid", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// FIXME howto implement flag based completion for a already given clusterid
fmt.Printf("args:%v\n", args)
return clusterMachineListCompletion("123")
})
clusterMachineCmd.AddCommand(clusterMachineListCmd)
clusterMachineCmd.AddCommand(clusterMachineSSHCmd)
clusterMachineCmd.AddCommand(clusterMachineConsoleCmd)
clusterCmd.AddCommand(clusterCreateCmd)
clusterCmd.AddCommand(clusterListCmd)
clusterCmd.AddCommand(clusterKubeconfigCmd)
clusterCmd.AddCommand(clusterDeleteCmd)
clusterCmd.AddCommand(clusterDescribeCmd)
clusterCmd.AddCommand(clusterInputsCmd)
clusterCmd.AddCommand(clusterReconcileCmd)
clusterCmd.AddCommand(clusterUpdateCmd)
clusterCmd.AddCommand(clusterMachineCmd)
clusterCmd.AddCommand(clusterLogsCmd)
}
func clusterCreate() error {
name := viper.GetString("name")
desc := viper.GetString("description")
partition := viper.GetString("partition")
project := viper.GetString("project")
purpose := viper.GetString("purpose")
machineType := viper.GetString("machinetype")
machineImageAndVersion := viper.GetString("machineimage")
firewallType := viper.GetString("firewalltype")
firewallImage := viper.GetString("firewallimage")
cri := viper.GetString("cri")
minsize := viper.GetInt32("minsize")
maxsize := viper.GetInt32("maxsize")
maxsurge := viper.GetString("maxsurge")
maxunavailable := viper.GetString("maxunavailable")
allowprivileged := viper.GetBool("allowprivileged")
defaultingress := viper.GetBool("defaultingress")
labels := viper.GetStringSlice("labels")
// FIXME helper and validation
networks := viper.GetStringSlice("external-networks")
autoUpdateKubernetes := false
autoUpdateMachineImage := false
maintenanceBegin := "220000+0100"
maintenanceEnd := "233000+0100"
kubernetesEnabled := false
version := viper.GetString("version")
if version == "" {
request := cluster.NewListConstraintsParams()
constraints, err := cloud.Cluster.ListConstraints(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.ListConstraintsDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
availableVersions := constraints.Payload.KubernetesVersions
if len(availableVersions) == 0 {
log.Fatalf("no kubernetes versions available to deploy")
}
sortedVersions := make([]*semver.Version, len(availableVersions))
for i, r := range availableVersions {
v, err := semver.NewVersion(r)
if err != nil {
log.Fatalf("Error parsing version: %s", err)
}
sortedVersions[i] = v
}
sort.Sort(semver.Collection(sortedVersions))
version = sortedVersions[len(sortedVersions)-1].String()
}
machineImage := models.V1MachineImage{}
if machineImageAndVersion != "" {
machineImageParts := strings.Split(machineImageAndVersion, "-")
if len(machineImageParts) == 2 {
machineImage = models.V1MachineImage{
Name: &machineImageParts[0],
Version: &machineImageParts[1],
}
} else {
log.Fatalf("given machineimage:%s is invalid must be in the form <name>-<version>", machineImageAndVersion)
}
}
labelMap := make(map[string]string)
for _, l := range labels {
parts := strings.SplitN(l, "=", 2)
if len(parts) != 2 {
log.Fatalf("provided labels must be in the form <key>=<value>, found: %s", l)
}
labelMap[parts[0]] = parts[1]
}
var workerCRI models.V1beta1CRI
if cri == "containerd" {
workerCRI = models.V1beta1CRI{
Name: &cri,
ContainerRuntimes: []*models.V1beta1ContainerRuntime{
{
Type: &cri,
// FIXME what is the content of ProviderConfig
ProviderConfig: "",
},
},
}
}
scr := &models.V1ClusterCreateRequest{
ProjectID: &project,
Name: &name,
Labels: labelMap,
Description: &desc,
Purpose: &purpose,
Workers: []*models.V1Worker{
{
Minimum: &minsize,
Maximum: &maxsize,
MaxSurge: &maxsurge,
MaxUnavailable: &maxunavailable,
MachineType: &machineType,
MachineImage: &machineImage,
CRI: &workerCRI,
},
},
FirewallSize: &firewallType,
FirewallImage: &firewallImage,
Kubernetes: &models.V1Kubernetes{
AllowPrivilegedContainers: &allowprivileged,
Version: &version,
},
Maintenance: &models.V1Maintenance{
AutoUpdate: &models.V1MaintenanceAutoUpdate{
KubernetesVersion: &autoUpdateKubernetes,
MachineImage: &autoUpdateMachineImage,
},
TimeWindow: &models.V1MaintenanceTimeWindow{
Begin: &maintenanceBegin,
End: &maintenanceEnd,
},
},
AdditionalNetworks: networks,
PartitionID: &partition,
Addons: &models.V1Addons{
KubernetesDashboard: &kubernetesEnabled,
NginxIngress: &defaultingress,
},
}
request := cluster.NewCreateClusterParams()
request.SetBody(scr)
shoot, err := cloud.Cluster.CreateCluster(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.CreateClusterConflict:
return output.HTTPError(e.Payload)
case *cluster.CreateClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(shoot.Payload)
}
func clusterList() error {
tenant := viper.GetString("tenant")
partition := viper.GetString("partition")
project := viper.GetString("project")
var cfr *models.V1ClusterFindRequest
if tenant != "" || partition != "" || project != "" {
cfr = &models.V1ClusterFindRequest{}
if tenant != "" {
cfr.Tenant = &tenant
}
if project != "" {
cfr.ProjectID = &project
}
if partition != "" {
cfr.PartitionID = &partition
}
}
if cfr != nil {
fcp := cluster.NewFindClustersParams()
fcp.SetBody(cfr)
response, err := cloud.Cluster.FindClusters(fcp, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClustersDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(response.Payload)
}
request := cluster.NewListClustersParams()
shoots, err := cloud.Cluster.ListClusters(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.ListClustersDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(shoots.Payload)
}
func clusterKubeconfig(args []string) error {
ci, err := clusterID("credentials", args)
if err != nil {
return err
}
request := cluster.NewGetClusterKubeconfigTplParams()
request.SetID(ci)
credentials, err := cloud.Cluster.GetClusterKubeconfigTpl(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.GetClusterKubeconfigTplDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
// kubeconfig with cluster
kubeconfigContent := *credentials.Payload.Kubeconfig
kubeconfigFile := viper.GetString("kubeConfig")
authContext, err := getAuthContext(kubeconfigFile)
if err != nil {
return err
}
if !authContext.AuthProviderOidc {
return fmt.Errorf("active user %s has no oidc authProvider, check config", authContext.User)
}
cfg := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(kubeconfigContent), cfg)
if err != nil {
return err
}
// identify clustername
clusterNames, err := auth.GetClusterNames(cfg)
if err != nil {
return err
}
if len(clusterNames) != 1 {
return fmt.Errorf("expected one cluster in config, got %d", len(clusterNames))
}
userName := authContext.User
clusterName := clusterNames[0]
contextName := fmt.Sprintf("%s@%s", userName, clusterName)
// merge with current user credentials
err = auth.AddUser(cfg, *authContext)
if err != nil {
return err
}
err = auth.AddContext(cfg, contextName, clusterName, userName)
if err != nil {
return err
}
auth.SetCurrentContext(cfg, contextName)
mergedKubeconfig, err := yaml.Marshal(cfg)
if err != nil {
return err
}
// print kubeconfig
fmt.Println(string(mergedKubeconfig))
return nil
}
type sshkeypair struct {
privatekey []byte
publickey []byte
}
func sshKeyPair(clusterID string) (*sshkeypair, error) {
request := cluster.NewGetSSHKeyPairParams()
request.SetID(clusterID)
credentials, err := cloud.Cluster.GetSSHKeyPair(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.GetSSHKeyPairDefault:
return nil, output.HTTPError(e.Payload)
default:
return nil, output.UnconventionalError(err)
}
}
privateKey, err := base64.StdEncoding.DecodeString(*credentials.Payload.SSHKeyPair.PrivateKey)
if err != nil {
return nil, err
}
publicKey, err := base64.StdEncoding.DecodeString(*credentials.Payload.SSHKeyPair.PublicKey)
if err != nil {
return nil, err
}
return &sshkeypair{
privatekey: privateKey,
publickey: publicKey,
}, nil
}
func reconcileCluster(args []string) error {
ci, err := clusterID("reconcile", args)
if err != nil {
return err
}
request := cluster.NewReconcileClusterParams()
request.SetID(ci)
shoot, err := cloud.Cluster.ReconcileCluster(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.ReconcileClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(shoot.Payload)
}
func updateCluster(args []string) error {
ci, err := clusterID("update", args)
if err != nil {
return err
}
minsize := viper.GetInt32("minsize")
maxsize := viper.GetInt32("maxsize")
version := viper.GetString("version")
firewallType := viper.GetString("firewalltype")
firewallImage := viper.GetString("firewallimage")
machineType := viper.GetString("machinetype")
machineImageAndVersion := viper.GetString("machineimage")
purpose := viper.GetString("purpose")
addLabels := viper.GetStringSlice("addlabels")
removeLabels := viper.GetStringSlice("removelabels")
request := cluster.NewUpdateClusterParams()
cur := &models.V1ClusterUpdateRequest{
ID: &ci,
}
worker := &models.V1Worker{}
cur.Workers = append(cur.Workers, worker)
if minsize != 0 || maxsize != 0 {
if minsize != 0 {
cur.Workers[0].Minimum = &minsize
}
if maxsize != 0 {
cur.Workers[0].Maximum = &maxsize
}
}
machineImage := models.V1MachineImage{}
if machineImageAndVersion != "" {
machineImageParts := strings.Split(machineImageAndVersion, "-")
if len(machineImageParts) == 2 {
machineImage = models.V1MachineImage{
Name: &machineImageParts[0],
Version: &machineImageParts[1],
}
} else {
log.Fatalf("given machineimage:%s is invalid must be in the form <name>-<version>", machineImageAndVersion)
}
cur.Workers[0].MachineImage = &machineImage
}
if machineType != "" {
cur.Workers[0].MachineType = &machineType
}
if firewallImage != "" {
cur.FirewallImage = &firewallImage
}
if firewallType != "" {
cur.FirewallSize = &firewallType
}
if purpose != "" {
cur.Purpose = &purpose
}
if len(addLabels) > 0 || len(removeLabels) > 0 {
findRequest := cluster.NewFindClusterParams()
findRequest.SetID(ci)
shoot, err := cloud.Cluster.FindCluster(findRequest, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
labelMap := shoot.Payload.Shoot.Metadata.Labels
for _, l := range removeLabels {
parts := strings.SplitN(l, "=", 2)
delete(labelMap, parts[0])
}
for _, l := range addLabels {
parts := strings.SplitN(l, "=", 2)
if len(parts) != 2 {
log.Fatalf("provided labels must be in the form <key>=<value>, found: %s", l)
}
labelMap[parts[0]] = parts[1]
}
cur.Labels = labelMap
}
k8s := &models.V1Kubernetes{}
if version != "" {
k8s.Version = &version
}
if viper.IsSet("allowprivileged") {
if !viper.GetBool("i-am-aware-of-dangerous-settings") {
return fmt.Errorf("allowprivileged is set but you forgot to add --i-am-aware-of-dangerous-settings")
}
allowPrivileged := viper.GetBool("allowprivileged")
k8s.AllowPrivilegedContainers = &allowPrivileged
}
cur.Kubernetes = k8s
request.SetBody(cur)
shoot, err := cloud.Cluster.UpdateCluster(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.UpdateClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(shoot.Payload)
}
func clusterDelete(args []string) error {
ci, err := clusterID("delete", args)
if err != nil {
return err
}
findRequest := cluster.NewFindClusterParams()
findRequest.SetID(ci)
resp, err := cloud.Cluster.FindCluster(findRequest, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
printer.Print(resp.Payload)
firstPartOfClusterID := strings.Split(resp.Payload.Shoot.Metadata.UID, "-")[0]
fmt.Println("Please answer some security questions to delete this cluster")
err = helper.Prompt("first part of clusterID:", firstPartOfClusterID)
if err != nil {
return err
}
err = helper.Prompt("Clustername:", resp.Payload.Shoot.Metadata.Name)
if err != nil {
return err
}
request := cluster.NewDeleteClusterParams()
request.SetID(ci)
c, err := cloud.Cluster.DeleteCluster(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.DeleteClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(c.Payload)
}
func clusterDescribe(args []string) error {
ci, err := clusterID("describe", args)
if err != nil {
return err
}
findRequest := cluster.NewFindClusterParams()
findRequest.SetID(ci)
shoot, err := cloud.Cluster.FindCluster(findRequest, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return printer.Print(shoot.Payload)
}
func clusterMachines(args []string) error {
ci, err := clusterID("machines", args)
if err != nil {
return err
}
findRequest := cluster.NewFindClusterParams()
findRequest.SetID(ci)
shoot, err := cloud.Cluster.FindCluster(findRequest, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
fmt.Println("Cluster:")
printer.Print(shoot.Payload)
// FIXME this is a ugly hack to reset the printer and have a new header.
printer, err = output.NewPrinter(
viper.GetString("output-format"),
viper.GetString("order"),
viper.GetString("template"),
viper.GetBool("no-headers"),
)
if err != nil {
log.Fatalf("unable to initialize printer:%v", err)
}
fmt.Println("\nMachines:")
return printer.Print(shoot.Payload.Machines)
}
func clusterLogs(args []string) error {
ci, err := clusterID("logs", args)
if err != nil {
return err
}
findRequest := cluster.NewFindClusterParams()
findRequest.SetID(ci)
shoot, err := cloud.Cluster.FindCluster(findRequest, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
var conditions []*models.V1beta1Condition
if shoot.Payload != nil && shoot.Payload.Shoot != nil && shoot.Payload.Shoot.Status != nil {
conditions = shoot.Payload.Shoot.Status.Conditions
}
return printer.Print(conditions)
}
func clusterInputs() error {
request := cluster.NewListConstraintsParams()
sc, err := cloud.Cluster.ListConstraints(request, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.ListConstraintsDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
return output.YAMLPrinter{}.Print(sc)
}
func clusterMachineSSH(args []string, console bool) error {
cid, err := clusterID("ssh", args)
if err != nil {
return err
}
mid := viper.GetString("machineid")
findRequest := cluster.NewFindClusterParams()
findRequest.SetID(cid)
shoot, err := cloud.Cluster.FindCluster(findRequest, cloud.Auth)
if err != nil {
switch e := err.(type) {
case *cluster.FindClusterDefault:
return output.HTTPError(e.Payload)
default:
return output.UnconventionalError(err)
}
}
keypair, err := sshKeyPair(cid)
if err != nil {
return err
}
for _, m := range shoot.Payload.Machines {
if *m.ID == mid {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("unable determine home directory:%v", err)
}
privateKeyFile := path.Join(home, "."+programName, "."+cid+".id_rsa")
err = ioutil.WriteFile(privateKeyFile, keypair.privatekey, 0600)
if err != nil {
return fmt.Errorf("unable to write private key:%s error:%v", privateKeyFile, err)
}
defer os.Remove(privateKeyFile)
if console {
fmt.Printf("access console via ssh\n")
bmcConsolePort := "5222"
err := ssh("-i", privateKeyFile, mid+"@"+cloud.ConsoleHost, "-p", bmcConsolePort)
return err
}
networks := m.Allocation.Networks
feature := m.Allocation.Image.Features[0]
switch feature {
case "firewall":
for _, nw := range networks {
if *nw.Underlay || *nw.Private {
continue
}
for _, ip := range nw.Ips {
if portOpen(ip, "22", time.Second) {
err := ssh("-i", privateKeyFile, "metal"+"@"+ip)
return err
}
}
}
case "machine":
// FIXME metal user is not allowed to execute
// ip vrf exec <tenantvrf> ssh <machineip>
return fmt.Errorf("machine access via ssh not implemented")
default:
return fmt.Errorf("unknown machine type:%s", feature)
}
}
}
return fmt.Errorf("machine:%s not found in cluster:%s", mid, cid)
}
func ssh(args ...string) error {
path, err := exec.LookPath("ssh")
if err != nil {
return fmt.Errorf("unable to locate ssh in path")
}
fmt.Printf("%s %s\n", path, strings.Join(args, " "))
cmd := exec.Command(path, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
return cmd.Run()
}
func portOpen(ip string, port string, timeout time.Duration) bool {
address := net.JoinHostPort(ip, port)
conn, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
return false
}
if conn != nil {
_ = conn.Close()
return true
}
return false
}
func clusterID(verb string, args []string) (string, error) {
if len(args) == 0 {
return "", fmt.Errorf("cluster %s requires clusterID as argument", verb)
}
if len(args) == 1 {
return args[0], nil