-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
main.go
258 lines (210 loc) · 7.95 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
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
/*
* Copyright 2016 Martin Helmich <kontakt@martin-helmich.de>
*
* 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 (
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/martin-helmich/prometheus-nginxlog-exporter/config"
"github.com/martin-helmich/prometheus-nginxlog-exporter/discovery"
"github.com/martin-helmich/prometheus-nginxlog-exporter/relabeling"
"github.com/martin-helmich/prometheus-nginxlog-exporter/tail"
"github.com/prometheus/client_golang/prometheus"
"github.com/satyrius/gonx"
)
// Metrics is a struct containing pointers to all metrics that should be
// exposed to Prometheus
type Metrics struct {
countTotal *prometheus.CounterVec
bytesTotal *prometheus.CounterVec
upstreamSeconds *prometheus.SummaryVec
upstreamSecondsHist *prometheus.HistogramVec
responseSeconds *prometheus.SummaryVec
responseSecondsHist *prometheus.HistogramVec
parseErrorsTotal prometheus.Counter
}
// Init initializes a metrics struct
func (m *Metrics) Init(cfg *config.NamespaceConfig) {
cfg.MustCompile()
labels := cfg.OrderedLabelNames
for _, r := range relabeling.DefaultRelabelings {
labels = append(labels, r.TargetLabel)
}
for i := range cfg.RelabelConfigs {
labels = append(labels, cfg.RelabelConfigs[i].TargetLabel)
}
m.countTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: cfg.Name,
Name: "http_response_count_total",
Help: "Amount of processed HTTP requests",
}, labels)
m.bytesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: cfg.Name,
Name: "http_response_size_bytes",
Help: "Total amount of transferred bytes",
}, labels)
m.upstreamSeconds = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: cfg.Name,
Name: "http_upstream_time_seconds",
Help: "Time needed by upstream servers to handle requests",
}, labels)
m.upstreamSecondsHist = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: cfg.Name,
Name: "http_upstream_time_seconds_hist",
Help: "Time needed by upstream servers to handle requests",
}, labels)
m.responseSeconds = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: cfg.Name,
Name: "http_response_time_seconds",
Help: "Time needed by NGINX to handle requests",
}, labels)
m.responseSecondsHist = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: cfg.Name,
Name: "http_response_time_seconds_hist",
Help: "Time needed by NGINX to handle requests",
}, labels)
m.parseErrorsTotal = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: cfg.Name,
Name: "parse_errors_total",
Help: "Total number of log file lines that could not be parsed",
})
prometheus.MustRegister(m.countTotal)
prometheus.MustRegister(m.bytesTotal)
prometheus.MustRegister(m.upstreamSeconds)
prometheus.MustRegister(m.upstreamSecondsHist)
prometheus.MustRegister(m.responseSeconds)
prometheus.MustRegister(m.responseSecondsHist)
prometheus.MustRegister(m.parseErrorsTotal)
}
func main() {
var opts config.StartupFlags
var cfg = config.Config{
Listen: config.ListenConfig{
Port: 4040,
Address: "0.0.0.0",
},
}
flag.IntVar(&opts.ListenPort, "listen-port", 4040, "HTTP port to listen on")
flag.StringVar(&opts.Format, "format", `$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"`, "NGINX access log format")
flag.StringVar(&opts.Namespace, "namespace", "nginx", "namespace to use for metric names")
flag.StringVar(&opts.ConfigFile, "config-file", "", "Configuration file to read from")
flag.BoolVar(&opts.EnableExperimentalFeatures, "enable-experimental", false, "Set this flag to enable experimental features")
flag.Parse()
opts.Filenames = flag.Args()
loadConfig(&opts, &cfg)
fmt.Printf("using configuration %+v\n", cfg)
if stabilityError := cfg.StabilityWarnings(); stabilityError != nil && !opts.EnableExperimentalFeatures {
fmt.Fprintf(os.Stderr, "Your configuration file contains an option that is explicitly labeled as experimental feature:\n\n %s\n\n", stabilityError.Error())
fmt.Fprintln(os.Stderr, "Use the -enable-experimental flag or the enable_experimental option to enable these features. Use them at your own peril.")
os.Exit(1)
}
if cfg.Consul.Enable {
setupConsul(&cfg)
}
for _, ns := range cfg.Namespaces {
fmt.Printf("starting listener for namespace %s\n", ns.Name)
go processNamespace(ns)
}
listenAddr := fmt.Sprintf("%s:%d", cfg.Listen.Address, cfg.Listen.Port)
fmt.Printf("running HTTP server on address %s\n", listenAddr)
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(listenAddr, nil)
}
func loadConfig(opts *config.StartupFlags, cfg *config.Config) {
if opts.ConfigFile != "" {
fmt.Printf("loading configuration file %s\n", opts.ConfigFile)
if err := config.LoadConfigFromFile(cfg, opts.ConfigFile); err != nil {
panic(err)
}
} else if err := config.LoadConfigFromFlags(cfg, opts); err != nil {
panic(err)
}
}
func setupConsul(cfg *config.Config) {
registrator, err := discovery.NewConsulRegistrator(cfg)
if err != nil {
panic(err)
}
fmt.Printf("registering service in Consul\n")
if err := registrator.RegisterConsul(); err != nil {
panic(err)
}
exitChan := make(chan os.Signal, 1)
signal.Notify(exitChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-exitChan
fmt.Printf("unregistering service in Consul\n")
registrator.UnregisterConsul()
os.Exit(0)
}()
}
func processNamespace(nsCfg config.NamespaceConfig) {
parser := gonx.NewParser(nsCfg.Format)
metrics := Metrics{}
metrics.Init(&nsCfg)
for _, f := range nsCfg.SourceFiles {
t, err := tail.NewFollower(f)
if err != nil {
panic(err)
}
t.OnError(func(err error) {
panic(err)
})
go processSourceFile(nsCfg, t, parser, &metrics)
}
}
func processSourceFile(nsCfg config.NamespaceConfig, t tail.Follower, parser *gonx.Parser, metrics *Metrics) {
relabelings := relabeling.NewRelabelings(nsCfg.RelabelConfigs)
relabelings = append(relabeling.DefaultRelabelings, relabelings...)
staticLabelValues := nsCfg.OrderedLabelValues
totalLabelCount := len(staticLabelValues) + len(relabelings)
relabelLabelOffset := len(staticLabelValues)
labelValues := make([]string, totalLabelCount)
for i := range staticLabelValues {
labelValues[i] = staticLabelValues[i]
}
for line := range t.Lines() {
entry, err := parser.ParseString(line.Text)
if err != nil {
fmt.Printf("error while parsing line '%s': %s\n", line.Text, err)
metrics.parseErrorsTotal.Inc()
continue
}
for i := range relabelings {
if str, err := entry.Field(relabelings[i].SourceValue); err == nil {
mapped, err := relabelings[i].Map(str)
if err == nil {
labelValues[i+relabelLabelOffset] = mapped
}
}
}
metrics.countTotal.WithLabelValues(labelValues...).Inc()
if bytes, err := entry.FloatField("body_bytes_sent"); err == nil {
metrics.bytesTotal.WithLabelValues(labelValues...).Add(bytes)
}
if upstreamTime, err := entry.FloatField("upstream_response_time"); err == nil {
metrics.upstreamSeconds.WithLabelValues(labelValues...).Observe(upstreamTime)
metrics.upstreamSecondsHist.WithLabelValues(labelValues...).Observe(upstreamTime)
}
if responseTime, err := entry.FloatField("request_time"); err == nil {
metrics.responseSeconds.WithLabelValues(labelValues...).Observe(responseTime)
metrics.responseSecondsHist.WithLabelValues(labelValues...).Observe(responseTime)
}
}
}