-
Notifications
You must be signed in to change notification settings - Fork 10
/
dns.go
218 lines (183 loc) · 5.02 KB
/
dns.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
/*
Copyright 2018-2022 Mailgun Technologies Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gubernator
import (
"context"
"math/rand"
"net"
"os"
"time"
"github.com/mailgun/holster/v4/setter"
"github.com/miekg/dns"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// Adapted from TimothyYe/godns
// DNSResolver represents a dns resolver
type DNSResolver struct {
Servers []string
random *rand.Rand
}
// NewFromResolvConf initializes DnsResolver from resolv.conf like file.
func NewFromResolvConf(path string) (*DNSResolver, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return &DNSResolver{}, errors.New("no such file or directory: " + path)
}
config, err := dns.ClientConfigFromFile(path)
if err != nil {
return &DNSResolver{}, err
}
var servers []string
if len(config.Servers) == 0 {
return &DNSResolver{}, errors.New("no servers in config")
}
for _, ipAddress := range config.Servers {
servers = append(servers, net.JoinHostPort(ipAddress, "53"))
}
return &DNSResolver{servers, rand.New(rand.NewSource(time.Now().UnixNano()))}, nil
}
func (r *DNSResolver) lookupHost(host string, dnsType uint16, delay uint32) ([]net.IP, uint32, error) {
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
switch dnsType {
case dns.TypeA:
m1.Question[0] = dns.Question{Name: dns.Fqdn(host), Qtype: dns.TypeA, Qclass: dns.ClassINET}
case dns.TypeAAAA:
m1.Question[0] = dns.Question{Name: dns.Fqdn(host), Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}
}
in, err := dns.Exchange(m1, r.Servers[r.random.Intn(len(r.Servers))])
var result []net.IP
if err != nil {
return result, 0, err
}
if in.Rcode != dns.RcodeSuccess {
return result, 0, errors.New(dns.RcodeToString[in.Rcode])
}
if dnsType == dns.TypeA {
if len(in.Answer) > 0 {
for _, record := range in.Answer {
if t, ok := record.(*dns.A); ok {
result = append(result, t.A)
delay = min(delay, record.Header().Ttl)
}
}
} else {
return result, 0, errors.New("not useful")
}
}
if dnsType == dns.TypeAAAA {
if len(in.Answer) > 0 {
for _, record := range in.Answer {
if t, ok := record.(*dns.AAAA); ok {
result = append(result, t.AAAA)
delay = min(delay, record.Header().Ttl)
}
}
} else {
return result, 0, errors.New("not useful")
}
}
return result, delay, nil
}
type DNSPoolConfig struct {
// (Required) The FQDN that should resolve to gubernator instance ip addresses
FQDN string
// (Required) Filesystem path to "/etc/resolv.conf", override for testing
ResolvConf string
// (Required) Own GRPC address
OwnAddress string
// (Required) Called when the list of gubernators in the pool updates
OnUpdate UpdateFunc
Logger FieldLogger
}
type DNSPool struct {
log FieldLogger
conf DNSPoolConfig
ctx context.Context
cancel context.CancelFunc
}
func NewDNSPool(conf DNSPoolConfig) (*DNSPool, error) {
setter.SetDefault(&conf.Logger, logrus.WithField("category", "gubernator"))
if conf.OwnAddress == "" {
return nil, errors.New("Advertise.GRPCAddress is required")
}
ctx, cancel := context.WithCancel(context.Background())
pool := &DNSPool{
log: conf.Logger,
conf: conf,
ctx: ctx,
cancel: cancel,
}
go pool.task()
return pool, nil
}
func peer(ip string, self string, ipv6 bool) PeerInfo {
if ipv6 {
ip = "[" + ip + "]"
}
grpc := ip + ":1051"
return PeerInfo{
DataCenter: "",
HTTPAddress: ip + ":1050",
GRPCAddress: grpc,
IsOwner: grpc == self,
}
}
func min(a uint32, b uint32) uint32 {
if a < b {
return a
} else {
return b
}
}
func (p *DNSPool) task() {
for {
var delay uint32 = 300
resolver, err := NewFromResolvConf(p.conf.ResolvConf)
if err != nil {
p.log.Warn("No resolver: ", err)
} else {
ipv4, delay4, err4 := resolver.lookupHost(p.conf.FQDN, dns.TypeA, delay)
ipv6, delay6, err6 := resolver.lookupHost(p.conf.FQDN, dns.TypeAAAA, delay)
var update []PeerInfo
if err4 == nil {
delay = min(delay, delay4)
for _, ip := range ipv4 {
update = append(update, peer(ip.String(), p.conf.OwnAddress, false))
}
}
if err6 == nil {
delay = min(delay, delay6)
for _, ip := range ipv6 {
update = append(update, peer(ip.String(), p.conf.OwnAddress, false))
}
}
if len(update) > 0 {
p.conf.OnUpdate(update)
} else {
p.log.Error("Looking up peers: ", err4, err6)
}
}
p.log.Debug("DNS poll delay: ", delay)
select {
case <-p.ctx.Done():
return
case <-time.After(time.Duration(delay) * time.Second):
}
}
}
func (p *DNSPool) Close() {
p.cancel()
}