|
| 1 | +/* |
| 2 | +Copyright 2024 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 | + |
| 17 | +// Package metrics contain libraries for generating custom resource metrics configurations |
| 18 | +// for kube-state-metrics from metrics markers in Go source files. |
| 19 | +package metrics |
| 20 | + |
| 21 | +import ( |
| 22 | + "fmt" |
| 23 | + "sort" |
| 24 | + |
| 25 | + "sigs.k8s.io/controller-tools/pkg/crd" |
| 26 | + "sigs.k8s.io/controller-tools/pkg/genall" |
| 27 | + "sigs.k8s.io/controller-tools/pkg/loader" |
| 28 | + ctrlmarkers "sigs.k8s.io/controller-tools/pkg/markers" |
| 29 | + |
| 30 | + customresourcestate "sigs.k8s.io/controller-tools/pkg/metrics/internal/config" |
| 31 | + "sigs.k8s.io/controller-tools/pkg/metrics/markers" |
| 32 | +) |
| 33 | + |
| 34 | +// Generator generates kube-state-metrics custom resource configuration files. |
| 35 | +type Generator struct{} |
| 36 | + |
| 37 | +var _ genall.Generator = &Generator{} |
| 38 | +var _ genall.NeedsTypeChecking = &Generator{} |
| 39 | + |
| 40 | +// RegisterMarkers registers all markers needed by this Generator |
| 41 | +// into the given registry. |
| 42 | +func (g Generator) RegisterMarkers(into *ctrlmarkers.Registry) error { |
| 43 | + for _, m := range markers.MarkerDefinitions { |
| 44 | + if err := m.Register(into); err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return nil |
| 50 | +} |
| 51 | + |
| 52 | +// Generate generates artifacts produced by this marker. |
| 53 | +// It's called after RegisterMarkers has been called. |
| 54 | +func (g Generator) Generate(ctx *genall.GenerationContext) error { |
| 55 | + // Create the parser which is specific to the metric generator. |
| 56 | + parser := newParser( |
| 57 | + &crd.Parser{ |
| 58 | + Collector: ctx.Collector, |
| 59 | + Checker: ctx.Checker, |
| 60 | + }, |
| 61 | + ) |
| 62 | + |
| 63 | + // Loop over all passed packages. |
| 64 | + for _, pkg := range ctx.Roots { |
| 65 | + // skip packages which don't import metav1 because they can't define a CRD without meta v1. |
| 66 | + metav1 := pkg.Imports()["k8s.io/apimachinery/pkg/apis/meta/v1"] |
| 67 | + if metav1 == nil { |
| 68 | + continue |
| 69 | + } |
| 70 | + |
| 71 | + // parse the given package to feed crd.FindKubeKinds with Kubernetes Objects. |
| 72 | + parser.NeedPackage(pkg) |
| 73 | + |
| 74 | + kubeKinds := crd.FindKubeKinds(parser.Parser, metav1) |
| 75 | + if len(kubeKinds) == 0 { |
| 76 | + // no objects in the roots |
| 77 | + return nil |
| 78 | + } |
| 79 | + |
| 80 | + // Create metrics for all Custom Resources in this package. |
| 81 | + // This creates the customresourcestate.Resource object which contains all metric |
| 82 | + // definitions for the Custom Resource, if it is part of the package. |
| 83 | + for _, gv := range kubeKinds { |
| 84 | + if err := parser.NeedResourceFor(pkg, gv); err != nil { |
| 85 | + return err |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + // Initialize empty customresourcestate configuration file and fill it with the |
| 91 | + // customresourcestate.Resource objects from the parser. |
| 92 | + metrics := customresourcestate.Metrics{ |
| 93 | + Spec: customresourcestate.MetricsSpec{ |
| 94 | + Resources: []customresourcestate.Resource{}, |
| 95 | + }, |
| 96 | + } |
| 97 | + |
| 98 | + for _, resource := range parser.CustomResourceStates { |
| 99 | + if resource == nil { |
| 100 | + continue |
| 101 | + } |
| 102 | + if len(resource.Metrics) > 0 { |
| 103 | + // Sort the metrics to get a deterministic output. |
| 104 | + sort.Slice(resource.Metrics, func(i, j int) bool { |
| 105 | + return resource.Metrics[i].Name < resource.Metrics[j].Name |
| 106 | + }) |
| 107 | + |
| 108 | + metrics.Spec.Resources = append(metrics.Spec.Resources, *resource) |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // Sort the resources by GVK to get a deterministic output. |
| 113 | + sort.Slice(metrics.Spec.Resources, func(i, j int) bool { |
| 114 | + a := metrics.Spec.Resources[i].GroupVersionKind.String() |
| 115 | + b := metrics.Spec.Resources[j].GroupVersionKind.String() |
| 116 | + return a < b |
| 117 | + }) |
| 118 | + |
| 119 | + // Write the rendered yaml to the context which will result in stdout. |
| 120 | + virtualFilePath := "metrics.yaml" |
| 121 | + if err := ctx.WriteYAML(virtualFilePath, "", []interface{}{metrics}, genall.WithTransform(addCustomResourceStateKind)); err != nil { |
| 122 | + return fmt.Errorf("WriteYAML to %s: %w", virtualFilePath, err) |
| 123 | + } |
| 124 | + |
| 125 | + return nil |
| 126 | +} |
| 127 | + |
| 128 | +// CheckFilter indicates the loader.NodeFilter (if any) that should be used |
| 129 | +// to prune out unused types/packages when type-checking (nodes for which |
| 130 | +// the filter returns true are considered "interesting"). This filter acts |
| 131 | +// as a baseline -- all types the pass through this filter will be checked, |
| 132 | +// but more than that may also be checked due to other generators' filters. |
| 133 | +func (Generator) CheckFilter() loader.NodeFilter { |
| 134 | + // Re-use controller-tools filter to filter out unrelated nodes that aren't used |
| 135 | + // in CRD generation, like interfaces and struct fields without JSON tag. |
| 136 | + return crd.Generator{}.CheckFilter() |
| 137 | +} |
| 138 | + |
| 139 | +// addCustomResourceStateKind adds the correct kind because we don't have a correct |
| 140 | +// kubernetes-style object as configuration definition. |
| 141 | +func addCustomResourceStateKind(obj map[string]interface{}) error { |
| 142 | + obj["kind"] = "CustomResourceStateMetrics" |
| 143 | + return nil |
| 144 | +} |
0 commit comments