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