-
Notifications
You must be signed in to change notification settings - Fork 712
/
resolver.go
234 lines (211 loc) · 5.02 KB
/
resolver.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
package appclient
import (
"net"
"net/url"
"strconv"
"strings"
"time"
"github.com/miekg/dns"
log "github.com/sirupsen/logrus"
"github.com/weaveworks/scope/common/xfer"
)
const (
dnsPollInterval = 5 * time.Minute
)
// fastStartTicker is a ticker that 'ramps up' from 1 sec to duration.
func fastStartTicker(duration time.Duration) <-chan time.Time {
c := make(chan time.Time, 1)
go func() {
d := 1 * time.Second
for {
time.Sleep(d)
d = d * 2
if d > duration {
d = duration
}
select {
case c <- time.Now():
default:
}
}
}()
return c
}
// Resolver is a thing that can be stopped...
type Resolver interface {
Stop()
}
type staticResolver struct {
ResolverConfig
failedResolutions map[string]struct{}
quit chan struct{}
}
// LookupIP type is used for looking up IPs.
type LookupIP func(host string) (ips []net.IP, err error)
// Target is a parsed representation of the app location.
type Target struct {
original string // the original url string
url *url.URL // the parsed url
hostname string // the hostname (without port) from the url
port int // the port, or a sensible default
}
func (t Target) String() string {
return net.JoinHostPort(t.hostname, strconv.Itoa(t.port))
}
// ResolverConfig is the config for a resolver.
type ResolverConfig struct {
Targets []Target
Set func(string, []url.URL)
// Optional
Lookup LookupIP
Ticker func(time.Duration) <-chan time.Time
}
// NewResolver periodically resolves the targets, and calls the set
// function with all the resolved IPs. It explictiy supports targets which
// resolve to multiple IPs. It uses the supplied DNS server name.
func NewResolver(config ResolverConfig) (Resolver, error) {
if config.Lookup == nil {
config.Lookup = net.LookupIP
}
if config.Ticker == nil {
config.Ticker = fastStartTicker
}
r := staticResolver{
ResolverConfig: config,
failedResolutions: map[string]struct{}{},
quit: make(chan struct{}),
}
go r.loop()
return r, nil
}
// LookupUsing produces a LookupIP function for the given DNS server.
func LookupUsing(dnsServer string) func(host string) (ips []net.IP, err error) {
client := dns.Client{
Net: "tcp",
}
return func(host string) (ips []net.IP, err error) {
m := &dns.Msg{}
m.SetQuestion(dns.Fqdn(host), dns.TypeA)
in, _, err := client.Exchange(m, dnsServer)
if err != nil {
return nil, err
}
result := []net.IP{}
for _, answer := range in.Answer {
if a, ok := answer.(*dns.A); ok {
result = append(result, a.A)
}
}
return result, nil
}
}
func (r staticResolver) loop() {
r.resolve()
t := r.Ticker(dnsPollInterval)
for {
select {
case <-t:
r.resolve()
case <-r.quit:
return
}
}
}
func (r staticResolver) Stop() {
close(r.quit)
}
// ParseTargets deals with missing information in the targets string, defaulting
// the scheme, port etc.
func ParseTargets(urls []string) ([]Target, error) {
var targets []Target
for _, u := range urls {
// naked hostnames (such as "localhost") are interpreted as relative URLs
// so we add a scheme if u doesn't have one.
prefixAdded := false
if !strings.Contains(u, "://") {
prefixAdded = true
if strings.HasSuffix(u, ":443") {
u = "https://" + u
} else {
u = "http://" + u
}
}
parsed, err := url.Parse(u)
if err != nil {
return nil, err
}
var hostname string
var port int
if strings.Contains(parsed.Host, ":") {
var portStr string
hostname, portStr, err = net.SplitHostPort(parsed.Host)
if err != nil {
return nil, err
}
port, err = strconv.Atoi(portStr)
if err != nil {
return nil, err
}
} else {
if prefixAdded {
port = xfer.AppPort
} else if strings.HasPrefix(u, "https://") {
port = 443
} else {
port = 80
}
hostname = parsed.Host
}
targets = append(targets, Target{
original: u,
url: parsed,
hostname: hostname,
port: port,
})
}
return targets, nil
}
func (r staticResolver) resolve() {
for _, t := range r.Targets {
ips := r.resolveOne(t)
urls := makeURLs(t, ips)
r.Set(t.hostname, urls)
}
}
func makeURLs(t Target, ips []string) []url.URL {
result := []url.URL{}
for _, ip := range ips {
u := *t.url
u.Host = net.JoinHostPort(ip, strconv.Itoa(t.port))
result = append(result, u)
}
return result
}
func (r staticResolver) resolveOne(t Target) []string {
var addrs []net.IP
if addr := net.ParseIP(t.hostname); addr != nil {
addrs = []net.IP{addr}
} else {
var err error
addrs, err = r.Lookup(t.hostname)
if err != nil {
if _, ok := r.failedResolutions[t.hostname]; !ok {
log.Warnf("Cannot resolve '%s': %v", t.hostname, err)
// Only log the error once
r.failedResolutions[t.hostname] = struct{}{}
}
return []string{}
}
// Allow logging errors in future resolutions
delete(r.failedResolutions, t.hostname)
}
endpoints := make([]string, 0, len(addrs))
for _, addr := range addrs {
// For now, ignore IPv6
if addr.To4() == nil {
continue
}
endpoints = append(endpoints, addr.String())
}
return endpoints
}