3 * Copyright 2018 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 // Package dns implements a dns resolver to be installed as the default resolver
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"
42 resolver.Register(NewBuilder())
47 defaultFreq = time.Minute * 30
48 defaultDNSSvrPort = "53"
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="
56 errMissingAddr = errors.New("dns resolver: missing address")
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")
66 defaultResolver netResolver = net.DefaultResolver
69 var 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) {
72 return dialer.DialContext(ctx, network, authority)
76 var customAuthorityResolver = func(authority string) (netResolver, error) {
77 host, port, err := parseTarget(authority, defaultDNSSvrPort)
82 authorityWithPort := net.JoinHostPort(host, port)
86 Dial: customAuthorityDialler(authorityWithPort),
90 // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers.
91 func NewBuilder() resolver.Builder {
92 return &dnsBuilder{minFreq: defaultFreq}
95 type dnsBuilder struct {
96 // minimum frequency of polling the DNS server.
100 // Build creates and starts a DNS resolver that watches the name resolution of the target.
101 func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) {
102 host, port, err := parseTarget(target.Endpoint, defaultPort)
108 if net.ParseIP(host) != nil {
109 host, _ = formatIP(host)
110 addr := []resolver.Address{{Addr: host + ":" + port}}
114 rn: make(chan struct{}, 1),
115 q: make(chan struct{}),
122 // DNS address (non-IP).
123 ctx, cancel := context.WithCancel(context.Background())
126 backoff: backoff.Exponential{MaxDelay: b.minFreq},
133 rn: make(chan struct{}, 1),
134 disableServiceConfig: opts.DisableServiceConfig,
137 if target.Authority == "" {
138 d.resolver = defaultResolver
140 d.resolver, err = customAuthorityResolver(target.Authority)
151 // Scheme returns the naming scheme of this resolver builder, which is "dns".
152 func (b *dnsBuilder) Scheme() string {
156 type 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)
162 // ipResolver watches for the name resolution update for an IP address.
163 type 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.
171 // ResolveNow resend the address it stores, no resolution is needed.
172 func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) {
174 case i.rn <- struct{}{}:
179 // Close closes the ipResolver.
180 func (i *ipResolver) Close() {
184 func (i *ipResolver) watcher() {
188 i.cc.NewAddress(i.ip)
195 // dnsResolver watches for the name resolution update for a non-IP target.
196 type dnsResolver struct {
198 backoff backoff.Exponential
204 cancel context.CancelFunc
205 cc resolver.ClientConn
206 // rn channel is used by ResolveNow() to force an immediate resolution of the target.
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).
216 disableServiceConfig bool
219 // ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
220 func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) {
222 case d.rn <- struct{}{}:
227 // Close closes the dnsResolver.
228 func (d *dnsResolver) Close() {
234 func (d *dnsResolver) watcher() {
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 {
248 d.t.Reset(d.backoff.Backoff(d.retryCount))
253 d.cc.NewServiceConfig(sc)
254 d.cc.NewAddress(result)
258 func (d *dnsResolver) lookupSRV() []resolver.Address {
259 var newAddrs []resolver.Address
260 _, srvs, err := d.resolver.LookupSRV(d.ctx, "grpclb", "tcp", d.host)
262 grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err)
265 for _, s := range srvs {
266 lbAddrs, err := d.resolver.LookupHost(d.ctx, s.Target)
268 grpclog.Infof("grpc: failed load balancer address dns lookup due to %v.\n", err)
271 for _, a := range lbAddrs {
274 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
277 addr := a + ":" + strconv.Itoa(int(s.Port))
278 newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target})
284 func (d *dnsResolver) lookupTXT() string {
285 ss, err := d.resolver.LookupTXT(d.ctx, d.host)
287 grpclog.Infof("grpc: failed dns TXT record lookup due to %v.\n", err)
291 for _, s := range ss {
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)
300 return strings.TrimPrefix(res, txtAttribute)
303 func (d *dnsResolver) lookupHost() []resolver.Address {
304 var newAddrs []resolver.Address
305 addrs, err := d.resolver.LookupHost(d.ctx, d.host)
307 grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err)
310 for _, a := range addrs {
313 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
316 addr := a + ":" + d.port
317 newAddrs = append(newAddrs, resolver.Address{Addr: addr})
322 func (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 {
330 return newAddrs, canaryingSC(sc)
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.
336 func formatIP(addr string) (addrIP string, ok bool) {
337 ip := net.ParseIP(addr)
344 return "[" + addr + "]", true
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 sqarue brackets, brackets
350 // are strippd when setting the host.
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"
356 func parseTarget(target, defaultPort string) (host, port string, err error) {
358 return "", "", errMissingAddr
360 if ip := net.ParseIP(target); ip != nil {
361 // target is an IPv4 or IPv6(without brackets) address
362 return target, defaultPort, nil
364 if host, port, err = net.SplitHostPort(target); err == nil {
366 // If the port field is empty (target ends with colon), e.g. "[::1]:", this is an error.
367 return "", "", errEndsWithColon
369 // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port
371 // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.
374 return host, port, nil
376 if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {
377 // target doesn't have port
378 return host, port, nil
380 return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)
383 type 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"`
390 func containsString(a *[]string, b string) bool {
394 for _, c := range *a {
402 func chosenByPercentage(a *int) bool {
406 return grpcrand.Intn(100)+1 <= *a
409 func canaryingSC(js string) string {
414 err := json.Unmarshal([]byte(js), &rcs)
416 grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err)
419 cliHostname, err := os.Hostname()
421 grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err)
425 for _, c := range rcs {
426 if !containsString(c.ClientLanguage, golang) ||
427 !chosenByPercentage(c.Percentage) ||
428 !containsString(c.ClientHostName, cliHostname) ||
429 c.ServiceConfig == nil {
432 sc = string(*c.ServiceConfig)