-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdcache.go
488 lines (416 loc) · 9.9 KB
/
dcache.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package dcache
import (
"context"
"hash/fnv"
"math"
"net"
"time"
gonanoid "github.com/matoous/go-nanoid"
"github.com/oleiade/lane"
"github.com/coredns/coredns/plugin/pkg/cache"
"github.com/coredns/coredns/plugin/metrics"
"github.com/goccy/go-json"
"github.com/coredns/coredns/plugin/pkg/response"
"github.com/go-redis/redis/v8"
"github.com/coredns/coredns/request"
"github.com/coredns/coredns/plugin"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/miekg/dns"
)
const name = "dcache"
// Dcache is a plugin that distribute shard successCache.
type Dcache struct {
init bool
Addr string
Next plugin.Handler
log clog.P
id string
successCache *CacheRepository
errorCache *CacheRepository
subscribeCon *redis.Client
publishCon *redis.Client
queue *lane.Queue
}
func New(host string) *Dcache {
s, _ := NewCacheRepository(10000)
e, _ := NewCacheRepository(10000)
return &Dcache{
Addr: host,
successCache: s,
errorCache: e,
id: gonanoid.MustID(10),
queue: lane.NewQueue(),
}
}
// ServeDNS implements the plugin.Handler interface.
func (d *Dcache) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := &request.Request{Req: r, W: w}
unix := time.Now().UTC().Unix()
rw := NewResponsePrinter(w, d.log, d, *state)
s := metrics.WithServer(ctx)
cr, eHit := d.errorCache.Get(unix, state)
if eHit {
d.log.Debug("errorCache hit")
cacheHits.WithLabelValues(s).Inc()
cr.Response.SetReply(r)
_ = w.WriteMsg(cr.Response)
return dns.RcodeSuccess, nil
}
cr, sHit := d.successCache.Get(unix, state)
if sHit {
d.log.Debug("successCache hit")
cacheHits.WithLabelValues(s).Inc()
cr.Response.SetReply(r)
_ = w.WriteMsg(cr.Response)
return dns.RcodeSuccess, nil
}
cacheMisses.WithLabelValues(s).Inc()
return plugin.NextOrFailure(d.Name(), d.Next, ctx, rw, r)
}
func (d *Dcache) connect() error {
ctx := context.Background()
d.publishCon = redis.NewClient(&redis.Options{
Addr: d.Addr,
PoolSize: 1,
})
d.subscribeCon = redis.NewClient(&redis.Options{
Addr: d.Addr,
PoolSize: 1,
})
if cmd := d.subscribeCon.Ping(ctx); cmd.Err() != nil {
d.log.Error("failed connect redis", cmd.Err())
return cmd.Err()
}
if cmd := d.publishCon.Ping(ctx); cmd.Err() != nil {
d.log.Error("failed connect redis", cmd.Err())
return cmd.Err()
}
return nil
}
// Name implements the Handler interface.
func (d *Dcache) Name() string {
return name
}
func (d *Dcache) runSubscribe() {
d.log.Info("start distribute cache receive routine")
defer func() {
_ = d.subscribeCon.Close()
}()
ctx := context.Background()
sub := d.subscribeCon.Subscribe(ctx, d.Name())
for {
m, err := sub.ReceiveMessage(ctx)
if err != nil {
d.log.Errorf("failed receive %s", err)
s := metrics.WithServer(ctx)
redisErr.WithLabelValues(s).Inc()
time.Sleep(10 * time.Second)
continue
}
d.log.Debug("receive message", m.String())
ans := &AnswerCache{}
if err := json.Unmarshal([]byte(m.Payload), ans); err != nil {
d.log.Errorf("error unmarshal %s got %v", err, ans)
continue
}
if d.id == ans.By {
d.log.Debug("ignore own cache")
continue
}
if ans.Error {
if err = d.errorCache.Set(ans); err != nil {
d.log.Errorf("error cache set failed got %v err %s", m, err)
d.log.Error(err)
}
continue
}
if err = d.successCache.Set(ans); err != nil {
d.log.Errorf("success cache set failed got %v err %s", m, err)
d.log.Error(err)
continue
}
}
}
func (d *Dcache) minTTL(msg *dns.Msg) uint32 {
min := uint32(math.MaxUint32)
for _, ans := range msg.Answer {
if min > ans.Header().Ttl {
min = ans.Header().Ttl
}
}
return min
}
func (d *Dcache) publish(ans *AnswerCache) {
// truncated data not cache.
if ans.Response.Truncated {
return
}
ctx := context.Background()
b, err := ans.MarshalJSON()
if err != nil {
d.log.Errorf("failed marshal %s %v", err, ans)
return
}
cmd := d.publishCon.Publish(ctx, d.Name(), string(b))
if cmd.Err() != nil {
s := metrics.WithServer(ctx)
redisErr.WithLabelValues(s).Inc()
d.log.Errorf("error publish err %s", cmd.Err())
return
}
}
func (d *Dcache) runPublish() {
d.log.Info("start distribute cache publish routine")
defer func() {
_ = d.publishCon.Close()
}()
for {
item := d.queue.Dequeue()
if item == nil {
time.Sleep(1 * time.Second)
continue
}
ans := item.(*AnswerCache)
d.publish(ans)
}
}
type ResponseWriter struct {
dns.ResponseWriter
log clog.P
cache *Dcache
state request.Request
do bool
prefetch bool
remoteAddr net.Addr
}
// RemoteAddr implements the dns.ResponseWriter interface.
func (r *ResponseWriter) RemoteAddr() net.Addr {
if r.remoteAddr != nil {
return r.remoteAddr
}
return r.ResponseWriter.RemoteAddr()
}
// NewResponsePrinter returns ResponseWriter.
func NewResponsePrinter(w dns.ResponseWriter, log clog.P, d *Dcache, state request.Request) *ResponseWriter {
return &ResponseWriter{
ResponseWriter: w,
log: log,
cache: d,
state: state,
}
}
// WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard output.
func (r *ResponseWriter) WriteMsg(res *dns.Msg) error {
do := false
now := time.Now().UTC()
mt, opt := response.Typify(res, now)
if opt != nil {
do = opt.Do()
}
res.Answer = filterRRSlice(res.Answer, do)
res.Ns = filterRRSlice(res.Ns, do)
res.Extra = filterRRSlice(res.Extra, do)
ans := &AnswerCache{
Name: r.state.Name(),
Type: dns.Type(res.Question[0].Qtype),
Do: do,
Response: res,
TimeToDie: now.Unix() + int64(r.cache.minTTL(res)),
By: r.cache.id,
}
switch mt {
case
response.NoError,
response.Delegation:
r.cache.queue.Enqueue(ans)
case
response.NameError,
response.NoData,
response.ServerError:
ans.Error = true
r.cache.queue.Enqueue(ans)
case response.OtherError:
// do not cache
default:
r.log.Warningf("unknown type %#v", mt)
}
return r.ResponseWriter.WriteMsg(res)
}
func NewCacheRepository(size int) (*CacheRepository, error) {
return &CacheRepository{
items: cache.New(size),
}, nil
}
type CacheRepository struct {
items *cache.Cache
}
type AnswerCache struct {
Name string `json:"name"`
Response *dns.Msg `json:"response"`
Type dns.Type `json:"type"`
Do bool `json:"do"`
TimeToDie int64 `json:"time_to_die"`
By string `json:"by"`
Error bool
}
func (a *AnswerCache) MarshalJSON() ([]byte, error) {
if a == nil {
return nil, nil
}
b, err := a.Response.Pack()
if err != nil {
return nil, err
}
return json.Marshal(&struct {
Response []byte
Type dns.Type
Do bool
TimeToDie int64
By string
Error bool
Name string
}{
Response: b,
Type: a.Type,
Do: a.Do,
TimeToDie: a.TimeToDie,
By: a.By,
Error: a.Error,
Name: a.Name,
})
}
func (a *AnswerCache) UnmarshalJSON(data []byte) error {
if a == nil {
return nil
}
ans := &struct {
Type dns.Type
Do bool
TimeToDie int64
Response []byte
By string
Error bool
Name string
}{
Type: a.Type,
Do: a.Do,
TimeToDie: a.TimeToDie,
By: a.By,
Error: a.Error,
Name: a.Name,
}
if err := json.Unmarshal(data, &ans); err != nil {
return err
}
a.Type = ans.Type
a.Do = ans.Do
a.TimeToDie = ans.TimeToDie
a.Response = &dns.Msg{}
a.By = ans.By
a.Name = ans.Name
a.Error = ans.Error
return a.Response.Unpack(ans.Response)
}
// by https://github.com/coredns/coredns/blob/002b748ccd6b7cc2e3a65f1bd71509f80b95d342/plugin/cache/cache.go#L68-L87
func (*CacheRepository) key(qname string, m *dns.Msg, t uint16) (bool, uint64) {
// We don't store truncated responses.
if m.Truncated {
return false, 0
}
// Nor errors or Meta or Update.
if t == uint16(response.OtherError) || t == uint16(response.Meta) || t == uint16(response.Update) {
return false, 0
}
return true, hash(qname, t)
}
func hash(qname string, qtype uint16) uint64 {
h := fnv.New64()
_, err := h.Write([]byte{byte(qtype >> 8)})
if err != nil {
return 0
}
_, err = h.Write([]byte{byte(qtype)})
if err != nil {
return 0
}
_, err = h.Write([]byte(qname))
if err != nil {
return 0
}
return h.Sum64()
}
func (c *CacheRepository) Get(now int64, r *request.Request) (*AnswerCache, bool) {
ok, key := c.key(r.QName(), r.Req, r.QType())
if !ok {
return nil, false
}
v, ok := c.items.Get(key)
if !ok {
return nil, false
}
cn, ok := v.(*AnswerCache)
if !ok {
s := metrics.WithServer(context.Background())
corruptedCache.WithLabelValues(s).Inc()
return nil, false
}
expire := now-cn.TimeToDie > 0
if expire {
c.items.Remove(key)
return nil, false
}
return cn, true
}
func (c *CacheRepository) Set(msg *AnswerCache) error {
qtype := msg.Type
name := msg.Name
newExtra := make([]dns.RR, len(msg.Response.Extra))
j := 0
for _, e := range msg.Response.Extra {
if e.Header().Rrtype == dns.TypeOPT {
continue
}
newExtra[j] = e
j++
}
msg.Response.Extra = newExtra[:j]
ok, key := c.key(name, msg.Response, uint16(qtype))
if !ok {
return nil
}
_ = c.items.Add(key, msg)
return nil
}
//https://github.com/coredns/coredns/blob/002b748ccd6b7cc2e3a65f1bd71509f80b95d342/plugin/cache/dnssec.go#L24-L46
func filterRRSlice(rrs []dns.RR, do bool) []dns.RR {
j := 0
rs := make([]dns.RR, len(rrs), len(rrs))
for _, r := range rrs {
if !do && isDNSSEC(r) {
continue
}
if r.Header().Rrtype == dns.TypeOPT {
continue
}
rs[j] = r
j++
}
return rs[:j]
}
// client explicitly asked for it.
//https://github.com/coredns/coredns/blob/002b748ccd6b7cc2e3a65f1bd71509f80b95d342/plugin/cache/dnssec.go#L5-L22
func isDNSSEC(r dns.RR) bool {
switch r.Header().Rrtype {
case dns.TypeNSEC:
return true
case dns.TypeNSEC3:
return true
case dns.TypeDS:
return true
case dns.TypeRRSIG:
return true
case dns.TypeSIG:
return true
}
return false
}