blob: 4af67422c6b9b00e27c7f7278384e31014087263 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001/*
2 *
3 * Copyright 2018 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19// Package dns implements a dns resolver to be installed as the default resolver
20// in grpc.
21package dns
22
23import (
24 "encoding/json"
25 "errors"
26 "fmt"
27 "net"
28 "os"
29 "strconv"
30 "strings"
31 "sync"
32 "time"
33
34 "golang.org/x/net/context"
35 "google.golang.org/grpc/grpclog"
36 "google.golang.org/grpc/internal/backoff"
37 "google.golang.org/grpc/internal/grpcrand"
38 "google.golang.org/grpc/resolver"
39)
40
41func init() {
42 resolver.Register(NewBuilder())
43}
44
45const (
46 defaultPort = "443"
47 defaultFreq = time.Minute * 30
48 golang = "GO"
49 // In DNS, service config is encoded in a TXT record via the mechanism
50 // described in RFC-1464 using the attribute name grpc_config.
51 txtAttribute = "grpc_config="
52)
53
54var (
55 errMissingAddr = errors.New("dns resolver: missing address")
56
57 // Addresses ending with a colon that is supposed to be the separator
58 // between host and port is not allowed. E.g. "::" is a valid address as
59 // it is an IPv6 address (host only) and "[::]:" is invalid as it ends with
60 // a colon as the host and port separator
61 errEndsWithColon = errors.New("dns resolver: missing port after port-separator colon")
62)
63
64// NewBuilder creates a dnsBuilder which is used to factory DNS resolvers.
65func NewBuilder() resolver.Builder {
66 return &dnsBuilder{minFreq: defaultFreq}
67}
68
69type dnsBuilder struct {
70 // minimum frequency of polling the DNS server.
71 minFreq time.Duration
72}
73
74// Build creates and starts a DNS resolver that watches the name resolution of the target.
75func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) {
76 host, port, err := parseTarget(target.Endpoint, defaultPort)
77 if err != nil {
78 return nil, err
79 }
80
81 // IP address.
82 if net.ParseIP(host) != nil {
83 host, _ = formatIP(host)
84 addr := []resolver.Address{{Addr: host + ":" + port}}
85 i := &ipResolver{
86 cc: cc,
87 ip: addr,
88 rn: make(chan struct{}, 1),
89 q: make(chan struct{}),
90 }
91 cc.NewAddress(addr)
92 go i.watcher()
93 return i, nil
94 }
95
96 // DNS address (non-IP).
97 ctx, cancel := context.WithCancel(context.Background())
98 d := &dnsResolver{
99 freq: b.minFreq,
100 backoff: backoff.Exponential{MaxDelay: b.minFreq},
101 host: host,
102 port: port,
103 ctx: ctx,
104 cancel: cancel,
105 cc: cc,
106 t: time.NewTimer(0),
107 rn: make(chan struct{}, 1),
108 disableServiceConfig: opts.DisableServiceConfig,
109 }
110
111 if target.Authority == "" {
112 d.resolver = defaultResolver
113 } else {
114 d.resolver, err = customAuthorityResolver(target.Authority)
115 if err != nil {
116 return nil, err
117 }
118 }
119
120 d.wg.Add(1)
121 go d.watcher()
122 return d, nil
123}
124
125// Scheme returns the naming scheme of this resolver builder, which is "dns".
126func (b *dnsBuilder) Scheme() string {
127 return "dns"
128}
129
130type netResolver interface {
131 LookupHost(ctx context.Context, host string) (addrs []string, err error)
132 LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*net.SRV, err error)
133 LookupTXT(ctx context.Context, name string) (txts []string, err error)
134}
135
136// ipResolver watches for the name resolution update for an IP address.
137type ipResolver struct {
138 cc resolver.ClientConn
139 ip []resolver.Address
140 // rn channel is used by ResolveNow() to force an immediate resolution of the target.
141 rn chan struct{}
142 q chan struct{}
143}
144
145// ResolveNow resend the address it stores, no resolution is needed.
146func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) {
147 select {
148 case i.rn <- struct{}{}:
149 default:
150 }
151}
152
153// Close closes the ipResolver.
154func (i *ipResolver) Close() {
155 close(i.q)
156}
157
158func (i *ipResolver) watcher() {
159 for {
160 select {
161 case <-i.rn:
162 i.cc.NewAddress(i.ip)
163 case <-i.q:
164 return
165 }
166 }
167}
168
169// dnsResolver watches for the name resolution update for a non-IP target.
170type dnsResolver struct {
171 freq time.Duration
172 backoff backoff.Exponential
173 retryCount int
174 host string
175 port string
176 resolver netResolver
177 ctx context.Context
178 cancel context.CancelFunc
179 cc resolver.ClientConn
180 // rn channel is used by ResolveNow() to force an immediate resolution of the target.
181 rn chan struct{}
182 t *time.Timer
183 // wg is used to enforce Close() to return after the watcher() goroutine has finished.
184 // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we
185 // replace the real lookup functions with mocked ones to facilitate testing.
186 // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes
187 // will warns lookup (READ the lookup function pointers) inside watcher() goroutine
188 // has data race with replaceNetFunc (WRITE the lookup function pointers).
189 wg sync.WaitGroup
190 disableServiceConfig bool
191}
192
193// ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
194func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) {
195 select {
196 case d.rn <- struct{}{}:
197 default:
198 }
199}
200
201// Close closes the dnsResolver.
202func (d *dnsResolver) Close() {
203 d.cancel()
204 d.wg.Wait()
205 d.t.Stop()
206}
207
208func (d *dnsResolver) watcher() {
209 defer d.wg.Done()
210 for {
211 select {
212 case <-d.ctx.Done():
213 return
214 case <-d.t.C:
215 case <-d.rn:
216 }
217 result, sc := d.lookup()
218 // Next lookup should happen within an interval defined by d.freq. It may be
219 // more often due to exponential retry on empty address list.
220 if len(result) == 0 {
221 d.retryCount++
222 d.t.Reset(d.backoff.Backoff(d.retryCount))
223 } else {
224 d.retryCount = 0
225 d.t.Reset(d.freq)
226 }
227 d.cc.NewServiceConfig(sc)
228 d.cc.NewAddress(result)
229 }
230}
231
232func (d *dnsResolver) lookupSRV() []resolver.Address {
233 var newAddrs []resolver.Address
234 _, srvs, err := d.resolver.LookupSRV(d.ctx, "grpclb", "tcp", d.host)
235 if err != nil {
236 grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err)
237 return nil
238 }
239 for _, s := range srvs {
240 lbAddrs, err := d.resolver.LookupHost(d.ctx, s.Target)
241 if err != nil {
242 grpclog.Infof("grpc: failed load balancer address dns lookup due to %v.\n", err)
243 continue
244 }
245 for _, a := range lbAddrs {
246 a, ok := formatIP(a)
247 if !ok {
248 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
249 continue
250 }
251 addr := a + ":" + strconv.Itoa(int(s.Port))
252 newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target})
253 }
254 }
255 return newAddrs
256}
257
258func (d *dnsResolver) lookupTXT() string {
259 ss, err := d.resolver.LookupTXT(d.ctx, d.host)
260 if err != nil {
261 grpclog.Infof("grpc: failed dns TXT record lookup due to %v.\n", err)
262 return ""
263 }
264 var res string
265 for _, s := range ss {
266 res += s
267 }
268
269 // TXT record must have "grpc_config=" attribute in order to be used as service config.
270 if !strings.HasPrefix(res, txtAttribute) {
271 grpclog.Warningf("grpc: TXT record %v missing %v attribute", res, txtAttribute)
272 return ""
273 }
274 return strings.TrimPrefix(res, txtAttribute)
275}
276
277func (d *dnsResolver) lookupHost() []resolver.Address {
278 var newAddrs []resolver.Address
279 addrs, err := d.resolver.LookupHost(d.ctx, d.host)
280 if err != nil {
281 grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err)
282 return nil
283 }
284 for _, a := range addrs {
285 a, ok := formatIP(a)
286 if !ok {
287 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
288 continue
289 }
290 addr := a + ":" + d.port
291 newAddrs = append(newAddrs, resolver.Address{Addr: addr})
292 }
293 return newAddrs
294}
295
296func (d *dnsResolver) lookup() ([]resolver.Address, string) {
297 newAddrs := d.lookupSRV()
298 // Support fallback to non-balancer address.
299 newAddrs = append(newAddrs, d.lookupHost()...)
300 if d.disableServiceConfig {
301 return newAddrs, ""
302 }
303 sc := d.lookupTXT()
304 return newAddrs, canaryingSC(sc)
305}
306
307// formatIP returns ok = false if addr is not a valid textual representation of an IP address.
308// If addr is an IPv4 address, return the addr and ok = true.
309// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true.
310func formatIP(addr string) (addrIP string, ok bool) {
311 ip := net.ParseIP(addr)
312 if ip == nil {
313 return "", false
314 }
315 if ip.To4() != nil {
316 return addr, true
317 }
318 return "[" + addr + "]", true
319}
320
321// parseTarget takes the user input target string and default port, returns formatted host and port info.
322// If target doesn't specify a port, set the port to be the defaultPort.
323// If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets
324// are strippd when setting the host.
325// examples:
326// target: "www.google.com" defaultPort: "443" returns host: "www.google.com", port: "443"
327// target: "ipv4-host:80" defaultPort: "443" returns host: "ipv4-host", port: "80"
328// target: "[ipv6-host]" defaultPort: "443" returns host: "ipv6-host", port: "443"
329// target: ":80" defaultPort: "443" returns host: "localhost", port: "80"
330func parseTarget(target, defaultPort string) (host, port string, err error) {
331 if target == "" {
332 return "", "", errMissingAddr
333 }
334 if ip := net.ParseIP(target); ip != nil {
335 // target is an IPv4 or IPv6(without brackets) address
336 return target, defaultPort, nil
337 }
338 if host, port, err = net.SplitHostPort(target); err == nil {
339 if port == "" {
340 // If the port field is empty (target ends with colon), e.g. "[::1]:", this is an error.
341 return "", "", errEndsWithColon
342 }
343 // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port
344 if host == "" {
345 // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.
346 host = "localhost"
347 }
348 return host, port, nil
349 }
350 if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {
351 // target doesn't have port
352 return host, port, nil
353 }
354 return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)
355}
356
357type rawChoice struct {
358 ClientLanguage *[]string `json:"clientLanguage,omitempty"`
359 Percentage *int `json:"percentage,omitempty"`
360 ClientHostName *[]string `json:"clientHostName,omitempty"`
361 ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"`
362}
363
364func containsString(a *[]string, b string) bool {
365 if a == nil {
366 return true
367 }
368 for _, c := range *a {
369 if c == b {
370 return true
371 }
372 }
373 return false
374}
375
376func chosenByPercentage(a *int) bool {
377 if a == nil {
378 return true
379 }
380 return grpcrand.Intn(100)+1 <= *a
381}
382
383func canaryingSC(js string) string {
384 if js == "" {
385 return ""
386 }
387 var rcs []rawChoice
388 err := json.Unmarshal([]byte(js), &rcs)
389 if err != nil {
390 grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err)
391 return ""
392 }
393 cliHostname, err := os.Hostname()
394 if err != nil {
395 grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err)
396 return ""
397 }
398 var sc string
399 for _, c := range rcs {
400 if !containsString(c.ClientLanguage, golang) ||
401 !chosenByPercentage(c.Percentage) ||
402 !containsString(c.ClientHostName, cliHostname) ||
403 c.ServiceConfig == nil {
404 continue
405 }
406 sc = string(*c.ServiceConfig)
407 break
408 }
409 return sc
410}