/
handler_coredns.go
76 lines (69 loc) · 1.83 KB
/
handler_coredns.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
package dns
import (
"reflect"
"unsafe"
"beryju.io/gravity/pkg/roles/dns/utils"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
_ "github.com/coredns/coredns/core/plugin"
"github.com/coredns/coredns/coremain"
"github.com/miekg/dns"
_ "github.com/ori-edge/k8s_gateway"
"go.uber.org/zap"
)
const CoreDNSType = "coredns"
type CoreDNS struct {
c map[string]string
log *zap.Logger
instance *caddy.Instance
srv *dnsserver.Server
}
func NewCoreDNS(z *Zone, rawConfig map[string]string) *CoreDNS {
core := &CoreDNS{
c: rawConfig,
}
core.log = z.log.With(zap.String("handler", core.Identifier()))
dnsserver.Quiet = true
corefile := caddy.CaddyfileInput{
Contents: []byte(core.c["config"]),
Filepath: "in-memory",
ServerTypeName: "dns",
}
core.log.Info("starting coredns", zap.String("version", coremain.CoreVersion))
instance, err := caddy.Start(corefile)
if err != nil {
core.log.Warn("failed to start codedns", zap.Error(err))
return core
}
core.instance = instance
rawSrv := core.instance.Servers()
if len(rawSrv) < 1 {
core.log.Warn("No server configured")
return core
}
for _, srv := range rawSrv {
rs := reflect.ValueOf(&srv).Elem()
rf := rs.FieldByName("server")
rfs := reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem().Interface().(caddy.Server)
if dss, ok := rfs.(*dnsserver.Server); ok {
core.srv = dss
return core
}
}
core.log.Warn("no compatible server found")
return core
}
func (core *CoreDNS) Identifier() string {
return CoreDNSType
}
func (core *CoreDNS) Handle(w *utils.FakeDNSWriter, r *utils.DNSRequest) *dns.Msg {
if core.instance == nil {
return nil
}
core.srv.ServeDNS(r.Context(), w, r.Msg)
// fall to next handler when no record is found
if w.Msg().Rcode == dns.RcodeNameError {
return nil
}
return w.Msg()
}