rebase: update kubernetes to v1.21.2

Updated kubernetes packages to latest release.
resizefs package has been included into k8s.io/mount-utils
package. updated code to use the same.

Updates: #1968

Signed-off-by: Rakshith R <rar@redhat.com>
This commit is contained in:
Rakshith R
2021-06-25 10:29:51 +05:30
committed by mergify[bot]
parent 8ce5ae16c1
commit 1b23d78113
1115 changed files with 98825 additions and 12365 deletions

View File

@ -6,5 +6,6 @@ approvers:
- RainbowMango
reviewers:
- sig-instrumentation-reviewers
- YoyinZyc
labels:
- sig/instrumentation

View File

@ -49,10 +49,10 @@ type StableCollector interface {
// is a convenient assistant for custom collectors.
// It is recommend that inherit BaseStableCollector when implementing custom collectors.
type BaseStableCollector struct {
descriptors map[string]*Desc // stores all descriptors by pair<fqName, Desc>, these are collected from DescribeWithStability().
registrable map[string]*Desc // stores registrable descriptors by pair<fqName, Desc>, is a subset of descriptors.
hidden map[string]*Desc // stores hidden descriptors by pair<fqName, Desc>, is a subset of descriptors.
self StableCollector
descriptors map[string]*Desc // stores all descriptors by pair<fqName, Desc>, these are collected from DescribeWithStability().
registerable map[string]*Desc // stores registerable descriptors by pair<fqName, Desc>, is a subset of descriptors.
hidden map[string]*Desc // stores hidden descriptors by pair<fqName, Desc>, is a subset of descriptors.
self StableCollector
}
// DescribeWithStability sends all descriptors to the provided channel.
@ -64,7 +64,7 @@ func (bsc *BaseStableCollector) DescribeWithStability(ch chan<- *Desc) {
// Describe sends all descriptors to the provided channel.
// It intend to be called by prometheus registry.
func (bsc *BaseStableCollector) Describe(ch chan<- *prometheus.Desc) {
for _, d := range bsc.registrable {
for _, d := range bsc.registerable {
ch <- d.toPrometheusDesc()
}
}
@ -128,11 +128,11 @@ func (bsc *BaseStableCollector) init(self StableCollector) {
}
func (bsc *BaseStableCollector) trackRegistrableDescriptor(d *Desc) {
if bsc.registrable == nil {
bsc.registrable = make(map[string]*Desc)
if bsc.registerable == nil {
bsc.registerable = make(map[string]*Desc)
}
bsc.registrable[d.fqName] = d
bsc.registerable[d.fqName] = d
}
func (bsc *BaseStableCollector) trackHiddenDescriptor(d *Desc) {
@ -158,7 +158,7 @@ func (bsc *BaseStableCollector) Create(version *semver.Version, self StableColle
}
}
if len(bsc.registrable) > 0 {
if len(bsc.registerable) > 0 {
return true
}
@ -173,7 +173,7 @@ func (bsc *BaseStableCollector) ClearState() {
}
bsc.descriptors = nil
bsc.registrable = nil
bsc.registerable = nil
bsc.hidden = nil
bsc.self = nil
}

View File

@ -17,8 +17,10 @@ limitations under the License.
package metrics
import (
"context"
"github.com/blang/semver"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
)
// Counter is our internal representation for our wrapping struct around prometheus
@ -30,6 +32,9 @@ type Counter struct {
selfCollector
}
// The implementation of the Metric interface is expected by testutil.GetCounterMetricValue.
var _ Metric = &Counter{}
// NewCounter returns an object which satisfies the kubeCollector and CounterMetric interfaces.
// However, the object returned will not measure anything unless the collector is first
// registered, since the metric is lazily instantiated.
@ -45,6 +50,14 @@ func NewCounter(opts *CounterOpts) *Counter {
return kc
}
func (c *Counter) Desc() *prometheus.Desc {
return c.metric.Desc()
}
func (c *Counter) Write(to *dto.Metric) error {
return c.metric.Write(to)
}
// Reset resets the underlying prometheus Counter to start counting from 0 again
func (c *Counter) Reset() {
if !c.IsCreated() {
@ -79,6 +92,11 @@ func (c *Counter) initializeDeprecatedMetric() {
c.initializeMetric()
}
// WithContext allows the normal Counter metric to pass in context. The context is no-op now.
func (c *Counter) WithContext(ctx context.Context) CounterMetric {
return c.CounterMetric
}
// CounterVec is the internal representation of our wrapping struct around prometheus
// counterVecs. CounterVec implements both kubeCollector and CounterVecMetric.
type CounterVec struct {
@ -94,13 +112,20 @@ type CounterVec struct {
func NewCounterVec(opts *CounterOpts, labels []string) *CounterVec {
opts.StabilityLevel.setDefaults()
fqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)
allowListLock.RLock()
if allowList, ok := labelValueAllowLists[fqName]; ok {
opts.LabelValueAllowLists = allowList
}
allowListLock.RUnlock()
cv := &CounterVec{
CounterVec: noopCounterVec,
CounterOpts: opts,
originalLabels: labels,
lazyMetric: lazyMetric{},
}
cv.lazyInit(cv, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))
cv.lazyInit(cv, fqName)
return cv
}
@ -140,6 +165,9 @@ func (v *CounterVec) WithLabelValues(lvs ...string) CounterMetric {
if !v.IsCreated() {
return noop // return no-op counter
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)
}
return v.CounterVec.WithLabelValues(lvs...)
}
@ -151,6 +179,9 @@ func (v *CounterVec) With(labels map[string]string) CounterMetric {
if !v.IsCreated() {
return noop // return no-op counter
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainLabelMap(labels)
}
return v.CounterVec.With(labels)
}
@ -176,3 +207,27 @@ func (v *CounterVec) Reset() {
v.CounterVec.Reset()
}
// WithContext returns wrapped CounterVec with context
func (v *CounterVec) WithContext(ctx context.Context) *CounterVecWithContext {
return &CounterVecWithContext{
ctx: ctx,
CounterVec: *v,
}
}
// CounterVecWithContext is the wrapper of CounterVec with context.
type CounterVecWithContext struct {
CounterVec
ctx context.Context
}
// WithLabelValues is the wrapper of CounterVec.WithLabelValues.
func (vc *CounterVecWithContext) WithLabelValues(lvs ...string) CounterMetric {
return vc.CounterVec.WithLabelValues(lvs...)
}
// With is the wrapper of CounterVec.With.
func (vc *CounterVecWithContext) With(labels map[string]string) CounterMetric {
return vc.CounterVec.With(labels)
}

View File

@ -17,6 +17,7 @@ limitations under the License.
package metrics
import (
"context"
"github.com/blang/semver"
"github.com/prometheus/client_golang/prometheus"
@ -73,6 +74,11 @@ func (g *Gauge) initializeDeprecatedMetric() {
g.initializeMetric()
}
// WithContext allows the normal Gauge metric to pass in context. The context is no-op now.
func (g *Gauge) WithContext(ctx context.Context) GaugeMetric {
return g.GaugeMetric
}
// GaugeVec is the internal representation of our wrapping struct around prometheus
// gaugeVecs. kubeGaugeVec implements both kubeCollector and KubeGaugeVec.
type GaugeVec struct {
@ -88,13 +94,20 @@ type GaugeVec struct {
func NewGaugeVec(opts *GaugeOpts, labels []string) *GaugeVec {
opts.StabilityLevel.setDefaults()
fqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)
allowListLock.RLock()
if allowList, ok := labelValueAllowLists[fqName]; ok {
opts.LabelValueAllowLists = allowList
}
allowListLock.RUnlock()
cv := &GaugeVec{
GaugeVec: noopGaugeVec,
GaugeOpts: opts,
originalLabels: labels,
lazyMetric: lazyMetric{},
}
cv.lazyInit(cv, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))
cv.lazyInit(cv, fqName)
return cv
}
@ -133,6 +146,9 @@ func (v *GaugeVec) WithLabelValues(lvs ...string) GaugeMetric {
if !v.IsCreated() {
return noop // return no-op gauge
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)
}
return v.GaugeVec.WithLabelValues(lvs...)
}
@ -144,6 +160,9 @@ func (v *GaugeVec) With(labels map[string]string) GaugeMetric {
if !v.IsCreated() {
return noop // return no-op gauge
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainLabelMap(labels)
}
return v.GaugeVec.With(labels)
}
@ -191,3 +210,27 @@ func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc {
return newGaugeFunc(opts, function, v)
}
// WithContext returns wrapped GaugeVec with context
func (v *GaugeVec) WithContext(ctx context.Context) *GaugeVecWithContext {
return &GaugeVecWithContext{
ctx: ctx,
GaugeVec: *v,
}
}
// GaugeVecWithContext is the wrapper of GaugeVec with context.
type GaugeVecWithContext struct {
GaugeVec
ctx context.Context
}
// WithLabelValues is the wrapper of GaugeVec.WithLabelValues.
func (vc *GaugeVecWithContext) WithLabelValues(lvs ...string) GaugeMetric {
return vc.GaugeVec.WithLabelValues(lvs...)
}
// With is the wrapper of GaugeVec.With.
func (vc *GaugeVecWithContext) With(labels map[string]string) GaugeMetric {
return vc.GaugeVec.With(labels)
}

View File

@ -17,6 +17,7 @@ limitations under the License.
package metrics
import (
"context"
"github.com/blang/semver"
"github.com/prometheus/client_golang/prometheus"
)
@ -83,6 +84,11 @@ func (h *Histogram) initializeDeprecatedMetric() {
h.initializeMetric()
}
// WithContext allows the normal Histogram metric to pass in context. The context is no-op now.
func (h *Histogram) WithContext(ctx context.Context) ObserverMetric {
return h.ObserverMetric
}
// HistogramVec is the internal representation of our wrapping struct around prometheus
// histogramVecs.
type HistogramVec struct {
@ -98,13 +104,20 @@ type HistogramVec struct {
func NewHistogramVec(opts *HistogramOpts, labels []string) *HistogramVec {
opts.StabilityLevel.setDefaults()
fqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)
allowListLock.RLock()
if allowList, ok := labelValueAllowLists[fqName]; ok {
opts.LabelValueAllowLists = allowList
}
allowListLock.RUnlock()
v := &HistogramVec{
HistogramVec: noopHistogramVec,
HistogramOpts: opts,
originalLabels: labels,
lazyMetric: lazyMetric{},
}
v.lazyInit(v, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))
v.lazyInit(v, fqName)
return v
}
@ -139,6 +152,9 @@ func (v *HistogramVec) WithLabelValues(lvs ...string) ObserverMetric {
if !v.IsCreated() {
return noop
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)
}
return v.HistogramVec.WithLabelValues(lvs...)
}
@ -150,6 +166,9 @@ func (v *HistogramVec) With(labels map[string]string) ObserverMetric {
if !v.IsCreated() {
return noop
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainLabelMap(labels)
}
return v.HistogramVec.With(labels)
}
@ -175,3 +194,27 @@ func (v *HistogramVec) Reset() {
v.HistogramVec.Reset()
}
// WithContext returns wrapped HistogramVec with context
func (v *HistogramVec) WithContext(ctx context.Context) *HistogramVecWithContext {
return &HistogramVecWithContext{
ctx: ctx,
HistogramVec: *v,
}
}
// HistogramVecWithContext is the wrapper of HistogramVec with context.
type HistogramVecWithContext struct {
HistogramVec
ctx context.Context
}
// WithLabelValues is the wrapper of HistogramVec.WithLabelValues.
func (vc *HistogramVecWithContext) WithLabelValues(lvs ...string) ObserverMetric {
return vc.HistogramVec.WithLabelValues(lvs...)
}
// With is the wrapper of HistogramVec.With.
func (vc *HistogramVecWithContext) With(labels map[string]string) ObserverMetric {
return vc.HistogramVec.With(labels)
}

View File

@ -87,10 +87,24 @@ func (r *lazyMetric) lazyInit(self kubeCollector, fqName string) {
r.self = self
}
// determineDeprecationStatus figures out whether the lazy metric should be deprecated or not.
// preprocessMetric figures out whether the lazy metric should be hidden or not.
// This method takes a Version argument which should be the version of the binary in which
// this code is currently being executed.
func (r *lazyMetric) determineDeprecationStatus(version semver.Version) {
// this code is currently being executed. A metric can be hidden under two conditions:
// 1. if the metric is deprecated and is outside the grace period (i.e. has been
// deprecated for more than one release
// 2. if the metric is manually disabled via a CLI flag.
//
// Disclaimer: disabling a metric via a CLI flag has higher precedence than
// deprecation and will override show-hidden-metrics for the explicitly
// disabled metric.
func (r *lazyMetric) preprocessMetric(version semver.Version) {
disabledMetricsLock.RLock()
defer disabledMetricsLock.RUnlock()
// disabling metrics is higher in precedence than showing hidden metrics
if _, ok := disabledMetrics[r.fqName]; ok {
r.isHidden = true
return
}
selfVersion := r.self.DeprecatedVersion()
if selfVersion == nil {
return
@ -99,6 +113,7 @@ func (r *lazyMetric) determineDeprecationStatus(version semver.Version) {
if selfVersion.LTE(version) {
r.isDeprecated = true
}
if ShouldShowHidden() {
klog.Warningf("Hidden metrics (%s) have been manually overridden, showing this very deprecated metric.", r.fqName)
return
@ -126,7 +141,7 @@ func (r *lazyMetric) IsDeprecated() bool {
// created.
func (r *lazyMetric) Create(version *semver.Version) bool {
if version != nil {
r.determineDeprecationStatus(*version)
r.preprocessMetric(*version)
}
// let's not create if this metric is slated to be hidden
if r.IsHidden() {

View File

@ -18,6 +18,7 @@ package metrics
import (
"fmt"
"regexp"
"github.com/blang/semver"
"github.com/spf13/pflag"
@ -28,6 +29,8 @@ import (
// Options has all parameters needed for exposing metrics from components
type Options struct {
ShowHiddenMetricsForVersion string
DisabledMetrics []string
AllowListMapping map[string]string
}
// NewOptions returns default metrics options
@ -37,12 +40,20 @@ func NewOptions() *Options {
// Validate validates metrics flags options.
func (o *Options) Validate() []error {
var errs []error
err := validateShowHiddenMetricsVersion(parseVersion(version.Get()), o.ShowHiddenMetricsForVersion)
if err != nil {
return []error{err}
errs = append(errs, err)
}
return nil
if err := validateAllowMetricLabel(o.AllowListMapping); err != nil {
errs = append(errs, err)
}
if len(errs) == 0 {
return nil
}
return errs
}
// AddFlags adds flags for exposing component metrics.
@ -56,13 +67,33 @@ func (o *Options) AddFlags(fs *pflag.FlagSet) {
"The format is <major>.<minor>, e.g.: '1.16'. "+
"The purpose of this format is make sure you have the opportunity to notice if the next release hides additional metrics, "+
"rather than being surprised when they are permanently removed in the release after that.")
fs.StringSliceVar(&o.DisabledMetrics,
"disabled-metrics",
o.DisabledMetrics,
"This flag provides an escape hatch for misbehaving metrics. "+
"You must provide the fully qualified metric name in order to disable it. "+
"Disclaimer: disabling metrics is higher in precedence than showing hidden metrics.")
fs.StringToStringVar(&o.AllowListMapping, "allow-metric-labels", o.AllowListMapping,
"The map from metric-label to value allow-list of this label. The key's format is <MetricName>,<LabelName>. "+
"The value's format is <allowed_value>,<allowed_value>..."+
"e.g. metric1,label1='v1,v2,v3', metric1,label2='v1,v2,v3' metric2,label1='v1,v2,v3'.")
}
// Apply applies parameters into global configuration of metrics.
func (o *Options) Apply() {
if o != nil && len(o.ShowHiddenMetricsForVersion) > 0 {
if o == nil {
return
}
if len(o.ShowHiddenMetricsForVersion) > 0 {
SetShowHidden()
}
// set disabled metrics
for _, metricName := range o.DisabledMetrics {
SetDisabledMetric(metricName)
}
if o.AllowListMapping != nil {
SetLabelAllowListFromCLI(o.AllowListMapping)
}
}
func validateShowHiddenMetricsVersion(currentVersion semver.Version, targetVersionStr string) error {
@ -77,3 +108,18 @@ func validateShowHiddenMetricsVersion(currentVersion semver.Version, targetVersi
return nil
}
func validateAllowMetricLabel(allowListMapping map[string]string) error {
if allowListMapping == nil {
return nil
}
metricNameRegex := `[a-zA-Z_:][a-zA-Z0-9_:]*`
labelRegex := `[a-zA-Z_][a-zA-Z0-9_]*`
for k := range allowListMapping {
reg := regexp.MustCompile(metricNameRegex + `,` + labelRegex)
if reg.FindString(k) != k {
return fmt.Errorf("--allow-metric-labels must has a list of kv pair with format `metricName:labelName=labelValue, labelValue,...`")
}
}
return nil
}

View File

@ -18,10 +18,17 @@ package metrics
import (
"fmt"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"k8s.io/apimachinery/pkg/util/sets"
)
var (
labelValueAllowLists = map[string]*MetricLabelAllowList{}
allowListLock sync.RWMutex
)
// KubeOpts is superset struct for prometheus.Opts. The prometheus Opts structure
@ -31,15 +38,16 @@ import (
// Name must be set to a non-empty string. DeprecatedVersion is defined only
// if the metric for which this options applies is, in fact, deprecated.
type KubeOpts struct {
Namespace string
Subsystem string
Name string
Help string
ConstLabels map[string]string
DeprecatedVersion string
deprecateOnce sync.Once
annotateOnce sync.Once
StabilityLevel StabilityLevel
Namespace string
Subsystem string
Name string
Help string
ConstLabels map[string]string
DeprecatedVersion string
deprecateOnce sync.Once
annotateOnce sync.Once
StabilityLevel StabilityLevel
LabelValueAllowLists *MetricLabelAllowList
}
// BuildFQName joins the given three name components by "_". Empty name
@ -140,16 +148,17 @@ func (o *GaugeOpts) toPromGaugeOpts() prometheus.GaugeOpts {
// and can safely be left at their zero value, although it is strongly
// encouraged to set a Help string.
type HistogramOpts struct {
Namespace string
Subsystem string
Name string
Help string
ConstLabels map[string]string
Buckets []float64
DeprecatedVersion string
deprecateOnce sync.Once
annotateOnce sync.Once
StabilityLevel StabilityLevel
Namespace string
Subsystem string
Name string
Help string
ConstLabels map[string]string
Buckets []float64
DeprecatedVersion string
deprecateOnce sync.Once
annotateOnce sync.Once
StabilityLevel StabilityLevel
LabelValueAllowLists *MetricLabelAllowList
}
// Modify help description on the metric description.
@ -186,19 +195,20 @@ func (o *HistogramOpts) toPromHistogramOpts() prometheus.HistogramOpts {
// a help string and to explicitly set the Objectives field to the desired value
// as the default value will change in the upcoming v0.10 of the library.
type SummaryOpts struct {
Namespace string
Subsystem string
Name string
Help string
ConstLabels map[string]string
Objectives map[float64]float64
MaxAge time.Duration
AgeBuckets uint32
BufCap uint32
DeprecatedVersion string
deprecateOnce sync.Once
annotateOnce sync.Once
StabilityLevel StabilityLevel
Namespace string
Subsystem string
Name string
Help string
ConstLabels map[string]string
Objectives map[float64]float64
MaxAge time.Duration
AgeBuckets uint32
BufCap uint32
DeprecatedVersion string
deprecateOnce sync.Once
annotateOnce sync.Once
StabilityLevel StabilityLevel
LabelValueAllowLists *MetricLabelAllowList
}
// Modify help description on the metric description.
@ -243,3 +253,49 @@ func (o *SummaryOpts) toPromSummaryOpts() prometheus.SummaryOpts {
BufCap: o.BufCap,
}
}
type MetricLabelAllowList struct {
labelToAllowList map[string]sets.String
}
func (allowList *MetricLabelAllowList) ConstrainToAllowedList(labelNameList, labelValueList []string) {
for index, value := range labelValueList {
name := labelNameList[index]
if allowValues, ok := allowList.labelToAllowList[name]; ok {
if !allowValues.Has(value) {
labelValueList[index] = "unexpected"
}
}
}
}
func (allowList *MetricLabelAllowList) ConstrainLabelMap(labels map[string]string) {
for name, value := range labels {
if allowValues, ok := allowList.labelToAllowList[name]; ok {
if !allowValues.Has(value) {
labels[name] = "unexpected"
}
}
}
}
func SetLabelAllowListFromCLI(allowListMapping map[string]string) {
allowListLock.Lock()
defer allowListLock.Unlock()
for metricLabelName, labelValues := range allowListMapping {
metricName := strings.Split(metricLabelName, ",")[0]
labelName := strings.Split(metricLabelName, ",")[1]
valueSet := sets.NewString(strings.Split(labelValues, ",")...)
allowList, ok := labelValueAllowLists[metricName]
if ok {
allowList.labelToAllowList[labelName] = valueSet
} else {
labelToAllowList := make(map[string]sets.String)
labelToAllowList[labelName] = valueSet
labelValueAllowLists[metricName] = &MetricLabelAllowList{
labelToAllowList,
}
}
}
}

View File

@ -17,11 +17,8 @@ limitations under the License.
package metrics
import (
"os"
"time"
"github.com/prometheus/procfs"
"k8s.io/klog/v2"
)
@ -44,24 +41,11 @@ func RegisterProcessStartTime(registrationFunc func(Registerable) error) error {
start = float64(time.Now().Unix())
}
// processStartTime is a lazy metric which only get initialized after registered.
// so we have to explicitly create it before setting the label value. Otherwise
// it is a noop.
if !processStartTime.IsCreated() {
processStartTime.initializeMetric()
// so we need to register the metric first and then set the value for it
if err = registrationFunc(processStartTime); err != nil {
return err
}
processStartTime.WithLabelValues().Set(start)
return registrationFunc(processStartTime)
}
func getProcessStart() (float64, error) {
pid := os.Getpid()
p, err := procfs.NewProc(pid)
if err != nil {
return 0, err
}
if stat, err := p.Stat(); err == nil {
return stat.StartTime()
}
return 0, err
return nil
}

View File

@ -0,0 +1,38 @@
// +build !windows
/*
Copyright 2019 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 metrics
import (
"os"
"github.com/prometheus/procfs"
)
func getProcessStart() (float64, error) {
pid := os.Getpid()
p, err := procfs.NewProc(pid)
if err != nil {
return 0, err
}
if stat, err := p.Stat(); err == nil {
return stat.StartTime()
}
return 0, err
}

View File

@ -0,0 +1,33 @@
// +build windows
/*
Copyright 2019 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 metrics
import (
"golang.org/x/sys/windows"
)
func getProcessStart() (float64, error) {
processHandle := windows.CurrentProcess()
var creationTime, exitTime, kernelTime, userTime windows.Filetime
if err := windows.GetProcessTimes(processHandle, &creationTime, &exitTime, &kernelTime, &userTime); err != nil {
return 0, err
}
return float64(creationTime.Nanoseconds() / 1e9), nil
}

View File

@ -30,10 +30,12 @@ import (
)
var (
showHiddenOnce sync.Once
showHidden atomic.Value
registries []*kubeRegistry // stores all registries created by NewKubeRegistry()
registriesLock sync.RWMutex
showHiddenOnce sync.Once
disabledMetricsLock sync.RWMutex
showHidden atomic.Value
registries []*kubeRegistry // stores all registries created by NewKubeRegistry()
registriesLock sync.RWMutex
disabledMetrics = map[string]struct{}{}
)
// shouldHide be used to check if a specific metric with deprecated version should be hidden
@ -61,6 +63,12 @@ func ValidateShowHiddenMetricsVersion(v string) []error {
return nil
}
func SetDisabledMetric(name string) {
disabledMetricsLock.Lock()
defer disabledMetricsLock.Unlock()
disabledMetrics[name] = struct{}{}
}
// SetShowHidden will enable showing hidden metrics. This will no-opt
// after the initial call
func SetShowHidden() {

View File

@ -17,6 +17,7 @@ limitations under the License.
package metrics
import (
"context"
"github.com/blang/semver"
"github.com/prometheus/client_golang/prometheus"
)
@ -74,6 +75,11 @@ func (s *Summary) initializeDeprecatedMetric() {
s.initializeMetric()
}
// WithContext allows the normal Summary metric to pass in context. The context is no-op now.
func (s *Summary) WithContext(ctx context.Context) ObserverMetric {
return s.ObserverMetric
}
// SummaryVec is the internal representation of our wrapping struct around prometheus
// summaryVecs.
//
@ -93,12 +99,19 @@ type SummaryVec struct {
func NewSummaryVec(opts *SummaryOpts, labels []string) *SummaryVec {
opts.StabilityLevel.setDefaults()
fqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)
allowListLock.RLock()
if allowList, ok := labelValueAllowLists[fqName]; ok {
opts.LabelValueAllowLists = allowList
}
allowListLock.RUnlock()
v := &SummaryVec{
SummaryOpts: opts,
originalLabels: labels,
lazyMetric: lazyMetric{},
}
v.lazyInit(v, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))
v.lazyInit(v, fqName)
return v
}
@ -133,6 +146,9 @@ func (v *SummaryVec) WithLabelValues(lvs ...string) ObserverMetric {
if !v.IsCreated() {
return noop
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)
}
return v.SummaryVec.WithLabelValues(lvs...)
}
@ -144,6 +160,9 @@ func (v *SummaryVec) With(labels map[string]string) ObserverMetric {
if !v.IsCreated() {
return noop
}
if v.LabelValueAllowLists != nil {
v.LabelValueAllowLists.ConstrainLabelMap(labels)
}
return v.SummaryVec.With(labels)
}
@ -169,3 +188,27 @@ func (v *SummaryVec) Reset() {
v.SummaryVec.Reset()
}
// WithContext returns wrapped SummaryVec with context
func (v *SummaryVec) WithContext(ctx context.Context) *SummaryVecWithContext {
return &SummaryVecWithContext{
ctx: ctx,
SummaryVec: *v,
}
}
// SummaryVecWithContext is the wrapper of SummaryVec with context.
type SummaryVecWithContext struct {
SummaryVec
ctx context.Context
}
// WithLabelValues is the wrapper of SummaryVec.WithLabelValues.
func (vc *SummaryVecWithContext) WithLabelValues(lvs ...string) ObserverMetric {
return vc.SummaryVec.WithLabelValues(lvs...)
}
// With is the wrapper of SummaryVec.With.
func (vc *SummaryVecWithContext) With(labels map[string]string) ObserverMetric {
return vc.SummaryVec.With(labels)
}

View File

@ -281,21 +281,6 @@ func (hist *Histogram) Average() float64 {
return hist.GetSampleSum() / float64(hist.GetSampleCount())
}
// Clear clears all fields of the wrapped histogram
func (hist *Histogram) Clear() {
if hist.SampleCount != nil {
*hist.SampleCount = 0
}
if hist.SampleSum != nil {
*hist.SampleSum = 0
}
for _, b := range hist.Bucket {
if b.CumulativeCount != nil {
*b.CumulativeCount = 0
}
}
}
// Validate makes sure the wrapped histogram has all necessary fields set and with valid values.
func (hist *Histogram) Validate() error {
if hist.SampleCount == nil || hist.GetSampleCount() == 0 {
@ -318,7 +303,7 @@ func (hist *Histogram) Validate() error {
return nil
}
// GetGaugeMetricValue extract metric value from GaugeMetric
// GetGaugeMetricValue extracts metric value from GaugeMetric
func GetGaugeMetricValue(m metrics.GaugeMetric) (float64, error) {
metricProto := &dto.Metric{}
if err := m.Write(metricProto); err != nil {
@ -327,7 +312,7 @@ func GetGaugeMetricValue(m metrics.GaugeMetric) (float64, error) {
return metricProto.Gauge.GetValue(), nil
}
// GetCounterMetricValue extract metric value from CounterMetric
// GetCounterMetricValue extracts metric value from CounterMetric
func GetCounterMetricValue(m metrics.CounterMetric) (float64, error) {
metricProto := &dto.Metric{}
if err := m.(metrics.Metric).Write(metricProto); err != nil {
@ -336,7 +321,7 @@ func GetCounterMetricValue(m metrics.CounterMetric) (float64, error) {
return metricProto.Counter.GetValue(), nil
}
// GetHistogramMetricValue extract sum of all samples from ObserverMetric
// GetHistogramMetricValue extracts sum of all samples from ObserverMetric
func GetHistogramMetricValue(m metrics.ObserverMetric) (float64, error) {
metricProto := &dto.Metric{}
if err := m.(metrics.Metric).Write(metricProto); err != nil {
@ -345,6 +330,15 @@ func GetHistogramMetricValue(m metrics.ObserverMetric) (float64, error) {
return metricProto.Histogram.GetSampleSum(), nil
}
// GetHistogramMetricCount extracts count of all samples from ObserverMetric
func GetHistogramMetricCount(m metrics.ObserverMetric) (uint64, error) {
metricProto := &dto.Metric{}
if err := m.(metrics.Metric).Write(metricProto); err != nil {
return 0, fmt.Errorf("error writing m: %v", err)
}
return metricProto.Histogram.GetSampleCount(), nil
}
// LabelsMatch returns true if metric has all expected labels otherwise false
func LabelsMatch(metric *dto.Metric, labelFilter map[string]string) bool {
metricLabels := map[string]string{}