diff --git a/docs/metrics.md b/docs/metrics.md index 1d6f80267..152d07ecf 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -1,14 +1,14 @@ # Cluster Network Addons Operator Metrics +### kubevirt_cnao_cr_kubemacpool_aggregated +Total count of KubeMacPool manager pods deployed by CNAO CR. Type: Gauge. + ### kubevirt_cnao_cr_kubemacpool_deployed KubeMacpool is deployed by CNAO CR. Type: Gauge. ### kubevirt_cnao_cr_ready CNAO CR Ready. Type: Gauge. -### kubevirt_cnao_cr_kubemacpool_aggregated -Total count of KubeMacPool manager pods deployed by CNAO CR. Type: Gauge. - ### kubevirt_cnao_kubemacpool_duplicate_macs Total count of duplicate KubeMacPool MAC addresses. Type: Gauge. diff --git a/go.mod b/go.mod index 2dea624af..61cb31f59 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/gobwas/glob v0.2.3 github.com/google/go-github/v32 v32.1.0 github.com/kubevirt/monitoring/pkg/metrics/parser v0.0.0-20231024120544-6a3ba1a680b4 - github.com/machadovilaca/operator-observability v0.0.7 + github.com/machadovilaca/operator-observability v0.0.19-0.20240326121036-9f2e5a31675f github.com/onsi/ginkgo/v2 v2.11.0 github.com/onsi/gomega v1.27.10 github.com/openshift/api v0.0.0 @@ -72,7 +72,7 @@ require ( github.com/containerd/continuity v0.3.0 // indirect github.com/containerd/ttrpc v1.2.2 // indirect github.com/cyphar/filepath-securejoin v0.2.4 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/docker/cli v20.10.21+incompatible // indirect github.com/docker/distribution v2.8.2+incompatible // indirect github.com/docker/docker v24.0.7+incompatible // indirect @@ -181,7 +181,7 @@ require ( github.com/pelletier/go-toml v1.9.3 // indirect github.com/peterbourgon/diskv v2.0.1+incompatible // indirect github.com/pjbgf/sha1cd v0.3.0 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.4.0 // indirect github.com/prometheus/procfs v0.11.1 // indirect github.com/rivo/uniseg v0.2.0 // indirect @@ -249,7 +249,7 @@ require ( k8s.io/kube-aggregator v0.26.3 // indirect k8s.io/kube-openapi v0.0.0-20230717233707-2695361300d9 // indirect k8s.io/kubernetes v1.28.1 // indirect - k8s.io/utils v0.0.0-20230505201702-9f6742963106 // indirect + k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect kubevirt.io/containerized-data-importer-api v1.57.0-alpha1 // indirect kubevirt.io/controller-lifecycle-operator-sdk/api v0.0.0-20220329064328-f3cc58c6ed90 // indirect oras.land/oras-go v1.2.2 // indirect @@ -259,7 +259,7 @@ require ( sigs.k8s.io/kubebuilder/v3 v3.0.0-alpha.0.0.20210803185103-51e4a9aa5055 // indirect sigs.k8s.io/kustomize/api v0.13.5-0.20230601165947-6ce0bf390ce3 // indirect sigs.k8s.io/kustomize/kyaml v0.14.3-0.20230601165947-6ce0bf390ce3 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.3.0 // indirect sigs.k8s.io/yaml v1.3.0 // indirect ) diff --git a/go.sum b/go.sum index d41871a04..58bed259e 100644 --- a/go.sum +++ b/go.sum @@ -371,8 +371,9 @@ github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhr github.com/dave/kerr v0.0.0-20170318121727-bc25dd6abe8e/go.mod h1:qZqlPyPvfsDJt+3wHJ1EvSXDuVjFTK0j2p/ca+gtsb8= github.com/dave/rebecca v0.9.1/go.mod h1:N6XYdMD/OKw3lkF3ywh8Z6wPGuwNFDNtWYEMFWEmXBA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/daviddengcn/go-colortext v1.0.0/go.mod h1:zDqEI5NVUop5QPpVJUxE9UO10hRnmkD5G4Pmri9+m4c= github.com/deislabs/oras v0.11.1/go.mod h1:39lCtf8Q6WDC7ul9cnyWXONNzKvabEKk+AX+L0ImnQk= github.com/denisenkom/go-mssqldb v0.0.0-20190515213511-eb9f6a1743f3/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM= @@ -1083,8 +1084,8 @@ github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0U github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= github.com/lovoo/gcloud-opentracing v0.3.0/go.mod h1:ZFqk2y38kMDDikZPAK7ynTTGuyt17nSPdS3K5e+ZTBY= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= -github.com/machadovilaca/operator-observability v0.0.7 h1:4eYTuxBJQupw+i/Kw3yv8KQnViEh4CiYSol//A0K0Fs= -github.com/machadovilaca/operator-observability v0.0.7/go.mod h1:B1d+efJGa36WWcLYH2ZhqbjiH/OGv/b7nhe9Vb0WL+8= +github.com/machadovilaca/operator-observability v0.0.19-0.20240326121036-9f2e5a31675f h1:IDCLOdVCpsP9bkcp/K3pFdG8DKfbNgrBttLqQZ9wGbg= +github.com/machadovilaca/operator-observability v0.0.19-0.20240326121036-9f2e5a31675f/go.mod h1:9Loa1KSieWz/Yv7wJrU1gn7jnNXf75biAnefXb3ty+M= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= @@ -1363,8 +1364,9 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pkg/term v0.0.0-20180730021639-bffc007b7fd5/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/povsister/scp v0.0.0-20210427074412-33febfd9f13e h1:VtsDti2SgX7M7jy0QAyGgb162PeHLrOaNxmcYOtaGsY= github.com/poy/onpar v0.0.0-20190519213022-ee068f8ea4d1 h1:oL4IBbcqwhhNWh31bjOX8C/OCy0zs9906d/VUru+bqg= @@ -2561,8 +2563,8 @@ k8s.io/utils v0.0.0-20210527160623-6fdb442a123b/go.mod h1:jPW/WVKK9YHAvNhRxK0md/ k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20220210201930-3a6ce19ff2f9/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -k8s.io/utils v0.0.0-20230505201702-9f6742963106 h1:EObNQ3TW2D+WptiYXlApGNLVy0zm/JIBVY9i+M4wpAU= -k8s.io/utils v0.0.0-20230505201702-9f6742963106/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= kubevirt.io/api v1.0.0 h1:RBdXP5CDhE0v5qL2OUQdrYyRrHe/F68Z91GWqBDF6nw= kubevirt.io/api v1.0.0/go.mod h1:CJ4vZsaWhVN3jNbyc9y3lIZhw8nUHbWjap0xHABQiqc= kubevirt.io/client-go v1.0.0 h1:MMn41j/lFd+lJ7gWn7yuIZYW/aT9fI3bUimAuxAQ+Xk= @@ -2609,8 +2611,9 @@ sigs.k8s.io/kustomize/kustomize/v4 v4.5.7/go.mod h1:VSNKEH9D9d9bLiWEGbS6Xbg/Ih0t sigs.k8s.io/kustomize/kyaml v0.13.3 h1:tNNQIC+8cc+aXFTVg+RtQAOsjwUdYBZRAgYOVI3RBc4= sigs.k8s.io/kustomize/kyaml v0.13.3/go.mod h1:/ya3Gk4diiQzlE4mBh7wykyLRFZNvqlbh+JnwQ9Vhrc= sigs.k8s.io/structured-merge-diff/v4 v4.0.3/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= +sigs.k8s.io/structured-merge-diff/v4 v4.3.0 h1:UZbZAZfX0wV2zr7YZorDz6GXROfDFj6LvqCRm4VUVKk= +sigs.k8s.io/structured-merge-diff/v4 v4.3.0/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/docs/metrics.go b/vendor/github.com/machadovilaca/operator-observability/pkg/docs/metrics.go index c17532caa..8271230bd 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/docs/metrics.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/docs/metrics.go @@ -63,6 +63,8 @@ func BuildMetricsDocsWithCustomTemplate( allDocs = append(allDocs, buildMetricsDocs(recordingRules)...) } + sortMetricsDocs(allDocs) + buf := bytes.NewBufferString("") err = tpl.Execute(buf, allDocs) if err != nil { @@ -89,7 +91,6 @@ func buildMetricsDocs[T docOptions](items []T) []metricDocs { ExtraFields: metricOpts.ExtraFields, } } - sortMetricsDocs(metricsDocs) return metricsDocs } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go index f8437efc1..35015f51a 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go @@ -2,6 +2,7 @@ package operatormetrics import ( "fmt" + "strings" "github.com/prometheus/client_golang/prometheus" ) @@ -19,9 +20,20 @@ type Collector struct { } type CollectorResult struct { - Metric Metric - Labels []string - Value float64 + Metric Metric + Labels []string + ConstLabels map[string]string + Value float64 +} + +func (c Collector) hash() string { + var sb strings.Builder + + for _, cm := range c.Metrics { + sb.WriteString(cm.GetOpts().Name) + } + + return sb.String() } func (c Collector) Describe(ch chan<- *prometheus.Desc) { @@ -47,42 +59,41 @@ func (c Collector) Collect(ch chan<- prometheus.Metric) { } func collectValue(ch chan<- prometheus.Metric, metric Metric, cr CollectorResult) error { + var mType prometheus.ValueType + switch metric.GetType() { case CounterType: - m := metric.getCollector().(prometheus.Counter) - m.Add(cr.Value) - m.Collect(ch) + mType = prometheus.CounterValue case GaugeType: - m := metric.getCollector().(prometheus.Gauge) - m.Set(cr.Value) - m.Collect(ch) - case HistogramType: - m := metric.getCollector().(prometheus.Histogram) - m.Observe(cr.Value) - m.Collect(ch) - case SummaryType: - m := metric.getCollector().(prometheus.Summary) - m.Observe(cr.Value) - m.Collect(ch) + mType = prometheus.GaugeValue case CounterVecType: - m := metric.getCollector().(prometheus.CounterVec) - m.WithLabelValues(cr.Labels...).Add(cr.Value) - m.Collect(ch) + mType = prometheus.CounterValue case GaugeVecType: - m := metric.getCollector().(prometheus.GaugeVec) - m.WithLabelValues(cr.Labels...).Set(cr.Value) - m.Collect(ch) - case HistogramVecType: - m := metric.getCollector().(prometheus.HistogramVec) - m.WithLabelValues(cr.Labels...).Observe(cr.Value) - m.Collect(ch) - case SummaryVecType: - m := metric.getCollector().(prometheus.SummaryVec) - m.WithLabelValues(cr.Labels...).Observe(cr.Value) - m.Collect(ch) + mType = prometheus.GaugeValue default: - return fmt.Errorf("encountered unknown type %v", metric.GetType()) + return fmt.Errorf("encountered unsupported type for collector %v", metric.GetType()) + } + + labels := map[string]string{} + for k, v := range cr.ConstLabels { + labels[k] = v + } + for k, v := range metric.GetOpts().ConstLabels { + labels[k] = v + } + + desc := prometheus.NewDesc( + metric.GetOpts().Name, + metric.GetOpts().Help, + metric.GetOpts().labels, + labels, + ) + + cm, err := prometheus.NewConstMetric(desc, mType, cr.Value, cr.Labels...) + if err != nil { + return err } + ch <- cm return nil } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go index b1cf44220..ddca79de4 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go @@ -27,6 +27,10 @@ func (c *Counter) GetType() MetricType { return CounterType } +func (c *Counter) GetBaseType() MetricType { + return CounterType +} + func (c *Counter) getCollector() prometheus.Collector { return c.Counter } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go index 9cc16bf9c..568ce6c7b 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go @@ -13,6 +13,8 @@ var _ Metric = &CounterVec{} // NewCounterVec creates a new CounterVec. The CounterVec must be registered // with the Prometheus registry through RegisterMetrics. func NewCounterVec(metricOpts MetricOpts, labels []string) *CounterVec { + metricOpts.labels = labels + return &CounterVec{ CounterVec: *prometheus.NewCounterVec(prometheus.CounterOpts(convertOpts(metricOpts)), labels), metricOpts: metricOpts, @@ -27,6 +29,10 @@ func (c *CounterVec) GetType() MetricType { return CounterVecType } +func (c *CounterVec) GetBaseType() MetricType { + return CounterType +} + func (c *CounterVec) getCollector() prometheus.Collector { return c.CounterVec } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go index 03b783e51..de2699b2c 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go @@ -27,6 +27,10 @@ func (c *Gauge) GetType() MetricType { return GaugeType } +func (c *Gauge) GetBaseType() MetricType { + return GaugeType +} + func (c *Gauge) getCollector() prometheus.Collector { return c.Gauge } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go index e773c41fe..c771dece9 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go @@ -13,6 +13,8 @@ var _ Metric = &GaugeVec{} // NewGaugeVec creates a new GaugeVec. The GaugeVec must be registered // with the Prometheus registry through RegisterMetrics. func NewGaugeVec(metricOpts MetricOpts, labels []string) *GaugeVec { + metricOpts.labels = labels + return &GaugeVec{ GaugeVec: *prometheus.NewGaugeVec(prometheus.GaugeOpts(convertOpts(metricOpts)), labels), metricOpts: metricOpts, @@ -27,6 +29,10 @@ func (c *GaugeVec) GetType() MetricType { return GaugeVecType } +func (c *GaugeVec) GetBaseType() MetricType { + return GaugeType +} + func (c *GaugeVec) getCollector() prometheus.Collector { return c.GaugeVec } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go index c37ac1ca8..b764835e2 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go @@ -1,8 +1,6 @@ package operatormetrics import ( - "time" - "github.com/prometheus/client_golang/prometheus" ) @@ -10,23 +8,14 @@ type Histogram struct { prometheus.Histogram metricOpts MetricOpts - histogramOpts HistogramOpts + histogramOpts prometheus.HistogramOpts } var _ Metric = &Histogram{} -type HistogramOpts struct { - Buckets []float64 - NativeHistogramBucketFactor float64 - NativeHistogramZeroThreshold float64 - NativeHistogramMaxBucketNumber uint32 - NativeHistogramMinResetDuration time.Duration - NativeHistogramMaxZeroThreshold float64 -} - // NewHistogram creates a new Histogram. The Histogram must be registered with the // Prometheus registry through RegisterMetrics. -func NewHistogram(metricOpts MetricOpts, histogramOpts HistogramOpts) *Histogram { +func NewHistogram(metricOpts MetricOpts, histogramOpts prometheus.HistogramOpts) *Histogram { return &Histogram{ Histogram: prometheus.NewHistogram(makePrometheusHistogramOpts(metricOpts, histogramOpts)), metricOpts: metricOpts, @@ -34,24 +23,18 @@ func NewHistogram(metricOpts MetricOpts, histogramOpts HistogramOpts) *Histogram } } -func makePrometheusHistogramOpts(metricOpts MetricOpts, histogramOpts HistogramOpts) prometheus.HistogramOpts { - return prometheus.HistogramOpts{ - Name: metricOpts.Name, - Help: metricOpts.Help, - ConstLabels: metricOpts.ConstLabels, - NativeHistogramBucketFactor: histogramOpts.NativeHistogramBucketFactor, - NativeHistogramZeroThreshold: histogramOpts.NativeHistogramZeroThreshold, - NativeHistogramMaxBucketNumber: histogramOpts.NativeHistogramMaxBucketNumber, - NativeHistogramMinResetDuration: histogramOpts.NativeHistogramMinResetDuration, - NativeHistogramMaxZeroThreshold: histogramOpts.NativeHistogramMaxZeroThreshold, - } +func makePrometheusHistogramOpts(metricOpts MetricOpts, histogramOpts prometheus.HistogramOpts) prometheus.HistogramOpts { + histogramOpts.Name = metricOpts.Name + histogramOpts.Help = metricOpts.Help + histogramOpts.ConstLabels = metricOpts.ConstLabels + return histogramOpts } func (c *Histogram) GetOpts() MetricOpts { return c.metricOpts } -func (c *Histogram) GetHistogramOpts() HistogramOpts { +func (c *Histogram) GetHistogramOpts() prometheus.HistogramOpts { return c.histogramOpts } @@ -59,6 +42,10 @@ func (c *Histogram) GetType() MetricType { return HistogramType } +func (c *Histogram) GetBaseType() MetricType { + return HistogramType +} + func (c *Histogram) getCollector() prometheus.Collector { return c.Histogram } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go index 555a05e65..f272495f1 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go @@ -6,14 +6,14 @@ type HistogramVec struct { prometheus.HistogramVec metricOpts MetricOpts - histogramOpts HistogramOpts + histogramOpts prometheus.HistogramOpts } var _ Metric = &HistogramVec{} // NewHistogramVec creates a new HistogramVec. The HistogramVec must be // registered with the Prometheus registry through RegisterMetrics. -func NewHistogramVec(metricOpts MetricOpts, histogramOpts HistogramOpts, labels []string) *HistogramVec { +func NewHistogramVec(metricOpts MetricOpts, histogramOpts prometheus.HistogramOpts, labels []string) *HistogramVec { return &HistogramVec{ HistogramVec: *prometheus.NewHistogramVec(makePrometheusHistogramOpts(metricOpts, histogramOpts), labels), metricOpts: metricOpts, @@ -25,7 +25,7 @@ func (c *HistogramVec) GetOpts() MetricOpts { return c.metricOpts } -func (c *HistogramVec) GetHistogramOpts() HistogramOpts { +func (c *HistogramVec) GetHistogramOpts() prometheus.HistogramOpts { return c.histogramOpts } @@ -33,6 +33,10 @@ func (c *HistogramVec) GetType() MetricType { return HistogramVecType } +func (c *HistogramVec) GetBaseType() MetricType { + return HistogramType +} + func (c *HistogramVec) getCollector() prometheus.Collector { return c.HistogramVec } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go index b31ac7ff1..108d86bb9 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go @@ -3,17 +3,18 @@ package operatormetrics import "github.com/prometheus/client_golang/prometheus" type MetricOpts struct { - Name string - Help string - + Name string + Help string ConstLabels map[string]string - ExtraFields map[string]string + + labels []string } type Metric interface { GetOpts() MetricOpts GetType() MetricType + GetBaseType() MetricType getCollector() prometheus.Collector } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go index f2396882e..b1e803067 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go @@ -5,6 +5,10 @@ import ( ) type RegistryFunc func(c prometheus.Collector) error +type UnregisterFunc func(c prometheus.Collector) bool // Register is the function used to register metrics and collectors by this package. var Register RegistryFunc = prometheus.Register + +// Unregister is the function used to unregister metrics and collectors by this package. +var Unregister UnregisterFunc = prometheus.Unregister diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go index 5179b0934..3bf9d37c8 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go @@ -1,8 +1,6 @@ package operatormetrics import ( - "time" - "github.com/prometheus/client_golang/prometheus" ) @@ -10,21 +8,14 @@ type Summary struct { prometheus.Summary metricOpts MetricOpts - summaryOpts SummaryOpts + summaryOpts prometheus.SummaryOpts } var _ Metric = &Summary{} -type SummaryOpts struct { - Objectives map[float64]float64 - MaxAge time.Duration - AgeBuckets uint32 - BufCap uint32 -} - // NewSummary creates a new Summary. The Summary must be registered with the // Prometheus registry through RegisterMetrics. -func NewSummary(metricOpts MetricOpts, summaryOpts SummaryOpts) *Summary { +func NewSummary(metricOpts MetricOpts, summaryOpts prometheus.SummaryOpts) *Summary { return &Summary{ Summary: prometheus.NewSummary(makePrometheusSummaryOpts(metricOpts, summaryOpts)), metricOpts: metricOpts, @@ -32,23 +23,18 @@ func NewSummary(metricOpts MetricOpts, summaryOpts SummaryOpts) *Summary { } } -func makePrometheusSummaryOpts(metricOpts MetricOpts, summaryOpts SummaryOpts) prometheus.SummaryOpts { - return prometheus.SummaryOpts{ - Name: metricOpts.Name, - Help: metricOpts.Help, - ConstLabels: metricOpts.ConstLabels, - Objectives: summaryOpts.Objectives, - MaxAge: summaryOpts.MaxAge, - AgeBuckets: summaryOpts.AgeBuckets, - BufCap: summaryOpts.BufCap, - } +func makePrometheusSummaryOpts(metricOpts MetricOpts, summaryOpts prometheus.SummaryOpts) prometheus.SummaryOpts { + summaryOpts.Name = metricOpts.Name + summaryOpts.Help = metricOpts.Help + summaryOpts.ConstLabels = metricOpts.ConstLabels + return summaryOpts } func (c *Summary) GetOpts() MetricOpts { return c.metricOpts } -func (c *Summary) GetSummaryOpts() SummaryOpts { +func (c *Summary) GetSummaryOpts() prometheus.SummaryOpts { return c.summaryOpts } @@ -56,6 +42,10 @@ func (c *Summary) GetType() MetricType { return SummaryType } +func (c *Summary) GetBaseType() MetricType { + return SummaryType +} + func (c *Summary) getCollector() prometheus.Collector { return c.Summary } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go index f53e798f3..6ea8bc542 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go @@ -6,14 +6,14 @@ type SummaryVec struct { prometheus.SummaryVec metricOpts MetricOpts - summaryOpts SummaryOpts + summaryOpts prometheus.SummaryOpts } var _ Metric = &SummaryVec{} // NewSummaryVec creates a new SummaryVec. The SummaryVec must be // registered with the Prometheus registry through RegisterMetrics. -func NewSummaryVec(metricOpts MetricOpts, summaryOpts SummaryOpts, labels []string) *SummaryVec { +func NewSummaryVec(metricOpts MetricOpts, summaryOpts prometheus.SummaryOpts, labels []string) *SummaryVec { return &SummaryVec{ SummaryVec: *prometheus.NewSummaryVec(makePrometheusSummaryOpts(metricOpts, summaryOpts), labels), metricOpts: metricOpts, @@ -25,7 +25,7 @@ func (c *SummaryVec) GetOpts() MetricOpts { return c.metricOpts } -func (c *SummaryVec) GetSummaryOpts() SummaryOpts { +func (c *SummaryVec) GetSummaryOpts() prometheus.SummaryOpts { return c.summaryOpts } @@ -33,6 +33,10 @@ func (c *SummaryVec) GetType() MetricType { return SummaryVecType } +func (c *SummaryVec) GetBaseType() MetricType { + return SummaryType +} + func (c *SummaryVec) getCollector() prometheus.Collector { return c.SummaryVec } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go index d9a36a95c..fd500c7dc 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go @@ -1,15 +1,23 @@ package operatormetrics +import ( + "fmt" + "sort" +) + var operatorRegistry = newRegistry() type operatorRegisterer struct { - registeredMetrics map[string]Metric + registeredMetrics map[string]Metric + + registeredCollectors map[string]Collector registeredCollectorMetrics map[string]Metric } func newRegistry() operatorRegisterer { return operatorRegisterer{ registeredMetrics: map[string]Metric{}, + registeredCollectors: map[string]Collector{}, registeredCollectorMetrics: map[string]Metric{}, } } @@ -18,11 +26,17 @@ func newRegistry() operatorRegisterer { func RegisterMetrics(allMetrics ...[]Metric) error { for _, metricList := range allMetrics { for _, metric := range metricList { - err := Register(metric.getCollector()) + if metricExists(metric) { + err := unregisterMetric(metric) + if err != nil { + return err + } + } + + err := registerMetric(metric) if err != nil { return err } - operatorRegistry.registeredMetrics[metric.GetOpts().Name] = metric } } @@ -32,13 +46,16 @@ func RegisterMetrics(allMetrics ...[]Metric) error { // RegisterCollector registers the collector with the Prometheus registry. func RegisterCollector(collectors ...Collector) error { for _, collector := range collectors { - err := Register(collector) - if err != nil { - return err + if collectorExists(collector) { + err := unregisterCollector(collector) + if err != nil { + return err + } } - for _, cm := range collector.Metrics { - operatorRegistry.registeredCollectorMetrics[cm.GetOpts().Name] = cm + err := registerCollector(collector) + if err != nil { + return err } } @@ -57,5 +74,92 @@ func ListMetrics() []Metric { result = append(result, rc) } + sort.Slice(result, func(i, j int) bool { + return result[i].GetOpts().Name < result[j].GetOpts().Name + }) + return result } + +// CleanRegistry removes all registered metrics. +func CleanRegistry() error { + for _, metric := range operatorRegistry.registeredMetrics { + err := unregisterMetric(metric) + if err != nil { + return err + } + } + + for _, collector := range operatorRegistry.registeredCollectors { + err := unregisterCollector(collector) + if err != nil { + return err + } + } + + return nil +} + +func metricExists(metric Metric) bool { + _, ok := operatorRegistry.registeredMetrics[metric.GetOpts().Name] + return ok +} + +func unregisterMetric(metric Metric) error { + if succeeded := Unregister(metric.getCollector()); succeeded { + delete(operatorRegistry.registeredMetrics, metric.GetOpts().Name) + return nil + } + + return fmt.Errorf("failed to unregister from Prometheus client metric %s", metric.GetOpts().Name) +} + +func registerMetric(metric Metric) error { + err := Register(metric.getCollector()) + if err != nil { + return err + } + operatorRegistry.registeredMetrics[metric.GetOpts().Name] = metric + + return nil +} + +func collectorExists(collector Collector) bool { + _, ok := operatorRegistry.registeredCollectors[collector.hash()] + return ok +} + +func unregisterCollector(collector Collector) error { + if succeeded := Unregister(collector); succeeded { + delete(operatorRegistry.registeredCollectors, collector.hash()) + for _, metric := range collector.Metrics { + delete(operatorRegistry.registeredCollectorMetrics, metric.GetOpts().Name) + } + return nil + } + + return fmt.Errorf("failed to unregister from Prometheus client collector with metrics: %s", buildCollectorMetricListString(collector)) +} + +func registerCollector(collector Collector) error { + err := Register(collector) + if err != nil { + return err + } + + operatorRegistry.registeredCollectors[collector.hash()] = collector + for _, cm := range collector.Metrics { + operatorRegistry.registeredCollectorMetrics[cm.GetOpts().Name] = cm + } + + return nil +} + +func buildCollectorMetricListString(collector Collector) string { + metricsList := "" + for _, metric := range collector.Metrics { + metricsList += metric.GetOpts().Name + ", " + } + metricsList = metricsList[:len(metricsList)-2] + return metricsList +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go index 1f12d3e26..2f0b186b5 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go @@ -2,6 +2,7 @@ package operatorrules import ( "fmt" + "sort" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -42,7 +43,7 @@ func buildPrometheusRuleSpec() (*promv1.PrometheusRuleSpec, error) { if len(operatorRegistry.registeredAlerts) != 0 { groups = append(groups, promv1.RuleGroup{ Name: "alerts.rules", - Rules: buildAlertsRules(), + Rules: ListAlerts(), }) } @@ -60,14 +61,13 @@ func buildRecordingRulesRules() []promv1.Rule { rules = append(rules, promv1.Rule{ Record: recordingRule.MetricsOpts.Name, Expr: recordingRule.Expr, + Labels: recordingRule.MetricsOpts.ConstLabels, }) } - return rules -} + sort.Slice(rules, func(i, j int) bool { + return rules[i].Record < rules[j].Record + }) -func buildAlertsRules() []promv1.Rule { - var rules []promv1.Rule - rules = append(rules, operatorRegistry.registeredAlerts...) return rules } diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go index 6a639836d..add4b675a 100644 --- a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go @@ -2,25 +2,29 @@ package operatorrules import ( promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + "sort" ) var operatorRegistry = newRegistry() type operatorRegisterer struct { - registeredRecordingRules []RecordingRule - registeredAlerts []promv1.Rule + registeredRecordingRules map[string]RecordingRule + registeredAlerts map[string]promv1.Rule } func newRegistry() operatorRegisterer { return operatorRegisterer{ - registeredRecordingRules: []RecordingRule{}, + registeredRecordingRules: map[string]RecordingRule{}, + registeredAlerts: map[string]promv1.Rule{}, } } // RegisterRecordingRules registers the given recording rules. func RegisterRecordingRules(recordingRules ...[]RecordingRule) error { for _, recordingRuleList := range recordingRules { - operatorRegistry.registeredRecordingRules = append(operatorRegistry.registeredRecordingRules, recordingRuleList...) + for _, recordingRule := range recordingRuleList { + operatorRegistry.registeredRecordingRules[recordingRule.MetricsOpts.Name] = recordingRule + } } return nil @@ -29,7 +33,9 @@ func RegisterRecordingRules(recordingRules ...[]RecordingRule) error { // RegisterAlerts registers the given alerts. func RegisterAlerts(alerts ...[]promv1.Rule) error { for _, alertList := range alerts { - operatorRegistry.registeredAlerts = append(operatorRegistry.registeredAlerts, alertList...) + for _, alert := range alertList { + operatorRegistry.registeredAlerts[alert.Alert] = alert + } } return nil @@ -37,10 +43,34 @@ func RegisterAlerts(alerts ...[]promv1.Rule) error { // ListRecordingRules returns the registered recording rules. func ListRecordingRules() []RecordingRule { - return operatorRegistry.registeredRecordingRules + var rules []RecordingRule + for _, rule := range operatorRegistry.registeredRecordingRules { + rules = append(rules, rule) + } + + sort.Slice(rules, func(i, j int) bool { + return rules[i].GetOpts().Name < rules[j].GetOpts().Name + }) + + return rules } // ListAlerts returns the registered alerts. func ListAlerts() []promv1.Rule { - return operatorRegistry.registeredAlerts + var alerts []promv1.Rule + for _, alert := range operatorRegistry.registeredAlerts { + alerts = append(alerts, alert) + } + + sort.Slice(alerts, func(i, j int) bool { + return alerts[i].Alert < alerts[j].Alert + }) + + return alerts +} + +// CleanRegistry removes all registered rules and alerts. +func CleanRegistry() error { + operatorRegistry = newRegistry() + return nil } diff --git a/vendor/k8s.io/utils/pointer/pointer.go b/vendor/k8s.io/utils/pointer/pointer.go index b8103223a..b673a6425 100644 --- a/vendor/k8s.io/utils/pointer/pointer.go +++ b/vendor/k8s.io/utils/pointer/pointer.go @@ -14,12 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Deprecated: Use functions in k8s.io/utils/ptr instead: ptr.To to obtain +// a pointer, ptr.Deref to dereference a pointer, ptr.Equal to compare +// dereferenced pointers. package pointer import ( - "fmt" - "reflect" "time" + + "k8s.io/utils/ptr" ) // AllPtrFieldsNil tests whether all pointer fields in a struct are nil. This is useful when, @@ -28,383 +31,219 @@ import ( // // This function is only valid for structs and pointers to structs. Any other // type will cause a panic. Passing a typed nil pointer will return true. -func AllPtrFieldsNil(obj interface{}) bool { - v := reflect.ValueOf(obj) - if !v.IsValid() { - panic(fmt.Sprintf("reflect.ValueOf() produced a non-valid Value for %#v", obj)) - } - if v.Kind() == reflect.Ptr { - if v.IsNil() { - return true - } - v = v.Elem() - } - for i := 0; i < v.NumField(); i++ { - if v.Field(i).Kind() == reflect.Ptr && !v.Field(i).IsNil() { - return false - } - } - return true -} - -// Int returns a pointer to an int -func Int(i int) *int { - return &i -} +// +// Deprecated: Use ptr.AllPtrFieldsNil instead. +var AllPtrFieldsNil = ptr.AllPtrFieldsNil + +// Int returns a pointer to an int. +var Int = ptr.To[int] // IntPtr is a function variable referring to Int. // -// Deprecated: Use Int instead. +// Deprecated: Use ptr.To instead. var IntPtr = Int // for back-compat // IntDeref dereferences the int ptr and returns it if not nil, or else // returns def. -func IntDeref(ptr *int, def int) int { - if ptr != nil { - return *ptr - } - return def -} +var IntDeref = ptr.Deref[int] // IntPtrDerefOr is a function variable referring to IntDeref. // -// Deprecated: Use IntDeref instead. +// Deprecated: Use ptr.Deref instead. var IntPtrDerefOr = IntDeref // for back-compat // Int32 returns a pointer to an int32. -func Int32(i int32) *int32 { - return &i -} +var Int32 = ptr.To[int32] // Int32Ptr is a function variable referring to Int32. // -// Deprecated: Use Int32 instead. +// Deprecated: Use ptr.To instead. var Int32Ptr = Int32 // for back-compat // Int32Deref dereferences the int32 ptr and returns it if not nil, or else // returns def. -func Int32Deref(ptr *int32, def int32) int32 { - if ptr != nil { - return *ptr - } - return def -} +var Int32Deref = ptr.Deref[int32] // Int32PtrDerefOr is a function variable referring to Int32Deref. // -// Deprecated: Use Int32Deref instead. +// Deprecated: Use ptr.Deref instead. var Int32PtrDerefOr = Int32Deref // for back-compat // Int32Equal returns true if both arguments are nil or both arguments // dereference to the same value. -func Int32Equal(a, b *int32) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var Int32Equal = ptr.Equal[int32] // Uint returns a pointer to an uint -func Uint(i uint) *uint { - return &i -} +var Uint = ptr.To[uint] // UintPtr is a function variable referring to Uint. // -// Deprecated: Use Uint instead. +// Deprecated: Use ptr.To instead. var UintPtr = Uint // for back-compat // UintDeref dereferences the uint ptr and returns it if not nil, or else // returns def. -func UintDeref(ptr *uint, def uint) uint { - if ptr != nil { - return *ptr - } - return def -} +var UintDeref = ptr.Deref[uint] // UintPtrDerefOr is a function variable referring to UintDeref. // -// Deprecated: Use UintDeref instead. +// Deprecated: Use ptr.Deref instead. var UintPtrDerefOr = UintDeref // for back-compat // Uint32 returns a pointer to an uint32. -func Uint32(i uint32) *uint32 { - return &i -} +var Uint32 = ptr.To[uint32] // Uint32Ptr is a function variable referring to Uint32. // -// Deprecated: Use Uint32 instead. +// Deprecated: Use ptr.To instead. var Uint32Ptr = Uint32 // for back-compat // Uint32Deref dereferences the uint32 ptr and returns it if not nil, or else // returns def. -func Uint32Deref(ptr *uint32, def uint32) uint32 { - if ptr != nil { - return *ptr - } - return def -} +var Uint32Deref = ptr.Deref[uint32] // Uint32PtrDerefOr is a function variable referring to Uint32Deref. // -// Deprecated: Use Uint32Deref instead. +// Deprecated: Use ptr.Deref instead. var Uint32PtrDerefOr = Uint32Deref // for back-compat // Uint32Equal returns true if both arguments are nil or both arguments // dereference to the same value. -func Uint32Equal(a, b *uint32) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var Uint32Equal = ptr.Equal[uint32] // Int64 returns a pointer to an int64. -func Int64(i int64) *int64 { - return &i -} +var Int64 = ptr.To[int64] // Int64Ptr is a function variable referring to Int64. // -// Deprecated: Use Int64 instead. +// Deprecated: Use ptr.To instead. var Int64Ptr = Int64 // for back-compat // Int64Deref dereferences the int64 ptr and returns it if not nil, or else // returns def. -func Int64Deref(ptr *int64, def int64) int64 { - if ptr != nil { - return *ptr - } - return def -} +var Int64Deref = ptr.Deref[int64] // Int64PtrDerefOr is a function variable referring to Int64Deref. // -// Deprecated: Use Int64Deref instead. +// Deprecated: Use ptr.Deref instead. var Int64PtrDerefOr = Int64Deref // for back-compat // Int64Equal returns true if both arguments are nil or both arguments // dereference to the same value. -func Int64Equal(a, b *int64) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var Int64Equal = ptr.Equal[int64] // Uint64 returns a pointer to an uint64. -func Uint64(i uint64) *uint64 { - return &i -} +var Uint64 = ptr.To[uint64] // Uint64Ptr is a function variable referring to Uint64. // -// Deprecated: Use Uint64 instead. +// Deprecated: Use ptr.To instead. var Uint64Ptr = Uint64 // for back-compat // Uint64Deref dereferences the uint64 ptr and returns it if not nil, or else // returns def. -func Uint64Deref(ptr *uint64, def uint64) uint64 { - if ptr != nil { - return *ptr - } - return def -} +var Uint64Deref = ptr.Deref[uint64] // Uint64PtrDerefOr is a function variable referring to Uint64Deref. // -// Deprecated: Use Uint64Deref instead. +// Deprecated: Use ptr.Deref instead. var Uint64PtrDerefOr = Uint64Deref // for back-compat // Uint64Equal returns true if both arguments are nil or both arguments // dereference to the same value. -func Uint64Equal(a, b *uint64) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var Uint64Equal = ptr.Equal[uint64] // Bool returns a pointer to a bool. -func Bool(b bool) *bool { - return &b -} +var Bool = ptr.To[bool] // BoolPtr is a function variable referring to Bool. // -// Deprecated: Use Bool instead. +// Deprecated: Use ptr.To instead. var BoolPtr = Bool // for back-compat // BoolDeref dereferences the bool ptr and returns it if not nil, or else // returns def. -func BoolDeref(ptr *bool, def bool) bool { - if ptr != nil { - return *ptr - } - return def -} +var BoolDeref = ptr.Deref[bool] // BoolPtrDerefOr is a function variable referring to BoolDeref. // -// Deprecated: Use BoolDeref instead. +// Deprecated: Use ptr.Deref instead. var BoolPtrDerefOr = BoolDeref // for back-compat // BoolEqual returns true if both arguments are nil or both arguments // dereference to the same value. -func BoolEqual(a, b *bool) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var BoolEqual = ptr.Equal[bool] // String returns a pointer to a string. -func String(s string) *string { - return &s -} +var String = ptr.To[string] // StringPtr is a function variable referring to String. // -// Deprecated: Use String instead. +// Deprecated: Use ptr.To instead. var StringPtr = String // for back-compat // StringDeref dereferences the string ptr and returns it if not nil, or else // returns def. -func StringDeref(ptr *string, def string) string { - if ptr != nil { - return *ptr - } - return def -} +var StringDeref = ptr.Deref[string] // StringPtrDerefOr is a function variable referring to StringDeref. // -// Deprecated: Use StringDeref instead. +// Deprecated: Use ptr.Deref instead. var StringPtrDerefOr = StringDeref // for back-compat // StringEqual returns true if both arguments are nil or both arguments // dereference to the same value. -func StringEqual(a, b *string) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var StringEqual = ptr.Equal[string] // Float32 returns a pointer to a float32. -func Float32(i float32) *float32 { - return &i -} +var Float32 = ptr.To[float32] // Float32Ptr is a function variable referring to Float32. // -// Deprecated: Use Float32 instead. +// Deprecated: Use ptr.To instead. var Float32Ptr = Float32 // Float32Deref dereferences the float32 ptr and returns it if not nil, or else // returns def. -func Float32Deref(ptr *float32, def float32) float32 { - if ptr != nil { - return *ptr - } - return def -} +var Float32Deref = ptr.Deref[float32] // Float32PtrDerefOr is a function variable referring to Float32Deref. // -// Deprecated: Use Float32Deref instead. +// Deprecated: Use ptr.Deref instead. var Float32PtrDerefOr = Float32Deref // for back-compat // Float32Equal returns true if both arguments are nil or both arguments // dereference to the same value. -func Float32Equal(a, b *float32) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var Float32Equal = ptr.Equal[float32] // Float64 returns a pointer to a float64. -func Float64(i float64) *float64 { - return &i -} +var Float64 = ptr.To[float64] // Float64Ptr is a function variable referring to Float64. // -// Deprecated: Use Float64 instead. +// Deprecated: Use ptr.To instead. var Float64Ptr = Float64 // Float64Deref dereferences the float64 ptr and returns it if not nil, or else // returns def. -func Float64Deref(ptr *float64, def float64) float64 { - if ptr != nil { - return *ptr - } - return def -} +var Float64Deref = ptr.Deref[float64] // Float64PtrDerefOr is a function variable referring to Float64Deref. // -// Deprecated: Use Float64Deref instead. +// Deprecated: Use ptr.Deref instead. var Float64PtrDerefOr = Float64Deref // for back-compat // Float64Equal returns true if both arguments are nil or both arguments // dereference to the same value. -func Float64Equal(a, b *float64) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var Float64Equal = ptr.Equal[float64] // Duration returns a pointer to a time.Duration. -func Duration(d time.Duration) *time.Duration { - return &d -} +var Duration = ptr.To[time.Duration] // DurationDeref dereferences the time.Duration ptr and returns it if not nil, or else // returns def. -func DurationDeref(ptr *time.Duration, def time.Duration) time.Duration { - if ptr != nil { - return *ptr - } - return def -} +var DurationDeref = ptr.Deref[time.Duration] // DurationEqual returns true if both arguments are nil or both arguments // dereference to the same value. -func DurationEqual(a, b *time.Duration) bool { - if (a == nil) != (b == nil) { - return false - } - if a == nil { - return true - } - return *a == *b -} +var DurationEqual = ptr.Equal[time.Duration] diff --git a/vendor/k8s.io/utils/ptr/OWNERS b/vendor/k8s.io/utils/ptr/OWNERS new file mode 100644 index 000000000..0d6392752 --- /dev/null +++ b/vendor/k8s.io/utils/ptr/OWNERS @@ -0,0 +1,10 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- apelisse +- stewart-yu +- thockin +reviewers: +- apelisse +- stewart-yu +- thockin diff --git a/vendor/k8s.io/utils/ptr/README.md b/vendor/k8s.io/utils/ptr/README.md new file mode 100644 index 000000000..2ca8073dc --- /dev/null +++ b/vendor/k8s.io/utils/ptr/README.md @@ -0,0 +1,3 @@ +# Pointer + +This package provides some functions for pointer-based operations. diff --git a/vendor/k8s.io/utils/ptr/ptr.go b/vendor/k8s.io/utils/ptr/ptr.go new file mode 100644 index 000000000..659ed3b9e --- /dev/null +++ b/vendor/k8s.io/utils/ptr/ptr.go @@ -0,0 +1,73 @@ +/* +Copyright 2023 The Kubernetes Authors. + +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 ptr + +import ( + "fmt" + "reflect" +) + +// AllPtrFieldsNil tests whether all pointer fields in a struct are nil. This is useful when, +// for example, an API struct is handled by plugins which need to distinguish +// "no plugin accepted this spec" from "this spec is empty". +// +// This function is only valid for structs and pointers to structs. Any other +// type will cause a panic. Passing a typed nil pointer will return true. +func AllPtrFieldsNil(obj interface{}) bool { + v := reflect.ValueOf(obj) + if !v.IsValid() { + panic(fmt.Sprintf("reflect.ValueOf() produced a non-valid Value for %#v", obj)) + } + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return true + } + v = v.Elem() + } + for i := 0; i < v.NumField(); i++ { + if v.Field(i).Kind() == reflect.Ptr && !v.Field(i).IsNil() { + return false + } + } + return true +} + +// To returns a pointer to the given value. +func To[T any](v T) *T { + return &v +} + +// Deref dereferences ptr and returns the value it points to if no nil, or else +// returns def. +func Deref[T any](ptr *T, def T) T { + if ptr != nil { + return *ptr + } + return def +} + +// Equal returns true if both arguments are nil or both arguments +// dereference to the same value. +func Equal[T comparable](a, b *T) bool { + if (a == nil) != (b == nil) { + return false + } + if a == nil { + return true + } + return *a == *b +} diff --git a/vendor/modules.txt b/vendor/modules.txt index ea1edb411..78b31025c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -196,7 +196,7 @@ github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1 # github.com/cyphar/filepath-securejoin v0.2.4 ## explicit; go 1.13 github.com/cyphar/filepath-securejoin -# github.com/davecgh/go-spew v1.1.1 +# github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew # github.com/docker/cli v20.10.21+incompatible @@ -621,8 +621,8 @@ github.com/lib/pq/scram # github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de ## explicit github.com/liggitt/tabwriter -# github.com/machadovilaca/operator-observability v0.0.7 -## explicit; go 1.20 +# github.com/machadovilaca/operator-observability v0.0.19-0.20240326121036-9f2e5a31675f +## explicit; go 1.19 github.com/machadovilaca/operator-observability/pkg/docs github.com/machadovilaca/operator-observability/pkg/operatormetrics github.com/machadovilaca/operator-observability/pkg/operatorrules @@ -876,7 +876,7 @@ github.com/pjbgf/sha1cd/ubc # github.com/pkg/errors v0.9.1 ## explicit github.com/pkg/errors -# github.com/pmezard/go-difflib v1.0.0 +# github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 ## explicit github.com/pmezard/go-difflib/difflib # github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.64.1 @@ -1881,7 +1881,7 @@ k8s.io/kubectl/pkg/validation # k8s.io/kubernetes v1.28.1 ## explicit; go 1.20 k8s.io/kubernetes/pkg/apis/core -# k8s.io/utils v0.0.0-20230505201702-9f6742963106 +# k8s.io/utils v0.0.0-20230726121419-3b25d923346b ## explicit; go 1.18 k8s.io/utils/buffer k8s.io/utils/clock @@ -1894,6 +1894,7 @@ k8s.io/utils/lru k8s.io/utils/net k8s.io/utils/path k8s.io/utils/pointer +k8s.io/utils/ptr k8s.io/utils/strings/slices k8s.io/utils/trace # kubevirt.io/api v0.0.0-20230706190111-5527663af491 => kubevirt.io/api v1.0.0 @@ -2250,7 +2251,7 @@ sigs.k8s.io/kustomize/kyaml/yaml/merge2 sigs.k8s.io/kustomize/kyaml/yaml/merge3 sigs.k8s.io/kustomize/kyaml/yaml/schema sigs.k8s.io/kustomize/kyaml/yaml/walk -# sigs.k8s.io/structured-merge-diff/v4 v4.2.3 +# sigs.k8s.io/structured-merge-diff/v4 v4.3.0 ## explicit; go 1.13 sigs.k8s.io/structured-merge-diff/v4/fieldpath sigs.k8s.io/structured-merge-diff/v4/schema diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/elements.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/elements.go index 7e5dc7582..5d3707a5b 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/elements.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/elements.go @@ -73,7 +73,7 @@ type Atom struct { } // Scalar (AKA "primitive") represents a type which has a single value which is -// either numeric, string, or boolean. +// either numeric, string, or boolean, or untyped for any of them. // // TODO: split numeric into float/int? Something even more fine-grained? type Scalar string @@ -82,6 +82,7 @@ const ( Numeric = Scalar("numeric") String = Scalar("string") Boolean = Scalar("boolean") + Untyped = Scalar("untyped") ) // ElementRelationship is an enum of the different possible relationships diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/schemaschema.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/schemaschema.go index 7d64d1308..e4c5caa2a 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/schemaschema.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/schema/schemaschema.go @@ -110,7 +110,7 @@ var SchemaSchemaYAML = `types: scalar: string - name: deduceInvalidDiscriminator type: - scalar: bool + scalar: boolean - name: fields type: list: diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go index 913644083..09209ec82 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go @@ -113,11 +113,12 @@ func (w *mergingWalker) doLeaf() { w.rule(w) } -func (w *mergingWalker) doScalar(t *schema.Scalar) (errs ValidationErrors) { - errs = append(errs, validateScalar(t, w.lhs, "lhs: ")...) - errs = append(errs, validateScalar(t, w.rhs, "rhs: ")...) - if len(errs) > 0 { - return errs +func (w *mergingWalker) doScalar(t *schema.Scalar) ValidationErrors { + // Make sure at least one side is a valid scalar. + lerrs := validateScalar(t, w.lhs, "lhs: ") + rerrs := validateScalar(t, w.rhs, "rhs: ") + if len(lerrs) > 0 && len(rerrs) > 0 { + return append(lerrs, rerrs...) } // All scalars are leaf fields. diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/typed.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/typed.go index d63a97fe2..6411bd51a 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/typed.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/typed.go @@ -45,6 +45,10 @@ func AsTyped(v value.Value, s *schema.Schema, typeRef schema.TypeRef) (*TypedVal // conforms to the schema, for cases where that has already been checked or // where you're going to call a method that validates as a side-effect (like // ToFieldSet). +// +// Deprecated: This function was initially created because validation +// was expensive. Now that this has been solved, objects should always +// be created as validated, using `AsTyped`. func AsTypedUnvalidated(v value.Value, s *schema.Schema, typeRef schema.TypeRef) *TypedValue { tv := &TypedValue{ value: v, @@ -125,12 +129,13 @@ func (tv TypedValue) Compare(rhs *TypedValue) (c *Comparison, err error) { Modified: fieldpath.NewSet(), Added: fieldpath.NewSet(), } + a := value.NewFreelistAllocator() _, err = merge(&tv, rhs, func(w *mergingWalker) { if w.lhs == nil { c.Added.Insert(w.path) } else if w.rhs == nil { c.Removed.Insert(w.path) - } else if !value.Equals(w.rhs, w.lhs) { + } else if !value.EqualsUsing(a, w.rhs, w.lhs) { // TODO: Equality is not sufficient for this. // Need to implement equality check on the value type. c.Modified.Insert(w.path) diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/validate.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/validate.go index 378d30219..edddbafa4 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/validate.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/validate.go @@ -102,6 +102,12 @@ func validateScalar(t *schema.Scalar, v value.Value, prefix string) (errs Valida if !v.IsBool() { return errorf("%vexpected boolean, got %v", prefix, v) } + case schema.Untyped: + if !v.IsFloat() && !v.IsInt() && !v.IsString() && !v.IsBool() { + return errorf("%vexpected any scalar, got %v", prefix, v) + } + default: + return errorf("%vunexpected scalar type in schema: %v", prefix, *t) } return nil } diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapreflect.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapreflect.go index dc8b8c720..c38402b99 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapreflect.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapreflect.go @@ -136,7 +136,7 @@ func (r mapReflect) EqualsUsing(a Allocator, m Map) bool { if !ok { return false } - return Equals(vr.mustReuse(lhsVal, entry, nil, nil), value) + return EqualsUsing(a, vr.mustReuse(lhsVal, entry, nil, nil), value) }) } diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapunstructured.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapunstructured.go index d8e208628..c3ae00b18 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapunstructured.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/value/mapunstructured.go @@ -88,12 +88,12 @@ func (m mapUnstructuredInterface) EqualsUsing(a Allocator, other Map) bool { } vv := a.allocValueUnstructured() defer a.Free(vv) - return other.Iterate(func(key string, value Value) bool { + return other.IterateUsing(a, func(key string, value Value) bool { lhsVal, ok := m[key] if !ok { return false } - return Equals(vv.reuse(lhsVal), value) + return EqualsUsing(a, vv.reuse(lhsVal), value) }) } @@ -168,12 +168,12 @@ func (m mapUnstructuredString) EqualsUsing(a Allocator, other Map) bool { } vv := a.allocValueUnstructured() defer a.Free(vv) - return other.Iterate(func(key string, value Value) bool { + return other.IterateUsing(a, func(key string, value Value) bool { lhsVal, ok := m[key] if !ok { return false } - return Equals(vv.reuse(lhsVal), value) + return EqualsUsing(a, vv.reuse(lhsVal), value) }) } diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/value/reflectcache.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/value/reflectcache.go index a5a467c0f..f0d58d42c 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/value/reflectcache.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/value/reflectcache.go @@ -154,7 +154,9 @@ func buildStructCacheEntry(t reflect.Type, infos map[string]*FieldCacheEntry, fi if field.Type.Kind() == reflect.Ptr { e = field.Type.Elem() } - buildStructCacheEntry(e, infos, append(fieldPath, field.Index)) + if e.Kind() == reflect.Struct { + buildStructCacheEntry(e, infos, append(fieldPath, field.Index)) + } continue } info := &FieldCacheEntry{JsonName: jsonName, isOmitEmpty: isOmitempty, fieldPath: append(fieldPath, field.Index), fieldType: field.Type}