blob: c368db62ea11f366cd15293dd0adb0fcb3af2026 [file] [log] [blame]
kesavand2cde6582020-06-22 04:56:23 -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/envconfig"
37 "google.golang.org/grpc/internal/grpcrand"
38 "google.golang.org/grpc/resolver"
39 "google.golang.org/grpc/serviceconfig"
40)
41
42// EnableSRVLookups controls whether the DNS resolver attempts to fetch gRPCLB
43// addresses from SRV records. Must not be changed after init time.
44var EnableSRVLookups = false
45
46func init() {
47 resolver.Register(NewBuilder())
48}
49
50const (
51 defaultPort = "443"
52 defaultDNSSvrPort = "53"
53 golang = "GO"
54 // txtPrefix is the prefix string to be prepended to the host name for txt record lookup.
55 txtPrefix = "_grpc_config."
56 // In DNS, service config is encoded in a TXT record via the mechanism
57 // described in RFC-1464 using the attribute name grpc_config.
58 txtAttribute = "grpc_config="
59)
60
61var (
62 errMissingAddr = errors.New("dns resolver: missing address")
63
64 // Addresses ending with a colon that is supposed to be the separator
65 // between host and port is not allowed. E.g. "::" is a valid address as
66 // it is an IPv6 address (host only) and "[::]:" is invalid as it ends with
67 // a colon as the host and port separator
68 errEndsWithColon = errors.New("dns resolver: missing port after port-separator colon")
69)
70
71var (
72 defaultResolver netResolver = net.DefaultResolver
73 // To prevent excessive re-resolution, we enforce a rate limit on DNS
74 // resolution requests.
75 minDNSResRate = 30 * time.Second
76)
77
78var customAuthorityDialler = func(authority string) func(ctx context.Context, network, address string) (net.Conn, error) {
79 return func(ctx context.Context, network, address string) (net.Conn, error) {
80 var dialer net.Dialer
81 return dialer.DialContext(ctx, network, authority)
82 }
83}
84
85var customAuthorityResolver = func(authority string) (netResolver, error) {
86 host, port, err := parseTarget(authority, defaultDNSSvrPort)
87 if err != nil {
88 return nil, err
89 }
90
91 authorityWithPort := net.JoinHostPort(host, port)
92
93 return &net.Resolver{
94 PreferGo: true,
95 Dial: customAuthorityDialler(authorityWithPort),
96 }, nil
97}
98
99// NewBuilder creates a dnsBuilder which is used to factory DNS resolvers.
100func NewBuilder() resolver.Builder {
101 return &dnsBuilder{}
102}
103
104type dnsBuilder struct{}
105
106// Build creates and starts a DNS resolver that watches the name resolution of the target.
107func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
108 host, port, err := parseTarget(target.Endpoint, defaultPort)
109 if err != nil {
110 return nil, err
111 }
112
113 // IP address.
114 if ipAddr, ok := formatIP(host); ok {
115 addr := []resolver.Address{{Addr: ipAddr + ":" + port}}
116 cc.UpdateState(resolver.State{Addresses: addr})
117 return deadResolver{}, nil
118 }
119
120 // DNS address (non-IP).
121 ctx, cancel := context.WithCancel(context.Background())
122 d := &dnsResolver{
123 host: host,
124 port: port,
125 ctx: ctx,
126 cancel: cancel,
127 cc: cc,
128 rn: make(chan struct{}, 1),
129 disableServiceConfig: opts.DisableServiceConfig,
130 }
131
132 if target.Authority == "" {
133 d.resolver = defaultResolver
134 } else {
135 d.resolver, err = customAuthorityResolver(target.Authority)
136 if err != nil {
137 return nil, err
138 }
139 }
140
141 d.wg.Add(1)
142 go d.watcher()
143 d.ResolveNow(resolver.ResolveNowOptions{})
144 return d, nil
145}
146
147// Scheme returns the naming scheme of this resolver builder, which is "dns".
148func (b *dnsBuilder) Scheme() string {
149 return "dns"
150}
151
152type netResolver interface {
153 LookupHost(ctx context.Context, host string) (addrs []string, err error)
154 LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*net.SRV, err error)
155 LookupTXT(ctx context.Context, name string) (txts []string, err error)
156}
157
158// deadResolver is a resolver that does nothing.
159type deadResolver struct{}
160
161func (deadResolver) ResolveNow(resolver.ResolveNowOptions) {}
162
163func (deadResolver) Close() {}
164
165// dnsResolver watches for the name resolution update for a non-IP target.
166type dnsResolver struct {
167 host string
168 port string
169 resolver netResolver
170 ctx context.Context
171 cancel context.CancelFunc
172 cc resolver.ClientConn
173 // rn channel is used by ResolveNow() to force an immediate resolution of the target.
174 rn chan struct{}
175 // wg is used to enforce Close() to return after the watcher() goroutine has finished.
176 // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we
177 // replace the real lookup functions with mocked ones to facilitate testing.
178 // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes
179 // will warns lookup (READ the lookup function pointers) inside watcher() goroutine
180 // has data race with replaceNetFunc (WRITE the lookup function pointers).
181 wg sync.WaitGroup
182 disableServiceConfig bool
183}
184
185// ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
186func (d *dnsResolver) ResolveNow(resolver.ResolveNowOptions) {
187 select {
188 case d.rn <- struct{}{}:
189 default:
190 }
191}
192
193// Close closes the dnsResolver.
194func (d *dnsResolver) Close() {
195 d.cancel()
196 d.wg.Wait()
197}
198
199func (d *dnsResolver) watcher() {
200 defer d.wg.Done()
201 for {
202 select {
203 case <-d.ctx.Done():
204 return
205 case <-d.rn:
206 }
207
208 state, err := d.lookup()
209 if err != nil {
210 d.cc.ReportError(err)
211 } else {
212 d.cc.UpdateState(*state)
213 }
214
215 // Sleep to prevent excessive re-resolutions. Incoming resolution requests
216 // will be queued in d.rn.
217 t := time.NewTimer(minDNSResRate)
218 select {
219 case <-t.C:
220 case <-d.ctx.Done():
221 t.Stop()
222 return
223 }
224 }
225}
226
227func (d *dnsResolver) lookupSRV() ([]resolver.Address, error) {
228 if !EnableSRVLookups {
229 return nil, nil
230 }
231 var newAddrs []resolver.Address
232 _, srvs, err := d.resolver.LookupSRV(d.ctx, "grpclb", "tcp", d.host)
233 if err != nil {
234 err = handleDNSError(err, "SRV") // may become nil
235 return nil, err
236 }
237 for _, s := range srvs {
238 lbAddrs, err := d.resolver.LookupHost(d.ctx, s.Target)
239 if err != nil {
240 err = handleDNSError(err, "A") // may become nil
241 if err == nil {
242 // If there are other SRV records, look them up and ignore this
243 // one that does not exist.
244 continue
245 }
246 return nil, err
247 }
248 for _, a := range lbAddrs {
249 ip, ok := formatIP(a)
250 if !ok {
251 return nil, fmt.Errorf("dns: error parsing A record IP address %v", a)
252 }
253 addr := ip + ":" + strconv.Itoa(int(s.Port))
254 newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target})
255 }
256 }
257 return newAddrs, nil
258}
259
260var filterError = func(err error) error {
261 if dnsErr, ok := err.(*net.DNSError); ok && !dnsErr.IsTimeout && !dnsErr.IsTemporary {
262 // Timeouts and temporary errors should be communicated to gRPC to
263 // attempt another DNS query (with backoff). Other errors should be
264 // suppressed (they may represent the absence of a TXT record).
265 return nil
266 }
267 return err
268}
269
270func handleDNSError(err error, lookupType string) error {
271 err = filterError(err)
272 if err != nil {
273 err = fmt.Errorf("dns: %v record lookup error: %v", lookupType, err)
274 grpclog.Infoln(err)
275 }
276 return err
277}
278
279func (d *dnsResolver) lookupTXT() *serviceconfig.ParseResult {
280 ss, err := d.resolver.LookupTXT(d.ctx, txtPrefix+d.host)
281 if err != nil {
282 if envconfig.TXTErrIgnore {
283 return nil
284 }
285 if err = handleDNSError(err, "TXT"); err != nil {
286 return &serviceconfig.ParseResult{Err: err}
287 }
288 return nil
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("dns: TXT record %v missing %v attribute", res, txtAttribute)
298 // This is not an error; it is the equivalent of not having a service config.
299 return nil
300 }
301 sc := canaryingSC(strings.TrimPrefix(res, txtAttribute))
302 return d.cc.ParseServiceConfig(sc)
303}
304
305func (d *dnsResolver) lookupHost() ([]resolver.Address, error) {
306 var newAddrs []resolver.Address
307 addrs, err := d.resolver.LookupHost(d.ctx, d.host)
308 if err != nil {
309 err = handleDNSError(err, "A")
310 return nil, err
311 }
312 for _, a := range addrs {
313 ip, ok := formatIP(a)
314 if !ok {
315 return nil, fmt.Errorf("dns: error parsing A record IP address %v", a)
316 }
317 addr := ip + ":" + d.port
318 newAddrs = append(newAddrs, resolver.Address{Addr: addr})
319 }
320 return newAddrs, nil
321}
322
323func (d *dnsResolver) lookup() (*resolver.State, error) {
324 srv, srvErr := d.lookupSRV()
325 addrs, hostErr := d.lookupHost()
326 if hostErr != nil && (srvErr != nil || len(srv) == 0) {
327 return nil, hostErr
328 }
329 state := &resolver.State{
330 Addresses: append(addrs, srv...),
331 }
332 if !d.disableServiceConfig {
333 state.ServiceConfig = d.lookupTXT()
334 }
335 return state, nil
336}
337
338// formatIP returns ok = false if addr is not a valid textual representation of an IP address.
339// If addr is an IPv4 address, return the addr and ok = true.
340// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true.
341func formatIP(addr string) (addrIP string, ok bool) {
342 ip := net.ParseIP(addr)
343 if ip == nil {
344 return "", false
345 }
346 if ip.To4() != nil {
347 return addr, true
348 }
349 return "[" + addr + "]", true
350}
351
352// parseTarget takes the user input target string and default port, returns formatted host and port info.
353// If target doesn't specify a port, set the port to be the defaultPort.
354// If target is in IPv6 format and host-name is enclosed in square brackets, brackets
355// are stripped when setting the host.
356// examples:
357// target: "www.google.com" defaultPort: "443" returns host: "www.google.com", port: "443"
358// target: "ipv4-host:80" defaultPort: "443" returns host: "ipv4-host", port: "80"
359// target: "[ipv6-host]" defaultPort: "443" returns host: "ipv6-host", port: "443"
360// target: ":80" defaultPort: "443" returns host: "localhost", port: "80"
361func parseTarget(target, defaultPort string) (host, port string, err error) {
362 if target == "" {
363 return "", "", errMissingAddr
364 }
365 if ip := net.ParseIP(target); ip != nil {
366 // target is an IPv4 or IPv6(without brackets) address
367 return target, defaultPort, nil
368 }
369 if host, port, err = net.SplitHostPort(target); err == nil {
370 if port == "" {
371 // If the port field is empty (target ends with colon), e.g. "[::1]:", this is an error.
372 return "", "", errEndsWithColon
373 }
374 // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port
375 if host == "" {
376 // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.
377 host = "localhost"
378 }
379 return host, port, nil
380 }
381 if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {
382 // target doesn't have port
383 return host, port, nil
384 }
385 return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)
386}
387
388type rawChoice struct {
389 ClientLanguage *[]string `json:"clientLanguage,omitempty"`
390 Percentage *int `json:"percentage,omitempty"`
391 ClientHostName *[]string `json:"clientHostName,omitempty"`
392 ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"`
393}
394
395func containsString(a *[]string, b string) bool {
396 if a == nil {
397 return true
398 }
399 for _, c := range *a {
400 if c == b {
401 return true
402 }
403 }
404 return false
405}
406
407func chosenByPercentage(a *int) bool {
408 if a == nil {
409 return true
410 }
411 return grpcrand.Intn(100)+1 <= *a
412}
413
414func canaryingSC(js string) string {
415 if js == "" {
416 return ""
417 }
418 var rcs []rawChoice
419 err := json.Unmarshal([]byte(js), &rcs)
420 if err != nil {
421 grpclog.Warningf("dns: error parsing service config json: %v", err)
422 return ""
423 }
424 cliHostname, err := os.Hostname()
425 if err != nil {
426 grpclog.Warningf("dns: error getting client hostname: %v", err)
427 return ""
428 }
429 var sc string
430 for _, c := range rcs {
431 if !containsString(c.ClientLanguage, golang) ||
432 !chosenByPercentage(c.Percentage) ||
433 !containsString(c.ClientHostName, cliHostname) ||
434 c.ServiceConfig == nil {
435 continue
436 }
437 sc = string(*c.ServiceConfig)
438 break
439 }
440 return sc
441}