-
Notifications
You must be signed in to change notification settings - Fork 0
/
probe.go
212 lines (178 loc) · 6.26 KB
/
probe.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
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"github.com/webdevops/myuplink-exporter/myuplink"
)
const (
DefaultTimeout = 30
)
func myuplinkProbe(w http.ResponseWriter, r *http.Request) {
var err error
var timeoutSeconds float64
// startTime := time.Now()
contextLogger := buildContextLoggerFromRequest(r)
registry := prometheus.NewRegistry()
// If a timeout is configured via the Prometheus header, add it to the request.
timeoutSeconds, err = getPrometheusTimeout(r, DefaultTimeout)
if err != nil {
contextLogger.Error(err.Error())
http.Error(w, fmt.Sprintf("failed to parse timeout from Prometheus header: %s", err), http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds*float64(time.Second)))
defer cancel()
r = r.WithContext(ctx)
// use timeout as max cache time as mostly it's also the scrape time
cacheTime := time.Duration(timeoutSeconds) * time.Second
if v := r.URL.Query().Get("cache"); v != "" {
cacheTime, err = time.ParseDuration(v)
if err != nil {
contextLogger.Error(err.Error())
http.Error(w, fmt.Sprintf("failed to parse cache from query param: %s", err), http.StatusBadRequest)
return
}
}
metrics := NewMyUplinkMetrics(registry)
systemList, err := cacheResult(
"systems",
func() (interface{}, error) {
return myuplinkClient.GetSystems(ctx)
},
)
if err != nil {
contextLogger.Error(err.Error())
http.Error(w, fmt.Sprintf("failed to fetch system list from myUplink: %s", err), http.StatusBadRequest)
return
}
for _, system := range systemList.(*myuplink.ResultSystems).Systems {
metrics.system.With(prometheus.Labels{
"systemID": system.SystemID,
"systemName": clearText(system.Name),
"country": clearText(system.Country),
}).Set(1)
for _, device := range system.Devices {
if !device.IsConnectionStateAllowed(Opts.MyUplink.Device.AllowedConnectionStates) {
contextLogger.Warnf(`ignoring system "%s" device "%s", connection state is "%s"`, system.Name, device.ID, device.ConnectionState)
continue
}
metrics.systemDevice.With(prometheus.Labels{
"systemID": system.SystemID,
"deviceID": device.ID,
"deviceName": clearText(device.Product.Name),
"serialNumber": clearText(device.Product.SerialNumber),
"connectionState": clearText(device.ConnectionState),
"firmwareVersion": clearText(device.CurrentFwVersion),
}).Set(1)
devicePoints, err := cacheResultWithDuration(
fmt.Sprintf("devicePoints:%s", device.ID),
cacheTime,
func() (interface{}, error) {
return myuplinkClient.GetSystemDevicePoints(ctx, device.ID)
},
)
if err != nil {
contextLogger.Error(err.Error())
http.Error(w, fmt.Sprintf("failed to fetch device points from myUplink: %s", err), http.StatusBadRequest)
return
}
for _, devicePoint := range *devicePoints.(*myuplink.SystemDevicePoints) {
if devicePoint.Value != nil {
metrics.systemDevicePoint.With(prometheus.Labels{
"systemID": system.SystemID,
"deviceID": device.ID,
"category": clearText(devicePoint.Category),
"parameterID": devicePoint.ParameterID,
"parameterName": clearText(devicePoint.ParameterName),
"parameterUnit": clearText(devicePoint.ParameterUnit),
}).Set(*devicePoint.Value)
// enum translation
enumValue := fmt.Sprintf("%d", int64(*devicePoint.Value))
for _, enumVal := range devicePoint.EnumValues {
enumMetricVal := float64(0)
if enumVal.Value == enumValue {
enumMetricVal = 1
}
metrics.systemDevicePointEnum.With(prometheus.Labels{
"systemID": system.SystemID,
"deviceID": device.ID,
"category": clearText(devicePoint.Category),
"parameterID": devicePoint.ParameterID,
"parameterName": clearText(devicePoint.ParameterName),
"parameterUnit": clearText(devicePoint.ParameterUnit),
"valueText": clearText(enumVal.Text),
}).Set(enumMetricVal)
}
// total values (counters)
for _, totalParameterID := range Opts.MyUplink.Device.CalcTotalParameters {
if strings.EqualFold(devicePoint.ParameterID, totalParameterID) {
metrics.systemDevicePointTotal.With(prometheus.Labels{
"systemID": system.SystemID,
"deviceID": device.ID,
"category": clearText(devicePoint.Category),
"parameterID": devicePoint.ParameterID,
"parameterName": clearText(devicePoint.ParameterName),
"parameterUnit": clearText(devicePoint.ParameterUnit),
}).Set(totalParamCache.getParameterValue(device.ID, devicePoint.ParameterID, devicePoint))
}
}
}
}
}
}
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
}
func buildContextLoggerFromRequest(r *http.Request) *zap.SugaredLogger {
return logger.With(zap.String("requestPath", r.URL.Path))
}
func getPrometheusTimeout(r *http.Request, defaultTimeout float64) (timeout float64, err error) {
// If a timeout is configured via the Prometheus header, add it to the request.
if v := r.Header.Get("X-Prometheus-Scrape-Timeout-Seconds"); v != "" {
timeout, err = strconv.ParseFloat(v, 64)
if err != nil {
return
}
}
if timeout == 0 {
timeout = defaultTimeout
}
return
}
// cacheResult caches template function results (eg. Azure REST API resource information)
func cacheResult(cacheKey string, callback func() (interface{}, error)) (interface{}, error) {
if val, ok := globalCache.Get(cacheKey); ok {
return val, nil
}
ret, err := callback()
if err != nil {
return nil, err
}
globalCache.SetDefault(cacheKey, ret)
return ret, nil
}
func cacheResultWithDuration(cacheKey string, cacheTime time.Duration, callback func() (interface{}, error)) (interface{}, error) {
if val, ok := globalCache.Get(cacheKey); ok {
return val, nil
}
ret, err := callback()
if err != nil {
return nil, err
}
globalCache.Set(cacheKey, ret, cacheTime)
return ret, nil
}
func clearText(val string) string {
// remove soft hyphen
val = strings.ReplaceAll(val, "\u00AD", "")
// remove possible space chars
val = strings.TrimSpace(val)
return val
}