forked from dynport/metrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nginx.go
132 lines (120 loc) · 2.64 KB
/
nginx.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
package main
import (
"bufio"
"bytes"
"strconv"
"strings"
)
const (
nginxActiveConnectionsPrefix = "Active connections: "
nginxSecondLineState = "secondLine"
NGINX = "nginx"
)
func init() {
parser.Add(NGINX, "http://127.0.0.1:8080", "Collect nginx metrics")
}
type Nginx struct {
Address string
Raw []byte
ActiveConnections int64
Accepts int64
Handled int64
Requests int64
Reading int64
Writing int64
Waiting int64
}
func (n *Nginx) Metrics() []*Metric {
return []*Metric{
{Key: "ActiveConnections", Value: n.ActiveConnections},
}
}
func parseIntE(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
}
func (nginx *Nginx) Load(raw []byte) error {
var e error
scanner := bufio.NewScanner(bytes.NewReader(raw))
state := ""
for scanner.Scan() {
txt := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(txt, nginxActiveConnectionsPrefix) {
nginx.ActiveConnections, e = parseIntE(strings.TrimPrefix(txt, nginxActiveConnectionsPrefix))
if e != nil {
return e
}
} else if strings.HasPrefix(txt, "server accepts") {
state = nginxSecondLineState
} else if state == nginxSecondLineState {
fields := strings.Fields(txt)
if len(fields) == 3 {
nginx.Accepts, e = parseIntE(fields[0])
if e != nil {
return e
}
nginx.Handled, e = parseIntE(fields[1])
if e != nil {
return e
}
nginx.Requests, e = parseIntE(fields[2])
if e != nil {
return e
}
}
state = ""
} else if strings.HasPrefix(txt, "Reading") {
fields := strings.Fields(txt)
last := ""
for _, f := range fields {
switch last {
case "Reading:":
nginx.Reading, e = parseIntE(f)
if e != nil {
return e
}
case "Writing:":
nginx.Writing, e = parseIntE(f)
if e != nil {
return e
}
case "Waiting:":
nginx.Waiting, e = parseIntE(f)
if e != nil {
return e
}
}
last = f
}
}
}
return scanner.Err()
}
func (self *Nginx) Prefix() string {
return "nginx"
}
func (nginx *Nginx) Collect(c *MetricsCollection) error {
var e error
if len(nginx.Raw) == 0 {
nginx.Raw, e = FetchURL(nginx.Address)
if e != nil {
return e
}
}
e = nginx.Load(nginx.Raw)
if e != nil {
return e
}
h := MetricsMap{
"ActiveConnections": nginx.ActiveConnections,
"Accepts": nginx.Accepts,
"Handled": nginx.Handled,
"Requests": nginx.Requests,
"Reading": nginx.Reading,
"Writing": nginx.Writing,
"Waiting": nginx.Waiting,
}
for k, v := range h {
c.Add(k, v)
}
return nil
}