-
Notifications
You must be signed in to change notification settings - Fork 124
/
metrics.go
278 lines (234 loc) · 8.31 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
Copyright 2019 The Machine Controller 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 controller
import (
"context"
"fmt"
"time"
"github.com/prometheus/client_golang/prometheus"
clusterv1alpha1 "github.com/kubermatic/machine-controller/pkg/apis/cluster/v1alpha1"
"github.com/kubermatic/machine-controller/pkg/cloudprovider"
"github.com/kubermatic/machine-controller/pkg/providerconfig"
providerconfigtypes "github.com/kubermatic/machine-controller/pkg/providerconfig/types"
"k8s.io/apimachinery/pkg/api/equality"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
const (
metricsPrefix = "machine_controller_"
metricRegatherWaitPeriod = 10 * time.Minute
)
// NewMachineControllerMetrics creates new MachineControllerMetrics
// with default values initialized, so metrics always show up.
func NewMachineControllerMetrics() *MetricsCollection {
cm := &MetricsCollection{
Workers: prometheus.NewGauge(prometheus.GaugeOpts{
Name: metricsPrefix + "workers",
Help: "The number of running machine controller workers",
}),
Errors: prometheus.NewCounter(prometheus.CounterOpts{
Name: metricsPrefix + "errors_total",
Help: "The total number or unexpected errors the controller encountered",
}),
Provisioning: prometheus.NewHistogram(prometheus.HistogramOpts{
Name: metricsPrefix + "provisioning_time_seconds",
Help: "Histogram of times spent from creating a Machine to ready state in the cluster",
Buckets: prometheus.ExponentialBuckets(32, 1.5, 10),
}),
Deprovisioning: prometheus.NewHistogram(prometheus.HistogramOpts{
Name: metricsPrefix + "deprovisioning_time_seconds",
Help: "Histogram of times spent from deleting a Machine to be removed from cluster and cloud provider",
Buckets: prometheus.ExponentialBuckets(32, 1.5, 10),
}),
}
// Set default values, so that these metrics always show up
cm.Workers.Set(0)
cm.Errors.Add(0)
return cm
}
type MachineCollector struct {
ctx context.Context
client ctrlruntimeclient.Client
machines *prometheus.Desc
machineCreated *prometheus.Desc
machineDeleted *prometheus.Desc
}
type machineMetricLabels struct {
KubeletVersion string
CloudProvider providerconfigtypes.CloudProvider
OperatingSystem providerconfigtypes.OperatingSystem
ProviderLabels map[string]string
}
// Counter turns a label collection into a Prometheus counter.
func (l *machineMetricLabels) Counter(value uint) prometheus.Counter {
labels := make(map[string]string)
labelNames := make([]string, 0)
if len(l.KubeletVersion) > 0 {
labels["kubelet_version"] = l.KubeletVersion
}
if len(l.CloudProvider) > 0 {
labels["provider"] = string(l.CloudProvider)
}
if len(l.OperatingSystem) > 0 {
labels["os"] = string(l.OperatingSystem)
}
for k, v := range l.ProviderLabels {
labels[k] = v
}
for k := range labels {
labelNames = append(labelNames, k)
}
counterVec := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: metricsPrefix + "machines_total",
Help: "Total number of machines",
}, labelNames)
counter := counterVec.With(labels)
counter.Add(float64(value))
return counter
}
func NewMachineCollector(ctx context.Context, client ctrlruntimeclient.Client) *MachineCollector {
// Start periodically calling the providers SetMetricsForMachines in a dedicated go routine
skg := providerconfig.NewConfigVarResolver(ctx, client)
go func() {
metricGatheringExecutor := func() {
machines := &clusterv1alpha1.MachineList{}
if err := client.List(ctx, machines); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to list machines for SetMetricsForMachines: %w", err))
return
}
var machineList clusterv1alpha1.MachineList
for _, machine := range machines.Items {
machineList.Items = append(machineList.Items, *machine.DeepCopy())
}
if len(machineList.Items) < 1 {
return
}
providerMachineMap := map[providerconfigtypes.CloudProvider]*clusterv1alpha1.MachineList{}
for _, machine := range machines.Items {
providerConfig, err := providerconfigtypes.GetConfig(machine.Spec.ProviderSpec)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to get providerSpec for SetMetricsForMachines: %w", err))
continue
}
if _, exists := providerMachineMap[providerConfig.CloudProvider]; !exists {
providerMachineMap[providerConfig.CloudProvider] = &clusterv1alpha1.MachineList{}
}
providerMachineMap[providerConfig.CloudProvider].Items = append(providerMachineMap[providerConfig.CloudProvider].Items, machine)
}
for provider, providerMachineList := range providerMachineMap {
prov, err := cloudprovider.ForProvider(provider, skg)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to get cloud provider for SetMetricsForMachines:: %q: %w", provider, err))
continue
}
if err := prov.SetMetricsForMachines(*providerMachineList); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to call prov.SetInstanceNumberForMachines: %w", err))
continue
}
}
}
for {
metricGatheringExecutor()
time.Sleep(metricRegatherWaitPeriod)
}
}()
return &MachineCollector{
ctx: ctx,
client: client,
machines: prometheus.NewDesc(
metricsPrefix+"machines",
"The number of machines managed by this machine controller",
[]string{}, nil,
),
machineCreated: prometheus.NewDesc(
metricsPrefix+"machine_created",
"Timestamp of the machine's creation time",
[]string{"machine"}, nil,
),
machineDeleted: prometheus.NewDesc(
metricsPrefix+"machine_deleted",
"Timestamp of the machine's deletion time",
[]string{"machine"}, nil,
),
}
}
// Describe implements the prometheus.Collector interface.
func (mc MachineCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- mc.machines
ch <- mc.machineCreated
ch <- mc.machineDeleted
}
// Collect implements the prometheus.Collector interface.
func (mc MachineCollector) Collect(ch chan<- prometheus.Metric) {
machines := &clusterv1alpha1.MachineList{}
if err := mc.client.List(mc.ctx, machines); err != nil {
return
}
cvr := providerconfig.NewConfigVarResolver(mc.ctx, mc.client)
machineCountByLabels := make(map[*machineMetricLabels]uint)
for _, machine := range machines.Items {
ch <- prometheus.MustNewConstMetric(
mc.machineCreated,
prometheus.GaugeValue,
float64(machine.CreationTimestamp.Unix()),
machine.Name,
)
if machine.DeletionTimestamp != nil {
ch <- prometheus.MustNewConstMetric(
mc.machineDeleted,
prometheus.GaugeValue,
float64(machine.DeletionTimestamp.Unix()),
machine.Name,
)
}
providerConfig, err := providerconfigtypes.GetConfig(machine.Spec.ProviderSpec)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to determine providerSpec for machine %s: %w", machine.Name, err))
continue
}
provider, err := cloudprovider.ForProvider(providerConfig.CloudProvider, cvr)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to determine provider provider: %w", err))
continue
}
labels, err := provider.MachineMetricsLabels(&machine)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to determine machine metrics labels: %w", err))
continue
}
metricsLabels := machineMetricLabels{
KubeletVersion: machine.Spec.Versions.Kubelet,
CloudProvider: providerConfig.CloudProvider,
OperatingSystem: providerConfig.OperatingSystem,
ProviderLabels: labels,
}
var key *machineMetricLabels
for p := range machineCountByLabels {
if equality.Semantic.DeepEqual(*p, metricsLabels) {
key = p
break
}
}
if key == nil {
key = &metricsLabels
}
machineCountByLabels[key]++
}
// ensure that we always report at least a machines=0
if len(machineCountByLabels) == 0 {
machineCountByLabels[&machineMetricLabels{}] = 0
}
for info, count := range machineCountByLabels {
ch <- info.Counter(count)
}
}