forked from coredns/coredns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
erratic.go
95 lines (77 loc) · 1.84 KB
/
erratic.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
// Package erratic implements a plugin that returns erratic answers (delayed, dropped).
package erratic
import (
"sync/atomic"
"time"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
"golang.org/x/net/context"
)
// Erratic is a plugin that returns erratic repsonses to each client.
type Erratic struct {
drop uint64
delay uint64
duration time.Duration
truncate uint64
q uint64 // counter of queries
}
// ServeDNS implements the plugin.Handler interface.
func (e *Erratic) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
drop := false
delay := false
trunc := false
queryNr := atomic.LoadUint64(&e.q)
atomic.AddUint64(&e.q, 1)
if e.drop > 0 && queryNr%e.drop == 0 {
drop = true
}
if e.delay > 0 && queryNr%e.delay == 0 {
delay = true
}
if e.truncate > 0 && queryNr&e.truncate == 0 {
trunc = true
}
m := new(dns.Msg)
m.SetReply(r)
m.Compress = true
m.Authoritative = true
if trunc {
m.Truncated = true
}
// small dance to copy rrA or rrAAAA into a non-pointer var that allows us to overwrite the ownername
// in a non-racy way.
switch state.QType() {
case dns.TypeA:
rr := *(rrA.(*dns.A))
rr.Header().Name = state.QName()
m.Answer = append(m.Answer, &rr)
case dns.TypeAAAA:
rr := *(rrAAAA.(*dns.AAAA))
rr.Header().Name = state.QName()
m.Answer = append(m.Answer, &rr)
default:
if !drop {
if delay {
time.Sleep(e.duration)
}
// coredns will return error.
return dns.RcodeServerFailure, nil
}
}
if drop {
return 0, nil
}
if delay {
time.Sleep(e.duration)
}
state.SizeAndDo(m)
w.WriteMsg(m)
return 0, nil
}
// Name implements the Handler interface.
func (e *Erratic) Name() string { return "erratic" }
var (
rrA, _ = dns.NewRR(". IN 0 A 192.0.2.53")
rrAAAA, _ = dns.NewRR(". IN 0 AAAA 2001:DB8::53")
)