forked from openshift/osde2e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetrics.go
More file actions
275 lines (230 loc) · 8.93 KB
/
metrics.go
File metadata and controls
275 lines (230 loc) · 8.93 KB
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
package common
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/onsi/ginkgo/reporters"
"github.com/openshift/osde2e/pkg/config"
"github.com/openshift/osde2e/pkg/events"
"github.com/openshift/osde2e/pkg/metadata"
"github.com/openshift/osde2e/pkg/state"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/expfmt"
)
const (
prometheusFileNamePattern string = "%s.%s.metrics.prom"
cicdPrefix string = "cicd_"
jUnitMetricName string = cicdPrefix + "jUnitResult"
metadataMetricName string = cicdPrefix + "metadata"
addonMetricName string = cicdPrefix + "addon_metadata"
eventMetricName string = cicdPrefix + "event"
)
var junitFileRegex, logFileRegex *regexp.Regexp
// Metrics is the metrics object which can parse jUnit and JSON metadata and produce Prometheus metrics.
type Metrics struct {
metricRegistry *prometheus.Registry
jUnitGatherer *prometheus.GaugeVec
metadataGatherer *prometheus.GaugeVec
addonGatherer *prometheus.GaugeVec
eventGatherer *prometheus.CounterVec
}
// NewMetrics creates a new metrics object using the given config object.
func NewMetrics() *Metrics {
// Set up Prometheus metrics registry and gatherers
metricRegistry := prometheus.NewRegistry()
jUnitGatherer := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: jUnitMetricName,
},
[]string{"install_version", "upgrade_version", "environment", "phase", "suite", "testname", "result"},
)
metadataGatherer := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: metadataMetricName,
},
[]string{"install_version", "upgrade_version", "environment", "metadata_name"},
)
addonGatherer := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: addonMetricName,
},
[]string{"install_version", "upgrade_version", "environment", "metadata_name", "phase"},
)
eventGatherer := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: eventMetricName,
},
[]string{"install_version", "upgrade_version", "environment", "event"},
)
metricRegistry.MustRegister(jUnitGatherer)
metricRegistry.MustRegister(metadataGatherer)
metricRegistry.MustRegister(addonGatherer)
metricRegistry.MustRegister(eventGatherer)
return &Metrics{
metricRegistry: metricRegistry,
jUnitGatherer: jUnitGatherer,
metadataGatherer: metadataGatherer,
addonGatherer: addonGatherer,
eventGatherer: eventGatherer,
}
}
func init() {
junitFileRegex = regexp.MustCompile("^junit.*\\.xml$")
logFileRegex = regexp.MustCompile("^.*\\.(log|txt)$")
}
// WritePrometheusFile collects data and writes it out in the prometheus export file format (https://github.com/prometheus/docs/blob/master/content/docs/instrumenting/exposition_formats.md)
// Returns the prometheus file name.
func (m *Metrics) WritePrometheusFile(reportDir string) (string, error) {
files, err := ioutil.ReadDir(reportDir)
if err != nil {
return "", err
}
for _, file := range files {
if file != nil {
// This directory name is the name of the current phase we're in, so record it and iterate through these results
if file.IsDir() {
phase := file.Name()
phaseDir := filepath.Join(reportDir, phase)
phaseFiles, err := ioutil.ReadDir(phaseDir)
if err != nil {
return "", err
}
for _, phaseFile := range phaseFiles {
// Process the jUnit XML result files
if junitFileRegex.MatchString(phaseFile.Name()) {
// TODO: The addon metric prefix should reference the addon job being run to further avoid collision
m.processJUnitXMLFile(phase, filepath.Join(phaseDir, phaseFile.Name()))
} else if phaseFile.Name() == metadata.AddonMetadataFile {
m.processJSONFile(m.addonGatherer, filepath.Join(phaseDir, phaseFile.Name()), phase)
}
}
} else if file.Name() == metadata.CustomMetadataFile {
m.processJSONFile(m.metadataGatherer, filepath.Join(reportDir, file.Name()), "")
}
}
}
m.processEvents(m.eventGatherer)
prometheusFileName := fmt.Sprintf(prometheusFileNamePattern, state.Instance.Cluster.ID, config.Instance.JobName)
output, err := m.registryToExpositionFormat()
if err != nil {
return "", err
}
err = ioutil.WriteFile(filepath.Join(reportDir, prometheusFileName), output, os.FileMode(0644))
if err != nil {
return "", err
}
return prometheusFileName, nil
}
// jUnit file processing
// processJUnitXMLFile will add results to the prometheusOutput that look like:
//
// cicd_jUnitResult {environment="prod", install_version="install-version", result="passed|failed|skipped", phase="currentphase", suite="suitename",
// testname="testname", upgrade_version="upgrade-version"} testLength
func (m *Metrics) processJUnitXMLFile(phase string, junitFile string) (err error) {
cfg := config.Instance
state := state.Instance
data, err := ioutil.ReadFile(junitFile)
if err != nil {
return err
}
// Use Ginkgo's JUnitTestSuite to unmarshal the JUnit XML file
var testSuite reporters.JUnitTestSuite
if err = xml.Unmarshal(data, &testSuite); err != nil {
return err
}
for _, testcase := range testSuite.TestCases {
var result string
if testcase.FailureMessage != nil {
result = "failed"
} else if testcase.Skipped != nil {
result = "skipped"
} else {
result = "passed"
}
m.jUnitGatherer.WithLabelValues(state.Cluster.Version, state.Upgrade.ReleaseName, cfg.OCM.Env, phase, testSuite.Name, testcase.Name, result).Add(testcase.Time)
}
return nil
}
// JSON file processing
// processJSONFile takes a JSON file and converts it into prometheus metrics of the general format:
//
// cicd_[addon_]metadata{environment="prod", install_version="install-version",
// metadata_name="full.path.to.field.separated.by.periiod",
// upgrade_version="upgrade-version"[, phase="install"]} userAssignedValue
//
// Notes: Only numerical values or strings that look like numerical values will be captured. This is because
// Prometheus can only have numerical metric values and capturing strings through the use of labels is
// of questionable value.
func (m *Metrics) processJSONFile(gatherer *prometheus.GaugeVec, jsonFile string, phase string) (err error) {
data, err := ioutil.ReadFile(jsonFile)
if err != nil {
return err
}
var jsonOutput interface{}
if err = json.Unmarshal(data, &jsonOutput); err != nil {
return err
}
m.jsonToPrometheusOutput(gatherer, phase, jsonOutput.(map[string]interface{}), []string{})
return nil
}
// jsonToPrometheusOutput will take the JSON and write it into the gauge vector.
func (m *Metrics) jsonToPrometheusOutput(gatherer *prometheus.GaugeVec, phase string, jsonOutput map[string]interface{}, context []string) {
cfg := config.Instance
state := state.Instance
for k, v := range jsonOutput {
fullContext := append(context, k)
switch jsonObject := v.(type) {
case map[string]interface{}:
m.jsonToPrometheusOutput(gatherer, phase, jsonObject, fullContext)
default:
metadataName := strings.Join(fullContext, ".")
// Due to current limitations in the Spyglass metadata lens, all fields in a metadata
// object need to be strings to display properly. Rather than look for float64 types, we'll
// try to parse the float out of the JSON value. That way, if the number is in a string object
// we'll still be able to use it numerically instead of shoving it into the label as we'd
// otherwise have to do.
stringValue := fmt.Sprintf("%v", jsonObject)
// We're only concerned with tracking float values in Prometheus as they're the only thing we can measure
if floatValue, err := strconv.ParseFloat(stringValue, 64); err == nil {
if phase != "" {
gatherer.WithLabelValues(state.Cluster.Version, state.Upgrade.ReleaseName, cfg.OCM.Env, metadataName, phase).Add(floatValue)
} else {
gatherer.WithLabelValues(state.Cluster.Version, state.Upgrade.ReleaseName, cfg.OCM.Env, metadataName).Add(floatValue)
}
}
}
}
}
// Event processing
// processEvents will search the events list for events that have occurred over the osde2e run
// and output them in the Prometheus metrics.
func (m *Metrics) processEvents(gatherer *prometheus.CounterVec) {
cfg := config.Instance
state := state.Instance
for _, event := range events.GetListOfEvents() {
gatherer.WithLabelValues(state.Cluster.Version, state.Upgrade.ReleaseName, cfg.OCM.Env, event).Inc()
}
}
// Generic Prometheus export file building functions
// registryToExpositionFormat takes all of the gathered metrics and writes them out in the exposition format
func (m *Metrics) registryToExpositionFormat() ([]byte, error) {
buf := &bytes.Buffer{}
encoder := expfmt.NewEncoder(buf, expfmt.FmtText)
metricFamilies, err := m.metricRegistry.Gather()
if err != nil {
return []byte{}, fmt.Errorf("error while gathering metrics: %v", err)
}
for _, metricFamily := range metricFamilies {
if err := encoder.Encode(metricFamily); err != nil {
return []byte{}, fmt.Errorf("error encoding metric family: %v", err)
}
}
return buf.Bytes(), nil
}