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
|
package errors
import (
"bytes"
"context"
"errors"
"fmt"
golog "log"
"math/rand"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/dnstest"
"github.com/coredns/coredns/plugin/test"
"github.com/miekg/dns"
)
func TestErrors(t *testing.T) {
buf := bytes.Buffer{}
golog.SetOutput(&buf)
em := errorHandler{eLogger: errorLogger}
testErr := errors.New("test error")
tests := []struct {
next plugin.Handler
expectedCode int
expectedLog string
expectedErr error
}{
{
next: genErrorHandler(dns.RcodeSuccess, nil),
expectedCode: dns.RcodeSuccess,
expectedLog: "",
expectedErr: nil,
},
{
next: genErrorHandler(dns.RcodeNotAuth, testErr),
expectedCode: dns.RcodeNotAuth,
expectedLog: fmt.Sprintf("%d %s: %v\n", dns.RcodeNotAuth, "example.org. A", testErr),
expectedErr: testErr,
},
}
ctx := context.TODO()
req := new(dns.Msg)
req.SetQuestion("example.org.", dns.TypeA)
for i, tc := range tests {
em.Next = tc.next
buf.Reset()
rec := dnstest.NewRecorder(&test.ResponseWriter{})
code, err := em.ServeDNS(ctx, rec, req)
if err != tc.expectedErr {
t.Errorf("Test %d: Expected error %v, but got %v",
i, tc.expectedErr, err)
}
if code != tc.expectedCode {
t.Errorf("Test %d: Expected status code %d, but got %d",
i, tc.expectedCode, code)
}
if log := buf.String(); !strings.Contains(log, tc.expectedLog) {
t.Errorf("Test %d: Expected log %q, but got %q",
i, tc.expectedLog, log)
}
}
}
func TestConsLogger(t *testing.T) {
buf := bytes.Buffer{}
golog.SetOutput(&buf)
consLogger(5, "^Error.*!$", 3*time.Second)
exp := "[ERROR] plugin/errors: 5 errors like '^Error.*!$' occurred in last 3s"
act := buf.String()
if !strings.Contains(act, exp) {
t.Errorf("Unexpected log message, expected to contain %q, actual %q", exp, act)
}
}
func TestLogPattern(t *testing.T) {
h := &errorHandler{
patterns: []*pattern{{
count: 4,
period: 2 * time.Second,
pattern: regexp.MustCompile("^Error.*!$"),
}},
cLogger: testConsLogger,
}
loggedData = loggedData[:0]
h.logPattern(0)
expLen := 1
if len(loggedData) != expLen {
t.Errorf("Unexpected number of logged messages, expected %d, actual %d",
expLen, len(loggedData))
}
expCnt := uint32(4)
if loggedData[0].cnt != expCnt {
t.Errorf("Unexpected 'count' in logged message, expected %d, actual %d",
expCnt, loggedData[0].cnt)
}
expPat := "^Error.*!$"
actPat := loggedData[0].pat
if actPat != expPat {
t.Errorf("Unexpected 'pattern' in logged message, expected %s, actual %s",
expPat, actPat)
}
expPer := "2s"
actPer := loggedData[0].dur.String()
if actPer != expPer {
t.Errorf("Unexpected 'period' in logged message, expected %s, actual %s",
expPer, actPer)
}
h.logPattern(0)
if len(loggedData) != expLen {
t.Errorf("Unexpected number of logged messages, expected %d, actual %d",
expLen, len(loggedData))
}
}
func TestInc(t *testing.T) {
h := &errorHandler{
stopFlag: 1,
patterns: []*pattern{{
period: 2 * time.Second,
pattern: regexp.MustCompile("^Error.*!$"),
}},
cLogger: testConsLogger,
}
ret := h.inc(0)
if ret {
t.Error("Unexpected return value, expected false, actual true")
}
h.stopFlag = 0
ret = h.inc(0)
if !ret {
t.Error("Unexpected return value, expected true, actual false")
}
expCnt := uint32(1)
actCnt := atomic.LoadUint32(&h.patterns[0].count)
if actCnt != expCnt {
t.Errorf("Unexpected 'count', expected %d, actual %d", expCnt, actCnt)
}
t1 := h.patterns[0].timer()
if t1 == nil {
t.Error("Unexpected 'timer', expected not nil")
}
ret = h.inc(0)
if !ret {
t.Error("Unexpected return value, expected true, actual false")
}
expCnt = uint32(2)
actCnt = atomic.LoadUint32(&h.patterns[0].count)
if actCnt != expCnt {
t.Errorf("Unexpected 'count', expected %d, actual %d", expCnt, actCnt)
}
t2 := h.patterns[0].timer()
if t2 != t1 {
t.Error("Unexpected 'timer', expected the same")
}
ret = t1.Stop()
if !ret {
t.Error("Timer was unexpectedly stopped before")
}
ret = t2.Stop()
if ret {
t.Error("Timer was unexpectedly not stopped before")
}
}
func TestStop(t *testing.T) {
h := &errorHandler{
patterns: []*pattern{{
period: 2 * time.Second,
pattern: regexp.MustCompile("^Error.*!$"),
}},
cLogger: testConsLogger,
}
loggedData = loggedData[:0]
h.inc(0)
h.inc(0)
h.inc(0)
expCnt := uint32(3)
actCnt := atomic.LoadUint32(&h.patterns[0].count)
if actCnt != expCnt {
t.Fatalf("Unexpected initial 'count', expected %d, actual %d", expCnt, actCnt)
}
h.stop()
expCnt = uint32(0)
actCnt = atomic.LoadUint32(&h.patterns[0].count)
if actCnt != expCnt {
t.Errorf("Unexpected 'count', expected %d, actual %d", expCnt, actCnt)
}
expStop := uint32(1)
actStop := h.stopFlag
if actStop != expStop {
t.Errorf("Unexpected 'stop', expected %d, actual %d", expStop, actStop)
}
t1 := h.patterns[0].timer()
if t1 == nil {
t.Error("Unexpected 'timer', expected not nil")
} else if t1.Stop() {
t.Error("Timer was unexpectedly not stopped before")
}
expLen := 1
if len(loggedData) != expLen {
t.Errorf("Unexpected number of logged messages, expected %d, actual %d",
expLen, len(loggedData))
}
expCnt = uint32(3)
actCnt = loggedData[0].cnt
if actCnt != expCnt {
t.Errorf("Unexpected 'count' in logged message, expected %d, actual %d",
expCnt, actCnt)
}
}
func TestServeDNSConcurrent(t *testing.T) {
eg := newErrorGenerator()
rep := &errorReport{}
h := &errorHandler{
patterns: []*pattern{
{
period: 3 * time.Nanosecond,
pattern: regexp.MustCompile("Failed"),
},
{
period: 2 * time.Nanosecond,
pattern: regexp.MustCompile("down$"),
},
},
cLogger: func(cnt uint32, pattern string, p time.Duration) {
rep.incLoggerCnt()
if pattern == "Failed" {
rep.incConsolidated(Err0, cnt)
} else if pattern == "down$" {
rep.incConsolidated(Err1, cnt)
}
},
eLogger: func(code int, n, t, e string) {
switch e {
case ErrStr0:
rep.incPassed(Err0)
case ErrStr1:
rep.incPassed(Err1)
case ErrStr2:
rep.incPassed(Err2)
case ErrStr3:
rep.incPassed(Err3)
}
},
Next: eg,
}
ctx := context.TODO()
r := new(dns.Msg)
w := &test.ResponseWriter{}
var wg sync.WaitGroup
runnersCnt := 9
runner := func() {
defer wg.Done()
for !eg.done() {
h.ServeDNS(ctx, w, r)
}
}
wg.Add(runnersCnt)
for ; runnersCnt > 0; runnersCnt-- {
go runner()
}
stopCalled := false
for !eg.done() {
if !stopCalled &&
atomic.LoadUint32(&rep.s[Err0]) > ErrCnt0/2 &&
atomic.LoadUint32(&rep.s[Err1]) > ErrCnt1/2 {
h.stop()
stopCalled = true
}
h.ServeDNS(ctx, w, r)
}
if !stopCalled {
h.stop()
}
wg.Wait()
time.Sleep(time.Millisecond)
if rep.loggerCnt() < 3 {
t.Errorf("Perhaps logger was never called by timer")
}
if rep.consolidated(Err0) == 0 {
t.Errorf("Err0 was never reported by consLogger")
}
if rep.consolidated(Err1) == 0 {
t.Errorf("Err1 was never reported by consLogger")
}
if rep.consolidated(Err0)+rep.passed(Err0) != ErrCnt0 {
t.Errorf("Unexpected Err0 count, expected %d, reported by consLogger %d and by ServeDNS %d",
ErrCnt0, rep.consolidated(Err0), rep.passed(Err0))
}
if rep.consolidated(Err1)+rep.passed(Err1) != ErrCnt1 {
t.Errorf("Unexpected Err1 count, expected %d, reported by consLogger %d and by ServeDNS %d",
ErrCnt1, rep.consolidated(Err1), rep.passed(Err1))
}
if rep.passed(Err2) != ErrCnt2 {
t.Errorf("Unexpected Err2 count, expected %d, reported by ServeDNS %d",
ErrCnt2, rep.passed(Err2))
}
if rep.passed(Err3) != ErrCnt3 {
t.Errorf("Unexpected Err3 count, expected %d, reported by ServeDNS %d",
ErrCnt3, rep.passed(Err3))
}
}
type logData struct {
cnt uint32
pat string
dur time.Duration
}
var loggedData []logData
func testConsLogger(cnt uint32, pattern string, p time.Duration) {
loggedData = append(loggedData, logData{cnt, pattern, p})
}
// error generator
const (
Err0 = iota
Err1
Err2
Err3
ErrStr0 = "Failed to connect"
ErrStr1 = "Upstream is down"
ErrStr2 = "Access denied"
ErrStr3 = "Yet another error"
ErrCnt0 = 120000
ErrCnt1 = 130000
ErrCnt2 = 150000
ErrCnt3 = 100000
)
type errorBunch struct {
cnt int32
err error
}
type errorGenerator struct {
errors [4]errorBunch
doneFlag uint32
}
func newErrorGenerator() *errorGenerator {
rand.Seed(time.Now().UnixNano())
return &errorGenerator{
errors: [4]errorBunch{
{ErrCnt0, fmt.Errorf(ErrStr0)},
{ErrCnt1, fmt.Errorf(ErrStr1)},
{ErrCnt2, fmt.Errorf(ErrStr2)},
{ErrCnt3, fmt.Errorf(ErrStr3)},
},
}
}
func (sh *errorGenerator) done() bool {
return atomic.LoadUint32(&sh.doneFlag) > 0
}
func (sh *errorGenerator) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
i := rand.Int()
for c := 0; c < 4; c++ {
errInd := (i + c) & 3
if atomic.AddInt32(&sh.errors[errInd].cnt, -1) >= 0 {
return 0, sh.errors[errInd].err
}
atomic.AddInt32(&sh.errors[errInd].cnt, 1)
}
atomic.StoreUint32(&sh.doneFlag, 1)
return 0, nil
}
func (sh *errorGenerator) Name() string { return "errorGenerator" }
// error report
type errorReport struct {
s [4]uint32
p [4]uint32
l uint32
}
func (er *errorReport) consolidated(i int) uint32 {
return atomic.LoadUint32(&er.s[i])
}
func (er *errorReport) incConsolidated(i int, cnt uint32) {
atomic.AddUint32(&er.s[i], cnt)
}
func (er *errorReport) passed(i int) uint32 {
return atomic.LoadUint32(&er.p[i])
}
func (er *errorReport) incPassed(i int) {
atomic.AddUint32(&er.p[i], 1)
}
func (er *errorReport) loggerCnt() uint32 {
return atomic.LoadUint32(&er.l)
}
func (er *errorReport) incLoggerCnt() {
atomic.AddUint32(&er.l, 1)
}
func genErrorHandler(rcode int, err error) plugin.Handler {
return plugin.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
return rcode, err
})
}
|