/
process_exporter.go
418 lines (398 loc) · 12.9 KB
/
process_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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package main
// Author: Valentin Kuznetsov <vkuznet [AT] gmail {DOT} com>
// Example of cmsweb data-service exporter for prometheus.io
import (
"errors"
"flag"
"fmt"
"log"
"net/http"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/procfs"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/process"
)
var (
listeningAddress = flag.String("address", ":18000", "address to expose metrics on 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("prefix", "process_exporter", "namespace/prefix to use")
pid = flag.Int("pid", 0, "PID of the process we're going to scrape")
verbose = flag.Bool("verbose", false, "verbose output")
)
type Exporter struct {
URI string
mutex sync.Mutex
// metrics from process collector
cpuTotal *prometheus.Desc
openFDs, maxFDs *prometheus.Desc
vsize, maxVsize *prometheus.Desc
rss *prometheus.Desc
// node specific metrics
memPercent *prometheus.Desc
memTotal *prometheus.Desc
memFree *prometheus.Desc
swapPercent *prometheus.Desc
swapTotal *prometheus.Desc
swapFree *prometheus.Desc
cpuPercent *prometheus.Desc
numThreads *prometheus.Desc
numCpus *prometheus.Desc
load1 *prometheus.Desc
load5 *prometheus.Desc
load15 *prometheus.Desc
//process specific metrics
procCpu *prometheus.Desc
topCpu *prometheus.Desc
procMem *prometheus.Desc
openFiles *prometheus.Desc
totCon *prometheus.Desc
lisCon *prometheus.Desc
estCon *prometheus.Desc
closeCon *prometheus.Desc
timeCon *prometheus.Desc
}
func NewExporter(uri string) *Exporter {
return &Exporter{
URI: uri,
// metrics from process collector
cpuTotal: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "process_cpu_seconds_total"),
"Total user and system CPU time spent in seconds (process collector)",
nil, nil,
),
openFDs: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "process_open_fds"),
"Number of open file descriptors (process collector)",
nil, nil,
),
maxFDs: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "process_max_fds"),
"Maximum number of open file descriptors (process collector)",
nil, nil,
),
vsize: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "process_virtual_memory_bytes"),
"Virtual memory size in bytes (process collector)",
nil, nil,
),
maxVsize: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "process_virtual_memory_max_bytes"),
"Maximum amount of virtual memory available in bytes (process collector)",
nil, nil,
),
rss: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "process_resident_memory_bytes"),
"Resident memory size in bytes (process collector)",
nil, nil,
),
// custom metrics
memPercent: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "memory_percent"),
"Virtual memory usage of the server",
nil,
nil),
memTotal: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "memory_total"),
"Virtual total memory usage of the server",
nil,
nil),
memFree: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "memory_free"),
"Virtual free memory usage of the server",
nil,
nil),
swapPercent: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "swap_percent"),
"Swap memory usage of the server",
nil,
nil),
swapTotal: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "swap_total"),
"Virtual total swap usage of the server",
nil,
nil),
swapFree: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "swap_free"),
"Virtual free swap 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",
nil,
nil),
numCpus: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "num_cpus"),
"Number of CPUs usable by the current process",
nil,
nil),
load1: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "load1"),
"Load average in last 1m",
nil,
nil),
load5: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "load5"),
"Load average in last 5m",
nil,
nil),
load15: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "load15"),
"Load average in last 15m",
nil,
nil),
topCpu: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "top_cpu"),
"process CPU reported by top",
nil,
nil),
procCpu: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "proc_cpu"),
"process CPU",
nil,
nil),
procMem: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "proc_mem"),
"process memory",
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),
closeCon: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "close_wait_connections"),
"Server CLOSE_WAIT number of connections",
nil,
nil),
timeCon: prometheus.NewDesc(
prometheus.BuildFQName(*namespace, "", "time_wait_connections"),
"Server TIME_WAIT number of connections",
nil,
nil),
}
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
// metrics from process collector
ch <- e.cpuTotal
ch <- e.openFDs
ch <- e.maxFDs
ch <- e.vsize
ch <- e.maxVsize
ch <- e.rss
// node specific metrics
ch <- e.memPercent
ch <- e.memTotal
ch <- e.memFree
ch <- e.swapPercent
ch <- e.swapTotal
ch <- e.swapFree
ch <- e.numThreads
ch <- e.cpuPercent
ch <- e.numCpus
ch <- e.load1
ch <- e.load5
ch <- e.load15
// process specific metrics
ch <- e.topCpu
ch <- e.procCpu
ch <- e.procMem
ch <- e.totCon
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)
}
return
}
// helper function which collects exporter attributes
func (e *Exporter) collect(ch chan<- prometheus.Metric) error {
var mempct, memtot, memfree float64
if v, e := mem.VirtualMemory(); e == nil {
mempct = v.UsedPercent
memtot = float64(v.Total)
memfree = float64(v.Free)
}
var swappct, swaptot, swapfree float64
if v, e := mem.SwapMemory(); e == nil {
swappct = v.UsedPercent
swaptot = float64(v.Total)
swapfree = float64(v.Free)
}
var cpupct float64
// Percent calculates the percentage of cpu used either per CPU or combined.
// If an interval of 0 is given it will compare the current cpu times against the last call.
// Returns one value per cpu, or a single value if percpu is set to false.
if c, e := cpu.Percent(time.Millisecond, false); e == nil {
for _, v := range c {
cpupct += v
}
// cpupct = c[0] // one value since we didn't ask per cpu
}
var load1, load5, load15 float64
if l, e := load.Avg(); e == nil {
load1 = l.Load1
load5 = l.Load5
load15 = l.Load15
}
var cpuTotal, vsize, rss, openFDs, maxFDs, maxVsize float64
if proc, err := procfs.NewProc(int(*pid)); err == nil {
if stat, err := proc.Stat(); err == nil {
// CPUTime returns the total CPU user and system time in seconds.
cpuTotal = float64(stat.CPUTime())
vsize = float64(stat.VirtualMemory())
rss = float64(stat.ResidentMemory())
}
if fds, err := proc.FileDescriptorsLen(); err == nil {
openFDs = float64(fds)
}
if limits, err := proc.NewLimits(); err == nil {
maxFDs = float64(limits.OpenFiles)
maxVsize = float64(limits.AddressSpace)
}
}
// get cpu usage from top
topCpu, err := top(int(*pid))
if err != nil {
log.Printf("ERROR: %s", err)
}
var procCpu, procMem float64
var estCon, lisCon, othCon, totCon, closeCon, timeCon, openFiles float64
var nThreads float64
if proc, err := process.NewProcess(int32(*pid)); err == nil {
// CPU_Percent returns how many percent of the CPU time this process uses
if v, e := proc.CPUPercent(); e == nil {
procCpu = float64(v)
}
if v, e := proc.MemoryPercent(); e == nil {
procMem = float64(v)
}
if v, e := proc.NumThreads(); e == nil {
nThreads = float64(v)
}
if connections, e := proc.Connections(); e == nil {
for _, v := range connections {
if v.Status == "LISTEN" {
lisCon += 1
} else if v.Status == "ESTABLISHED" {
estCon += 1
} else if v.Status == "TIME_WAIT" {
timeCon += 1
} else if v.Status == "CLOSE_WAIT" {
closeCon += 1
} else {
othCon += 1
}
}
totCon = lisCon + estCon + timeCon + closeCon + othCon
}
if oFiles, e := proc.OpenFiles(); e == nil {
openFiles = float64(len(oFiles))
}
}
// metrics from process collector
ch <- prometheus.MustNewConstMetric(e.cpuTotal, prometheus.CounterValue, cpuTotal)
ch <- prometheus.MustNewConstMetric(e.openFDs, prometheus.CounterValue, openFDs)
ch <- prometheus.MustNewConstMetric(e.maxFDs, prometheus.CounterValue, maxFDs)
ch <- prometheus.MustNewConstMetric(e.vsize, prometheus.CounterValue, vsize)
ch <- prometheus.MustNewConstMetric(e.maxVsize, prometheus.CounterValue, maxVsize)
ch <- prometheus.MustNewConstMetric(e.rss, prometheus.CounterValue, rss)
// node specific metrics
ch <- prometheus.MustNewConstMetric(e.memPercent, prometheus.CounterValue, mempct)
ch <- prometheus.MustNewConstMetric(e.memTotal, prometheus.CounterValue, memtot)
ch <- prometheus.MustNewConstMetric(e.memFree, prometheus.CounterValue, memfree)
ch <- prometheus.MustNewConstMetric(e.swapPercent, prometheus.CounterValue, swappct)
ch <- prometheus.MustNewConstMetric(e.swapTotal, prometheus.CounterValue, swaptot)
ch <- prometheus.MustNewConstMetric(e.swapFree, prometheus.CounterValue, swapfree)
ch <- prometheus.MustNewConstMetric(e.numCpus, prometheus.CounterValue, float64(runtime.NumCPU()))
ch <- prometheus.MustNewConstMetric(e.load1, prometheus.CounterValue, load1)
ch <- prometheus.MustNewConstMetric(e.load5, prometheus.CounterValue, load5)
ch <- prometheus.MustNewConstMetric(e.load15, prometheus.CounterValue, load15)
// process specific metrics
ch <- prometheus.MustNewConstMetric(e.topCpu, prometheus.CounterValue, topCpu)
ch <- prometheus.MustNewConstMetric(e.procCpu, prometheus.CounterValue, procCpu)
ch <- prometheus.MustNewConstMetric(e.procMem, prometheus.CounterValue, procMem)
ch <- prometheus.MustNewConstMetric(e.numThreads, prometheus.CounterValue, nThreads)
ch <- prometheus.MustNewConstMetric(e.cpuPercent, prometheus.CounterValue, cpupct)
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)
ch <- prometheus.MustNewConstMetric(e.closeCon, prometheus.CounterValue, closeCon)
ch <- prometheus.MustNewConstMetric(e.timeCon, prometheus.CounterValue, timeCon)
return nil
}
func top(pid int) (float64, error) {
if runtime.GOOS != "linux" {
msg := fmt.Sprintf("unable to run top single snapshot on %v", runtime.GOOS)
return 0, errors.New(msg)
}
cmd := exec.Command("top", "-b", "-n", "1", "-p", fmt.Sprintf("%d", pid))
stdout, err := cmd.Output()
if err != nil {
return 0, err
}
arr := strings.Split(string(stdout), "\n")
last := arr[len(arr)-2]
var fields []string
for _, v := range strings.Split(last, " ") {
if len(v) > 1 && v != " " {
fields = append(fields, v)
}
}
if len(fields) > 6 {
cpu, err := strconv.ParseFloat(fields[6], 64)
if err != nil {
return 0, err
}
return cpu, nil
}
return 0, errors.New("insufficient number of fields in top output")
}
// 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))
}