Skip to content

Commit 4d969ac

Browse files
authored
Merge pull request kubernetes#99257 from chenyw1990/fixedLogFormatJsonPanic
fix json log format panic, change the flag name in flagIsSet
2 parents d51f243 + edff740 commit 4d969ac

File tree

5 files changed

+83
-18
lines changed

5 files changed

+83
-18
lines changed

cmd/kube-apiserver/app/options/globalflags_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ func TestAddCustomGlobalFlags(t *testing.T) {
3636
// flag set. This allows us to test against all global flags from
3737
// flags.CommandLine.
3838
nfs := namedFlagSets.FlagSet("test")
39+
nfs.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)
3940
globalflag.AddGlobalFlags(nfs, "test-cmd")
4041
AddCustomGlobalFlags(nfs)
4142

@@ -46,11 +47,11 @@ func TestAddCustomGlobalFlags(t *testing.T) {
4647

4748
// Get all flags from flags.CommandLine, except flag `test.*`.
4849
wantedFlag := []string{"help"}
49-
pflag.CommandLine.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)
5050
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
51+
normalizeFunc := nfs.GetNormalizeFunc()
5152
pflag.VisitAll(func(flag *pflag.Flag) {
5253
if !strings.Contains(flag.Name, "test.") {
53-
wantedFlag = append(wantedFlag, flag.Name)
54+
wantedFlag = append(wantedFlag, string(normalizeFunc(nfs, flag.Name)))
5455
}
5556
})
5657
sort.Strings(wantedFlag)

pkg/kubelet/apis/config/validation/validation_test.go

+45
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2424
utilerrors "k8s.io/apimachinery/pkg/util/errors"
25+
componentbaseconfig "k8s.io/component-base/config"
2526
kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config"
2627
)
2728

@@ -106,6 +107,50 @@ func TestValidateKubeletConfiguration(t *testing.T) {
106107
t.Errorf("expect no errors, got %v", allErrors)
107108
}
108109

