use istio client-go library instead of knative (#1661)
use istio client-go library instead of knative bump kubernetes dependency version change code coverage to codecov
This commit is contained in:
333
vendor/k8s.io/component-base/featuregate/feature_gate.go
generated
vendored
Normal file
333
vendor/k8s.io/component-base/featuregate/feature_gate.go
generated
vendored
Normal file
@@ -0,0 +1,333 @@
|
||||
/*
|
||||
Copyright 2016 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 featuregate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"k8s.io/klog"
|
||||
)
|
||||
|
||||
type Feature string
|
||||
|
||||
const (
|
||||
flagName = "feature-gates"
|
||||
|
||||
// allAlphaGate is a global toggle for alpha features. Per-feature key
|
||||
// values override the default set by allAlphaGate. Examples:
|
||||
// AllAlpha=false,NewFeature=true will result in newFeature=true
|
||||
// AllAlpha=true,NewFeature=false will result in newFeature=false
|
||||
allAlphaGate Feature = "AllAlpha"
|
||||
)
|
||||
|
||||
var (
|
||||
// The generic features.
|
||||
defaultFeatures = map[Feature]FeatureSpec{
|
||||
allAlphaGate: {Default: false, PreRelease: Alpha},
|
||||
}
|
||||
|
||||
// Special handling for a few gates.
|
||||
specialFeatures = map[Feature]func(known map[Feature]FeatureSpec, enabled map[Feature]bool, val bool){
|
||||
allAlphaGate: setUnsetAlphaGates,
|
||||
}
|
||||
)
|
||||
|
||||
type FeatureSpec struct {
|
||||
// Default is the default enablement state for the feature
|
||||
Default bool
|
||||
// LockToDefault indicates that the feature is locked to its default and cannot be changed
|
||||
LockToDefault bool
|
||||
// PreRelease indicates the maturity level of the feature
|
||||
PreRelease prerelease
|
||||
}
|
||||
|
||||
type prerelease string
|
||||
|
||||
const (
|
||||
// Values for PreRelease.
|
||||
Alpha = prerelease("ALPHA")
|
||||
Beta = prerelease("BETA")
|
||||
GA = prerelease("")
|
||||
|
||||
// Deprecated
|
||||
Deprecated = prerelease("DEPRECATED")
|
||||
)
|
||||
|
||||
// FeatureGate indicates whether a given feature is enabled or not
|
||||
type FeatureGate interface {
|
||||
// Enabled returns true if the key is enabled.
|
||||
Enabled(key Feature) bool
|
||||
// KnownFeatures returns a slice of strings describing the FeatureGate's known features.
|
||||
KnownFeatures() []string
|
||||
// DeepCopy returns a deep copy of the FeatureGate object, such that gates can be
|
||||
// set on the copy without mutating the original. This is useful for validating
|
||||
// config against potential feature gate changes before committing those changes.
|
||||
DeepCopy() MutableFeatureGate
|
||||
}
|
||||
|
||||
// MutableFeatureGate parses and stores flag gates for known features from
|
||||
// a string like feature1=true,feature2=false,...
|
||||
type MutableFeatureGate interface {
|
||||
FeatureGate
|
||||
|
||||
// AddFlag adds a flag for setting global feature gates to the specified FlagSet.
|
||||
AddFlag(fs *pflag.FlagSet)
|
||||
// Set parses and stores flag gates for known features
|
||||
// from a string like feature1=true,feature2=false,...
|
||||
Set(value string) error
|
||||
// SetFromMap stores flag gates for known features from a map[string]bool or returns an error
|
||||
SetFromMap(m map[string]bool) error
|
||||
// Add adds features to the featureGate.
|
||||
Add(features map[Feature]FeatureSpec) error
|
||||
}
|
||||
|
||||
// featureGate implements FeatureGate as well as pflag.Value for flag parsing.
|
||||
type featureGate struct {
|
||||
special map[Feature]func(map[Feature]FeatureSpec, map[Feature]bool, bool)
|
||||
|
||||
// lock guards writes to known, enabled, and reads/writes of closed
|
||||
lock sync.Mutex
|
||||
// known holds a map[Feature]FeatureSpec
|
||||
known *atomic.Value
|
||||
// enabled holds a map[Feature]bool
|
||||
enabled *atomic.Value
|
||||
// closed is set to true when AddFlag is called, and prevents subsequent calls to Add
|
||||
closed bool
|
||||
}
|
||||
|
||||
func setUnsetAlphaGates(known map[Feature]FeatureSpec, enabled map[Feature]bool, val bool) {
|
||||
for k, v := range known {
|
||||
if v.PreRelease == Alpha {
|
||||
if _, found := enabled[k]; !found {
|
||||
enabled[k] = val
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set, String, and Type implement pflag.Value
|
||||
var _ pflag.Value = &featureGate{}
|
||||
|
||||
func NewFeatureGate() *featureGate {
|
||||
known := map[Feature]FeatureSpec{}
|
||||
for k, v := range defaultFeatures {
|
||||
known[k] = v
|
||||
}
|
||||
|
||||
knownValue := &atomic.Value{}
|
||||
knownValue.Store(known)
|
||||
|
||||
enabled := map[Feature]bool{}
|
||||
enabledValue := &atomic.Value{}
|
||||
enabledValue.Store(enabled)
|
||||
|
||||
f := &featureGate{
|
||||
known: knownValue,
|
||||
special: specialFeatures,
|
||||
enabled: enabledValue,
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// Set parses a string of the form "key1=value1,key2=value2,..." into a
|
||||
// map[string]bool of known keys or returns an error.
|
||||
func (f *featureGate) Set(value string) error {
|
||||
m := make(map[string]bool)
|
||||
for _, s := range strings.Split(value, ",") {
|
||||
if len(s) == 0 {
|
||||
continue
|
||||
}
|
||||
arr := strings.SplitN(s, "=", 2)
|
||||
k := strings.TrimSpace(arr[0])
|
||||
if len(arr) != 2 {
|
||||
return fmt.Errorf("missing bool value for %s", k)
|
||||
}
|
||||
v := strings.TrimSpace(arr[1])
|
||||
boolValue, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid value of %s=%s, err: %v", k, v, err)
|
||||
}
|
||||
m[k] = boolValue
|
||||
}
|
||||
return f.SetFromMap(m)
|
||||
}
|
||||
|
||||
// SetFromMap stores flag gates for known features from a map[string]bool or returns an error
|
||||
func (f *featureGate) SetFromMap(m map[string]bool) error {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
|
||||
// Copy existing state
|
||||
known := map[Feature]FeatureSpec{}
|
||||
for k, v := range f.known.Load().(map[Feature]FeatureSpec) {
|
||||
known[k] = v
|
||||
}
|
||||
enabled := map[Feature]bool{}
|
||||
for k, v := range f.enabled.Load().(map[Feature]bool) {
|
||||
enabled[k] = v
|
||||
}
|
||||
|
||||
for k, v := range m {
|
||||
k := Feature(k)
|
||||
featureSpec, ok := known[k]
|
||||
if !ok {
|
||||
return fmt.Errorf("unrecognized feature gate: %s", k)
|
||||
}
|
||||
if featureSpec.LockToDefault && featureSpec.Default != v {
|
||||
return fmt.Errorf("cannot set feature gate %v to %v, feature is locked to %v", k, v, featureSpec.Default)
|
||||
}
|
||||
enabled[k] = v
|
||||
// Handle "special" features like "all alpha gates"
|
||||
if fn, found := f.special[k]; found {
|
||||
fn(known, enabled, v)
|
||||
}
|
||||
|
||||
if featureSpec.PreRelease == Deprecated {
|
||||
klog.Warningf("Setting deprecated feature gate %s=%t. It will be removed in a future release.", k, v)
|
||||
} else if featureSpec.PreRelease == GA {
|
||||
klog.Warningf("Setting GA feature gate %s=%t. It will be removed in a future release.", k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// Persist changes
|
||||
f.known.Store(known)
|
||||
f.enabled.Store(enabled)
|
||||
|
||||
klog.V(1).Infof("feature gates: %v", f.enabled)
|
||||
return nil
|
||||
}
|
||||
|
||||
// String returns a string containing all enabled feature gates, formatted as "key1=value1,key2=value2,...".
|
||||
func (f *featureGate) String() string {
|
||||
pairs := []string{}
|
||||
for k, v := range f.enabled.Load().(map[Feature]bool) {
|
||||
pairs = append(pairs, fmt.Sprintf("%s=%t", k, v))
|
||||
}
|
||||
sort.Strings(pairs)
|
||||
return strings.Join(pairs, ",")
|
||||
}
|
||||
|
||||
func (f *featureGate) Type() string {
|
||||
return "mapStringBool"
|
||||
}
|
||||
|
||||
// Add adds features to the featureGate.
|
||||
func (f *featureGate) Add(features map[Feature]FeatureSpec) error {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
|
||||
if f.closed {
|
||||
return fmt.Errorf("cannot add a feature gate after adding it to the flag set")
|
||||
}
|
||||
|
||||
// Copy existing state
|
||||
known := map[Feature]FeatureSpec{}
|
||||
for k, v := range f.known.Load().(map[Feature]FeatureSpec) {
|
||||
known[k] = v
|
||||
}
|
||||
|
||||
for name, spec := range features {
|
||||
if existingSpec, found := known[name]; found {
|
||||
if existingSpec == spec {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("feature gate %q with different spec already exists: %v", name, existingSpec)
|
||||
}
|
||||
|
||||
known[name] = spec
|
||||
}
|
||||
|
||||
// Persist updated state
|
||||
f.known.Store(known)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Enabled returns true if the key is enabled.
|
||||
func (f *featureGate) Enabled(key Feature) bool {
|
||||
if v, ok := f.enabled.Load().(map[Feature]bool)[key]; ok {
|
||||
return v
|
||||
}
|
||||
return f.known.Load().(map[Feature]FeatureSpec)[key].Default
|
||||
}
|
||||
|
||||
// AddFlag adds a flag for setting global feature gates to the specified FlagSet.
|
||||
func (f *featureGate) AddFlag(fs *pflag.FlagSet) {
|
||||
f.lock.Lock()
|
||||
// TODO(mtaufen): Shouldn't we just close it on the first Set/SetFromMap instead?
|
||||
// Not all components expose a feature gates flag using this AddFlag method, and
|
||||
// in the future, all components will completely stop exposing a feature gates flag,
|
||||
// in favor of componentconfig.
|
||||
f.closed = true
|
||||
f.lock.Unlock()
|
||||
|
||||
known := f.KnownFeatures()
|
||||
fs.Var(f, flagName, ""+
|
||||
"A set of key=value pairs that describe feature gates for alpha/experimental features. "+
|
||||
"Options are:\n"+strings.Join(known, "\n"))
|
||||
}
|
||||
|
||||
// KnownFeatures returns a slice of strings describing the FeatureGate's known features.
|
||||
// Deprecated and GA features are hidden from the list.
|
||||
func (f *featureGate) KnownFeatures() []string {
|
||||
var known []string
|
||||
for k, v := range f.known.Load().(map[Feature]FeatureSpec) {
|
||||
if v.PreRelease == GA || v.PreRelease == Deprecated {
|
||||
continue
|
||||
}
|
||||
known = append(known, fmt.Sprintf("%s=true|false (%s - default=%t)", k, v.PreRelease, v.Default))
|
||||
}
|
||||
sort.Strings(known)
|
||||
return known
|
||||
}
|
||||
|
||||
// DeepCopy returns a deep copy of the FeatureGate object, such that gates can be
|
||||
// set on the copy without mutating the original. This is useful for validating
|
||||
// config against potential feature gate changes before committing those changes.
|
||||
func (f *featureGate) DeepCopy() MutableFeatureGate {
|
||||
// Copy existing state.
|
||||
known := map[Feature]FeatureSpec{}
|
||||
for k, v := range f.known.Load().(map[Feature]FeatureSpec) {
|
||||
known[k] = v
|
||||
}
|
||||
enabled := map[Feature]bool{}
|
||||
for k, v := range f.enabled.Load().(map[Feature]bool) {
|
||||
enabled[k] = v
|
||||
}
|
||||
|
||||
// Store copied state in new atomics.
|
||||
knownValue := &atomic.Value{}
|
||||
knownValue.Store(known)
|
||||
enabledValue := &atomic.Value{}
|
||||
enabledValue.Store(enabled)
|
||||
|
||||
// Construct a new featureGate around the copied state.
|
||||
// Note that specialFeatures is treated as immutable by convention,
|
||||
// and we maintain the value of f.closed across the copy.
|
||||
return &featureGate{
|
||||
special: specialFeatures,
|
||||
known: knownValue,
|
||||
enabled: enabledValue,
|
||||
closed: f.closed,
|
||||
}
|
||||
}
|
||||
78
vendor/k8s.io/component-base/logs/logs.go
generated
vendored
Normal file
78
vendor/k8s.io/component-base/logs/logs.go
generated
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
Copyright 2014 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 logs
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"k8s.io/klog"
|
||||
)
|
||||
|
||||
const logFlushFreqFlagName = "log-flush-frequency"
|
||||
|
||||
var logFlushFreq = pflag.Duration(logFlushFreqFlagName, 5*time.Second, "Maximum number of seconds between log flushes")
|
||||
|
||||
func init() {
|
||||
klog.InitFlags(flag.CommandLine)
|
||||
}
|
||||
|
||||
// AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the
|
||||
// same value as the global flags.
|
||||
func AddFlags(fs *pflag.FlagSet) {
|
||||
fs.AddFlag(pflag.Lookup(logFlushFreqFlagName))
|
||||
}
|
||||
|
||||
// KlogWriter serves as a bridge between the standard log package and the glog package.
|
||||
type KlogWriter struct{}
|
||||
|
||||
// Write implements the io.Writer interface.
|
||||
func (writer KlogWriter) Write(data []byte) (n int, err error) {
|
||||
klog.InfoDepth(1, string(data))
|
||||
return len(data), nil
|
||||
}
|
||||
|
||||
// InitLogs initializes logs the way we want for kubernetes.
|
||||
func InitLogs() {
|
||||
log.SetOutput(KlogWriter{})
|
||||
log.SetFlags(0)
|
||||
// The default glog flush interval is 5 seconds.
|
||||
go wait.Forever(klog.Flush, *logFlushFreq)
|
||||
}
|
||||
|
||||
// FlushLogs flushes logs immediately.
|
||||
func FlushLogs() {
|
||||
klog.Flush()
|
||||
}
|
||||
|
||||
// NewLogger creates a new log.Logger which sends logs to klog.Info.
|
||||
func NewLogger(prefix string) *log.Logger {
|
||||
return log.New(KlogWriter{}, prefix, 0)
|
||||
}
|
||||
|
||||
// GlogSetter is a setter to set glog level.
|
||||
func GlogSetter(val string) (string, error) {
|
||||
var level klog.Level
|
||||
if err := level.Set(val); err != nil {
|
||||
return "", fmt.Errorf("failed set klog.logging.verbosity %s: %v", val, err)
|
||||
}
|
||||
return fmt.Sprintf("successfully set klog.logging.verbosity to %s", val), nil
|
||||
}
|
||||
12
vendor/k8s.io/component-base/metrics/OWNERS
generated
vendored
Normal file
12
vendor/k8s.io/component-base/metrics/OWNERS
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# See the OWNERS docs at https://go.k8s.io/owners
|
||||
|
||||
approvers:
|
||||
- piosz
|
||||
- brancz
|
||||
- logicalhan
|
||||
reviewers:
|
||||
- piosz
|
||||
- brancz
|
||||
- logicalhan
|
||||
labels:
|
||||
- sig/instrumentation
|
||||
165
vendor/k8s.io/component-base/metrics/counter.go
generated
vendored
Normal file
165
vendor/k8s.io/component-base/metrics/counter.go
generated
vendored
Normal file
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/blang/semver"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// Counter is our internal representation for our wrapping struct around prometheus
|
||||
// counters. Counter implements both kubeCollector and CounterMetric.
|
||||
type Counter struct {
|
||||
CounterMetric
|
||||
*CounterOpts
|
||||
lazyMetric
|
||||
selfCollector
|
||||
}
|
||||
|
||||
// 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.
|
||||
func NewCounter(opts *CounterOpts) *Counter {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
kc := &Counter{
|
||||
CounterOpts: opts,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
kc.setPrometheusCounter(noop)
|
||||
kc.lazyInit(kc)
|
||||
return kc
|
||||
}
|
||||
|
||||
// setPrometheusCounter sets the underlying CounterMetric object, i.e. the thing that does the measurement.
|
||||
func (c *Counter) setPrometheusCounter(counter prometheus.Counter) {
|
||||
c.CounterMetric = counter
|
||||
c.initSelfCollection(counter)
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (c *Counter) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(c.CounterOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
// initializeMetric invocation creates the actual underlying Counter. Until this method is called
|
||||
// the underlying counter is a no-op.
|
||||
func (c *Counter) initializeMetric() {
|
||||
c.CounterOpts.annotateStabilityLevel()
|
||||
// this actually creates the underlying prometheus counter.
|
||||
c.setPrometheusCounter(prometheus.NewCounter(c.CounterOpts.toPromCounterOpts()))
|
||||
}
|
||||
|
||||
// initializeDeprecatedMetric invocation creates the actual (but deprecated) Counter. Until this method
|
||||
// is called the underlying counter is a no-op.
|
||||
func (c *Counter) initializeDeprecatedMetric() {
|
||||
c.CounterOpts.markDeprecated()
|
||||
c.initializeMetric()
|
||||
}
|
||||
|
||||
// CounterVec is the internal representation of our wrapping struct around prometheus
|
||||
// counterVecs. CounterVec implements both kubeCollector and CounterVecMetric.
|
||||
type CounterVec struct {
|
||||
*prometheus.CounterVec
|
||||
*CounterOpts
|
||||
lazyMetric
|
||||
originalLabels []string
|
||||
}
|
||||
|
||||
// NewCounterVec returns an object which satisfies the kubeCollector and CounterVecMetric interfaces.
|
||||
// However, the object returned will not measure anything unless the collector is first
|
||||
// registered, since the metric is lazily instantiated.
|
||||
func NewCounterVec(opts *CounterOpts, labels []string) *CounterVec {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
cv := &CounterVec{
|
||||
CounterVec: noopCounterVec,
|
||||
CounterOpts: opts,
|
||||
originalLabels: labels,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
cv.lazyInit(cv)
|
||||
return cv
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (v *CounterVec) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(v.CounterOpts.DeprecatedVersion)
|
||||
|
||||
}
|
||||
|
||||
// initializeMetric invocation creates the actual underlying CounterVec. Until this method is called
|
||||
// the underlying counterVec is a no-op.
|
||||
func (v *CounterVec) initializeMetric() {
|
||||
v.CounterOpts.annotateStabilityLevel()
|
||||
v.CounterVec = prometheus.NewCounterVec(v.CounterOpts.toPromCounterOpts(), v.originalLabels)
|
||||
}
|
||||
|
||||
// initializeDeprecatedMetric invocation creates the actual (but deprecated) CounterVec. Until this method is called
|
||||
// the underlying counterVec is a no-op.
|
||||
func (v *CounterVec) initializeDeprecatedMetric() {
|
||||
v.CounterOpts.markDeprecated()
|
||||
v.initializeMetric()
|
||||
}
|
||||
|
||||
// Default Prometheus behavior actually results in the creation of a new metric
|
||||
// if a metric with the unique label values is not found in the underlying stored metricMap.
|
||||
// This means that if this function is called but the underlying metric is not registered
|
||||
// (which means it will never be exposed externally nor consumed), the metric will exist in memory
|
||||
// for perpetuity (i.e. throughout application lifecycle).
|
||||
//
|
||||
// For reference: https://github.com/prometheus/client_golang/blob/v0.9.2/prometheus/counter.go#L179-L197
|
||||
|
||||
// WithLabelValues returns the Counter for the given slice of label
|
||||
// values (same order as the VariableLabels in Desc). If that combination of
|
||||
// label values is accessed for the first time, a new Counter is created IFF the counterVec
|
||||
// has been registered to a metrics registry.
|
||||
func (v *CounterVec) WithLabelValues(lvs ...string) CounterMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop // return no-op counter
|
||||
}
|
||||
return v.CounterVec.WithLabelValues(lvs...)
|
||||
}
|
||||
|
||||
// With returns the Counter for the given Labels map (the label names
|
||||
// must match those of the VariableLabels in Desc). If that label map is
|
||||
// accessed for the first time, a new Counter is created IFF the counterVec has
|
||||
// been registered to a metrics registry.
|
||||
func (v *CounterVec) With(labels prometheus.Labels) CounterMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop // return no-op counter
|
||||
}
|
||||
return v.CounterVec.With(labels)
|
||||
}
|
||||
|
||||
// Delete deletes the metric where the variable labels are the same as those
|
||||
// passed in as labels. It returns true if a metric was deleted.
|
||||
//
|
||||
// It is not an error if the number and names of the Labels are inconsistent
|
||||
// with those of the VariableLabels in Desc. However, such inconsistent Labels
|
||||
// can never match an actual metric, so the method will always return false in
|
||||
// that case.
|
||||
func (v *CounterVec) Delete(labels prometheus.Labels) bool {
|
||||
if !v.IsCreated() {
|
||||
return false // since we haven't created the metric, we haven't deleted a metric with the passed in values
|
||||
}
|
||||
return v.CounterVec.Delete(labels)
|
||||
}
|
||||
164
vendor/k8s.io/component-base/metrics/gauge.go
generated
vendored
Normal file
164
vendor/k8s.io/component-base/metrics/gauge.go
generated
vendored
Normal file
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/blang/semver"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// Gauge is our internal representation for our wrapping struct around prometheus
|
||||
// gauges. kubeGauge implements both kubeCollector and KubeGauge.
|
||||
type Gauge struct {
|
||||
GaugeMetric
|
||||
*GaugeOpts
|
||||
lazyMetric
|
||||
selfCollector
|
||||
}
|
||||
|
||||
// NewGauge returns an object which satisfies the kubeCollector and KubeGauge interfaces.
|
||||
// However, the object returned will not measure anything unless the collector is first
|
||||
// registered, since the metric is lazily instantiated.
|
||||
func NewGauge(opts *GaugeOpts) *Gauge {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
kc := &Gauge{
|
||||
GaugeOpts: opts,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
kc.setPrometheusGauge(noop)
|
||||
kc.lazyInit(kc)
|
||||
return kc
|
||||
}
|
||||
|
||||
// setPrometheusGauge sets the underlying KubeGauge object, i.e. the thing that does the measurement.
|
||||
func (g *Gauge) setPrometheusGauge(gauge prometheus.Gauge) {
|
||||
g.GaugeMetric = gauge
|
||||
g.initSelfCollection(gauge)
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (g *Gauge) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(g.GaugeOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
// initializeMetric invocation creates the actual underlying Gauge. Until this method is called
|
||||
// the underlying gauge is a no-op.
|
||||
func (g *Gauge) initializeMetric() {
|
||||
g.GaugeOpts.annotateStabilityLevel()
|
||||
// this actually creates the underlying prometheus gauge.
|
||||
g.setPrometheusGauge(prometheus.NewGauge(g.GaugeOpts.toPromGaugeOpts()))
|
||||
}
|
||||
|
||||
// initializeDeprecatedMetric invocation creates the actual (but deprecated) Gauge. Until this method
|
||||
// is called the underlying gauge is a no-op.
|
||||
func (g *Gauge) initializeDeprecatedMetric() {
|
||||
g.GaugeOpts.markDeprecated()
|
||||
g.initializeMetric()
|
||||
}
|
||||
|
||||
// GaugeVec is the internal representation of our wrapping struct around prometheus
|
||||
// gaugeVecs. kubeGaugeVec implements both kubeCollector and KubeGaugeVec.
|
||||
type GaugeVec struct {
|
||||
*prometheus.GaugeVec
|
||||
*GaugeOpts
|
||||
lazyMetric
|
||||
originalLabels []string
|
||||
}
|
||||
|
||||
// NewGaugeVec returns an object which satisfies the kubeCollector and KubeGaugeVec interfaces.
|
||||
// However, the object returned will not measure anything unless the collector is first
|
||||
// registered, since the metric is lazily instantiated.
|
||||
func NewGaugeVec(opts *GaugeOpts, labels []string) *GaugeVec {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
cv := &GaugeVec{
|
||||
GaugeVec: noopGaugeVec,
|
||||
GaugeOpts: opts,
|
||||
originalLabels: labels,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
cv.lazyInit(cv)
|
||||
return cv
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (v *GaugeVec) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(v.GaugeOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
// initializeMetric invocation creates the actual underlying GaugeVec. Until this method is called
|
||||
// the underlying gaugeVec is a no-op.
|
||||
func (v *GaugeVec) initializeMetric() {
|
||||
v.GaugeOpts.annotateStabilityLevel()
|
||||
v.GaugeVec = prometheus.NewGaugeVec(v.GaugeOpts.toPromGaugeOpts(), v.originalLabels)
|
||||
}
|
||||
|
||||
// initializeDeprecatedMetric invocation creates the actual (but deprecated) GaugeVec. Until this method is called
|
||||
// the underlying gaugeVec is a no-op.
|
||||
func (v *GaugeVec) initializeDeprecatedMetric() {
|
||||
v.GaugeOpts.markDeprecated()
|
||||
v.initializeMetric()
|
||||
}
|
||||
|
||||
// Default Prometheus behavior actually results in the creation of a new metric
|
||||
// if a metric with the unique label values is not found in the underlying stored metricMap.
|
||||
// This means that if this function is called but the underlying metric is not registered
|
||||
// (which means it will never be exposed externally nor consumed), the metric will exist in memory
|
||||
// for perpetuity (i.e. throughout application lifecycle).
|
||||
//
|
||||
// For reference: https://github.com/prometheus/client_golang/blob/v0.9.2/prometheus/gauge.go#L190-L208
|
||||
|
||||
// WithLabelValues returns the GaugeMetric for the given slice of label
|
||||
// values (same order as the VariableLabels in Desc). If that combination of
|
||||
// label values is accessed for the first time, a new GaugeMetric is created IFF the gaugeVec
|
||||
// has been registered to a metrics registry.
|
||||
func (v *GaugeVec) WithLabelValues(lvs ...string) GaugeMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop // return no-op gauge
|
||||
}
|
||||
return v.GaugeVec.WithLabelValues(lvs...)
|
||||
}
|
||||
|
||||
// With returns the GaugeMetric for the given Labels map (the label names
|
||||
// must match those of the VariableLabels in Desc). If that label map is
|
||||
// accessed for the first time, a new GaugeMetric is created IFF the gaugeVec has
|
||||
// been registered to a metrics registry.
|
||||
func (v *GaugeVec) With(labels prometheus.Labels) GaugeMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop // return no-op gauge
|
||||
}
|
||||
return v.GaugeVec.With(labels)
|
||||
}
|
||||
|
||||
// Delete deletes the metric where the variable labels are the same as those
|
||||
// passed in as labels. It returns true if a metric was deleted.
|
||||
//
|
||||
// It is not an error if the number and names of the Labels are inconsistent
|
||||
// with those of the VariableLabels in Desc. However, such inconsistent Labels
|
||||
// can never match an actual metric, so the method will always return false in
|
||||
// that case.
|
||||
func (v *GaugeVec) Delete(labels prometheus.Labels) bool {
|
||||
if !v.IsCreated() {
|
||||
return false // since we haven't created the metric, we haven't deleted a metric with the passed in values
|
||||
}
|
||||
return v.GaugeVec.Delete(labels)
|
||||
}
|
||||
159
vendor/k8s.io/component-base/metrics/histogram.go
generated
vendored
Normal file
159
vendor/k8s.io/component-base/metrics/histogram.go
generated
vendored
Normal file
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/blang/semver"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// Histogram is our internal representation for our wrapping struct around prometheus
|
||||
// histograms. Summary implements both kubeCollector and ObserverMetric
|
||||
type Histogram struct {
|
||||
ObserverMetric
|
||||
*HistogramOpts
|
||||
lazyMetric
|
||||
selfCollector
|
||||
}
|
||||
|
||||
// NewHistogram returns an object which is Histogram-like. However, nothing
|
||||
// will be measured until the histogram is registered somewhere.
|
||||
func NewHistogram(opts *HistogramOpts) *Histogram {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
h := &Histogram{
|
||||
HistogramOpts: opts,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
h.setPrometheusHistogram(noopMetric{})
|
||||
h.lazyInit(h)
|
||||
return h
|
||||
}
|
||||
|
||||
// setPrometheusHistogram sets the underlying KubeGauge object, i.e. the thing that does the measurement.
|
||||
func (h *Histogram) setPrometheusHistogram(histogram prometheus.Histogram) {
|
||||
h.ObserverMetric = histogram
|
||||
h.initSelfCollection(histogram)
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (h *Histogram) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(h.HistogramOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
// initializeMetric invokes the actual prometheus.Histogram object instantiation
|
||||
// and stores a reference to it
|
||||
func (h *Histogram) initializeMetric() {
|
||||
h.HistogramOpts.annotateStabilityLevel()
|
||||
// this actually creates the underlying prometheus gauge.
|
||||
h.setPrometheusHistogram(prometheus.NewHistogram(h.HistogramOpts.toPromHistogramOpts()))
|
||||
}
|
||||
|
||||
// initializeDeprecatedMetric invokes the actual prometheus.Histogram object instantiation
|
||||
// but modifies the Help description prior to object instantiation.
|
||||
func (h *Histogram) initializeDeprecatedMetric() {
|
||||
h.HistogramOpts.markDeprecated()
|
||||
h.initializeMetric()
|
||||
}
|
||||
|
||||
// HistogramVec is the internal representation of our wrapping struct around prometheus
|
||||
// histogramVecs.
|
||||
type HistogramVec struct {
|
||||
*prometheus.HistogramVec
|
||||
*HistogramOpts
|
||||
lazyMetric
|
||||
originalLabels []string
|
||||
}
|
||||
|
||||
// NewHistogramVec returns an object which satisfies kubeCollector and wraps the
|
||||
// prometheus.HistogramVec object. However, the object returned will not measure
|
||||
// anything unless the collector is first registered, since the metric is lazily instantiated.
|
||||
func NewHistogramVec(opts *HistogramOpts, labels []string) *HistogramVec {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
v := &HistogramVec{
|
||||
HistogramVec: noopHistogramVec,
|
||||
HistogramOpts: opts,
|
||||
originalLabels: labels,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
v.lazyInit(v)
|
||||
return v
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (v *HistogramVec) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(v.HistogramOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
func (v *HistogramVec) initializeMetric() {
|
||||
v.HistogramOpts.annotateStabilityLevel()
|
||||
v.HistogramVec = prometheus.NewHistogramVec(v.HistogramOpts.toPromHistogramOpts(), v.originalLabels)
|
||||
}
|
||||
|
||||
func (v *HistogramVec) initializeDeprecatedMetric() {
|
||||
v.HistogramOpts.markDeprecated()
|
||||
v.initializeMetric()
|
||||
}
|
||||
|
||||
// Default Prometheus behavior actually results in the creation of a new metric
|
||||
// if a metric with the unique label values is not found in the underlying stored metricMap.
|
||||
// This means that if this function is called but the underlying metric is not registered
|
||||
// (which means it will never be exposed externally nor consumed), the metric will exist in memory
|
||||
// for perpetuity (i.e. throughout application lifecycle).
|
||||
//
|
||||
// For reference: https://github.com/prometheus/client_golang/blob/v0.9.2/prometheus/histogram.go#L460-L470
|
||||
|
||||
// WithLabelValues returns the ObserverMetric for the given slice of label
|
||||
// values (same order as the VariableLabels in Desc). If that combination of
|
||||
// label values is accessed for the first time, a new ObserverMetric is created IFF the HistogramVec
|
||||
// has been registered to a metrics registry.
|
||||
func (v *HistogramVec) WithLabelValues(lvs ...string) ObserverMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop
|
||||
}
|
||||
return v.HistogramVec.WithLabelValues(lvs...)
|
||||
}
|
||||
|
||||
// With returns the ObserverMetric for the given Labels map (the label names
|
||||
// must match those of the VariableLabels in Desc). If that label map is
|
||||
// accessed for the first time, a new ObserverMetric is created IFF the HistogramVec has
|
||||
// been registered to a metrics registry.
|
||||
func (v *HistogramVec) With(labels prometheus.Labels) ObserverMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop
|
||||
}
|
||||
return v.HistogramVec.With(labels)
|
||||
}
|
||||
|
||||
// Delete deletes the metric where the variable labels are the same as those
|
||||
// passed in as labels. It returns true if a metric was deleted.
|
||||
//
|
||||
// It is not an error if the number and names of the Labels are inconsistent
|
||||
// with those of the VariableLabels in Desc. However, such inconsistent Labels
|
||||
// can never match an actual metric, so the method will always return false in
|
||||
// that case.
|
||||
func (v *HistogramVec) Delete(labels prometheus.Labels) bool {
|
||||
if !v.IsCreated() {
|
||||
return false // since we haven't created the metric, we haven't deleted a metric with the passed in values
|
||||
}
|
||||
return v.HistogramVec.Delete(labels)
|
||||
}
|
||||
85
vendor/k8s.io/component-base/metrics/legacyregistry/registry.go
generated
vendored
Normal file
85
vendor/k8s.io/component-base/metrics/legacyregistry/registry.go
generated
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
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 legacyregistry
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"k8s.io/component-base/metrics"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultRegistry = metrics.NewKubeRegistry()
|
||||
// DefaultGatherer exposes the global registry gatherer
|
||||
DefaultGatherer prometheus.Gatherer = defaultRegistry
|
||||
)
|
||||
|
||||
func init() {
|
||||
RawMustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
|
||||
RawMustRegister(prometheus.NewGoCollector())
|
||||
}
|
||||
|
||||
// Handler returns an HTTP handler for the DefaultGatherer. It is
|
||||
// already instrumented with InstrumentHandler (using "prometheus" as handler
|
||||
// name).
|
||||
//
|
||||
// Deprecated: Please note the issues described in the doc comment of
|
||||
// InstrumentHandler. You might want to consider using promhttp.Handler instead.
|
||||
func Handler() http.Handler {
|
||||
return prometheus.InstrumentHandler("prometheus", promhttp.HandlerFor(defaultRegistry, promhttp.HandlerOpts{}))
|
||||
}
|
||||
|
||||
// Register registers a collectable metric but uses the global registry
|
||||
func Register(c metrics.Registerable) error {
|
||||
err := defaultRegistry.Register(c)
|
||||
// sideload global prom registry as fallback
|
||||
prometheus.Register(c)
|
||||
return err
|
||||
}
|
||||
|
||||
// MustRegister registers registerable metrics but uses the global registry.
|
||||
func MustRegister(cs ...metrics.Registerable) {
|
||||
defaultRegistry.MustRegister(cs...)
|
||||
// sideload global prom registry as fallback
|
||||
for _, c := range cs {
|
||||
prometheus.Register(c)
|
||||
}
|
||||
}
|
||||
|
||||
// RawMustRegister registers prometheus collectors but uses the global registry, this
|
||||
// bypasses the metric stability framework
|
||||
//
|
||||
// Deprecated
|
||||
func RawMustRegister(cs ...prometheus.Collector) {
|
||||
defaultRegistry.RawMustRegister(cs...)
|
||||
// sideload global prom registry as fallback
|
||||
for _, c := range cs {
|
||||
prometheus.Register(c)
|
||||
}
|
||||
}
|
||||
|
||||
// RawRegister registers a prometheus collector but uses the global registry, this
|
||||
// bypasses the metric stability framework
|
||||
//
|
||||
// Deprecated
|
||||
func RawRegister(c prometheus.Collector) error {
|
||||
err := defaultRegistry.RawRegister(c)
|
||||
// sideload global prom registry as fallback
|
||||
prometheus.Register(c)
|
||||
return err
|
||||
}
|
||||
206
vendor/k8s.io/component-base/metrics/metric.go
generated
vendored
Normal file
206
vendor/k8s.io/component-base/metrics/metric.go
generated
vendored
Normal file
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/blang/semver"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"k8s.io/klog"
|
||||
"sync"
|
||||
)
|
||||
|
||||
/*
|
||||
kubeCollector extends the prometheus.Collector interface to allow customization of the metric
|
||||
registration process. Defer metric initialization until Create() is called, which then
|
||||
delegates to the underlying metric's initializeMetric or initializeDeprecatedMetric
|
||||
method call depending on whether the metric is deprecated or not.
|
||||
*/
|
||||
type kubeCollector interface {
|
||||
Collector
|
||||
lazyKubeMetric
|
||||
DeprecatedVersion() *semver.Version
|
||||
// Each collector metric should provide an initialization function
|
||||
// for both deprecated and non-deprecated variants of a metric. This
|
||||
// is necessary since metric instantiation will be deferred
|
||||
// until the metric is actually registered somewhere.
|
||||
initializeMetric()
|
||||
initializeDeprecatedMetric()
|
||||
}
|
||||
|
||||
/*
|
||||
lazyKubeMetric defines our metric registration interface. lazyKubeMetric objects are expected
|
||||
to lazily instantiate metrics (i.e defer metric instantiation until when
|
||||
the Create() function is explicitly called).
|
||||
*/
|
||||
type lazyKubeMetric interface {
|
||||
Create(*semver.Version) bool
|
||||
IsCreated() bool
|
||||
IsHidden() bool
|
||||
IsDeprecated() bool
|
||||
}
|
||||
|
||||
/*
|
||||
lazyMetric implements lazyKubeMetric. A lazy metric is lazy because it waits until metric
|
||||
registration time before instantiation. Add it as an anonymous field to a struct that
|
||||
implements kubeCollector to get deferred registration behavior. You must call lazyInit
|
||||
with the kubeCollector itself as an argument.
|
||||
*/
|
||||
type lazyMetric struct {
|
||||
isDeprecated bool
|
||||
isHidden bool
|
||||
isCreated bool
|
||||
createLock sync.RWMutex
|
||||
markDeprecationOnce sync.Once
|
||||
createOnce sync.Once
|
||||
self kubeCollector
|
||||
}
|
||||
|
||||
func (r *lazyMetric) IsCreated() bool {
|
||||
r.createLock.RLock()
|
||||
defer r.createLock.RUnlock()
|
||||
return r.isCreated
|
||||
}
|
||||
|
||||
// lazyInit provides the lazyMetric with a reference to the kubeCollector it is supposed
|
||||
// to allow lazy initialization for. It should be invoked in the factory function which creates new
|
||||
// kubeCollector type objects.
|
||||
func (r *lazyMetric) lazyInit(self kubeCollector) {
|
||||
r.self = self
|
||||
}
|
||||
|
||||
// determineDeprecationStatus figures out whether the lazy metric should be deprecated 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) {
|
||||
selfVersion := r.self.DeprecatedVersion()
|
||||
if selfVersion == nil {
|
||||
return
|
||||
}
|
||||
r.markDeprecationOnce.Do(func() {
|
||||
if selfVersion.LTE(version) {
|
||||
r.isDeprecated = true
|
||||
}
|
||||
if ShouldShowHidden() {
|
||||
klog.Warningf("Hidden metrics have been manually overridden, showing this very deprecated metric.")
|
||||
return
|
||||
}
|
||||
if selfVersion.LT(version) {
|
||||
klog.Warningf("This metric has been deprecated for more than one release, hiding.")
|
||||
r.isHidden = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (r *lazyMetric) IsHidden() bool {
|
||||
return r.isHidden
|
||||
}
|
||||
|
||||
func (r *lazyMetric) IsDeprecated() bool {
|
||||
return r.isDeprecated
|
||||
}
|
||||
|
||||
// Create forces the initialization of metric which has been deferred until
|
||||
// the point at which this method is invoked. This method will determine whether
|
||||
// the metric is deprecated or hidden, no-opting if the metric should be considered
|
||||
// hidden. Furthermore, this function no-opts and returns true if metric is already
|
||||
// created.
|
||||
func (r *lazyMetric) Create(version *semver.Version) bool {
|
||||
if version != nil {
|
||||
r.determineDeprecationStatus(*version)
|
||||
}
|
||||
// let's not create if this metric is slated to be hidden
|
||||
if r.IsHidden() {
|
||||
return false
|
||||
}
|
||||
r.createOnce.Do(func() {
|
||||
r.createLock.Lock()
|
||||
defer r.createLock.Unlock()
|
||||
r.isCreated = true
|
||||
if r.IsDeprecated() {
|
||||
r.self.initializeDeprecatedMetric()
|
||||
} else {
|
||||
r.self.initializeMetric()
|
||||
}
|
||||
})
|
||||
return r.IsCreated()
|
||||
}
|
||||
|
||||
/*
|
||||
This code is directly lifted from the prometheus codebase. It's a convenience struct which
|
||||
allows you satisfy the Collector interface automatically if you already satisfy the Metric interface.
|
||||
|
||||
For reference: https://github.com/prometheus/client_golang/blob/v0.9.2/prometheus/collector.go#L98-L120
|
||||
*/
|
||||
type selfCollector struct {
|
||||
metric prometheus.Metric
|
||||
}
|
||||
|
||||
func (c *selfCollector) initSelfCollection(m prometheus.Metric) {
|
||||
c.metric = m
|
||||
}
|
||||
|
||||
func (c *selfCollector) Describe(ch chan<- *prometheus.Desc) {
|
||||
ch <- c.metric.Desc()
|
||||
}
|
||||
|
||||
func (c *selfCollector) Collect(ch chan<- prometheus.Metric) {
|
||||
ch <- c.metric
|
||||
}
|
||||
|
||||
// no-op vecs for convenience
|
||||
var noopCounterVec = &prometheus.CounterVec{}
|
||||
var noopHistogramVec = &prometheus.HistogramVec{}
|
||||
var noopSummaryVec = &prometheus.SummaryVec{}
|
||||
var noopGaugeVec = &prometheus.GaugeVec{}
|
||||
var noopObserverVec = &noopObserverVector{}
|
||||
|
||||
// just use a convenience struct for all the no-ops
|
||||
var noop = &noopMetric{}
|
||||
|
||||
type noopMetric struct{}
|
||||
|
||||
func (noopMetric) Inc() {}
|
||||
func (noopMetric) Add(float64) {}
|
||||
func (noopMetric) Dec() {}
|
||||
func (noopMetric) Set(float64) {}
|
||||
func (noopMetric) Sub(float64) {}
|
||||
func (noopMetric) Observe(float64) {}
|
||||
func (noopMetric) SetToCurrentTime() {}
|
||||
func (noopMetric) Desc() *prometheus.Desc { return nil }
|
||||
func (noopMetric) Write(*dto.Metric) error { return nil }
|
||||
func (noopMetric) Describe(chan<- *prometheus.Desc) {}
|
||||
func (noopMetric) Collect(chan<- prometheus.Metric) {}
|
||||
|
||||
type noopObserverVector struct{}
|
||||
|
||||
func (noopObserverVector) GetMetricWith(prometheus.Labels) (prometheus.Observer, error) {
|
||||
return noop, nil
|
||||
}
|
||||
func (noopObserverVector) GetMetricWithLabelValues(...string) (prometheus.Observer, error) {
|
||||
return noop, nil
|
||||
}
|
||||
func (noopObserverVector) With(prometheus.Labels) prometheus.Observer { return noop }
|
||||
func (noopObserverVector) WithLabelValues(...string) prometheus.Observer { return noop }
|
||||
func (noopObserverVector) CurryWith(prometheus.Labels) (prometheus.ObserverVec, error) {
|
||||
return noopObserverVec, nil
|
||||
}
|
||||
func (noopObserverVector) MustCurryWith(prometheus.Labels) prometheus.ObserverVec {
|
||||
return noopObserverVec
|
||||
}
|
||||
func (noopObserverVector) Describe(chan<- *prometheus.Desc) {}
|
||||
func (noopObserverVector) Collect(chan<- prometheus.Metric) {}
|
||||
211
vendor/k8s.io/component-base/metrics/opts.go
generated
vendored
Normal file
211
vendor/k8s.io/component-base/metrics/opts.go
generated
vendored
Normal file
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
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 (
|
||||
"fmt"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// KubeOpts is superset struct for prometheus.Opts. The prometheus Opts structure
|
||||
// is purposefully not embedded here because that would change struct initialization
|
||||
// in the manner which people are currently accustomed.
|
||||
//
|
||||
// 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 prometheus.Labels
|
||||
DeprecatedVersion string
|
||||
deprecateOnce sync.Once
|
||||
annotateOnce sync.Once
|
||||
StabilityLevel StabilityLevel
|
||||
}
|
||||
|
||||
// StabilityLevel represents the API guarantees for a given defined metric.
|
||||
type StabilityLevel string
|
||||
|
||||
const (
|
||||
// ALPHA metrics have no stability guarantees, as such, labels may
|
||||
// be arbitrarily added/removed and the metric may be deleted at any time.
|
||||
ALPHA StabilityLevel = "ALPHA"
|
||||
// STABLE metrics are guaranteed not be mutated and removal is governed by
|
||||
// the deprecation policy outlined in by the control plane metrics stability KEP.
|
||||
STABLE StabilityLevel = "STABLE"
|
||||
)
|
||||
|
||||
// CounterOpts is an alias for Opts. See there for doc comments.
|
||||
type CounterOpts KubeOpts
|
||||
|
||||
// Modify help description on the metric description.
|
||||
func (o *CounterOpts) markDeprecated() {
|
||||
o.deprecateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("(Deprecated since %v) %v", o.DeprecatedVersion, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// annotateStabilityLevel annotates help description on the metric description with the stability level
|
||||
// of the metric
|
||||
func (o *CounterOpts) annotateStabilityLevel() {
|
||||
o.annotateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("[%v] %v", o.StabilityLevel, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// convenience function to allow easy transformation to the prometheus
|
||||
// counterpart. This will do more once we have a proper label abstraction
|
||||
func (o *CounterOpts) toPromCounterOpts() prometheus.CounterOpts {
|
||||
return prometheus.CounterOpts{
|
||||
Namespace: o.Namespace,
|
||||
Subsystem: o.Subsystem,
|
||||
Name: o.Name,
|
||||
Help: o.Help,
|
||||
ConstLabels: o.ConstLabels,
|
||||
}
|
||||
}
|
||||
|
||||
// GaugeOpts is an alias for Opts. See there for doc comments.
|
||||
type GaugeOpts KubeOpts
|
||||
|
||||
// Modify help description on the metric description.
|
||||
func (o *GaugeOpts) markDeprecated() {
|
||||
o.deprecateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("(Deprecated since %v) %v", o.DeprecatedVersion, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// annotateStabilityLevel annotates help description on the metric description with the stability level
|
||||
// of the metric
|
||||
func (o *GaugeOpts) annotateStabilityLevel() {
|
||||
o.annotateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("[%v] %v", o.StabilityLevel, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// convenience function to allow easy transformation to the prometheus
|
||||
// counterpart. This will do more once we have a proper label abstraction
|
||||
func (o GaugeOpts) toPromGaugeOpts() prometheus.GaugeOpts {
|
||||
return prometheus.GaugeOpts{
|
||||
Namespace: o.Namespace,
|
||||
Subsystem: o.Subsystem,
|
||||
Name: o.Name,
|
||||
Help: o.Help,
|
||||
ConstLabels: o.ConstLabels,
|
||||
}
|
||||
}
|
||||
|
||||
// HistogramOpts bundles the options for creating a Histogram metric. It is
|
||||
// mandatory to set Name to a non-empty string. All other fields are optional
|
||||
// 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 prometheus.Labels
|
||||
Buckets []float64
|
||||
DeprecatedVersion string
|
||||
deprecateOnce sync.Once
|
||||
annotateOnce sync.Once
|
||||
StabilityLevel StabilityLevel
|
||||
}
|
||||
|
||||
// Modify help description on the metric description.
|
||||
func (o *HistogramOpts) markDeprecated() {
|
||||
o.deprecateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("(Deprecated since %v) %v", o.DeprecatedVersion, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// annotateStabilityLevel annotates help description on the metric description with the stability level
|
||||
// of the metric
|
||||
func (o *HistogramOpts) annotateStabilityLevel() {
|
||||
o.annotateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("[%v] %v", o.StabilityLevel, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// convenience function to allow easy transformation to the prometheus
|
||||
// counterpart. This will do more once we have a proper label abstraction
|
||||
func (o HistogramOpts) toPromHistogramOpts() prometheus.HistogramOpts {
|
||||
return prometheus.HistogramOpts{
|
||||
Namespace: o.Namespace,
|
||||
Subsystem: o.Subsystem,
|
||||
Name: o.Name,
|
||||
Help: o.Help,
|
||||
ConstLabels: o.ConstLabels,
|
||||
Buckets: o.Buckets,
|
||||
}
|
||||
}
|
||||
|
||||
// SummaryOpts bundles the options for creating a Summary metric. It is
|
||||
// mandatory to set Name to a non-empty string. While all other fields are
|
||||
// optional and can safely be left at their zero value, it is recommended to set
|
||||
// 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 prometheus.Labels
|
||||
Objectives map[float64]float64
|
||||
MaxAge time.Duration
|
||||
AgeBuckets uint32
|
||||
BufCap uint32
|
||||
DeprecatedVersion string
|
||||
deprecateOnce sync.Once
|
||||
annotateOnce sync.Once
|
||||
StabilityLevel StabilityLevel
|
||||
}
|
||||
|
||||
// Modify help description on the metric description.
|
||||
func (o *SummaryOpts) markDeprecated() {
|
||||
o.deprecateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("(Deprecated since %v) %v", o.DeprecatedVersion, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// annotateStabilityLevel annotates help description on the metric description with the stability level
|
||||
// of the metric
|
||||
func (o *SummaryOpts) annotateStabilityLevel() {
|
||||
o.annotateOnce.Do(func() {
|
||||
o.Help = fmt.Sprintf("[%v] %v", o.StabilityLevel, o.Help)
|
||||
})
|
||||
}
|
||||
|
||||
// convenience function to allow easy transformation to the prometheus
|
||||
// counterpart. This will do more once we have a proper label abstraction
|
||||
func (o SummaryOpts) toPromSummaryOpts() prometheus.SummaryOpts {
|
||||
return prometheus.SummaryOpts{
|
||||
Namespace: o.Namespace,
|
||||
Subsystem: o.Subsystem,
|
||||
Name: o.Name,
|
||||
Help: o.Help,
|
||||
ConstLabels: o.ConstLabels,
|
||||
Objectives: o.Objectives,
|
||||
MaxAge: o.MaxAge,
|
||||
AgeBuckets: o.AgeBuckets,
|
||||
BufCap: o.BufCap,
|
||||
}
|
||||
}
|
||||
64
vendor/k8s.io/component-base/metrics/processstarttime.go
generated
vendored
Normal file
64
vendor/k8s.io/component-base/metrics/processstarttime.go
generated
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/procfs"
|
||||
"k8s.io/klog"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
var processStartTime = prometheus.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "process_start_time_seconds",
|
||||
Help: "Start time of the process since unix epoch in seconds.",
|
||||
},
|
||||
[]string{},
|
||||
)
|
||||
|
||||
// Registerer is an interface expected by RegisterProcessStartTime in order to register the metric
|
||||
type Registerer interface {
|
||||
Register(prometheus.Collector) error
|
||||
}
|
||||
|
||||
// RegisterProcessStartTime registers the process_start_time_seconds to
|
||||
// a prometheus registry. This metric needs to be included to ensure counter
|
||||
// data fidelity.
|
||||
func RegisterProcessStartTime(registrationFunc func(prometheus.Collector) error) error {
|
||||
start, err := getProcessStart()
|
||||
if err != nil {
|
||||
klog.Errorf("Could not get process start time, %v", err)
|
||||
start = float64(time.Now().Unix())
|
||||
}
|
||||
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.NewStat(); err == nil {
|
||||
return stat.StartTime()
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
161
vendor/k8s.io/component-base/metrics/registry.go
generated
vendored
Normal file
161
vendor/k8s.io/component-base/metrics/registry.go
generated
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
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 (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/blang/semver"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
|
||||
apimachineryversion "k8s.io/apimachinery/pkg/version"
|
||||
"k8s.io/component-base/version"
|
||||
)
|
||||
|
||||
var (
|
||||
showHiddenOnce sync.Once
|
||||
showHidden atomic.Value
|
||||
)
|
||||
|
||||
// SetShowHidden will enable showing hidden metrics. This will no-opt
|
||||
// after the initial call
|
||||
func SetShowHidden() {
|
||||
showHiddenOnce.Do(func() {
|
||||
showHidden.Store(true)
|
||||
})
|
||||
}
|
||||
|
||||
// ShouldShowHidden returns whether showing hidden deprecated metrics
|
||||
// is enabled. While the primary usecase for this is internal (to determine
|
||||
// registration behavior) this can also be used to introspect
|
||||
func ShouldShowHidden() bool {
|
||||
return showHidden.Load() != nil && showHidden.Load().(bool)
|
||||
}
|
||||
|
||||
// Registerable is an interface for a collector metric which we
|
||||
// will register with KubeRegistry.
|
||||
type Registerable interface {
|
||||
prometheus.Collector
|
||||
Create(version *semver.Version) bool
|
||||
}
|
||||
|
||||
// KubeRegistry is an interface which implements a subset of prometheus.Registerer and
|
||||
// prometheus.Gatherer interfaces
|
||||
type KubeRegistry interface {
|
||||
// Deprecated
|
||||
RawRegister(prometheus.Collector) error
|
||||
// Deprecated
|
||||
RawMustRegister(...prometheus.Collector)
|
||||
Register(Registerable) error
|
||||
MustRegister(...Registerable)
|
||||
Unregister(Registerable) bool
|
||||
Gather() ([]*dto.MetricFamily, error)
|
||||
}
|
||||
|
||||
// kubeRegistry is a wrapper around a prometheus registry-type object. Upon initialization
|
||||
// the kubernetes binary version information is loaded into the registry object, so that
|
||||
// automatic behavior can be configured for metric versioning.
|
||||
type kubeRegistry struct {
|
||||
PromRegistry
|
||||
version semver.Version
|
||||
}
|
||||
|
||||
// Register registers a new Collector to be included in metrics
|
||||
// collection. It returns an error if the descriptors provided by the
|
||||
// Collector are invalid or if they — in combination with descriptors of
|
||||
// already registered Collectors — do not fulfill the consistency and
|
||||
// uniqueness criteria described in the documentation of metric.Desc.
|
||||
func (kr *kubeRegistry) Register(c Registerable) error {
|
||||
if c.Create(&kr.version) {
|
||||
return kr.PromRegistry.Register(c)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MustRegister works like Register but registers any number of
|
||||
// Collectors and panics upon the first registration that causes an
|
||||
// error.
|
||||
func (kr *kubeRegistry) MustRegister(cs ...Registerable) {
|
||||
metrics := make([]prometheus.Collector, 0, len(cs))
|
||||
for _, c := range cs {
|
||||
if c.Create(&kr.version) {
|
||||
metrics = append(metrics, c)
|
||||
}
|
||||
}
|
||||
kr.PromRegistry.MustRegister(metrics...)
|
||||
}
|
||||
|
||||
// RawRegister takes a native prometheus.Collector and registers the collector
|
||||
// to the registry. This bypasses metrics safety checks, so should only be used
|
||||
// to register custom prometheus collectors.
|
||||
//
|
||||
// Deprecated
|
||||
func (kr *kubeRegistry) RawRegister(c prometheus.Collector) error {
|
||||
return kr.PromRegistry.Register(c)
|
||||
}
|
||||
|
||||
// RawMustRegister takes a native prometheus.Collector and registers the collector
|
||||
// to the registry. This bypasses metrics safety checks, so should only be used
|
||||
// to register custom prometheus collectors.
|
||||
//
|
||||
// Deprecated
|
||||
func (kr *kubeRegistry) RawMustRegister(cs ...prometheus.Collector) {
|
||||
kr.PromRegistry.MustRegister(cs...)
|
||||
}
|
||||
|
||||
// Unregister unregisters the Collector that equals the Collector passed
|
||||
// in as an argument. (Two Collectors are considered equal if their
|
||||
// Describe method yields the same set of descriptors.) The function
|
||||
// returns whether a Collector was unregistered. Note that an unchecked
|
||||
// Collector cannot be unregistered (as its Describe method does not
|
||||
// yield any descriptor).
|
||||
func (kr *kubeRegistry) Unregister(collector Registerable) bool {
|
||||
return kr.PromRegistry.Unregister(collector)
|
||||
}
|
||||
|
||||
// Gather calls the Collect method of the registered Collectors and then
|
||||
// gathers the collected metrics into a lexicographically sorted slice
|
||||
// of uniquely named MetricFamily protobufs. Gather ensures that the
|
||||
// returned slice is valid and self-consistent so that it can be used
|
||||
// for valid exposition. As an exception to the strict consistency
|
||||
// requirements described for metric.Desc, Gather will tolerate
|
||||
// different sets of label names for metrics of the same metric family.
|
||||
func (kr *kubeRegistry) Gather() ([]*dto.MetricFamily, error) {
|
||||
return kr.PromRegistry.Gather()
|
||||
}
|
||||
|
||||
func newKubeRegistry(v apimachineryversion.Info) *kubeRegistry {
|
||||
r := &kubeRegistry{
|
||||
PromRegistry: prometheus.NewRegistry(),
|
||||
version: parseVersion(v),
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func registerMetadataMetrics(r *kubeRegistry) {
|
||||
RegisterBuildInfo(r)
|
||||
}
|
||||
|
||||
// NewKubeRegistry creates a new vanilla Registry without any Collectors
|
||||
// pre-registered.
|
||||
func NewKubeRegistry() KubeRegistry {
|
||||
r := newKubeRegistry(version.Get())
|
||||
registerMetadataMetrics(r)
|
||||
return r
|
||||
}
|
||||
166
vendor/k8s.io/component-base/metrics/summary.go
generated
vendored
Normal file
166
vendor/k8s.io/component-base/metrics/summary.go
generated
vendored
Normal file
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/blang/semver"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// Summary is our internal representation for our wrapping struct around prometheus
|
||||
// summaries. Summary implements both kubeCollector and ObserverMetric
|
||||
//
|
||||
// DEPRECATED: as per the metrics overhaul KEP
|
||||
type Summary struct {
|
||||
ObserverMetric
|
||||
*SummaryOpts
|
||||
lazyMetric
|
||||
selfCollector
|
||||
}
|
||||
|
||||
// NewSummary returns an object which is Summary-like. However, nothing
|
||||
// will be measured until the summary is registered somewhere.
|
||||
//
|
||||
// DEPRECATED: as per the metrics overhaul KEP
|
||||
func NewSummary(opts *SummaryOpts) *Summary {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
s := &Summary{
|
||||
SummaryOpts: opts,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
s.setPrometheusSummary(noopMetric{})
|
||||
s.lazyInit(s)
|
||||
return s
|
||||
}
|
||||
|
||||
// setPrometheusSummary sets the underlying KubeGauge object, i.e. the thing that does the measurement.
|
||||
func (s *Summary) setPrometheusSummary(summary prometheus.Summary) {
|
||||
s.ObserverMetric = summary
|
||||
s.initSelfCollection(summary)
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (s *Summary) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(s.SummaryOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
// initializeMetric invokes the actual prometheus.Summary object instantiation
|
||||
// and stores a reference to it
|
||||
func (s *Summary) initializeMetric() {
|
||||
s.SummaryOpts.annotateStabilityLevel()
|
||||
// this actually creates the underlying prometheus gauge.
|
||||
s.setPrometheusSummary(prometheus.NewSummary(s.SummaryOpts.toPromSummaryOpts()))
|
||||
}
|
||||
|
||||
// initializeDeprecatedMetric invokes the actual prometheus.Summary object instantiation
|
||||
// but modifies the Help description prior to object instantiation.
|
||||
func (s *Summary) initializeDeprecatedMetric() {
|
||||
s.SummaryOpts.markDeprecated()
|
||||
s.initializeMetric()
|
||||
}
|
||||
|
||||
// SummaryVec is the internal representation of our wrapping struct around prometheus
|
||||
// summaryVecs.
|
||||
//
|
||||
// DEPRECATED: as per the metrics overhaul KEP
|
||||
type SummaryVec struct {
|
||||
*prometheus.SummaryVec
|
||||
*SummaryOpts
|
||||
lazyMetric
|
||||
originalLabels []string
|
||||
}
|
||||
|
||||
// NewSummaryVec returns an object which satisfies kubeCollector and wraps the
|
||||
// prometheus.SummaryVec object. However, the object returned will not measure
|
||||
// anything unless the collector is first registered, since the metric is lazily instantiated.
|
||||
//
|
||||
// DEPRECATED: as per the metrics overhaul KEP
|
||||
func NewSummaryVec(opts *SummaryOpts, labels []string) *SummaryVec {
|
||||
// todo: handle defaulting better
|
||||
if opts.StabilityLevel == "" {
|
||||
opts.StabilityLevel = ALPHA
|
||||
}
|
||||
v := &SummaryVec{
|
||||
SummaryOpts: opts,
|
||||
originalLabels: labels,
|
||||
lazyMetric: lazyMetric{},
|
||||
}
|
||||
v.lazyInit(v)
|
||||
return v
|
||||
}
|
||||
|
||||
// DeprecatedVersion returns a pointer to the Version or nil
|
||||
func (v *SummaryVec) DeprecatedVersion() *semver.Version {
|
||||
return parseSemver(v.SummaryOpts.DeprecatedVersion)
|
||||
}
|
||||
|
||||
func (v *SummaryVec) initializeMetric() {
|
||||
v.SummaryOpts.annotateStabilityLevel()
|
||||
v.SummaryVec = prometheus.NewSummaryVec(v.SummaryOpts.toPromSummaryOpts(), v.originalLabels)
|
||||
}
|
||||
|
||||
func (v *SummaryVec) initializeDeprecatedMetric() {
|
||||
v.SummaryOpts.markDeprecated()
|
||||
v.initializeMetric()
|
||||
}
|
||||
|
||||
// Default Prometheus behavior actually results in the creation of a new metric
|
||||
// if a metric with the unique label values is not found in the underlying stored metricMap.
|
||||
// This means that if this function is called but the underlying metric is not registered
|
||||
// (which means it will never be exposed externally nor consumed), the metric will exist in memory
|
||||
// for perpetuity (i.e. throughout application lifecycle).
|
||||
//
|
||||
// For reference: https://github.com/prometheus/client_golang/blob/v0.9.2/prometheus/summary.go#L485-L495
|
||||
|
||||
// WithLabelValues returns the ObserverMetric for the given slice of label
|
||||
// values (same order as the VariableLabels in Desc). If that combination of
|
||||
// label values is accessed for the first time, a new ObserverMetric is created IFF the summaryVec
|
||||
// has been registered to a metrics registry.
|
||||
func (v *SummaryVec) WithLabelValues(lvs ...string) ObserverMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop
|
||||
}
|
||||
return v.SummaryVec.WithLabelValues(lvs...)
|
||||
}
|
||||
|
||||
// With returns the ObserverMetric for the given Labels map (the label names
|
||||
// must match those of the VariableLabels in Desc). If that label map is
|
||||
// accessed for the first time, a new ObserverMetric is created IFF the summaryVec has
|
||||
// been registered to a metrics registry.
|
||||
func (v *SummaryVec) With(labels prometheus.Labels) ObserverMetric {
|
||||
if !v.IsCreated() {
|
||||
return noop
|
||||
}
|
||||
return v.SummaryVec.With(labels)
|
||||
}
|
||||
|
||||
// Delete deletes the metric where the variable labels are the same as those
|
||||
// passed in as labels. It returns true if a metric was deleted.
|
||||
//
|
||||
// It is not an error if the number and names of the Labels are inconsistent
|
||||
// with those of the VariableLabels in Desc. However, such inconsistent Labels
|
||||
// can never match an actual metric, so the method will always return false in
|
||||
// that case.
|
||||
func (v *SummaryVec) Delete(labels prometheus.Labels) bool {
|
||||
if !v.IsCreated() {
|
||||
return false // since we haven't created the metric, we haven't deleted a metric with the passed in values
|
||||
}
|
||||
return v.SummaryVec.Delete(labels)
|
||||
}
|
||||
37
vendor/k8s.io/component-base/metrics/version.go
generated
vendored
Normal file
37
vendor/k8s.io/component-base/metrics/version.go
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
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 "k8s.io/component-base/version"
|
||||
|
||||
var (
|
||||
buildInfo = NewGaugeVec(
|
||||
&GaugeOpts{
|
||||
Name: "kubernetes_build_info",
|
||||
Help: "A metric with a constant '1' value labeled by major, minor, git version, git commit, git tree state, build date, Go version, and compiler from which Kubernetes was built, and platform on which it is running.",
|
||||
StabilityLevel: ALPHA,
|
||||
},
|
||||
[]string{"major", "minor", "gitVersion", "gitCommit", "gitTreeState", "buildDate", "goVersion", "compiler", "platform"},
|
||||
)
|
||||
)
|
||||
|
||||
// RegisterBuildInfo registers the build and version info in a metadata metric in prometheus
|
||||
func RegisterBuildInfo(r KubeRegistry) {
|
||||
info := version.Get()
|
||||
r.MustRegister(buildInfo)
|
||||
buildInfo.WithLabelValues(info.Major, info.Minor, info.GitVersion, info.GitCommit, info.GitTreeState, info.BuildDate, info.GoVersion, info.Compiler, info.Platform).Set(1)
|
||||
}
|
||||
48
vendor/k8s.io/component-base/metrics/version_parser.go
generated
vendored
Normal file
48
vendor/k8s.io/component-base/metrics/version_parser.go
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
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 (
|
||||
"fmt"
|
||||
"github.com/blang/semver"
|
||||
apimachineryversion "k8s.io/apimachinery/pkg/version"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const (
|
||||
versionRegexpString = `^v(\d+\.\d+\.\d+)`
|
||||
)
|
||||
|
||||
var (
|
||||
versionRe = regexp.MustCompile(versionRegexpString)
|
||||
)
|
||||
|
||||
func parseSemver(s string) *semver.Version {
|
||||
if s != "" {
|
||||
sv := semver.MustParse(s)
|
||||
return &sv
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func parseVersion(ver apimachineryversion.Info) semver.Version {
|
||||
matches := versionRe.FindAllStringSubmatch(ver.String(), -1)
|
||||
|
||||
if len(matches) != 1 {
|
||||
panic(fmt.Sprintf("version string \"%v\" doesn't match expected regular expression: \"%v\"", ver.String(), versionRe.String()))
|
||||
}
|
||||
return semver.MustParse(matches[0][1])
|
||||
}
|
||||
81
vendor/k8s.io/component-base/metrics/wrappers.go
generated
vendored
Normal file
81
vendor/k8s.io/component-base/metrics/wrappers.go
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
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 (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
)
|
||||
|
||||
// This file contains a series of interfaces which we explicitly define for
|
||||
// integrating with prometheus. We redefine the interfaces explicitly here
|
||||
// so that we can prevent breakage if methods are ever added to prometheus
|
||||
// variants of them.
|
||||
|
||||
// Collector defines a subset of prometheus.Collector interface methods
|
||||
type Collector interface {
|
||||
Describe(chan<- *prometheus.Desc)
|
||||
Collect(chan<- prometheus.Metric)
|
||||
}
|
||||
|
||||
// Metric defines a subset of prometheus.Metric interface methods
|
||||
type Metric interface {
|
||||
Desc() *prometheus.Desc
|
||||
Write(*dto.Metric) error
|
||||
}
|
||||
|
||||
// CounterMetric is a Metric that represents a single numerical value that only ever
|
||||
// goes up. That implies that it cannot be used to count items whose number can
|
||||
// also go down, e.g. the number of currently running goroutines. Those
|
||||
// "counters" are represented by Gauges.
|
||||
|
||||
// CounterMetric is an interface which defines a subset of the interface provided by prometheus.Counter
|
||||
type CounterMetric interface {
|
||||
Inc()
|
||||
Add(float64)
|
||||
}
|
||||
|
||||
// CounterVecMetric is an interface which prometheus.CounterVec satisfies.
|
||||
type CounterVecMetric interface {
|
||||
WithLabelValues(...string) CounterMetric
|
||||
With(prometheus.Labels) CounterMetric
|
||||
}
|
||||
|
||||
// GaugeMetric is an interface which defines a subset of the interface provided by prometheus.Gauge
|
||||
type GaugeMetric interface {
|
||||
Set(float64)
|
||||
Inc()
|
||||
Dec()
|
||||
Add(float64)
|
||||
Write(out *dto.Metric) error
|
||||
SetToCurrentTime()
|
||||
}
|
||||
|
||||
// ObserverMetric captures individual observations.
|
||||
type ObserverMetric interface {
|
||||
Observe(float64)
|
||||
}
|
||||
|
||||
// PromRegistry is an interface which implements a subset of prometheus.Registerer and
|
||||
// prometheus.Gatherer interfaces
|
||||
type PromRegistry interface {
|
||||
Register(prometheus.Collector) error
|
||||
MustRegister(...prometheus.Collector)
|
||||
Unregister(prometheus.Collector) bool
|
||||
Gather() ([]*dto.MetricFamily, error)
|
||||
}
|
||||
1
vendor/k8s.io/component-base/version/.gitattributes
generated
vendored
Normal file
1
vendor/k8s.io/component-base/version/.gitattributes
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
base.go export-subst
|
||||
63
vendor/k8s.io/component-base/version/base.go
generated
vendored
Normal file
63
vendor/k8s.io/component-base/version/base.go
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
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 version
|
||||
|
||||
// Base version information.
|
||||
//
|
||||
// This is the fallback data used when version information from git is not
|
||||
// provided via go ldflags. It provides an approximation of the Kubernetes
|
||||
// version for ad-hoc builds (e.g. `go build`) that cannot get the version
|
||||
// information from git.
|
||||
//
|
||||
// If you are looking at these fields in the git tree, they look
|
||||
// strange. They are modified on the fly by the build process. The
|
||||
// in-tree values are dummy values used for "git archive", which also
|
||||
// works for GitHub tar downloads.
|
||||
//
|
||||
// When releasing a new Kubernetes version, this file is updated by
|
||||
// build/mark_new_version.sh to reflect the new version, and then a
|
||||
// git annotated tag (using format vX.Y where X == Major version and Y
|
||||
// == Minor version) is created to point to the commit that updates
|
||||
// pkg/version/base.go
|
||||
var (
|
||||
// TODO: Deprecate gitMajor and gitMinor, use only gitVersion
|
||||
// instead. First step in deprecation, keep the fields but make
|
||||
// them irrelevant. (Next we'll take it out, which may muck with
|
||||
// scripts consuming the kubectl version output - but most of
|
||||
// these should be looking at gitVersion already anyways.)
|
||||
gitMajor string // major version, always numeric
|
||||
gitMinor string // minor version, numeric possibly followed by "+"
|
||||
|
||||
// semantic version, derived by build scripts (see
|
||||
// https://github.com/kubernetes/community/blob/master/contributors/design-proposals/release/versioning.md
|
||||
// for a detailed discussion of this field)
|
||||
//
|
||||
// TODO: This field is still called "gitVersion" for legacy
|
||||
// reasons. For prerelease versions, the build metadata on the
|
||||
// semantic version is a git hash, but the version itself is no
|
||||
// longer the direct output of "git describe", but a slight
|
||||
// translation to be semver compliant.
|
||||
|
||||
// NOTE: The $Format strings are replaced during 'git archive' thanks to the
|
||||
// companion .gitattributes file containing 'export-subst' in this same
|
||||
// directory. See also https://git-scm.com/docs/gitattributes
|
||||
gitVersion = "v0.0.0-master+$Format:%h$"
|
||||
gitCommit = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD)
|
||||
gitTreeState = "" // state of git tree, either "clean" or "dirty"
|
||||
|
||||
buildDate = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ')
|
||||
)
|
||||
39
vendor/k8s.io/component-base/version/def.bzl
generated
vendored
Normal file
39
vendor/k8s.io/component-base/version/def.bzl
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
# Copyright 2017 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.
|
||||
|
||||
# Implements hack/lib/version.sh's kube::version::ldflags() for Bazel.
|
||||
def version_x_defs():
|
||||
# This should match the list of packages in kube::version::ldflag
|
||||
stamp_pkgs = [
|
||||
"k8s.io/kubernetes/pkg/version",
|
||||
"k8s.io/kubernetes/vendor/k8s.io/component-base/version",
|
||||
]
|
||||
|
||||
# This should match the list of vars in kube::version::ldflags
|
||||
# It should also match the list of vars set in hack/print-workspace-status.sh.
|
||||
stamp_vars = [
|
||||
"buildDate",
|
||||
"gitCommit",
|
||||
"gitMajor",
|
||||
"gitMinor",
|
||||
"gitTreeState",
|
||||
"gitVersion",
|
||||
]
|
||||
|
||||
# Generate the cross-product.
|
||||
x_defs = {}
|
||||
for pkg in stamp_pkgs:
|
||||
for var in stamp_vars:
|
||||
x_defs["%s.%s" % (pkg, var)] = "{%s}" % var
|
||||
return x_defs
|
||||
42
vendor/k8s.io/component-base/version/version.go
generated
vendored
Normal file
42
vendor/k8s.io/component-base/version/version.go
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
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 version
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
apimachineryversion "k8s.io/apimachinery/pkg/version"
|
||||
)
|
||||
|
||||
// Get returns the overall codebase version. It's for detecting
|
||||
// what code a binary was built from.
|
||||
func Get() apimachineryversion.Info {
|
||||
// These variables typically come from -ldflags settings and in
|
||||
// their absence fallback to the settings in ./base.go
|
||||
return apimachineryversion.Info{
|
||||
Major: gitMajor,
|
||||
Minor: gitMinor,
|
||||
GitVersion: gitVersion,
|
||||
GitCommit: gitCommit,
|
||||
GitTreeState: gitTreeState,
|
||||
BuildDate: buildDate,
|
||||
GoVersion: runtime.Version(),
|
||||
Compiler: runtime.Compiler,
|
||||
Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user