/
stats.go
136 lines (110 loc) · 2.44 KB
/
stats.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
package main
import (
"fmt"
"log"
"strings"
"time"
"github.com/abh/geodns/querylog"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
)
type statsEntry struct {
Time int64
Origin string
Name string
Vendor string
Label string
Qtype string
PoolCC string
Count int
}
type Stats struct {
Count int
Map map[string]*statsEntry
}
var queries *prometheus.CounterVec
func NewStats() *Stats {
return &Stats{
Map: map[string]*statsEntry{},
}
}
func (s *Stats) Key(e *querylog.Entry) string {
return fmt.Sprintf("%s %s %s %d", e.Origin, e.Name, e.LabelName, e.Qtype)
}
func vendorName(n string) string {
idx := strings.Index(n, ".pool.ntp.org.")
// log.Printf("IDX for %s: %d", n, idx)
if idx <= 0 {
return ""
}
n = n[0:idx]
l := dns.SplitDomainName(n)
v := l[len(l)-1]
if len(v) == 1 && strings.ContainsAny(v, "01234") {
return ""
}
if len(v) == 2 {
// country code
return "_country"
}
if v == "asia" || v == "north-america" || v == "europe" || v == "south-america" || v == "oceania" || v == "africa" {
return "_continent"
}
return v
}
func (stats *Stats) Add(e *querylog.Entry) error {
if e.Rcode > 0 {
// NXDOMAIN, count separately?
return nil
}
if e.Answers == 0 {
// No answers, count separately?
return nil
}
var vendor, poolCC string
if e.Origin == "pool.ntp.org" || strings.HasSuffix(e.Origin, "ntppool.org") {
vendor = vendorName(e.Name)
var ok bool
poolCC, ok = getPoolCC(e.LabelName)
if !ok {
log.Printf("Could not get valid poolCC label for %+v", e)
}
}
stats.Count++
qtypeString := dns.TypeToString[e.Qtype]
userCC := ""
for _, cc := range e.Targets {
if len(cc) == 2 {
userCC = cc
break
}
}
// []string{"zone", "vendor", "usercc", "poolcc", "qtype"},
queries.WithLabelValues(e.Origin, vendor, userCC, poolCC, qtypeString).Inc()
key := stats.Key(e)
if s, ok := stats.Map[key]; ok {
s.Count++
} else {
stats.Map[key] = &statsEntry{
// Time: time.Unix(e.Time/int64(time.Second), 0),
Time: e.Time,
Origin: e.Origin,
Name: e.Name,
Vendor: vendor,
Label: e.LabelName,
PoolCC: poolCC,
Qtype: qtypeString,
Count: 1,
}
}
return nil
}
func (stats *Stats) Summarize() {
// pretty.Println(stats)
var timeStamp int64
for k := range stats.Map {
timeStamp = stats.Map[k].Time
break
}
fmt.Printf("Stats %s count total: %d, summarized: %d\n", time.Unix(timeStamp, 0).String(), stats.Count, len(stats.Map))
}