forked from rverst/coredns-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
92 lines (78 loc) · 2.05 KB
/
plugin.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
package redis
import (
"context"
"strings"
"time"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
const name = "redis"
type Plugin struct {
Redis *Redis
Next plugin.Handler
}
func (p *Plugin) Name() string {
return name
}
func (p *Plugin) Ready() bool {
ok, err := p.Redis.Ping()
if err != nil {
log.Error(err)
}
return ok
}
func (p *Plugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{Req: r, W: w}
qName := state.Name()
qType := state.QType()
if qName == "" || qType == dns.TypeNone {
return plugin.NextOrFailure(qName, p.Next, ctx, w, r)
}
if !strings.HasSuffix(qName, p.Redis.Zone) {
log.Debugf("unsupported zone for query %s", qName)
return plugin.NextOrFailure(qName, p.Next, ctx, w, r)
}
conn := p.Redis.Pool.Get()
if conn == nil {
log.Fatal("could not get a Redis connection")
}
defer conn.Close()
recordType := dns.TypeToString[qType]
answers, extras, err := p.Redis.LoadZoneRecords(recordType, qName, conn)
if err != nil {
log.Error(err)
return p.Redis.ErrorResponse(state, qName, dns.RcodeServerFailure, nil)
}
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative, m.RecursionAvailable, m.Compress = true, false, true
m.Answer = append(m.Answer, answers...)
m.Extra = append(m.Extra, extras...)
state.SizeAndDo(m)
m = state.Scrub(m)
err = w.WriteMsg(m)
if err != nil {
log.Error(err)
return p.Redis.ErrorResponse(state, qName, dns.RcodeServerFailure, nil)
}
return dns.RcodeSuccess, nil
}
// Update statistics about Redis Pools periodically
func (p *Plugin) updateRedisPoolStats(period time.Duration) {
t := time.NewTicker(period)
for {
<-t.C
redisPoolStats.WithLabelValues(
p.Redis.hostName,
p.Redis.Zone, "ActiveCount",
).Set(float64(p.Redis.Pool.Stats().ActiveCount))
redisPoolStats.WithLabelValues(
p.Redis.hostName,
p.Redis.Zone,
"IdleCount",
).Set(float64(p.Redis.Pool.Stats().IdleCount))
log.Debug("Updated Redis Pool Stats")
}
}