-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
main.go
905 lines (843 loc) · 26 KB
/
main.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
// Package main is the entrypoint of the compliance k8s_types_generator tool
// that is responsible for generating various configuration types of
// Kubernetes components.
package main
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
"unicode"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
bindir = ""
arch = ""
k8sComponents = []string{"kube-apiserver", "kube-scheduler", "kube-controller-manager", "kube-proxy", "kubelet"}
// https://kubernetes.io/releases/
k8sVersions = []string{
"v1.28.4",
"v1.27.3",
"v1.26.6",
"v1.25.11",
"v1.24.15",
}
// https://github.com/kubernetes/kubernetes/blob/c3e7eca7fd38454200819b60e58144d5727f1bbc/cluster/images/etcd/Makefile#L18
// "v3.0.17", "v3.1.20" removed because they do not have ARM64 tarballs
etcdVersions = []string{
"v3.5.10",
"v3.4.28",
"v3.3.17",
"v3.2.32",
}
knownFlags = []string{
// Make sure "--config" parsing is first as it implements the precedence rules
// between configuration and CLI args
"--config",
"--address",
"--admission-control-config-file",
"--allow-privileged",
"--anonymous-auth",
"--audit-log-maxage",
"--audit-log-maxbackup",
"--audit-log-maxsize",
"--audit-log-path",
"--audit-policy-file",
"--authentication-kubeconfig",
"--authorization-kubeconfig",
"--authorization-mode",
"--auto-tls",
"--bind-address",
"--cert-file",
"--client-ca-file",
"--client-cert-auth",
"--cluster-signing-cert-file",
"--cluster-signing-key-file",
"--data-dir",
"--disable-admission-plugins",
"--enable-admission-plugins",
"--enable-bootstrap-token-auth",
"--encryption-provider-config",
"--etcd-cafile",
"--etcd-certfile",
"--etcd-keyfile",
"--event-burst",
"--event-qps",
"--feature-gates",
"--hostname-override",
"--image-credential-provider-bin-dir",
"--image-credential-provider-config",
"--key-file",
"--kubeconfig",
"--kubelet-certificate-authority",
"--kubelet-client-certificate",
"--kubelet-client-key",
"--make-iptables-util-chains",
"--max-pods",
"--peer-auto-tls",
"--peer-cert-file",
"--peer-client-cert-auth",
"--peer-key-file",
"--peer-trusted-ca-file",
"--pod-max-pids",
"--profiling",
"--protect-kernel-defaults",
"--proxy-client-cert-file",
"--proxy-client-key-file",
"--read-only-port",
"--request-timeout",
"--requestheader-allowed-names",
"--requestheader-client-ca-file",
"--requestheader-extra-headers-prefix",
"--requestheader-group-headers",
"--requestheader-username-headers",
"--root-ca-file",
"--rotate-certificates",
"--rotate-server-certificates",
"--secure-port",
"--service-account-issuer",
"--service-account-key-file",
"--service-account-lookup",
"--service-account-private-key-file",
"--service-account-signing-key-file",
"--service-cluster-ip-range",
"--streaming-connection-idle-timeout",
"--terminated-pod-gc-threshold",
"--tls-cert-file",
"--tls-cipher-suites",
"--tls-min-version",
"--tls-private-key-file",
"--token-auth-file",
"--trusted-ca-file",
"--use-service-account-credentials",
}
// reference: https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletAuthentication
cliConfAssoc = map[string]string{
"kubelet.address": "address",
"kubelet.anonymous-auth": "authentication.anonymous.enabled",
"kubelet.authorization-mode": "authorization.mode",
"kubelet.client-ca-file": "authorization.x509.clientCAFile",
"kubelet.event-burst": "eventBurst",
"kubelet.event-qps": "eventRecordQPS",
"kubelet.feature-gates": "featureGates",
"kubelet.make-iptables-util-chains": "makeIPTablesUtilChains",
"kubelet.max-pods": "maxPods",
"kubelet.pod-max-pids": "podPidsLimit",
"kubelet.protect-kernel-defaults": "protectKernelDefaults",
"kubelet.read-only-port": "readOnlyPort",
"kubelet.rotate-certificates": "rotateCertificates",
"kubelet.rotate-server-certificates": "featureGates.RotateKubeletServerCertificate",
"kubelet.streaming-connection-idle-timeout": "streamingConnectionIdleTimeout",
"kubelet.tls-cert-file": "tlsCertFile",
"kubelet.tls-cipher-suites": "tlsCipherSuites",
"kubelet.tls-min-version": "tlsMinVersion",
"kubelet.tls-private-key-file": "tlsPrivateKeyFile",
"kube-scheduler.bind-address": "",
"kube-scheduler.profiling": "enableProfiling",
"kube-scheduler.contention-profiling": "enableContentionProfiling",
"kube-scheduler.requestheader-extra-headers-prefix": "",
"kube-scheduler.requestheader-group-headers": "",
"kube-scheduler.requestheader-username-headers": "",
"kube-scheduler.secure-port": "",
"kube-proxy.bind-address": "",
}
)
const preamble = `// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
// !!!
// This is a generated file: regenerate with go run ./pkg/compliance/tools/k8s_types_generator/main.go
// !!!
//revive:disable
package k8sconfig
import (
"time"
"strings"
)
`
type conf struct {
versions []string
flagName string
flagType string
flagDefault string
goType string
}
type komponent struct {
name string
version string
confs []*conf
}
// go run ./pkg/compliance/tools/k8s_types_generator/main.go ./pkg/compliance/tools/bin | gofmt > ./pkg/compliance/k8sconfig/types_generated.go
func main() {
dir, _ := os.Getwd()
if len(os.Args) < 2 {
fmt.Println("generator <bindir>")
log.Fatal("missing bindir path")
}
bindir = filepath.Join(dir, os.Args[1])
if info, err := os.Stat(bindir); err != nil || !info.IsDir() {
log.Fatalf("bindir path %s is not a directory", bindir)
}
uname, _ := exec.Command("uname", "-m").Output()
switch string(bytes.TrimSuffix(uname, []byte("\n"))) {
case "x86_64":
arch = "amd64"
case "aarch64":
arch = "arm64"
default:
log.Fatalf("could not resolve arch=%s", uname)
}
fmt.Print(preamble)
var allKomponents []*komponent
for _, component := range k8sComponents {
var komponents []*komponent
for _, version := range k8sVersions {
komp := downloadKubeComponentAndExtractFlags(component, version)
komponents = append(komponents, komp)
}
mergedKomp := unionKomponents(komponents...)
allKomponents = append(allKomponents, mergedKomp)
}
{
var komponents []*komponent
for _, version := range etcdVersions {
komp := downloadEtcdAndExtractFlags(version)
komponents = append(komponents, komp)
}
mergedKomp := unionKomponents(komponents...)
allKomponents = append(allKomponents, mergedKomp)
}
checkForKnownFlags(allKomponents, knownFlags)
for _, komp := range allKomponents {
sort.Slice(komp.confs, func(i, j int) bool {
ii := slices.Index(knownFlags, "--"+komp.confs[i].flagName)
jj := slices.Index(knownFlags, "--"+komp.confs[j].flagName)
return ii < jj
})
fmt.Println(printKomponentCode(komp))
}
}
func checkForKnownFlags(allKomponents []*komponent, knownFlags []string) {
var knownFlagsClone []string
knownFlagsClone = append(knownFlagsClone, knownFlags...)
for _, komponent := range allKomponents {
for _, conf := range komponent.confs {
i := slices.Index(knownFlagsClone, "--"+conf.flagName)
if i >= 0 {
knownFlagsClone = append(knownFlagsClone[:i], knownFlagsClone[i+1:]...)
}
}
}
if len(knownFlagsClone) > 0 {
panic(fmt.Errorf("these flags were not found: %v", knownFlagsClone))
}
}
func defaultedType(componentName string, conf *conf) *conf { //nolint:revive // TODO fix revive unused-parameter
if conf.flagName == "kubeconfig" || conf.flagName == "authentication-kubeconfig" {
conf.flagType = "kubeconfig"
} else if conf.flagType == "string" || conf.flagType == "stringArray" {
switch {
case strings.Contains(conf.flagName, "cert"),
strings.Contains(conf.flagName, "cafile"),
strings.Contains(conf.flagName, "ca-file"):
conf.flagType = "certificate_file"
case strings.HasSuffix(conf.flagName, "keyfile"),
strings.HasSuffix(conf.flagName, "key-file"),
strings.HasSuffix(conf.flagName, "key"):
conf.flagType = "key_file"
case strings.Contains(conf.flagName, "token"):
conf.flagType = "token_file"
case conf.flagName == "encryption-provider-config":
conf.flagType = "encryption_config_file"
case conf.flagName == "admission-control-config-file":
conf.flagType = "admission_config_file"
case conf.flagName == "config", conf.flagName == "audit-policy-file", conf.flagName == "image-credential-provider-config":
conf.flagType = "config_file"
case strings.Contains(conf.flagName, "dir"):
conf.flagType = "dir"
}
}
switch conf.flagType {
case "bool":
conf.flagDefault = parseTypeBool(conf.flagDefault)
conf.goType = "bool"
case "cidrs":
conf.flagDefault = parseTypeCIDRs(conf.flagDefault)
conf.goType = "string"
case "duration":
conf.flagDefault = parseTypeDuration(conf.flagDefault)
conf.goType = "time.Duration"
case "float", "float32":
conf.flagDefault = parseTypeFloat(conf.flagDefault)
conf.goType = "float64"
case "int", "int32", "quantity", "uint":
conf.flagDefault = parseTypeNumber(conf.flagDefault)
conf.goType = "int"
case "ip", "ipport":
conf.flagDefault = parseTypeIP(conf.flagDefault)
conf.goType = "string"
case "mapStringBool":
conf.flagDefault = parseEmptyDefault(conf.flagDefault)
conf.goType = "string"
case "mapStringString":
conf.flagDefault = parseEmptyDefault(conf.flagDefault)
conf.goType = "string"
case "namedCertKey":
conf.flagDefault = parseEmptyDefault(conf.flagDefault)
conf.goType = "string"
case "portRange":
conf.flagDefault = parseTypeRange(conf.flagDefault)
conf.goType = "string"
case "severity":
conf.flagDefault = parseTypeNumber(conf.flagDefault)
conf.goType = "int"
case "string",
"LocalMode", "ProxyMode", "RuntimeDefault": // https://kubernetes.io/docs/reference/config-api/kube-proxy-config.v1alpha1/#kubeproxy-config-k8s-io-v1alpha1-LocalMode
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "string"
case "kubeconfig":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sKubeconfigMeta"
case "certificate_file":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sCertFileMeta"
case "key_file":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sKeyFileMeta"
case "config_file":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sConfigFileMeta"
case "admission_config_file":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sAdmissionConfigFileMeta"
case "encryption_config_file":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sEncryptionProviderConfigFileMeta"
case "token_file":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sTokenFileMeta"
case "dir":
conf.flagDefault = parseTypeString(conf.flagDefault)
conf.goType = "*K8sDirMeta"
case "strings", "moduleSpec":
conf.flagDefault = parseTypeStringsArray(conf.flagDefault)
conf.goType = "[]string"
case "stringToString", "stringArray":
conf.flagDefault = parseEmptyDefault(conf.flagDefault)
conf.goType = "string"
case "traceLocation":
conf.flagDefault = parseEmptyDefault(conf.flagDefault)
conf.goType = "string"
case "colonSeparatedMultimapStringString":
// k8s.io/component-base/cli/flag
conf.flagDefault = parseEmptyDefault(conf.flagDefault)
conf.goType = "string"
}
if conf.flagDefault == "${name}.etcd" {
conf.flagDefault = ""
}
if conf.goType == "" {
log.Fatalf("unknown type for flag %q: %s (%q)", conf.flagName, conf.flagType, conf.flagDefault)
}
return conf
}
func unionKomponents(ks ...*komponent) *komponent {
var confs []*conf
for _, k := range ks {
for _, newConf := range k.confs {
var conf *conf
for _, c := range confs {
if c.flagName == newConf.flagName {
conf = c
}
}
if conf == nil {
confs = append(confs, newConf)
conf = newConf
} else {
if isKnownFlag(conf.flagName) && conf.flagType != newConf.flagType {
fmt.Fprintf(os.Stderr, "%s %s != %s\n", conf.flagName, conf.flagType, newConf.flagType)
panic("TODO: different types across versions")
}
if isKnownFlag(conf.flagName) && conf.flagDefault != newConf.flagDefault {
// special case for these flags for which the value itself is not important
if conf.flagName != "event-burst" && conf.flagName != "event-qps" {
fmt.Fprintf(os.Stderr, "%s %s != %s\n", conf.flagName, conf.flagDefault, newConf.flagDefault)
panic("TODO: different defaults across versions")
}
}
}
conf.versions = append(conf.versions, k.version)
}
}
sort.Slice(confs, func(i, j int) bool {
return strings.Compare(confs[i].flagName, confs[j].flagName) < 0
})
return &komponent{
name: ks[0].name,
version: ks[0].version,
confs: confs,
}
}
func printKomponentCode(komp *komponent) string {
printAssignment := func(c *conf, v string) string {
switch c.goType {
case "string", "ip":
return fmt.Sprintf("v := %s\nres.%s = &v", v, toGoField(c.flagName))
case "bool":
return fmt.Sprintf("res.%s = l.parseBool(%s)", toGoField(c.flagName), v)
case "float64":
return fmt.Sprintf("res.%s = l.parseFloat(%s, 64)", toGoField(c.flagName), v)
case "int", "uint":
return fmt.Sprintf("res.%s = l.parseInt(%s)", toGoField(c.flagName), v)
case "time.Duration":
return fmt.Sprintf("res.%s = l.parseDuration(%s)", toGoField(c.flagName), v)
case "[]string":
return fmt.Sprintf("res.%s = strings.Split(%s, \",\")", toGoField(c.flagName), v)
case "*K8sKubeconfigMeta":
return fmt.Sprintf("res.%s, _ = l.loadKubeconfigMeta(%s)", toGoField(c.flagName), v)
case "*K8sCertFileMeta":
return fmt.Sprintf("res.%s = l.loadCertFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sKeyFileMeta":
return fmt.Sprintf("res.%s = l.loadKeyFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sTokenFileMeta":
return fmt.Sprintf("res.%s = l.loadTokenFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sConfigFileMeta":
if komp.name == "kubelet" && c.flagName == "config" {
return fmt.Sprintf("res.%s = l.loadKubeletConfigFileMeta(%s)", toGoField(c.flagName), v)
}
return fmt.Sprintf("res.%s, _ = l.loadConfigFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sKubeletConfigFileMeta":
return fmt.Sprintf("res.%s = l.loadKubeletConfigFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sAdmissionConfigFileMeta":
return fmt.Sprintf("res.%s = l.loadAdmissionConfigFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sEncryptionProviderConfigFileMeta":
return fmt.Sprintf("res.%s = l.loadEncryptionProviderConfigFileMeta(%s)", toGoField(c.flagName), v)
case "*K8sDirMeta":
return fmt.Sprintf("res.%s = l.loadDirMeta(%s)", toGoField(c.flagName), v)
default:
panic(fmt.Errorf("non supported type %s %s %s %q for with default %s", komp.name, komp.version, c.flagName, c.goType, c.flagDefault))
}
}
titled := cases.Title(language.English, cases.NoLower).String(komp.name)
goStructName := strings.ReplaceAll(titled, "-", "")
s := ""
s += fmt.Sprintf("type K8s%sConfig struct {\n", goStructName)
for _, c := range komp.confs {
if !isKnownFlag(c.flagName) {
continue
}
goType := c.goType
if !strings.HasPrefix(goType, "*") && !strings.HasPrefix(goType, "[]") {
goType = "*" + goType
}
s += fmt.Sprintf(" %s %s `json:\"%s,omitempty\"` // versions: %s\n",
toGoField(c.flagName), goType, toGoJSONTag(c.flagName), strings.Join(c.versions, ", "))
}
s += " SkippedFlags map[string]string `json:\"skippedFlags,omitempty\"`\n"
s += "}\n"
s += fmt.Sprintf("func (l *loader) newK8s%sConfig(flags map[string]string) *K8s%sConfig {\n", goStructName, goStructName)
s += "if (flags == nil) { return nil }\n"
s += fmt.Sprintf("var res K8s%sConfig\n", goStructName)
for _, c := range komp.confs {
if !isKnownFlag(c.flagName) {
continue
}
s += fmt.Sprintf("if v, ok := flags[\"--%s\"]; ok {\n", c.flagName)
s += fmt.Sprintf("delete(flags, \"--%s\")\n", c.flagName)
s += printAssignment(c, "v") + "\n"
if c.flagDefault != "" {
// kube-apiserver and etcd components do not have any configuration file.
if komp.name != "kube-apiserver" && komp.name != "etcd" && komp.name != "kube-controller-manager" {
configCursor, ok := cliConfAssoc[komp.name+"."+c.flagName]
// Some components can be configured with both cli-args and a
// configuration file. We need to make sure the default value
// of a cli-args is filled only if the associated
// configuration in the config file is not setup.
if !ok {
panic(fmt.Errorf("missing %s configuration associated path to flag %q (default = %q)", komp.name, c.flagName, c.flagDefault))
}
if configCursor != "" {
s += fmt.Sprintf("\n} else if !l.configFileMetaHasField(res.Config, %q) {\n", configCursor)
} else {
s += "\n} else {\n"
}
} else {
s += "\n} else {\n"
}
s += printAssignment(c, fmt.Sprintf("%q", c.flagDefault))
}
s += "}\n"
}
s += "if len(flags) > 0 { res.SkippedFlags = flags }\n"
s += "return &res\n"
s += "}\n"
return s
}
func downloadEtcdAndExtractFlags(componentVersion string) *komponent {
const componentName = "etcd"
componentBin := path.Join(bindir, fmt.Sprintf("%s-%s", componentName, componentVersion))
componentTar := path.Join(bindir, fmt.Sprintf("%s-%s.tar.gz", componentName, componentVersion))
componentURL := fmt.Sprintf("https://github.com/etcd-io/etcd/releases/download/%s/etcd-%s-linux-%s.tar.gz",
componentVersion, componentVersion, arch)
if _, err := os.Stat(componentBin); os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "downloading %s into %s...", componentURL, componentBin)
if err := download(componentURL, componentTar); err != nil {
log.Fatal(err)
}
t, err := os.Open(componentTar)
if err != nil {
log.Fatal(err)
}
defer t.Close()
g, err := gzip.NewReader(t)
if err != nil {
log.Fatal(err)
}
r := tar.NewReader(g)
for {
header, err := r.Next()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if header.Typeflag == tar.TypeReg && strings.HasSuffix(header.Name, "/etcd") {
outFile, err := os.Create(componentBin)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(outFile, r); err != nil {
log.Fatal(err)
}
outFile.Close()
}
}
fmt.Fprintf(os.Stderr, "ok\n")
}
if err := os.Chmod(componentBin, 0770); err != nil {
log.Fatal(err)
}
cmd := exec.Command(componentBin, "-h")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "ETCD_UNSUPPORTED_ARCH=arm64")
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
var confs []*conf
scanner := bufio.NewScanner(bytes.NewReader(out))
for scanner.Scan() {
line := scanner.Text()
conf, ok := scanEtcdHelpLine(line)
if ok {
confs = append(confs, defaultedType(componentName, conf))
}
}
return &komponent{
name: componentName,
version: componentVersion,
confs: confs,
}
}
func downloadKubeComponentAndExtractFlags(componentName, componentVersion string) *komponent {
componentBin := path.Join(bindir, fmt.Sprintf("%s-%s", componentName, componentVersion))
componentURL := fmt.Sprintf("https://dl.k8s.io/%s/bin/linux/%s/%s",
componentVersion, arch, componentName)
if _, err := os.Stat(componentBin); os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "downloading %s into %s...", componentURL, componentBin)
if err := download(componentURL, componentBin); err != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stderr, "ok\n")
}
if err := os.Chmod(componentBin, 0770); err != nil {
log.Fatal(err)
}
cmd := exec.Command(componentBin, "-h")
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
var confs []*conf
scanner := bufio.NewScanner(bytes.NewReader(out))
for scanner.Scan() {
line := scanner.Text()
conf, ok := scanK8sHelpLine(line)
if ok {
confs = append(confs, defaultedType(componentName, conf))
}
}
return &komponent{
name: componentName,
version: componentVersion,
confs: confs,
}
}
func toGoField(s string) string {
caser := cases.Title(language.English, cases.NoLower)
return strings.ReplaceAll(caser.String(s), "-", "")
}
func toGoJSONTag(s string) string {
return s
}
func scanEtcdHelpLine(line string) (*conf, bool) {
var conf conf
var ok bool
str := eatWhitespace(line)
conf.flagName, str, ok = eatRegexp(str, "--([a-zA-Z0-9-]+)", 1)
if !ok {
return nil, false
}
if conf.flagName == "log-rotation-config-json" { // json flag
return nil, false
}
if strings.HasPrefix(conf.flagName, "experimental-") {
return nil, false
}
str = eatWhitespace(str)
if str == "" {
conf.flagDefault = "false"
conf.flagType = "bool"
return &conf, true
}
conf.flagDefault, str, ok = eatRegexp(str, "'(true|false)'", 1)
if ok {
conf.flagType = "bool"
conf.goType = "bool"
return &conf, true
}
conf.flagDefault, str, ok = eatRegexp(str, "([0-9]+)", 1)
if ok {
conf.flagType = "int"
conf.goType = "int"
return &conf, true
}
conf.flagDefault, _, ok = eatRegexp(str, "'(\\S*)'", 1)
if ok {
conf.flagType = "string"
conf.goType = "string"
return &conf, true
}
log.Fatalf("could not flag line: %s", line)
return nil, false
}
func scanK8sHelpLine(line string) (*conf, bool) {
var conf conf
var ok bool
str := eatWhitespace(line)
conf.flagName, str, ok = eatRegexp(str, "--([a-zA-Z0-9-]+)", 1)
if !ok {
return nil, false
}
str = eatWhitespace(str)
conf.flagType, str, ok = eatRegexp(str, "([a-zA-Z0-9]+)[ ]{3,}", 1)
if ok {
str = eatWhitespace(str)
}
if idx := strings.Index(str, "[default="); idx >= 0 {
conf.flagDefault = scanDefaultValue(str[idx+len("[default="):], '[', ']')
} else if idx := strings.Index(str, "[default "); idx >= 0 {
conf.flagDefault = scanDefaultValue(str[idx+len("[default "):], '[', ']')
} else if idx := strings.Index(str, "(default "); idx >= 0 {
conf.flagDefault = scanDefaultValue(str[idx+len("(default "):], '(', ')')
}
if conf.flagType == "" {
conf.flagType = "bool"
}
return &conf, true
}
func scanDefaultValue(str string, op, cl rune) string {
var length int
balance := 1
for _, r := range str {
if r == op {
balance++
} else if r == cl {
balance--
}
length++
if balance == 0 {
break
}
}
val := str[:length]
val = strings.TrimPrefix(val, string(op)+"default")
val = strings.TrimSuffix(val, string(cl))
return strings.TrimSpace(val)
}
func parseTypeBool(str string) string {
if str == "" {
return ""
}
b, err := strconv.ParseBool(str)
if err != nil {
log.Fatal(err)
}
if b {
return "true"
}
return "false"
}
func parseTypeCIDRs(str string) string {
var cidrs []string
for _, s := range strings.Split(str, ",") {
s = strings.TrimSpace(s)
_, _, err := net.ParseCIDR(s)
if err != nil {
log.Fatal(err)
}
cidrs = append(cidrs, s)
}
return strings.Join(cidrs, ",")
}
func parseTypeDuration(str string) string {
if str == "" {
return ""
}
_, err := time.ParseDuration(str)
if err != nil {
log.Fatal(err)
}
return str
}
func parseTypeFloat(str string) string {
if str == "" {
return ""
}
_, err := strconv.ParseFloat(str, 64)
if err != nil {
log.Fatal(err)
}
return str
}
func parseTypeNumber(str string) string {
if str == "" {
return ""
}
_, err := strconv.Atoi(str)
if err != nil {
log.Fatal(err)
}
return str
}
func parseTypeIP(str string) string {
ip := net.ParseIP(str)
return ip.String()
}
func parseTypeRange(str string) string {
r := regexp.MustCompile("^[0-9]+-[0-9]+$")
if !r.MatchString(str) {
log.Fatalf("bad range type default %q", str)
}
return str
}
func parseTypeString(str string) string {
if strings.HasPrefix(str, "\"") {
if !strings.HasSuffix(str, "\"") {
log.Fatalf("bad string type default %q", str)
}
return str[1 : len(str)-1]
}
if strings.HasPrefix(str, "'") {
if !strings.HasSuffix(str, "'") {
log.Fatalf("bad string type default %q", str)
}
return str[1 : len(str)-1]
}
return str
}
func parseTypeStringsArray(str string) string {
if strings.HasPrefix(str, "[") {
if !strings.HasSuffix(str, "]") {
log.Fatalf("bad string type default %q", str)
}
str = str[1 : len(str)-1]
}
strs := strings.Split(str, ",")
for i, str := range strs {
strs[i] = strings.TrimSpace(str)
}
return strings.Join(strs, ",")
}
func parseEmptyDefault(str string) string {
if str == "imagefs.available<15%,memory.available<100Mi,nodefs.available<10%,nodefs.inodesFree<5%" {
// special case for deprecated flag with said default kubelet --eviction-hard
return ""
}
if str != "" && str != "[]" && str != "none" && str != ":0" {
log.Fatalf("bad empty type default %q", str)
}
return ""
}
func eatWhitespace(str string) string {
i := 0
for _, r := range str {
if !unicode.IsSpace(r) {
break
}
i++
}
return str[i:]
}
func eatRegexp(str, reg string, group int) (string, string, bool) {
r := regexp.MustCompile("^" + reg)
loc := r.FindStringSubmatchIndex(str)
if loc != nil {
if loc[0] != 0 {
panic("programmer error")
}
if len(loc)/2 < group {
panic("programmer error")
}
return str[loc[2*group]:loc[2*group+1]], str[loc[1]:], true
}
return "", str, false
}
func download(url, dist string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("could not download %s: err %d", url, resp.StatusCode)
}
f, err := os.Create(dist)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}
func isKnownFlag(flag string) bool {
for _, cisFlag := range knownFlags {
if "--"+flag == cisFlag {
return true
}
}
return false
}