110+
successCase3 := &kubeletconfig.KubeletConfiguration{
111+
CgroupsPerQOS: true,
112+
EnforceNodeAllocatable: []string{"pods"},
113+
SystemReservedCgroup: "",
114+
KubeReservedCgroup: "",
115+
SystemCgroups: "",
116+
CgroupRoot: "",
117+
EventBurst: 10,
118+
EventRecordQPS: 5,
119+
HealthzPort: 10248,
120+
ImageGCHighThresholdPercent: 85,
121+
ImageGCLowThresholdPercent: 80,
122+
IPTablesDropBit: 15,
123+
IPTablesMasqueradeBit: 14,
124+
KubeAPIBurst: 10,
125+
KubeAPIQPS: 5,
126+
MaxOpenFiles: 1000000,
127+
MaxPods: 110,
128+
OOMScoreAdj: -999,
129+
PodsPerCore: 100,
130+
Port: 65535,
131+
ReadOnlyPort: 0,
132+
RegistryBurst: 10,
133+
RegistryPullQPS: 5,
134+
HairpinMode: kubeletconfig.PromiscuousBridge,
135+
NodeLeaseDurationSeconds: 1,
136+
CPUCFSQuotaPeriod: metav1.Duration{Duration: 50 * time.Millisecond},
137+
ReservedSystemCPUs: "0-3",
138+
TopologyManagerScope: kubeletconfig.ContainerTopologyManagerScope,
139+
TopologyManagerPolicy: kubeletconfig.NoneTopologyManagerPolicy,
140+
ShutdownGracePeriod: metav1.Duration{Duration: 10 * time.Minute},
141+
ShutdownGracePeriodCriticalPods: metav1.Duration{Duration: 0},
142+
FeatureGates: map[string]bool{
143+
"CustomCPUCFSQuotaPeriod": true,
144+
"GracefulNodeShutdown": true,
145+
},
146+
Logging: componentbaseconfig.LoggingConfiguration{
147+
Format: "json",
148+
},
149+
}
150+
if allErrors := ValidateKubeletConfiguration(successCase3); allErrors != nil {
151+
t.Errorf("expect no errors, got %v", allErrors)
152+
}
153+
109154
errorCase1 := &kubeletconfig.KubeletConfiguration{
110155
CgroupsPerQOS: false,
111156
EnforceNodeAllocatable: []string{"pods", "system-reserved", "kube-reserved", "illegal-key"},

staging/src/k8s.io/component-base/cli/globalflag/globalflags.go

+4-9
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"flag"
2121
"fmt"
2222
"os"
23-
"strings"
2423

2524
"github.com/spf13/pflag"
2625
"k8s.io/component-base/logs"
@@ -41,23 +40,19 @@ func AddGlobalFlags(fs *pflag.FlagSet, name string) {
4140
func addKlogFlags(fs *pflag.FlagSet) {
4241
local := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
4342
klog.InitFlags(local)
43+
normalizeFunc := fs.GetNormalizeFunc()
4444
local.VisitAll(func(fl *flag.Flag) {
45-
fl.Name = normalize(fl.Name)
45+
fl.Name = string(normalizeFunc(fs, fl.Name))
4646
fs.AddGoFlag(fl)
4747
})
4848
}
4949

50-
// normalize replaces underscores with hyphens
51-
// we should always use hyphens instead of underscores when registering component flags
52-
func normalize(s string) string {
53-
return strings.Replace(s, "_", "-", -1)
54-
}
55-
5650
// Register adds a flag to local that targets the Value associated with the Flag named globalName in flag.CommandLine.
5751
func Register(local *pflag.FlagSet, globalName string) {
5852
if f := flag.CommandLine.Lookup(globalName); f != nil {
5953
pflagFlag := pflag.PFlagFromGoFlag(f)
60-
pflagFlag.Name = normalize(pflagFlag.Name)
54+
normalizeFunc := local.GetNormalizeFunc()
55+
pflagFlag.Name = string(normalizeFunc(local, pflagFlag.Name))
6156
local.AddFlag(pflagFlag)
6257
} else {
6358
panic(fmt.Sprintf("failed to find flag in global flagset (flag): %s", globalName))

staging/src/k8s.io/component-base/cli/globalflag/globalflags_test.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,14 @@ import (
2424
"testing"
2525

2626
"github.com/spf13/pflag"
27+
2728
cliflag "k8s.io/component-base/cli/flag"
2829
)
2930

3031
func TestAddGlobalFlags(t *testing.T) {
3132
namedFlagSets := &cliflag.NamedFlagSets{}
3233
nfs := namedFlagSets.FlagSet("global")
34+
nfs.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)
3335
AddGlobalFlags(nfs, "test-cmd")
3436

3537
actualFlag := []string{}
@@ -40,9 +42,10 @@ func TestAddGlobalFlags(t *testing.T) {
4042
// Get all flags from flags.CommandLine, except flag `test.*`.
4143
wantedFlag := []string{"help"}
4244
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
45+
normalizeFunc := nfs.GetNormalizeFunc()
4346
pflag.VisitAll(func(flag *pflag.Flag) {
4447
if !strings.Contains(flag.Name, "test.") {
45-
wantedFlag = append(wantedFlag, normalize(flag.Name))
48+
wantedFlag = append(wantedFlag, string(normalizeFunc(nfs, flag.Name)))
4649
}
4750
})
4851
sort.Strings(wantedFlag)

staging/src/k8s.io/component-base/logs/options.go

+27-6
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ func NewOptions() *Options {
5757
func (o *Options) Validate() []error {
5858
errs := []error{}
5959
if o.LogFormat != defaultLogFormat {
60-
allFlags := unsupportedLoggingFlags()
60+
allFlags := unsupportedLoggingFlags(hyphensToUnderscores)
6161
for _, fname := range allFlags {
62-
if flagIsSet(fname) {
62+
if flagIsSet(fname, hyphensToUnderscores) {
6363
errs = append(errs, fmt.Errorf("non-default logging format doesn't honor flag: %s", fname))
6464
}
6565
}
@@ -70,11 +70,23 @@ func (o *Options) Validate() []error {
7070
return errs
7171
}
7272

73-
func flagIsSet(name string) bool {
73+
// hyphensToUnderscores replaces hyphens with underscores
74+
// we should always use underscores instead of hyphens when validate flags
75+
func hyphensToUnderscores(s string) string {
76+
return strings.Replace(s, "-", "_", -1)
77+
}
78+
79+
func flagIsSet(name string, normalizeFunc func(name string) string) bool {
7480
f := flag.Lookup(name)
7581
if f != nil {
7682
return f.DefValue != f.Value.String()
7783
}
84+
if normalizeFunc != nil {
85+
f = flag.Lookup(normalizeFunc(name))
86+
if f != nil {
87+
return f.DefValue != f.Value.String()
88+
}
89+
}
7890
pf := pflag.Lookup(name)
7991
if pf != nil {
8092
return pf.DefValue != pf.Value.String()
@@ -84,7 +96,12 @@ func flagIsSet(name string) bool {
8496

8597
// AddFlags add logging-format flag
8698
func (o *Options) AddFlags(fs *pflag.FlagSet) {
87-
unsupportedFlags := fmt.Sprintf("--%s", strings.Join(unsupportedLoggingFlags(), ", --"))
99+
normalizeFunc := func(name string) string {
100+
f := fs.GetNormalizeFunc()
101+
return string(f(fs, name))
102+
}
103+
104+
unsupportedFlags := fmt.Sprintf("--%s", strings.Join(unsupportedLoggingFlags(normalizeFunc), ", --"))
88105
formats := fmt.Sprintf(`"%s"`, strings.Join(logRegistry.List(), `", "`))
89106
fs.StringVar(&o.LogFormat, logFormatFlagName, defaultLogFormat, fmt.Sprintf("Sets the log format. Permitted formats: %s.\nNon-default formats don't honor these flags: %s.\nNon-default choices are currently alpha and subject to change without warning.", formats, unsupportedFlags))
90107

@@ -109,15 +126,19 @@ func (o *Options) Get() (logr.Logger, error) {
109126
return logRegistry.Get(o.LogFormat)
110127
}
111128

112-
func unsupportedLoggingFlags() []string {
129+
func unsupportedLoggingFlags(normalizeFunc func(name string) string) []string {
113130
allFlags := []string{}
114131

115132
// k8s.io/klog flags
116133
fs := &flag.FlagSet{}
117134
klog.InitFlags(fs)
118135
fs.VisitAll(func(flag *flag.Flag) {
119136
if _, found := supportedLogsFlags[flag.Name]; !found {
120-
allFlags = append(allFlags, strings.Replace(flag.Name, "_", "-", -1))
137+
name := flag.Name
138+
if normalizeFunc != nil {
139+
name = normalizeFunc(name)
140+
}
141+
allFlags = append(allFlags, name)
121142
}
122143
})
123144

0 commit comments

Comments
 (0)