aboutsummaryrefslogtreecommitdiff
path: root/middleware/metrics/handler.go
blob: 1a0acbe14b053e8579deb56f0e4f24075df00ce0 (plain) (blame)
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
package metrics

import (
	"time"

	"github.com/miekg/coredns/middleware"

	"github.com/miekg/dns"
	"golang.org/x/net/context"
)

func (m Metrics) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := middleware.State{W: w, Req: r}

	qname := state.QName()
	zone := middleware.Zones(m.ZoneNames).Matches(qname)
	if zone == "" {
		zone = "."
	}

	// Record response to get status code and size of the reply.
	rw := middleware.NewResponseRecorder(w)
	status, err := m.Next.ServeDNS(ctx, rw, r)

	Report(state, zone, rw.Rcode(), rw.Size(), rw.Start())

	return status, err
}

// Report is a plain reporting function that the server can use for REFUSED and other
// queries that are turned down because they don't match any middleware.
func Report(state middleware.State, zone, rcode string, size int, start time.Time) {
	if requestCount == nil {
		// no metrics are enabled
		return
	}

	// Proto and Family
	net := state.Proto()
	fam := "1"
	if state.Family() == 2 {
		fam = "2"
	}

	requestCount.WithLabelValues(zone, net, fam).Inc()
	requestDuration.WithLabelValues(zone).Observe(float64(time.Since(start) / time.Second))
	requestSize.WithLabelValues(zone, net).Observe(float64(state.Size()))
	if state.Do() {
		requestDo.WithLabelValues(zone).Inc()
	}
	typ := state.QType()
	if _, known := monitorType[typ]; known {
		requestType.WithLabelValues(zone, dns.Type(typ).String()).Inc()
	} else {
		requestType.WithLabelValues(zone, other).Inc()
	}

	responseSize.WithLabelValues(zone, net).Observe(float64(size))
	responseRcode.WithLabelValues(zone, rcode).Inc()
}

var monitorType = map[uint16]bool{
	dns.TypeAAAA:   true,
	dns.TypeA:      true,
	dns.TypeCNAME:  true,
	dns.TypeDNSKEY: true,
	dns.TypeDS:     true,
	dns.TypeMX:     true,
	dns.TypeNSEC3:  true,
	dns.TypeNSEC:   true,
	dns.TypeNS:     true,
	dns.TypePTR:    true,
	dns.TypeRRSIG:  true,
	dns.TypeSOA:    true,
	dns.TypeSRV:    true,
	dns.TypeTXT:    true,
}

const other = "other"