/
metrics_collector.go
84 lines (75 loc) · 2.51 KB
/
metrics_collector.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
/*
* This file is part of the KubeVirt project
*
* 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.
*
* Copyright 2023 Red Hat, Inc.
*
*/
package main
import (
"fmt"
"os"
"regexp"
"strings"
parser "github.com/kubevirt/monitoring/pkg/metrics/parser"
dto "github.com/prometheus/client_model/go"
)
// This should be used only for very rare cases where the naming conventions that are explained in the best practices:
// https://sdk.operatorframework.io/docs/best-practices/observability-best-practices/#metrics-guidelines
// should be ignored.
var excludedMetrics = map[string]struct{}{
"kubevirt_vmi_phase_count": struct{}{},
"cnv_abnormal": struct{}{},
}
// Extract the name, help, and type from the metrics doc file
func ExtractMetrics(metricsContent string) ([]parser.Metric, error) {
var metrics []parser.Metric
re := regexp.MustCompile(`### (.*)\n(.*Type: (Counter|Gauge|Histogram|Summary)\.\n)?`)
matches := re.FindAllStringSubmatch(metricsContent, -1)
for _, match := range matches {
name := match[1]
help := ""
if len(match) > 2 {
help = strings.TrimSpace(match[2])
}
typ := ""
if len(match) > 3 {
typ = match[3]
}
metrics = append(metrics, parser.Metric{Name: name, Help: help, Type: typ})
}
if len(metrics) == 0 {
return nil, fmt.Errorf("no metrics found")
}
return metrics, nil
}
// Read the metrics and parse them to a MetricFamily
func ReadMetrics(metricsPath string) ([]*dto.MetricFamily, error) {
metricsContent, err := os.ReadFile(metricsPath)
if err != nil {
return nil, fmt.Errorf("error reading metrics file: %s", err)
}
metrics, err := ExtractMetrics(string(metricsContent))
if err != nil {
return nil, fmt.Errorf("error parsing metrics file: %s", err)
}
var metricFamily []*dto.MetricFamily
for _, metric := range metrics {
// Remove ignored metrics from all rules
if _, isExcludedMetric := excludedMetrics[metric.Name]; !isExcludedMetric {
mf := parser.CreateMetricFamily(metric)
metricFamily = append(metricFamily, mf)
}
}
return metricFamily, nil
}