Skip to content

Commit d7d5ef2

Browse files
committed
lint fixes and privatize
1 parent 6f0d7a4 commit d7d5ef2

File tree

11 files changed

+394
-272
lines changed

11 files changed

+394
-272
lines changed

exp/metric-gen/metric/generator.go renamed to exp/metric-gen/generator/generator.go

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
16-
package metric
16+
package generator
1717

1818
import (
1919
"fmt"
@@ -23,20 +23,34 @@ import (
2323
"sigs.k8s.io/controller-tools/pkg/crd"
2424
"sigs.k8s.io/controller-tools/pkg/genall"
2525
"sigs.k8s.io/controller-tools/pkg/loader"
26-
"sigs.k8s.io/controller-tools/pkg/markers"
26+
ctrlmarkers "sigs.k8s.io/controller-tools/pkg/markers"
2727

28+
"k8s.io/kube-state-metrics/v2/exp/metric-gen/markers"
2829
"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
2930
)
3031

31-
type Generator struct{}
32+
// CustomResourceConfigGenerator implements the Generator interface from controller-tools.
33+
// It uses markers to generate a custom resource configuration for kube-state-metrics from go code.
34+
type CustomResourceConfigGenerator struct{}
3235

33-
func (Generator) CheckFilter() loader.NodeFilter {
34-
// Re-use controller-tools filter to filter out unrelated nodes that aren't used
35-
// in CRD generation, like interfaces and struct fields without JSON tag.
36-
return crd.Generator{}.CheckFilter()
36+
var _ genall.Generator = &CustomResourceConfigGenerator{}
37+
var _ genall.NeedsTypeChecking = &CustomResourceConfigGenerator{}
38+
39+
// RegisterMarkers registers all markers needed by this Generator
40+
// into the given registry.
41+
func (g CustomResourceConfigGenerator) RegisterMarkers(into *ctrlmarkers.Registry) error {
42+
for _, m := range markers.MarkerDefinitions {
43+
if err := m.Register(into); err != nil {
44+
return err
45+
}
46+
}
47+
48+
return nil
3749
}
3850

39-
func (g Generator) Generate(ctx *genall.GenerationContext) error {
51+
// Generate generates artifacts produced by this marker.
52+
// It's called *after* RegisterMarkers has been called.
53+
func (g CustomResourceConfigGenerator) Generate(ctx *genall.GenerationContext) error {
4054
// Create the parser which is specific to the metric generator.
4155
parser := newParser(
4256
&crd.Parser{
@@ -96,7 +110,7 @@ func (g Generator) Generate(ctx *genall.GenerationContext) error {
96110

97111
// Either a or b will not be the empty string, so we can compare them.
98112
var a, b string
99-
if metrics.Spec.Resources[i].MetricNamePrefix == nil {
113+
if metrics.Spec.Resources[i].MetricNamePrefix != nil {
100114
a = *metrics.Spec.Resources[i].MetricNamePrefix
101115
}
102116
if metrics.Spec.Resources[j].MetricNamePrefix != nil {
@@ -114,19 +128,20 @@ func (g Generator) Generate(ctx *genall.GenerationContext) error {
114128
return nil
115129
}
116130

131+
// CheckFilter indicates the loader.NodeFilter (if any) that should be used
132+
// to prune out unused types/packages when type-checking (nodes for which
133+
// the filter returns true are considered "interesting"). This filter acts
134+
// as a baseline -- all types the pass through this filter will be checked,
135+
// but more than that may also be checked due to other generators' filters.
136+
func (CustomResourceConfigGenerator) CheckFilter() loader.NodeFilter {
137+
// Re-use controller-tools filter to filter out unrelated nodes that aren't used
138+
// in CRD generation, like interfaces and struct fields without JSON tag.
139+
return crd.Generator{}.CheckFilter()
140+
}
141+
117142
// addCustomResourceStateKind adds the correct kind because we don't have a correct
118143
// kubernetes-style object as configuration definition.
119144
func addCustomResourceStateKind(obj map[string]interface{}) error {
120145
obj["kind"] = "CustomResourceStateMetrics"
121146
return nil
122147
}
123-
124-
func (g Generator) RegisterMarkers(into *markers.Registry) error {
125-
for _, m := range markerDefinitions {
126-
if err := m.Register(into); err != nil {
127-
return err
128-
}
129-
}
130-
131-
return nil
132-
}

exp/metric-gen/metric/parser.go renamed to exp/metric-gen/generator/parser.go

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
16-
package metric
16+
package generator
1717

1818
import (
1919
"fmt"
@@ -26,27 +26,28 @@ import (
2626
"k8s.io/klog/v2"
2727
"sigs.k8s.io/controller-tools/pkg/crd"
2828
"sigs.k8s.io/controller-tools/pkg/loader"
29-
"sigs.k8s.io/controller-tools/pkg/markers"
29+
ctrlmarkers "sigs.k8s.io/controller-tools/pkg/markers"
3030

31+
"k8s.io/kube-state-metrics/v2/exp/metric-gen/markers"
3132
"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
3233
)
3334

34-
type Parser struct {
35+
type parser struct {
3536
*crd.Parser
3637

3738
CustomResourceStates map[schema.GroupKind]customresourcestate.Resource
3839
FlattenedMetrics map[crd.TypeIdent][]customresourcestate.Metric
3940
}
4041

41-
func newParser(parser *crd.Parser) *Parser {
42-
return &Parser{
43-
Parser: parser,
42+
func newParser(p *crd.Parser) *parser {
43+
return &parser{
44+
Parser: p,
4445
CustomResourceStates: make(map[schema.GroupKind]customresourcestate.Resource),
4546
FlattenedMetrics: make(map[crd.TypeIdent][]customresourcestate.Metric),
4647
}
4748
}
4849

49-
func (p *Parser) NeedResourceFor(groupKind schema.GroupKind) {
50+
func (p *parser) NeedResourceFor(groupKind schema.GroupKind) {
5051
if _, exists := p.CustomResourceStates[groupKind]; exists {
5152
return
5253
}
@@ -61,9 +62,8 @@ func (p *Parser) NeedResourceFor(groupKind schema.GroupKind) {
6162

6263
resource := customresourcestate.Resource{
6364
GroupVersionKind: customresourcestate.GroupVersionKind{
64-
Group: groupKind.Group,
65-
Kind: groupKind.Kind,
66-
Version: "", // TODO
65+
Group: groupKind.Group,
66+
Kind: groupKind.Kind,
6767
},
6868
}
6969

@@ -74,9 +74,9 @@ func (p *Parser) NeedResourceFor(groupKind schema.GroupKind) {
7474
continue
7575
}
7676

77-
// Skip if namePrefix marker is not set to not create configuration for CRs used in other CRs.
78-
// e.g. to not create configuration for KubeadmControlPlaneTemplate.
79-
if m := typeInfo.Markers.Get(NameMarkerName); m == nil {
77+
// Skip if gvk marker is not set to not create configuration for CRs used in other CRs.
78+
// E.g. to not create configuration for KubeadmControlPlaneTemplate.
79+
if m := typeInfo.Markers.Get(markers.GVKMarkerName); m == nil {
8080
continue
8181
}
8282

@@ -101,7 +101,7 @@ func (p *Parser) NeedResourceFor(groupKind schema.GroupKind) {
101101

102102
for _, markerVals := range typeInfo.Markers {
103103
for _, val := range markerVals {
104-
if resourceMarker, isResourceMarker := val.(ResourceMarker); isResourceMarker {
104+
if resourceMarker, isResourceMarker := val.(markers.ResourceMarker); isResourceMarker {
105105
if err := resourceMarker.ApplyToResource(&resource); err != nil {
106106
pkg.AddError(loader.ErrFromNode(err /* an okay guess */, typeInfo.RawSpec))
107107
}
@@ -120,10 +120,10 @@ type generatorRequester interface {
120120
// generatorContext stores and provides information across a hierarchy of metric generators generation.
121121
type generatorContext struct {
122122
pkg *loader.Package
123-
info *markers.TypeInfo
123+
info *ctrlmarkers.TypeInfo
124124
generatorRequester generatorRequester
125125

126-
PackageMarkers markers.MarkerValues
126+
PackageMarkers ctrlmarkers.MarkerValues
127127
}
128128

129129
func newGeneratorContext(pkg *loader.Package, req generatorRequester) *generatorContext {
@@ -147,12 +147,12 @@ func (c *generatorContext) requestGenerator(pkgPath, typeName string) []customre
147147
})
148148
}
149149

150-
func generatorsFromMarkers(m markers.MarkerValues, basePath ...string) []customresourcestate.Generator {
150+
func generatorsFromMarkers(m ctrlmarkers.MarkerValues, basePath ...string) []customresourcestate.Generator {
151151
generators := []customresourcestate.Generator{}
152152

153153
for _, markerVals := range m {
154154
for _, val := range markerVals {
155-
if generatorMarker, isGeneratorMarker := val.(GeneratorMarker); isGeneratorMarker {
155+
if generatorMarker, isGeneratorMarker := val.(markers.LocalGeneratorMarker); isGeneratorMarker {
156156
if g := generatorMarker.ToGenerator(basePath...); g != nil {
157157
generators = append(generators, *g)
158158
}
@@ -163,7 +163,7 @@ func generatorsFromMarkers(m markers.MarkerValues, basePath ...string) []customr
163163
return generators
164164
}
165165

166-
func (p *Parser) NeedMetricsGeneratorFor(typ crd.TypeIdent) []customresourcestate.Generator {
166+
func (p *parser) NeedMetricsGeneratorFor(typ crd.TypeIdent) []customresourcestate.Generator {
167167
if _, knownMetrics := p.FlattenedMetrics[typ]; knownMetrics {
168168
return nil
169169
}
@@ -239,9 +239,9 @@ func generatorsFor(ctx *generatorContext, rawType ast.Expr) []customresourcestat
239239
func localNamedToGenerators(ctx *generatorContext, ident *ast.Ident) []customresourcestate.Generator {
240240
typeInfo := ctx.pkg.TypesInfo.TypeOf(ident)
241241
if typeInfo == types.Typ[types.Invalid] {
242-
// Expected to hit this error for types from not loaded packages
243-
// TODO(chrischdi): verify
244-
// klog.Warningf("Skipping unknown type: %v", loader.ErrFromNode(fmt.Errorf("unknown type %s", ident.Name), ident))
242+
// It is expected to hit this error for types from not loaded transitive package dependencies.
243+
// This leads to ignoring markers defined on the transitive types. Otherwise
244+
// markers on transitive types would lead to additional metrics.
245245
return nil
246246
}
247247

exp/metric-gen/main.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@ import (
2020
"os"
2121

2222
"github.com/spf13/pflag"
23-
"k8s.io/kube-state-metrics/v2/exp/metric-gen/metric"
2423
"sigs.k8s.io/controller-tools/pkg/genall"
2524
"sigs.k8s.io/controller-tools/pkg/genall/help"
2625
prettyhelp "sigs.k8s.io/controller-tools/pkg/genall/help/pretty"
2726
"sigs.k8s.io/controller-tools/pkg/loader"
2827
"sigs.k8s.io/controller-tools/pkg/markers"
28+
29+
"k8s.io/kube-state-metrics/v2/exp/metric-gen/generator"
2930
)
3031

3132
const (
@@ -54,7 +55,7 @@ func main() {
5455

5556
// Register the metric generator itself as marker so genall.FromOptions is able to initialize the runtime properly.
5657
// This also registers the markers inside the optionsRegistry so its available to print the marker docs.
57-
metricGenerator := metric.Generator{}
58+
metricGenerator := generator.CustomResourceConfigGenerator{}
5859
defn := markers.Must(markers.MakeDefinition(generatorName, markers.DescribesPackage, metricGenerator))
5960
if err := optionsRegistry.Register(defn); err != nil {
6061
panic(err)
@@ -75,14 +76,14 @@ func main() {
7576
// Load the passed packages as roots.
7677
roots, err := loader.LoadRoots(os.Args[1:]...)
7778
if err != nil {
78-
fmt.Fprint(os.Stderr, fmt.Sprintf("error: loading packages %v\n", err))
79+
fmt.Fprintf(os.Stderr, "error: loading packages %v\n", err)
7980
os.Exit(1)
8081
}
8182

8283
// Set up the generator runtime using controller-tools and passing our optionsRegistry.
8384
rt, err := genall.FromOptions(optionsRegistry, []string{generatorName})
8485
if err != nil {
85-
fmt.Fprint(os.Stderr, fmt.Sprintf("error: %v\n", err))
86+
fmt.Fprintf(os.Stderr, "error: %v\n", err)
8687
os.Exit(1)
8788
}
8889

exp/metric-gen/markers/gvk.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Copyright 2023 The Kubernetes Authors All rights reserved.
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+
package markers
17+
18+
import (
19+
"sigs.k8s.io/controller-tools/pkg/markers"
20+
21+
"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
22+
)
23+
24+
const (
25+
// GVKMarkerName is the marker for a GVK. Without a set GVKMarkerName the
26+
// generator will not generate any configuration for this GVK.
27+
GVKMarkerName = "Metrics:gvk"
28+
)
29+
30+
func init() {
31+
MarkerDefinitions = append(
32+
MarkerDefinitions,
33+
must(markers.MakeDefinition(GVKMarkerName, markers.DescribesType, gvkMarker{})).
34+
help(gvkMarker{}.Help()),
35+
)
36+
}
37+
38+
// gvkMarker implements ResourceMarker to opt-in metric generation for a gvk and configure a name prefix.
39+
type gvkMarker struct {
40+
NamePrefix string `marker:"namePrefix,optional"`
41+
}
42+
43+
var _ ResourceMarker = gvkMarker{}
44+
45+
// Help prints the help information for the gvkMarker.
46+
func (gvkMarker) Help() *markers.DefinitionHelp {
47+
return &markers.DefinitionHelp{
48+
Category: "Metrics",
49+
DetailedHelp: markers.DetailedHelp{
50+
Summary: "enables the creation of a customresourcestate Resource for the CRD and uses the given prefix for the metrics if configured.",
51+
Details: "",
52+
},
53+
FieldHelp: map[string]markers.DetailedHelp{},
54+
}
55+
}
56+
57+
func (n gvkMarker) ApplyToResource(resource *customresourcestate.Resource) error {
58+
resource.MetricNamePrefix = &n.NamePrefix
59+
return nil
60+
}

0 commit comments

Comments
 (0)