forked from muravsky/unity2promgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unitycollector.go
312 lines (276 loc) · 9.35 KB
/
unitycollector.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
package main
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/muravsky/gounity"
"github.com/prometheus/client_golang/prometheus"
)
//Metrics is a List of Metrics
type Metrics struct {
Metrics []Metric `json:"metrics"`
}
//Metric represents a unity prometheus metric
type Metric struct {
Name string `json:"name"`
Path string `json:"path"`
PromPath string `json:"prom_path"`
Description string `json:"description"`
Historic bool `json:"isHistoricalAvailable"`
Realtime bool `json:"isRealtimeAvailable"`
Unit string `json:"unitDisplayString"`
PromDesc *prometheus.Desc
PromGauge *prometheus.GaugeVec
}
func (m *Metric) addPrometheusDesc() *Metric {
log.Print("Prometheus Desc: " + m.PromPath)
//The metric name will be the PromPath + the unit if it's not empty
metricName := m.PromPath
if m.Unit != "" {
metricName = metricName + "_" + m.Unit
}
//To generate the labels we look at the metric path
labels := make([]string, 0)
labels = append(labels, "unity")
pathSplit := strings.Split(m.Path, ".")
//If the unity metric path contains "*" - the element before it will be used as a value identifier
//sp.*.net.device.*.pktsInRate => 0 -> sp; 2->device
for i, v := range pathSplit {
if v == "*" || v == "+" {
labels = append(labels, pathSplit[i-1])
}
}
m.PromDesc = prometheus.NewDesc(
metricName,
m.Description,
labels,
nil,
)
return m
}
func (m *Metric) addPrometheusGaugeVec(reg prometheus.Registerer) *Metric {
log.Print("Prometheus Desc: " + m.PromPath)
//The metric name will be the PromPath + the unit if it's not empty
metricName := m.PromPath
if m.Unit != "" {
metricName = metricName + "_" + m.Unit
}
//To generate the labels we look at the metric path
labels := make([]string, 0)
labels = append(labels, "unity")
pathSplit := strings.Split(m.Path, ".")
//If the unity metric path contains "*" - the element before it will be used as a value identifier
//sp.*.net.device.*.pktsInRate => 0 -> sp; 2->device
for i, v := range pathSplit {
if v == "*" || v == "+" {
labels = append(labels, pathSplit[i-1])
}
}
m.PromGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
//Namespace: "our_company",
//Subsystem: "blob_storage",
Name: metricName,
Help: m.Description,
},
labels,
)
return m
}
//Unity represents a single Unity RestAPI client
type Unity struct {
IP string `json:"ip"`
User string `json:"user"`
Port int `json:"port"`
Password string `json:"password"`
Session gounity.Session
Name string
}
//UnityCollector is a prometheus.collector wrapper a unity prometheus metric
type UnityCollector struct {
Unity Unity
Metrics []Metric
Exporter Exporter
PoolMetrics []*prometheus.GaugeVec
LUNMetrics []*prometheus.GaugeVec
StorageMetrics []*prometheus.GaugeVec
}
//NewUnityCollector wraps the Unity and Metrics into a collector
func NewUnityCollector(u Unity, ms []Metric, e Exporter, pm []*prometheus.GaugeVec, lm []*prometheus.GaugeVec, sm []*prometheus.GaugeVec) UnityCollector {
log.Print("unityCollector.go:NewUnityCollector - Unity: " + u.Name)
uc := UnityCollector{Metrics: ms, Unity: u, Exporter: e, PoolMetrics: pm, LUNMetrics: lm, StorageMetrics: sm}
return uc
}
func (uc UnityCollector) CollectMetrics() {
go func() {
//Slice of all realtime metrics in order to be possible to handle them in one request
realtimeMetrics := make([]Metric, 0)
realtimeMetricPaths := make([]string, 0)
labels := make([]string, 0)
labels = append(labels, uc.Unity.Name)
//Iterate over all metrics
for _, metric := range uc.Metrics {
if metric.Realtime {
//log.Print("UnityCollector - Collector: Realtime Metric - " + metric.PromPath)
realtimeMetrics = append(realtimeMetrics, metric)
realtimeMetricPaths = append(realtimeMetricPaths, metric.Path)
}
if metric.Historic {
// log.Print("UnityCollector - Collector: Historic Metric - " + metric.PromPath)
//MetricValue, err := uc.Session.GetmetricValue(p)
MetricValue, err := uc.Unity.Session.GetmetricValue(metric.Path)
if err != nil {
log.Print("UnityCollector - Collector: Could not get " + metric.PromPath)
} else {
//Historic Metric contians multiple result entries with [0] being the latest
if MetricValue.Entries[0].Content.Values != nil {
parseResult(MetricValue.Entries[0].Content.Values.(map[string]interface{}), metric.PromGauge, labels)
}
}
}
}
if len(realtimeMetricPaths) != 0 {
//Get and parse Realtime Metrics
// TODO: Muss async sein
log.Print("UnityCollector - Collector: Query Realtime Metrics with interval")
// The following is error handling for any bad calls from the Unity API
// Errors won't update the metrics, but will prevent the exporter from a fatal error
// This was put in due to occasional 422 errors received from the Unity API that was breaking shit
// by cthiel42
query, err := uc.Unity.Session.NewMetricRealTimeQuery(realtimeMetricPaths, uint32(uc.Exporter.Interval))
_ = query
_ = err
for i := 0; i < 5; i++ {
if i == 4 {
log.Print("Failed too many times. Metrics won't be updated")
return
} else if err != nil {
log.Print(err)
time.Sleep(time.Second)
query, err := uc.Unity.Session.NewMetricRealTimeQuery(realtimeMetricPaths, uint32(uc.Exporter.Interval))
_ = query
_ = err
} else {
break
}
}
// Waiting for the sampling of the metrics to be done
time.Sleep(time.Duration(query.Content.Interval) * time.Second)
// Get the results of the query
result, err := uc.Unity.Session.GetMetricRealTimeQueryResult(query.Content.ID)
if err != nil {
log.Print("Querying real time metric(s)")
} else {
// Parse the results
for i, v := range result.Entries {
//Real time metric have only one entry that will be returned for every metric
//parseResult([]string{uc.Unity.Name}, v.Content.Values.(map[string]interface{}))
parseResult(v.Content.Values.(map[string]interface{}), realtimeMetrics[i].PromGauge, labels)
}
}
}
}()
}
func (uc UnityCollector) CollectPoolMetrics() {
go func() {
//Slice of all realtime metrics in order to be possible to handle them in one request
Pools, err := uc.Unity.Session.GetPool()
log.Print(Pools)
if err != nil {
log.Fatal(err)
} else {
for _, p := range Pools.Entries {
labels := make([]string, 0)
labels = append(labels, uc.Unity.Name)
labels = append(labels, p.Content.ID)
labels = append(labels, p.Content.Name)
uc.PoolMetrics[0].WithLabelValues(labels...).Set(float64(p.Content.SizeFree))
uc.PoolMetrics[1].WithLabelValues(labels...).Set(float64(p.Content.SizeTotal))
uc.PoolMetrics[2].WithLabelValues(labels...).Set(float64(p.Content.SizeUsed))
uc.PoolMetrics[3].WithLabelValues(labels...).Set(float64(p.Content.SizeSubscribed))
}
}
}()
}
func (uc UnityCollector) CollectLUNMetrics() {
go func() {
//Slice of all realtime metrics in order to be possible to handle them in one request
LUNs, err := uc.Unity.Session.GetLUN()
log.Print(LUNs)
if err != nil {
log.Fatal(err)
} else {
for _, p := range LUNs.Entries {
labels := make([]string, 0)
labels = append(labels, uc.Unity.Name)
labels = append(labels, p.Content.ID)
labels = append(labels, p.Content.Name)
uc.LUNMetrics[0].WithLabelValues(labels...).Set(float64(p.Content.SizeTotal))
}
}
}()
}
func (uc UnityCollector) CollectStorageResourceMetrics() {
go func() {
//Slice of all realtime metrics in order to be possible to handle them in one request
StorageResources, err := uc.Unity.Session.GetStorageResource()
log.Print(StorageResources)
if err != nil {
log.Fatal(err)
} else {
for _, sr := range StorageResources.Entries {
labels := make([]string, 0)
labels = append(labels, uc.Unity.Name)
labels = append(labels, sr.Content.ID)
labels = append(labels, sr.Content.Name)
uc.StorageMetrics[0].WithLabelValues(labels...).Set(float64(sr.Content.SizeAllocated))
uc.StorageMetrics[1].WithLabelValues(labels...).Set(float64(sr.Content.SizeTotal))
uc.StorageMetrics[2].WithLabelValues(labels...).Set(float64(sr.Content.SizeUsed))
}
}
}()
}
//Sample valuesMap
// "values": {
// "spa": {
// "device1": 100
// }
// }
//// TODO: Description
func parseResult(valuesMap map[string]interface{}, promGauge *prometheus.GaugeVec, labels []string) {
//Current level of the values map
for key, val := range valuesMap {
labels := append(labels, key)
//Switch statement to decicde if current element is anohter map
//If yes -> further recursion
//If no -> print values
//log.Print(val)
switch vt := val.(type) {
//First case is an encaspulated value
case map[string]interface{}:
//go donw one more level
parseResult(
val.(map[string]interface{}),
promGauge,
labels)
//came to none map value
case string:
valstr := fmt.Sprintf("%s", vt)
val64, _ := strconv.ParseFloat(valstr, 64)
//log.Print(labels, vt," string ",valstr,val64 )
promGauge.WithLabelValues(labels...).Set(val64)
case int32, int64:
log.Print(labels, vt, " int")
case float64:
//log.Print(labels, vt," float" )
val, _ := val.(float64)
promGauge.WithLabelValues(labels...).Set(val)
default:
log.Print(labels, vt, " default")
val, _ := val.(float64)
promGauge.WithLabelValues(labels...).Set(val)
}
}
}