/
main.go
387 lines (343 loc) · 10.6 KB
/
main.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"encoding/json"
"flag"
"github.com/mitchellh/go-homedir"
"net/http"
"os"
"strconv"
"strings"
"time"
as_v1 "k8s.io/api/autoscaling/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
)
const (
defaultMetricsInterval = 30
defaultConditionLogging = false
defaultLoggingInterval = 60
defaultAddr = ":9296"
)
const rootDoc = `<html>
<head><title>HPA Exporter</title></head>
<body>
<h1>HPA Exporter</h1>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>
`
type currentMetrics struct {
Type string `json:"type"`
Resource struct {
Name string `json:"name"`
CurrentAverageUtilization int `json:"currentAverageUtilization"`
CurrentAverageValue string `json:"currentAverageValue"`
} `json:"resource"`
}
type condition struct {
Type string `json:"type"`
Status string `json:"status"`
LastTransitionTime time.Time `json:"lastTransitionTime"`
Reason string `json:"reason"`
Message string `json:"message"`
}
const (
conditionStatusTrue string = "True"
conditionStatusFalse string = "False"
)
var addr = flag.String("listen-address", defaultAddr, "The address to listen on for HTTP requests.")
var metricsInterval = flag.Int("metricsInterval", defaultMetricsInterval, "Interval to scrape HPA status.")
var loggingInterval = flag.Int("loggingInterval", defaultLoggingInterval, "Interval to logging HPA conditions.")
var conditionLogging = flag.Bool("conditionLogging", defaultConditionLogging, "Logging HPA conditions.")
var kubeClient = func() kubernetes.Interface {
var ret kubernetes.Interface
config, err := rest.InClusterConfig()
if err != nil {
var kubeconfigPath string
if os.Getenv("KUBECONFIG") == "" {
home, err := homedir.Dir()
if err != nil {
panic(err)
}
kubeconfigPath = home + "/.kube/config"
} else {
kubeconfigPath = os.Getenv("KUBECONFIG")
}
config, err = clientcmd.BuildConfigFromFlags("", kubeconfigPath)
if err != nil {
panic(err)
}
}
ret, err = kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
return ret
}()
var labels = []string{
"hpa_name",
"hpa_namespace",
"ref_kind",
"ref_name",
"ref_apiversion",
}
var annoLabels = []string{
"cond_status",
"cond_reason",
"cond_message",
}
var (
hpaCurrentPodsNum = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_current_pods_num",
Help: "Number of current pods by status.",
},
labels,
)
hpaDesiredPodsNum = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_desired_pods_num",
Help: "Number of desired pods by status.",
},
labels,
)
hpaMinPodsNum = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_min_pods_num",
Help: "Number of min pods by spec.",
},
labels,
)
hpaMaxPodsNum = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_max_pods_num",
Help: "Number of max pods by spec.",
},
labels,
)
hpaCurrentCpuValue = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_current_cpu_value",
Help: "Current cpu usage value.",
},
labels,
)
hpaCurrentCpuPercentage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_current_cpu_percentage",
Help: "Current cpu utilization calculated by HPA.",
},
labels,
)
hpaTargetCpuPercentage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_target_cpu_percentage",
Help: "Target CPU utilization set for HPA.",
},
labels,
)
hpaLastScaleSecond = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_last_scale_second",
Help: "Time the scale was last executed.",
},
labels,
)
hpaAbleToScale = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_able_to_scale",
Help: "status able to scale from annotation.",
},
append(labels, annoLabels...),
)
hpaScalingActive = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_scaling_active",
Help: "status scaling active from annotation.",
},
append(labels, annoLabels...),
)
hpaScalingLimited = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hpa_scaling_limited",
Help: "status scaling limited from annotation.",
},
append(labels, annoLabels...),
)
)
func init() {
prometheus.MustRegister(hpaCurrentPodsNum)
prometheus.MustRegister(hpaDesiredPodsNum)
prometheus.MustRegister(hpaMinPodsNum)
prometheus.MustRegister(hpaMaxPodsNum)
prometheus.MustRegister(hpaCurrentCpuValue)
prometheus.MustRegister(hpaCurrentCpuPercentage)
prometheus.MustRegister(hpaTargetCpuPercentage)
prometheus.MustRegister(hpaLastScaleSecond)
prometheus.MustRegister(hpaAbleToScale)
prometheus.MustRegister(hpaScalingActive)
prometheus.MustRegister(hpaScalingLimited)
}
func getHpaList() ([]as_v1.HorizontalPodAutoscaler, error) {
out, err := kubeClient.AutoscalingV1().HorizontalPodAutoscalers("").List(meta_v1.ListOptions{})
return out.Items, err
}
func currentAverageCpuValue(metrics currentMetrics) int {
val := strings.Trim(metrics.Resource.CurrentAverageValue, "m")
if i, e := strconv.ParseInt(val, 10, 64); e == nil {
return int(i)
} else {
log.Errorln(e)
return 0
}
}
func mergeLabels(m1, m2 map[string]string) map[string]string {
ans := map[string]string{}
for k, v := range m1 {
ans[k] = v
}
for k, v := range m2 {
ans[k] = v
}
return (ans)
}
func makeAnnotationCondLabels(cond condition) (prometheus.Labels, prometheus.Labels) {
labelForward := prometheus.Labels{
"cond_status": cond.Status,
"cond_reason": cond.Reason,
"cond_message": cond.Message,
}
var statusReverse string
if cond.Status == conditionStatusTrue {
statusReverse = conditionStatusFalse
} else {
statusReverse = conditionStatusTrue
}
labelReverse := prometheus.Labels{
"cond_status": statusReverse,
"cond_reason": "",
"cond_message": "",
}
return labelForward, labelReverse
}
func main() {
flag.Parse()
log.Info("start HPA exporter")
if *conditionLogging {
go func() {
for {
hpa, err := getHpaList()
if err != nil {
log.Errorln(err)
continue
}
for _, a := range hpa {
name := a.ObjectMeta.Name
logtext := a.ObjectMeta.Annotations["autoscaling.alpha.kubernetes.io/conditions"]
log.Infof("{\"name\":\"%s\",\"conditions\":%s}", name, logtext)
}
time.Sleep(time.Duration(*loggingInterval) * time.Second)
}
}()
}
go func() {
var (
annoLabelAbleToScale = map[string]prometheus.Labels{}
annoLabelAbleToScaleRev = map[string]prometheus.Labels{}
annoLabelScalingActive = map[string]prometheus.Labels{}
annoLabelScalingActiveRev = map[string]prometheus.Labels{}
annoLabelScalingLimited = map[string]prometheus.Labels{}
annoLabelScalingLimitedRev = map[string]prometheus.Labels{}
)
for {
hpa, err := getHpaList()
if err != nil {
log.Errorln(err)
continue
}
for _, a := range hpa {
label := prometheus.Labels{
"hpa_name": a.ObjectMeta.Name,
"hpa_namespace": a.ObjectMeta.Namespace,
"ref_kind": a.Spec.ScaleTargetRef.Kind,
"ref_name": a.Spec.ScaleTargetRef.Name,
"ref_apiversion": a.Spec.ScaleTargetRef.APIVersion,
}
metrJsonStr := a.ObjectMeta.Annotations["autoscaling.alpha.kubernetes.io/current-metrics"]
condJsonStr := a.ObjectMeta.Annotations["autoscaling.alpha.kubernetes.io/conditions"]
var metrics []currentMetrics
var conditions []condition
if e := json.Unmarshal([]byte(metrJsonStr), &metrics); e != nil {
log.Errorln(e)
continue
}
if e := json.Unmarshal([]byte(condJsonStr), &conditions); e != nil {
log.Errorln(e)
continue
}
var cpuVal int
if len(metrics) != 0 {
cpuVal = currentAverageCpuValue(metrics[0])
} else {
cpuVal = 0
}
hpaCurrentPodsNum.With(label).Set(float64(a.Status.CurrentReplicas))
hpaDesiredPodsNum.With(label).Set(float64(a.Status.DesiredReplicas))
if a.Spec.MinReplicas != nil {
hpaMinPodsNum.With(label).Set(float64(*a.Spec.MinReplicas))
}
hpaMaxPodsNum.With(label).Set(float64(a.Spec.MaxReplicas))
hpaCurrentCpuValue.With(label).Set(float64(cpuVal))
if a.Status.CurrentCPUUtilizationPercentage != nil {
hpaCurrentCpuPercentage.With(label).Set(float64(*a.Status.CurrentCPUUtilizationPercentage))
}
if a.Spec.TargetCPUUtilizationPercentage != nil {
hpaTargetCpuPercentage.With(label).Set(float64(*a.Spec.TargetCPUUtilizationPercentage))
}
if a.Status.LastScaleTime != nil {
hpaLastScaleSecond.With(label).Set(float64(a.Status.LastScaleTime.Unix()))
}
name := a.ObjectMeta.Name
for _, cond := range conditions {
switch cond.Type {
case "AbleToScale":
oldLabel := annoLabelAbleToScale[name]
oldLabelRev := annoLabelAbleToScaleRev[name]
annoLabelAbleToScale[name], annoLabelAbleToScaleRev[name] = makeAnnotationCondLabels(cond)
_ = hpaAbleToScale.Delete(mergeLabels(label, oldLabel))
_ = hpaAbleToScale.Delete(mergeLabels(label, oldLabelRev))
hpaAbleToScale.With(mergeLabels(label, annoLabelAbleToScale[name])).Set(float64(1))
hpaAbleToScale.With(mergeLabels(label, annoLabelAbleToScaleRev[name])).Set(float64(0))
case "ScalingActive":
oldLabel := annoLabelScalingActive[name]
oldLabelRev := annoLabelScalingActiveRev[name]
annoLabelScalingActive[name], annoLabelScalingActiveRev[name] = makeAnnotationCondLabels(cond)
_ = hpaScalingActive.Delete(mergeLabels(label, oldLabel))
_ = hpaScalingActive.Delete(mergeLabels(label, oldLabelRev))
hpaScalingActive.With(mergeLabels(label, annoLabelScalingActive[name])).Set(float64(1))
hpaScalingActive.With(mergeLabels(label, annoLabelScalingActiveRev[name])).Set(float64(0))
case "ScalingLimited":
oldLabel := annoLabelScalingLimited[name]
oldLabelRev := annoLabelScalingLimitedRev[name]
annoLabelScalingLimited[name], annoLabelScalingLimitedRev[name] = makeAnnotationCondLabels(cond)
_ = hpaScalingLimited.Delete(mergeLabels(label, oldLabel))
_ = hpaScalingLimited.Delete(mergeLabels(label, oldLabelRev))
hpaScalingLimited.With(mergeLabels(label, annoLabelScalingLimited[name])).Set(float64(1))
hpaScalingLimited.With(mergeLabels(label, annoLabelScalingLimitedRev[name])).Set(float64(0))
}
}
}
time.Sleep(time.Duration(*metricsInterval) * time.Second)
}
}()
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(rootDoc))
})
log.Fatal(http.ListenAndServe(*addr, nil))
}