-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvarnish_request_exporter.go
242 lines (221 loc) · 6.57 KB
/
varnish_request_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
// Copyright 2016-2020 Markus Lindenberg, Stig Bakken
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"flag"
"fmt"
"net/http"
"os"
"os/exec"
"os/signal"
"regexp"
"syscall"
"github.com/facebookgo/pidfile"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
)
const (
namespace = "varnish_request"
)
var (
listenAddress = flag.String("http.port", ":9151", "Host/port for HTTP server")
metricsPath = flag.String("http.metricsurl", "/metrics", "Prometheus metrics path")
httpHost = flag.String("varnish.host", "", "Virtual host to look for in Varnish logs (defaults to all hosts)")
mappingsFile = flag.String("varnish.path-mappings", "", "Name of file with path mappings")
instance = flag.String("varnish.instance", "", "Name of Varnish instance")
beFirstByte = flag.Bool("varnish.firstbyte", false, "Also export metrics for backend time to first byte")
userQuery = flag.String("varnish.query", "", "VSL query override (defaults to one that is generated")
sizes = flag.Bool("varnish.sizes", false, "Also export metrics for response size")
)
type pathMapping struct {
Pattern *regexp.Regexp
Replacement string
}
func main() {
flag.Parse()
// Listen to signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
err := pidfile.Write()
if pidfile.IsNotConfigured(err) {
log.Info("pidfile not configured")
} else if err != nil {
log.Fatal(err)
}
// Set up 'varnishncsa' pipe
cmdName := "varnishncsa"
vslQuery := buildVslQuery()
varnishFormat := buildVarnishNCSAFormat()
cmdArgs := buildVarnishNCSAArgs(vslQuery, varnishFormat)
log.Infof("Running command: %v %v\n", cmdName, cmdArgs)
cmd := exec.Command(cmdName, cmdArgs...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(cmdReader)
pathMappings, err := parseMappings(*mappingsFile)
if err != nil {
log.Fatal(err)
}
// Setup metrics
varnishMessages := prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_log_messages",
Help: "Current total log messages received.",
})
err = prometheus.Register(varnishMessages)
if err != nil {
log.Fatal(err)
}
varnishParseFailures := prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_log_parse_failure",
Help: "Number of errors while parsing log messages.",
})
err = prometheus.Register(varnishParseFailures)
if err != nil {
log.Fatal(err)
}
var msgs int64
go func() {
for scanner.Scan() {
varnishMessages.Inc()
content := scanner.Text()
msgs++
metrics, labels, err := parseMessage(content, pathMappings)
if err != nil {
log.Error(err)
continue
}
for _, metric := range metrics {
var collector prometheus.Collector
//collector, err = prometheus.RegisterOrGet(prometheus.NewHistogramVec(prometheus.HistogramOpts{
collector = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: namespace,
Name: metric.Name,
Help: fmt.Sprintf("Varnish request log value for %s", metric.Name),
}, labels.Names)
err := prometheus.Register(collector)
if err != nil {
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
collector = are.ExistingCollector.(*prometheus.HistogramVec)
} else {
log.Error(err)
continue
}
}
collector.(*prometheus.HistogramVec).WithLabelValues(labels.Values...).Observe(metric.Value)
}
}
}()
// Setup HTTP server
http.Handle(*metricsPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`<html>
<head><title>Varnish Request Exporter</title></head>
<body>
<h1>Varnish Request Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
go func() {
log.Infof("Starting Server: %s", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}()
go func() {
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
log.Infof("varnishncsa command exited")
log.Infof("Messages received: %d", msgs)
os.Exit(0)
}()
s := <-sigChan
log.Infof("Received %v, terminating", s)
log.Infof("Messages received: %d", msgs)
os.Exit(0)
}
func parseMappings(mappingsFile string) (mappings []pathMapping, err error) {
mappings = make([]pathMapping, 0)
if mappingsFile == "" {
return
}
inFile, err := os.Open(mappingsFile)
if err != nil {
log.Fatal(err)
}
defer func() { _ = inFile.Close() }()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
commentRegexp := regexp.MustCompile("(#.*|^\\s+|\\s+$)")
splitRegexp := regexp.MustCompile("\\s+")
lineNo := 0
for scanner.Scan() {
lineNo++
line := commentRegexp.ReplaceAllString(scanner.Text(), "")
if line == "" {
continue
}
parts := splitRegexp.Split(line, 2)
switch len(parts) {
case 1:
log.Debugf("mapping strip: %s", parts[0])
mappings = append(mappings, pathMapping{regexp.MustCompile(parts[0]), ""})
case 2:
log.Debugf("mapping replace: %s => %s", parts[0], parts[1])
mappings = append(mappings, pathMapping{regexp.MustCompile(parts[0]), parts[1]})
}
}
return
}
func buildVslQuery() string {
query := *userQuery
if *httpHost != "" {
if query != "" {
query += " and "
}
query += "ReqHeader:host eq \"" + *httpHost + "\""
}
return query
}
func buildVarnishNCSAFormat() string {
format := "method=\"%m\" status=%s path=\"%U\" cache=\"%{Varnish:hitmiss}x\" host=\"%{host}i\" time:%D"
if *beFirstByte {
format += " time_firstbyte:%{Varnish:time_firstbyte}x"
}
if *sizes {
format += " respsize:%b"
}
return format
}
func buildVarnishNCSAArgs(vslQuery string, format string) []string {
args := make([]string, 0)
args = append(args, "-F", format)
if vslQuery != "" {
args = append(args, "-q", vslQuery)
}
if *instance != "" {
args = append(args, "-n", *instance)
}
return args
}