-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
webserver.go
470 lines (392 loc) · 16.8 KB
/
webserver.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package loggers
import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"time"
"github.com/dmachard/go-dnscollector/dnsutils"
"github.com/dmachard/go-dnscollector/subprocessors"
"github.com/dmachard/go-logger"
)
type Webserver struct {
done chan bool
done_api chan bool
httpserver net.Listener
httpmux *http.ServeMux
channel chan dnsutils.DnsMessage
config *dnsutils.Config
logger *logger.Logger
stats *subprocessors.StatsStreams
}
func NewWebserver(config *dnsutils.Config, logger *logger.Logger) *Webserver {
logger.Info("webserver - enabled")
o := &Webserver{
done: make(chan bool),
done_api: make(chan bool),
config: config,
channel: make(chan dnsutils.DnsMessage, 512),
logger: logger,
}
// set the config
o.ReadConfig()
// init engine to compute statistics
o.stats = subprocessors.NewStreamsStats(config)
return o
}
func (c *Webserver) ReadConfig() {
// todo, checking value
}
func (o *Webserver) LogInfo(msg string, v ...interface{}) {
o.logger.Info("webserver - "+msg, v...)
}
func (o *Webserver) LogError(msg string, v ...interface{}) {
o.logger.Error("webserver - "+msg, v...)
}
func (o *Webserver) Channel() chan dnsutils.DnsMessage {
return o.channel
}
func (o *Webserver) Stop() {
o.LogInfo("stopping...")
// stopping http server
o.httpserver.Close()
// close output channel
o.LogInfo("closing channel")
close(o.channel)
// read done channel and block until run is terminated
<-o.done
close(o.done)
// block and wait until http api is terminated
<-o.done_api
close(o.done_api)
o.LogInfo(" stopped")
}
func (o *Webserver) BasicAuth(w http.ResponseWriter, r *http.Request) bool {
login, password, authOK := r.BasicAuth()
if !authOK {
return false
}
return (login == o.config.Loggers.WebServer.BasicAuthLogin) && (password == o.config.Loggers.WebServer.BasicAuthPwd)
}
func (s *Webserver) resetHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
switch r.Method {
case http.MethodDelete:
fmt.Fprintf(w, "success")
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) metricsHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
switch r.Method {
case http.MethodGet:
suffix := s.config.Loggers.WebServer.PrometheusSuffix
for _, stream := range s.stats.Streams() {
counters := s.stats.GetCounters(stream)
totalClients := s.stats.GetTotalClients(stream)
totalDomains := s.stats.GetTotalDomains(stream)
topDomains := s.stats.GetTopQnames(stream)
totalNxdomains := s.stats.GetTotalNxdomains(stream)
topNxdomains := s.stats.GetTopNxdomains(stream)
totalSlowdomains := s.stats.GetTotalSlowdomains(stream)
topSlowdomains := s.stats.GetTopSlowdomains(stream)
totalSuspiciousdomains := s.stats.GetTotalSuspiciousdomains(stream)
topSuspiciousdomains := s.stats.GetTopSuspiciousdomains(stream)
topClients := s.stats.GetTopClients(stream)
topRcodes := s.stats.GetTopRcodes(stream)
topRrtypes := s.stats.GetTopRrtypes(stream)
topTransports := s.stats.GetTopTransports(stream)
topIpProto := s.stats.GetTopIpProto(stream)
topOperations := s.stats.GetTopOperations(stream)
// docs
fmt.Fprintf(w, "# HELP %s_requesters_total Number of clients\n", suffix)
fmt.Fprintf(w, "# TYPE %s_requesters_total counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_requesters_top Number of hit per client, partitioned by client ip\n", suffix)
fmt.Fprintf(w, "# TYPE %s_requesters_top counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_total Number of domains\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_total counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_top Number of hit per domain, partitioned by qname\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_top counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_nx_total Number of unknown domains\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_nx_total counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_nx_top Number of hit per unknown domain, partitioned by qname\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_nx_top counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_slow_total Number of slow domains\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_slow_total counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_slow_top Number of hit per slow domain, partitioned by qname\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_slow_top counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_suspicious_total Number of suspicious domains\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_suspicious_total counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_domains_suspicious_top Number of hit per suspicious domains, partitioned by qname\n", suffix)
fmt.Fprintf(w, "# TYPE %s_domains_suspicious_top counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_pps Number of packets per second received\n", suffix)
fmt.Fprintf(w, "# TYPE %s_pps gauge\n", suffix)
fmt.Fprintf(w, "# HELP %s_pps_max Maximum number of packets per second received\n", suffix)
fmt.Fprintf(w, "# TYPE %s_pps_max counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_packets Number of packets\n", suffix)
fmt.Fprintf(w, "# TYPE %s_packets counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_operations Number of packet, partitioned by operations\n", suffix)
fmt.Fprintf(w, "# TYPE %s_operations counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_transports Number of packets, partitioned by transport\n", suffix)
fmt.Fprintf(w, "# TYPE %s_transports counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_ipproto Number of packets, partitioned by IP protocol\n", suffix)
fmt.Fprintf(w, "# TYPE %s_ipproto counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_qtypes Number of qtypes, partitioned by qtype\n", suffix)
fmt.Fprintf(w, "# TYPE %s_qtypes counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_rcodes Number of rcodes, partitioned by rcode type\n", suffix)
fmt.Fprintf(w, "# TYPE %s_rcodes counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_latency Number of queries answered, partitioned by latency interval\n", suffix)
fmt.Fprintf(w, "# TYPE %s_latency counter\n", suffix)
fmt.Fprintf(w, "# HELP %s_latency_max Maximum latency observed\n", suffix)
fmt.Fprintf(w, "# TYPE %s_latency_max counter\n", suffix)
// total uniq clients
fmt.Fprintf(w, "%s_requesters_total{stream=\"%s\"} %d\n", suffix, stream, totalClients)
for _, v := range topClients {
fmt.Fprintf(w, "%s_requesters_top{stream=\"%s\",ip=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// total uniq domains
fmt.Fprintf(w, "%s_domains_total{stream=\"%s\"} %d\n", suffix, stream, totalDomains)
for _, v := range topDomains {
fmt.Fprintf(w, "%s_domains_top{stream=\"%s\",domain=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
fmt.Fprintf(w, "%s_domains_nx_total{stream=\"%s\"} %d\n", suffix, stream, totalNxdomains)
for _, v := range topNxdomains {
fmt.Fprintf(w, "%s_domains_nx_top{stream=\"%s\",domain=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
fmt.Fprintf(w, "%s_domains_slow_total{stream=\"%s\"} %d\n", suffix, stream, totalSlowdomains)
for _, v := range topSlowdomains {
fmt.Fprintf(w, "%s_domains_slow_top{stream=\"%s\",domain=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
fmt.Fprintf(w, "%s_domains_suspicious_total{stream=\"%s\"} %d\n", suffix, stream, totalSuspiciousdomains)
for _, v := range topSuspiciousdomains {
fmt.Fprintf(w, "%s_domains_suspicious_top{stream=\"%s\",domain=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// pps
fmt.Fprintf(w, "%s_pps{stream=\"%s\"} %d\n", suffix, stream, counters.Pps)
fmt.Fprintf(w, "%s_pps_max{stream=\"%s\"} %d\n", suffix, stream, counters.PpsMax)
// number of total packet
fmt.Fprintf(w, "%s_packets{stream=\"%s\"} %d\n", suffix, stream, counters.Packets)
for _, v := range topOperations {
fmt.Fprintf(w, "%s_operations{stream=\"%s\",operation=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// transport repartition
for _, v := range topTransports {
fmt.Fprintf(w, "%s_transports{stream=\"%s\",transport=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// ip proto repartition
for _, v := range topIpProto {
fmt.Fprintf(w, "%s_ipproto{stream=\"%s\",ip=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// qtypes repartition
for _, v := range topRrtypes {
fmt.Fprintf(w, "%s_qtypes{stream=\"%s\",qtype=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// top rcodes
for _, v := range topRcodes {
fmt.Fprintf(w, "%s_rcodes{stream=\"%s\",rcode=\"%s\"} %d\n", suffix, stream, v.Name, v.Hit)
}
// latency
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\"<1ms\"} %d\n", suffix, stream, counters.Latency0_1)
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\"1-10ms\"} %d\n", suffix, stream, counters.Latency1_10)
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\"10-50ms\"} %d\n", suffix, stream, counters.Latency10_50)
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\"50-100ms\"} %d\n", suffix, stream, counters.Latency50_100)
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\"100-500ms\"} %d\n", suffix, stream, counters.Latency100_500)
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\"500-1s\"} %d\n", suffix, stream, counters.Latency500_1000)
fmt.Fprintf(w, "%s_latency{stream=\"%s\",latency=\">1s\"} %d\n", suffix, stream, counters.Latency1000_inf)
fmt.Fprintf(w, "%s_latency_max{stream=\"%s\"} %v\n", suffix, stream, counters.LatencyMax)
fmt.Fprintf(w, "%s_latency_min{stream=\"%s\"} %v\n", suffix, stream, counters.LatencyMin)
// qname length repartition
fmt.Fprintf(w, "%s_qname_len{stream=\"%s\",length=\"<10\"} %d\n", suffix, stream, counters.QnameLength0_10)
fmt.Fprintf(w, "%s_qname_len{stream=\"%s\",length=\"10-20\"} %d\n", suffix, stream, counters.QnameLength10_20)
fmt.Fprintf(w, "%s_qname_len{stream=\"%s\",length=\"20-40\"} %d\n", suffix, stream, counters.QnameLength20_40)
fmt.Fprintf(w, "%s_qname_len{stream=\"%s\",length=\"40-60\"} %d\n", suffix, stream, counters.QnameLength40_60)
fmt.Fprintf(w, "%s_qname_len{stream=\"%s\",length=\"60-100\"} %d\n", suffix, stream, counters.QnameLength60_100)
fmt.Fprintf(w, "%s_qname_len{stream=\"%s\",length=\">100\"} %d\n", suffix, stream, counters.QnameLength100_Inf)
fmt.Fprintf(w, "%s_qname_len_max{stream=\"%s\"} %v\n", suffix, stream, counters.QnameLengthMax)
fmt.Fprintf(w, "%s_qname_len_min{stream=\"%s\"} %v\n", suffix, stream, counters.QnameLengthMin)
// query length repartition
fmt.Fprintf(w, "%s_query_len{stream=\"%s\",length=\"<50b\"} %d\n", suffix, stream, counters.QueryLength0_50)
fmt.Fprintf(w, "%s_query_len{stream=\"%s\",length=\"50-100b\"} %d\n", suffix, stream, counters.QueryLength50_100)
fmt.Fprintf(w, "%s_query_len{stream=\"%s\",length=\"100-250b\"} %d\n", suffix, stream, counters.QueryLength100_250)
fmt.Fprintf(w, "%s_query_len{stream=\"%s\",length=\"250-500b\"} %d\n", suffix, stream, counters.QueryLength250_500)
fmt.Fprintf(w, "%s_query_len{stream=\"%s\",length=\">500b\"} %d\n", suffix, stream, counters.QueryLength500_Inf)
fmt.Fprintf(w, "%s_query_len_max{stream=\"%s\"} %v\n", suffix, stream, counters.QueryLengthMax)
fmt.Fprintf(w, "%s_query_len_min{stream=\"%s\"} %v\n", suffix, stream, counters.QueryLengthMin)
// reply length repartition
fmt.Fprintf(w, "%s_reply_len{stream=\"%s\",length=\"<50b\"} %d\n", suffix, stream, counters.ReplyLength0_50)
fmt.Fprintf(w, "%s_reply_len{stream=\"%s\",length=\"50-100b\"} %d\n", suffix, stream, counters.ReplyLength50_100)
fmt.Fprintf(w, "%s_reply_len{stream=\"%s\",length=\"100-250b\"} %d\n", suffix, stream, counters.ReplyLength100_250)
fmt.Fprintf(w, "%s_reply_len{stream=\"%s\",length=\"250-500b\"} %d\n", suffix, stream, counters.ReplyLength250_500)
fmt.Fprintf(w, "%s_reply_len{stream=\"%s\",length=\">500b\"} %d\n", suffix, stream, counters.ReplyLength500_Inf)
fmt.Fprintf(w, "%s_reply_len_max{stream=\"%s\"} %v\n", suffix, stream, counters.ReplyLengthMax)
fmt.Fprintf(w, "%s_reply_len_min{stream=\"%s\"} %v\n", suffix, stream, counters.ReplyLengthMin)
}
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) topRequestersHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
stream, ok := r.URL.Query()["stream"]
if !ok || len(stream) < 1 {
stream = []string{"global"}
}
t := s.stats.GetTopClients(stream[0])
json.NewEncoder(w).Encode(t)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) topAllDomainsHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
stream, ok := r.URL.Query()["stream"]
if !ok || len(stream) < 1 {
stream = []string{"global"}
}
t := s.stats.GetTopQnames(stream[0])
json.NewEncoder(w).Encode(t)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) topNxdDomainsHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
stream, ok := r.URL.Query()["stream"]
if !ok || len(stream) < 1 {
stream = []string{"global"}
}
t := s.stats.GetTopNxdomains(stream[0])
json.NewEncoder(w).Encode(t)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) topSlowDomainsHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
stream, ok := r.URL.Query()["stream"]
if !ok || len(stream) < 1 {
stream = []string{"global"}
}
t := s.stats.GetTopSlowdomains(stream[0])
json.NewEncoder(w).Encode(t)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) topSuspiciousDomainsHandler(w http.ResponseWriter, r *http.Request) {
if !s.BasicAuth(w, r) {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
stream, ok := r.URL.Query()["stream"]
if !ok || len(stream) < 1 {
stream = []string{"global"}
}
t := s.stats.GetTopSuspiciousdomains(stream[0])
json.NewEncoder(w).Encode(t)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (s *Webserver) ListenAndServe() {
s.LogInfo("starting http api...")
mux := http.NewServeMux()
mux.HandleFunc("/metrics", s.metricsHandler)
mux.HandleFunc("/reset", s.resetHandler)
mux.HandleFunc("/top/requesters", s.topRequestersHandler)
mux.HandleFunc("/top/domains", s.topAllDomainsHandler)
mux.HandleFunc("/top/domains/nxd", s.topNxdDomainsHandler)
mux.HandleFunc("/top/domains/slow", s.topSlowDomainsHandler)
mux.HandleFunc("/top/domains/suspicious", s.topSuspiciousDomainsHandler)
var err error
var listener net.Listener
addrlisten := s.config.Loggers.WebServer.ListenIP + ":" + strconv.Itoa(s.config.Loggers.WebServer.ListenPort)
// listening with tls enabled ?
if s.config.Loggers.WebServer.TlsSupport {
s.LogInfo("tls support enabled")
var cer tls.Certificate
cer, err = tls.LoadX509KeyPair(s.config.Loggers.WebServer.CertFile, s.config.Loggers.WebServer.KeyFile)
if err != nil {
s.logger.Fatal("loading certificate failed:", err)
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}
listener, err = tls.Listen("tcp", addrlisten, config)
} else {
// basic listening
listener, err = net.Listen("tcp", addrlisten)
}
// something wrong ?
if err != nil {
s.logger.Fatal("listening failed:", err)
}
s.httpserver = listener
s.httpmux = mux
s.LogInfo("is listening on %s", listener.Addr())
http.Serve(s.httpserver, s.httpmux)
s.LogInfo("terminated")
s.done_api <- true
}
func (s *Webserver) Run() {
s.LogInfo("running in background...")
// start http server
go s.ListenAndServe()
// init timer to compute qps
t1_interval := 1 * time.Second
t1 := time.NewTimer(t1_interval)
LOOP:
for {
select {
case dm, opened := <-s.channel:
if !opened {
s.LogInfo("channel closed")
break LOOP
}
// record the dnstap message
s.stats.Record(dm)
case <-t1.C:
// compute qps each second
s.stats.Compute()
// reset the timer
t1.Reset(t1_interval)
}
}
s.LogInfo("run terminated")
// the job is done
s.done <- true
}