1/*
2Copyright 2019 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package conversion
18
19import (
20	"fmt"
21	"strconv"
22	"sync"
23	"time"
24
25	"k8s.io/apimachinery/pkg/runtime"
26	"k8s.io/apimachinery/pkg/runtime/schema"
27	"k8s.io/component-base/metrics"
28	"k8s.io/component-base/metrics/legacyregistry"
29)
30
31var (
32	latencyBuckets = metrics.ExponentialBuckets(0.001, 2, 15)
33)
34
35// converterMetricFactory holds metrics for all CRD converters
36type converterMetricFactory struct {
37	// A map from a converter name to it's metric. Allows the converterMetric to be created
38	// again with the same metric for a specific converter (e.g. 'webhook').
39	durations   map[string]*metrics.HistogramVec
40	factoryLock sync.Mutex
41}
42
43func newConverterMertricFactory() *converterMetricFactory {
44	return &converterMetricFactory{durations: map[string]*metrics.HistogramVec{}, factoryLock: sync.Mutex{}}
45}
46
47var _ crConverterInterface = &converterMetric{}
48
49type converterMetric struct {
50	delegate  crConverterInterface
51	latencies *metrics.HistogramVec
52	crdName   string
53}
54
55func (c *converterMetricFactory) addMetrics(converterName string, crdName string, converter crConverterInterface) (crConverterInterface, error) {
56	c.factoryLock.Lock()
57	defer c.factoryLock.Unlock()
58	metric, exists := c.durations[converterName]
59	if !exists {
60		metric = metrics.NewHistogramVec(
61			&metrics.HistogramOpts{
62				Name:           fmt.Sprintf("apiserver_crd_%s_conversion_duration_seconds", converterName),
63				Help:           fmt.Sprintf("CRD %s conversion duration in seconds", converterName),
64				Buckets:        latencyBuckets,
65				StabilityLevel: metrics.ALPHA,
66			},
67			[]string{"crd_name", "from_version", "to_version", "succeeded"})
68		err := legacyregistry.Register(metric)
69		if err != nil {
70			return nil, err
71		}
72		c.durations[converterName] = metric
73	}
74	return &converterMetric{latencies: metric, delegate: converter, crdName: crdName}, nil
75}
76
77func (m *converterMetric) Convert(in runtime.Object, targetGV schema.GroupVersion) (runtime.Object, error) {
78	start := time.Now()
79	obj, err := m.delegate.Convert(in, targetGV)
80	fromVersion := in.GetObjectKind().GroupVersionKind().Version
81	toVersion := targetGV.Version
82
83	// only record this observation if the version is different
84	if fromVersion != toVersion {
85		m.latencies.WithLabelValues(
86			m.crdName, fromVersion, toVersion, strconv.FormatBool(err == nil)).Observe(time.Since(start).Seconds())
87	}
88	return obj, err
89}
90