Skip to content

Commit aa5f70d

Browse files
richabankerk8s-publishing-bot
authored andcommitted
Add flagz implementation and enablement in apiserver
Kubernetes-commit: da8dc433e9b5fb29f3cc91f79ed15f366addefd1
1 parent 35b7478 commit aa5f70d

File tree

5 files changed

+406
-0
lines changed

5 files changed

+406
-0
lines changed

zpages/features/kube_features.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ import (
2222
)
2323

2424
const (
25+
// owner: @richabanker
26+
// kep: https://kep.k8s.io/4828
27+
ComponentFlagz featuregate.Feature = "ComponentFlagz"
28+
2529
// owner: @richabanker
2630
// kep: https://kep.k8s.io/4827
2731
// alpha: v1.32
@@ -33,6 +37,9 @@ const (
3337

3438
func featureGates() map[featuregate.Feature]featuregate.VersionedSpecs {
3539
return map[featuregate.Feature]featuregate.VersionedSpecs{
40+
ComponentFlagz: {
41+
{Version: version.MustParse("1.32"), Default: false, PreRelease: featuregate.Alpha},
42+
},
3643
ComponentStatusz: {
3744
{Version: version.MustParse("1.32"), Default: false, PreRelease: featuregate.Alpha},
3845
},

zpages/flagz/flagreader.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Copyright 2024 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package flagz
18+
19+
import (
20+
"github.com/spf13/pflag"
21+
cliflag "k8s.io/component-base/cli/flag"
22+
)
23+
24+
type Reader interface {
25+
GetFlagz() map[string]string
26+
}
27+
28+
// NamedFlagSetsGetter implements Reader for cliflag.NamedFlagSets
29+
type NamedFlagSetsReader struct {
30+
FlagSets cliflag.NamedFlagSets
31+
}
32+
33+
func (n NamedFlagSetsReader) GetFlagz() map[string]string {
34+
return convertNamedFlagSetToFlags(&n.FlagSets)
35+
}
36+
37+
func convertNamedFlagSetToFlags(flagSets *cliflag.NamedFlagSets) map[string]string {
38+
flags := make(map[string]string)
39+
for _, fs := range flagSets.FlagSets {
40+
fs.VisitAll(func(flag *pflag.Flag) {
41+
if flag.Value != nil {
42+
value := flag.Value.String()
43+
if set, ok := flag.Annotations["classified"]; ok && len(set) > 0 {
44+
value = "CLASSIFIED"
45+
}
46+
flags[flag.Name] = value
47+
}
48+
})
49+
}
50+
51+
return flags
52+
}

zpages/flagz/flagreader_test.go

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/*
2+
Copyright 2024 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package flagz
18+
19+
import (
20+
"reflect"
21+
"testing"
22+
23+
"github.com/spf13/pflag"
24+
25+
"k8s.io/component-base/cli/flag"
26+
)
27+
28+
func TestConvertNamedFlagSetToFlags(t *testing.T) {
29+
tests := []struct {
30+
name string
31+
flagSets *flag.NamedFlagSets
32+
want map[string]string
33+
}{
34+
{
35+
name: "basic flags",
36+
flagSets: &flag.NamedFlagSets{
37+
FlagSets: map[string]*pflag.FlagSet{
38+
"test": flagSet(t, map[string]flagValue{
39+
"flag1": {value: "value1", sensitive: false},
40+
"flag2": {value: "value2", sensitive: false},
41+
}),
42+
},
43+
},
44+
want: map[string]string{
45+
"flag1": "value1",
46+
"flag2": "value2",
47+
},
48+
},
49+
{
50+
name: "classified flags",
51+
flagSets: &flag.NamedFlagSets{
52+
FlagSets: map[string]*pflag.FlagSet{
53+
"test": flagSet(t, map[string]flagValue{
54+
"secret1": {value: "value1", sensitive: true},
55+
"flag2": {value: "value2", sensitive: false},
56+
}),
57+
},
58+
},
59+
want: map[string]string{
60+
"flag2": "value2",
61+
"secret1": "CLASSIFIED",
62+
},
63+
},
64+
}
65+
66+
for _, tt := range tests {
67+
t.Run(tt.name, func(t *testing.T) {
68+
got := convertNamedFlagSetToFlags(tt.flagSets)
69+
if !reflect.DeepEqual(got, tt.want) {
70+
t.Errorf("ConvertNamedFlagSetToFlags() = %v, want %v", got, tt.want)
71+
}
72+
})
73+
}
74+
}
75+
76+
type flagValue struct {
77+
value string
78+
sensitive bool
79+
}
80+
81+
func flagSet(t *testing.T, flags map[string]flagValue) *pflag.FlagSet {
82+
fs := pflag.NewFlagSet("test-set", pflag.ContinueOnError)
83+
for flagName, flagVal := range flags {
84+
flagValue := ""
85+
fs.StringVar(&flagValue, flagName, flagVal.value, "test-usage")
86+
if flagVal.sensitive {
87+
err := fs.SetAnnotation(flagName, "classified", []string{"true"})
88+
if err != nil {
89+
t.Fatalf("unexpected error when setting flag annotation: %v", err)
90+
}
91+
}
92+
}
93+
94+
return fs
95+
}

zpages/flagz/flagz.go

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
/*
2+
Copyright 2024 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package flagz
18+
19+
import (
20+
"bytes"
21+
"fmt"
22+
"io"
23+
"math/rand"
24+
"net/http"
25+
"sort"
26+
"strings"
27+
"sync"
28+
29+
"github.com/munnerz/goautoneg"
30+
31+
"k8s.io/klog/v2"
32+
)
33+
34+
const (
35+
flagzHeaderFmt = `
36+
%s flags
37+
Warning: This endpoint is not meant to be machine parseable, has no formatting compatibility guarantees and is for debugging purposes only.
38+
39+
`
40+
)
41+
42+
var (
43+
flagzSeparators = []string{":", ": ", "=", " "}
44+
errUnsupportedMediaType = fmt.Errorf("media type not acceptable, must be: text/plain")
45+
)
46+
47+
type registry struct {
48+
response bytes.Buffer
49+
once sync.Once
50+
}
51+
52+
type mux interface {
53+
Handle(path string, handler http.Handler)
54+
}
55+
56+
func Install(m mux, componentName string, flagReader Reader) {
57+
var reg registry
58+
reg.installHandler(m, componentName, flagReader)
59+
}
60+
61+
func (reg *registry) installHandler(m mux, componentName string, flagReader Reader) {
62+
m.Handle("/flagz", reg.handleFlags(componentName, flagReader))
63+
}
64+
65+
func (reg *registry) handleFlags(componentName string, flagReader Reader) http.HandlerFunc {
66+
return func(w http.ResponseWriter, r *http.Request) {
67+
if !acceptableMediaType(r) {
68+
http.Error(w, errUnsupportedMediaType.Error(), http.StatusNotAcceptable)
69+
return
70+
}
71+
72+
reg.once.Do(func() {
73+
fmt.Fprintf(&reg.response, flagzHeaderFmt, componentName)
74+
if flagReader == nil {
75+
klog.Error("received nil flagReader")
76+
return
77+
}
78+
79+
randomIndex := rand.Intn(len(flagzSeparators))
80+
separator := flagzSeparators[randomIndex]
81+
// Randomize the delimiter for printing to prevent scraping of the response.
82+
printSortedFlags(&reg.response, flagReader.GetFlagz(), separator)
83+
})
84+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
85+
_, err := w.Write(reg.response.Bytes())
86+
if err != nil {
87+
klog.Errorf("error writing response: %v", err)
88+
http.Error(w, "error writing response", http.StatusInternalServerError)
89+
}
90+
}
91+
}
92+
93+
func acceptableMediaType(r *http.Request) bool {
94+
accepts := goautoneg.ParseAccept(r.Header.Get("Accept"))
95+
for _, accept := range accepts {
96+
if !mediaTypeMatches(accept) {
97+
continue
98+
}
99+
if len(accept.Params) == 0 {
100+
return true
101+
}
102+
if len(accept.Params) == 1 {
103+
if charset, ok := accept.Params["charset"]; ok && strings.EqualFold(charset, "utf-8") {
104+
return true
105+
}
106+
}
107+
}
108+
return false
109+
}
110+
111+
func mediaTypeMatches(a goautoneg.Accept) bool {
112+
return (a.Type == "text" || a.Type == "*") &&
113+
(a.SubType == "plain" || a.SubType == "*")
114+
}
115+
116+
func printSortedFlags(w io.Writer, flags map[string]string, separator string) {
117+
var sortedKeys []string
118+
for key := range flags {
119+
sortedKeys = append(sortedKeys, key)
120+
}
121+
122+
sort.Strings(sortedKeys)
123+
for _, key := range sortedKeys {
124+
fmt.Fprintf(w, "%s%s%s\n", key, separator, flags[key])
125+
}
126+
}

0 commit comments

Comments
 (0)