Skip to content

Commit

Permalink
lint fixes and privatize
Browse files Browse the repository at this point in the history
  • Loading branch information
chrischdi committed Aug 25, 2023
1 parent 6f0d7a4 commit d7d5ef2
Show file tree
Hide file tree
Showing 11 changed files with 394 additions and 272 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metric
package generator

import (
"fmt"
Expand All @@ -23,20 +23,34 @@ import (
"sigs.k8s.io/controller-tools/pkg/crd"
"sigs.k8s.io/controller-tools/pkg/genall"
"sigs.k8s.io/controller-tools/pkg/loader"
"sigs.k8s.io/controller-tools/pkg/markers"
ctrlmarkers "sigs.k8s.io/controller-tools/pkg/markers"

"k8s.io/kube-state-metrics/v2/exp/metric-gen/markers"
"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
)

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

func (Generator) CheckFilter() loader.NodeFilter {
// Re-use controller-tools filter to filter out unrelated nodes that aren't used
// in CRD generation, like interfaces and struct fields without JSON tag.
return crd.Generator{}.CheckFilter()
var _ genall.Generator = &CustomResourceConfigGenerator{}
var _ genall.NeedsTypeChecking = &CustomResourceConfigGenerator{}

// RegisterMarkers registers all markers needed by this Generator
// into the given registry.
func (g CustomResourceConfigGenerator) RegisterMarkers(into *ctrlmarkers.Registry) error {
for _, m := range markers.MarkerDefinitions {
if err := m.Register(into); err != nil {
return err
}
}

return nil
}

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

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

// CheckFilter indicates the loader.NodeFilter (if any) that should be used
// to prune out unused types/packages when type-checking (nodes for which
// the filter returns true are considered "interesting"). This filter acts
// as a baseline -- all types the pass through this filter will be checked,
// but more than that may also be checked due to other generators' filters.
func (CustomResourceConfigGenerator) CheckFilter() loader.NodeFilter {
// Re-use controller-tools filter to filter out unrelated nodes that aren't used
// in CRD generation, like interfaces and struct fields without JSON tag.
return crd.Generator{}.CheckFilter()
}

// addCustomResourceStateKind adds the correct kind because we don't have a correct
// kubernetes-style object as configuration definition.
func addCustomResourceStateKind(obj map[string]interface{}) error {
obj["kind"] = "CustomResourceStateMetrics"
return nil
}

func (g Generator) RegisterMarkers(into *markers.Registry) error {
for _, m := range markerDefinitions {
if err := m.Register(into); err != nil {
return err
}
}

return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metric
package generator

import (
"fmt"
Expand All @@ -26,27 +26,28 @@ import (
"k8s.io/klog/v2"
"sigs.k8s.io/controller-tools/pkg/crd"
"sigs.k8s.io/controller-tools/pkg/loader"
"sigs.k8s.io/controller-tools/pkg/markers"
ctrlmarkers "sigs.k8s.io/controller-tools/pkg/markers"

"k8s.io/kube-state-metrics/v2/exp/metric-gen/markers"
"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
)

type Parser struct {
type parser struct {
*crd.Parser

CustomResourceStates map[schema.GroupKind]customresourcestate.Resource
FlattenedMetrics map[crd.TypeIdent][]customresourcestate.Metric
}

func newParser(parser *crd.Parser) *Parser {
return &Parser{
Parser: parser,
func newParser(p *crd.Parser) *parser {
return &parser{
Parser: p,
CustomResourceStates: make(map[schema.GroupKind]customresourcestate.Resource),
FlattenedMetrics: make(map[crd.TypeIdent][]customresourcestate.Metric),
}
}

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

resource := customresourcestate.Resource{
GroupVersionKind: customresourcestate.GroupVersionKind{
Group: groupKind.Group,
Kind: groupKind.Kind,
Version: "", // TODO
Group: groupKind.Group,
Kind: groupKind.Kind,
},
}

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

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

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

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

PackageMarkers markers.MarkerValues
PackageMarkers ctrlmarkers.MarkerValues
}

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

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

for _, markerVals := range m {
for _, val := range markerVals {
if generatorMarker, isGeneratorMarker := val.(GeneratorMarker); isGeneratorMarker {
if generatorMarker, isGeneratorMarker := val.(markers.LocalGeneratorMarker); isGeneratorMarker {
if g := generatorMarker.ToGenerator(basePath...); g != nil {
generators = append(generators, *g)
}
Expand All @@ -163,7 +163,7 @@ func generatorsFromMarkers(m markers.MarkerValues, basePath ...string) []customr
return generators
}

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

Expand Down
9 changes: 5 additions & 4 deletions exp/metric-gen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ import (
"os"

"github.com/spf13/pflag"
"k8s.io/kube-state-metrics/v2/exp/metric-gen/metric"
"sigs.k8s.io/controller-tools/pkg/genall"
"sigs.k8s.io/controller-tools/pkg/genall/help"
prettyhelp "sigs.k8s.io/controller-tools/pkg/genall/help/pretty"
"sigs.k8s.io/controller-tools/pkg/loader"
"sigs.k8s.io/controller-tools/pkg/markers"

"k8s.io/kube-state-metrics/v2/exp/metric-gen/generator"
)

const (
Expand Down Expand Up @@ -54,7 +55,7 @@ func main() {

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

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

Expand Down
60 changes: 60 additions & 0 deletions exp/metric-gen/markers/gvk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
Copyright 2023 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package markers

import (
"sigs.k8s.io/controller-tools/pkg/markers"

"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
)

const (
// GVKMarkerName is the marker for a GVK. Without a set GVKMarkerName the
// generator will not generate any configuration for this GVK.
GVKMarkerName = "Metrics:gvk"
)

func init() {
MarkerDefinitions = append(
MarkerDefinitions,
must(markers.MakeDefinition(GVKMarkerName, markers.DescribesType, gvkMarker{})).
help(gvkMarker{}.Help()),
)
}

// gvkMarker implements ResourceMarker to opt-in metric generation for a gvk and configure a name prefix.
type gvkMarker struct {
NamePrefix string `marker:"namePrefix,optional"`
}

var _ ResourceMarker = gvkMarker{}

// Help prints the help information for the gvkMarker.
func (gvkMarker) Help() *markers.DefinitionHelp {
return &markers.DefinitionHelp{
Category: "Metrics",
DetailedHelp: markers.DetailedHelp{
Summary: "enables the creation of a customresourcestate Resource for the CRD and uses the given prefix for the metrics if configured.",
Details: "",
},
FieldHelp: map[string]markers.DetailedHelp{},
}
}

func (n gvkMarker) ApplyToResource(resource *customresourcestate.Resource) error {
resource.MetricNamePrefix = &n.NamePrefix
return nil
}
Loading

0 comments on commit d7d5ef2

Please sign in to comment.