-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain.go
102 lines (92 loc) · 2.61 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
package main
import (
"flag"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/client_golang/prometheus"
"crypto/tls"
"github.com/oliveagle/jsonpath"
"io/ioutil"
"encoding/json"
)
var addr = flag.String("listen-address", ":9116", "The address to listen on for HTTP requests.")
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Json Exporter</title></head>
<body>
<h1>Json Exporter</h1>
<p><a href="/probe">Run a probe</a></p>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>`))
})
flag.Parse()
http.HandleFunc("/probe", probeHandler)
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(*addr, nil))
}
func probeHandler(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
target := params.Get("target")
if target == "" {
http.Error(w, "Target parameter is missing", 400)
return
}
lookuppath := params.Get("jsonpath")
if target == "" {
http.Error(w, "The JsonPath to lookup", 400)
return
}
probeSuccessGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_success",
Help: "Displays whether or not the probe was a success",
})
probeDurationGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_duration_seconds",
Help: "Returns how long the probe took to complete in seconds",
})
valueGauge := prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "value",
Help: "Retrieved value",
},
)
registry := prometheus.NewRegistry()
registry.MustRegister(probeSuccessGauge)
registry.MustRegister(probeDurationGauge)
registry.MustRegister(valueGauge)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(target)
if err != nil {
log.Fatal(err)
} else {
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var json_data interface{}
json.Unmarshal([]byte(bytes), &json_data)
res, err := jsonpath.JsonPathLookup(json_data, lookuppath)
if err != nil {
http.Error(w, "Jsonpath not found", http.StatusNotFound)
return
}
log.Printf("Found value %v", res)
number, ok := res.(float64)
if !ok {
http.Error(w, "Values could not be parsed to Float64", http.StatusInternalServerError)
return
}
probeSuccessGauge.Set(1)
valueGauge.Set(number)
}
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
}