/
wmcore_exporter.go
296 lines (274 loc) · 8.14 KB
/
wmcore_exporter.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
package main
// Author: Valentin Kuznetsov <vkuznet [AT] gmail {DOT} com>
// Example of cmsweb data-service exporter for prometheus.io
import (
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/user"
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/vkuznet/x509proxy"
)
// const (
// namespace = "wmcore" // For Prometheus metrics.
// )
var (
listeningAddress = flag.String("port", ":18000", "port to expose metrics and web interface.")
metricsEndpoint = flag.String("endpoint", "/metrics", "Path under which to expose metrics.")
scrapeURI = flag.String("uri", "", "URI of server status page we're going to scrape")
namespace = flag.String("namespace", "wmcore", "namespace for prometheus metrics")
verbose = flag.Bool("verbose", false, "verbose output")
)
// global HTTP client
var _client = HttpClient()
// global client's x509 certificates
var _certs []tls.Certificate
// UserDN function parses user Distinguished Name (DN) from client's HTTP request
func UserDN(r *http.Request) string {
var names []interface{}
for _, cert := range r.TLS.PeerCertificates {
for _, name := range cert.Subject.Names {
switch v := name.Value.(type) {
case string:
names = append(names, v)
}
}
}
parts := names[:7]
return fmt.Sprintf("/DC=%s/DC=%s/OU=%s/OU=%s/CN=%s/CN=%s/CN=%s", parts...)
}
// client X509 certificates
func tlsCerts() ([]tls.Certificate, error) {
if len(_certs) != 0 {
return _certs, nil // use cached certs
}
uproxy := os.Getenv("X509_USER_PROXY")
uckey := os.Getenv("X509_USER_KEY")
ucert := os.Getenv("X509_USER_CERT")
// check if /tmp/x509up_u$UID exists, if so setup X509_USER_PROXY env
u, err := user.Current()
if err == nil {
fname := fmt.Sprintf("/tmp/x509up_u%s", u.Uid)
if _, err := os.Stat(fname); err == nil {
uproxy = fname
}
}
if *verbose {
log.Printf(uproxy, uckey, ucert)
}
if uproxy == "" && uckey == "" { // user doesn't have neither proxy or user certs
return nil, fmt.Errorf("Neither proxy or user certs are found, please setup X509 environment variables")
}
if uproxy != "" {
// use local implementation of LoadX409KeyPair instead of tls one
x509cert, err := x509proxy.LoadX509Proxy(uproxy)
if err != nil {
return nil, fmt.Errorf("failed to parse proxy X509 proxy set by X509_USER_PROXY: %v", err)
}
_certs = []tls.Certificate{x509cert}
return _certs, nil
}
x509cert, err := tls.LoadX509KeyPair(ucert, uckey)
if err != nil {
return nil, fmt.Errorf("failed to parse user X509 certificate: %v", err)
}
_certs = []tls.Certificate{x509cert}
return _certs, nil
}
// HttpClient provides HTTP client
func HttpClient() *http.Client {
// get X509 certs
certs, err := tlsCerts()
if err != nil {
fmt.Println("unable to get TLS certificate: ", err.Error())
return &http.Client{}
}
if len(certs) == 0 {
return &http.Client{}
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{Certificates: certs,
InsecureSkipVerify: true},
}
return &http.Client{Transport: tr}
}
type Exporter struct {
URI string
mutex sync.Mutex
scrapeFailures prometheus.Counter
uptime *prometheus.Desc
connections *prometheus.GaugeVec
memPercent *prometheus.Desc
swapPercent *prometheus.Desc
cpuPercent *prometheus.Desc
numThreads *prometheus.Desc
openFiles *prometheus.Desc
totCon *prometheus.Desc
lisCon *prometheus.Desc
estCon *prometheus.Desc
}
func NewExporter(uri string) *Exporter {
return &Exporter{
URI: uri,
uptime: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "uptime"),
"Current uptime in seconds",
nil,
nil),
connections: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: *namespace,
Name: "connections",
Help: "connection statuses",
},
[]string{"state"},
),
memPercent: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "memory_percent"),
"Virtual memory usage of the server",
nil,
nil),
cpuPercent: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "cpu_percent"),
"cpu percent of the server",
nil,
nil),
numThreads: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "num_threads"),
"Number of threads or Go routines",
nil,
nil),
openFiles: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "open_files"),
"Number of open files",
nil,
nil),
totCon: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "total_connections"),
"Server TOTAL number of connections",
nil,
nil),
lisCon: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "listen_connections"),
"Server LISTEN number of connections",
nil,
nil),
estCon: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "established_connections"),
"Server ESTABLISHED number of connections",
nil,
nil),
}
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- e.uptime
ch <- e.memPercent
ch <- e.cpuPercent
ch <- e.numThreads
ch <- e.openFiles
ch <- e.totCon
ch <- e.lisCon
ch <- e.estCon
}
// Collect performs metrics collectio of exporter attributes
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
e.mutex.Lock() // To protect metrics from concurrent collects.
defer e.mutex.Unlock()
if err := e.collect(ch); err != nil {
log.Printf("Error scraping: %s", err)
e.scrapeFailures.Inc()
e.scrapeFailures.Collect(ch)
}
return
}
// helper function which collects exporter attributes
func (e *Exporter) collect(ch chan<- prometheus.Metric) error {
// here is an example how we may collect server stats
// we'll make an HTTP call to server URI which will return
// status as a JSON document, then we'll assign metrics using JSON values
var req *http.Request
req, _ = http.NewRequest("GET", e.URI, nil)
req.Header.Add("Accept-Encoding", "identity")
req.Header.Add("Accept", "application/json")
resp, err := _client.Do(req)
if err != nil {
return fmt.Errorf("Error scraping apache: %v", err)
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
if err != nil {
data = []byte(err.Error())
}
return fmt.Errorf("Status %s (%d): %s", resp.Status, resp.StatusCode, data)
}
var rec map[string]interface{}
err = json.Unmarshal(data, &rec)
if err != nil {
return fmt.Errorf("Fail to unmarshal JSON data %s", err.Error())
}
if *verbose {
fmt.Println(string(data))
}
var mempct, cpupct float64
if v, ok := rec["memory_percent"]; ok {
mempct = v.(float64)
}
if v, ok := rec["cpu_percent"]; ok {
cpupct = v.(float64)
}
var nthr float64
if v, ok := rec["num_threads"]; ok {
nthr = v.(float64)
}
var openFiles float64
if v, ok := rec["OpenFiles"]; ok {
files := v.([]interface{})
openFiles = float64(len(files))
}
var uptime float64
if v, ok := rec["uptime"]; ok {
uptime = v.(float64)
}
var totCon, estCon, lisCon float64
if v, ok := rec["Connections"]; ok {
switch connections := v.(type) {
case []interface{}:
for _, c := range connections {
con := c.(map[string]interface{})
v, _ := con["status"]
switch v {
case "ESTABLISHED":
estCon += 1
case "LISTEN":
lisCon += 1
}
}
totCon = float64(len(connections))
}
}
ch <- prometheus.MustNewConstMetric(e.uptime, prometheus.CounterValue, uptime)
ch <- prometheus.MustNewConstMetric(e.memPercent, prometheus.CounterValue, mempct)
ch <- prometheus.MustNewConstMetric(e.cpuPercent, prometheus.CounterValue, cpupct)
ch <- prometheus.MustNewConstMetric(e.numThreads, prometheus.CounterValue, nthr)
ch <- prometheus.MustNewConstMetric(e.openFiles, prometheus.CounterValue, openFiles)
ch <- prometheus.MustNewConstMetric(e.totCon, prometheus.CounterValue, totCon)
ch <- prometheus.MustNewConstMetric(e.lisCon, prometheus.CounterValue, lisCon)
ch <- prometheus.MustNewConstMetric(e.estCon, prometheus.CounterValue, estCon)
return nil
}
// main function
func main() {
flag.Parse()
exporter := NewExporter(*scrapeURI)
prometheus.MustRegister(exporter)
log.Printf("Starting Server: %s", *listeningAddress)
http.Handle(*metricsEndpoint, promhttp.Handler())
log.Fatal(http.ListenAndServe(*listeningAddress, nil))
}