3 * Copyright 2017 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 "golang.org/x/net/context"
36 "google.golang.org/grpc/grpclog"
37 "google.golang.org/grpc/resolver"
41 resolver.Register(NewBuilder())
46 defaultFreq = time.Minute * 30
48 // In DNS, service config is encoded in a TXT record via the mechanism
49 // described in RFC-1464 using the attribute name grpc_config.
50 txtAttribute = "grpc_config="
53 var errMissingAddr = errors.New("missing address")
55 // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers.
56 func NewBuilder() resolver.Builder {
57 return &dnsBuilder{freq: defaultFreq}
60 type dnsBuilder struct {
61 // frequency of polling the DNS server.
65 // Build creates and starts a DNS resolver that watches the name resolution of the target.
66 func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) {
67 host, port, err := parseTarget(target.Endpoint)
73 if net.ParseIP(host) != nil {
74 host, _ = formatIP(host)
75 addr := []resolver.Address{{Addr: host + ":" + port}}
79 rn: make(chan struct{}, 1),
80 q: make(chan struct{}),
87 // DNS address (non-IP).
88 ctx, cancel := context.WithCancel(context.Background())
97 rn: make(chan struct{}, 1),
105 // Scheme returns the naming scheme of this resolver builder, which is "dns".
106 func (b *dnsBuilder) Scheme() string {
110 // ipResolver watches for the name resolution update for an IP address.
111 type ipResolver struct {
112 cc resolver.ClientConn
113 ip []resolver.Address
114 // rn channel is used by ResolveNow() to force an immediate resolution of the target.
119 // ResolveNow resend the address it stores, no resolution is needed.
120 func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) {
122 case i.rn <- struct{}{}:
127 // Close closes the ipResolver.
128 func (i *ipResolver) Close() {
132 func (i *ipResolver) watcher() {
136 i.cc.NewAddress(i.ip)
143 // dnsResolver watches for the name resolution update for a non-IP target.
144 type dnsResolver struct {
149 cancel context.CancelFunc
150 cc resolver.ClientConn
151 // rn channel is used by ResolveNow() to force an immediate resolution of the target.
154 // wg is used to enforce Close() to return after the watcher() goroutine has finished.
155 // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we
156 // replace the real lookup functions with mocked ones to facilitate testing.
157 // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes
158 // will warns lookup (READ the lookup function pointers) inside watcher() goroutine
159 // has data race with replaceNetFunc (WRITE the lookup function pointers).
163 // ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
164 func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) {
166 case d.rn <- struct{}{}:
171 // Close closes the dnsResolver.
172 func (d *dnsResolver) Close() {
178 func (d *dnsResolver) watcher() {
187 result, sc := d.lookup()
188 // Next lookup should happen after an interval defined by d.freq.
190 d.cc.NewServiceConfig(string(sc))
191 d.cc.NewAddress(result)
195 func (d *dnsResolver) lookupSRV() []resolver.Address {
196 var newAddrs []resolver.Address
197 _, srvs, err := lookupSRV(d.ctx, "grpclb", "tcp", d.host)
199 grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err)
202 for _, s := range srvs {
203 lbAddrs, err := lookupHost(d.ctx, s.Target)
205 grpclog.Warningf("grpc: failed load banlacer address dns lookup due to %v.\n", err)
208 for _, a := range lbAddrs {
211 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
214 addr := a + ":" + strconv.Itoa(int(s.Port))
215 newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target})
221 func (d *dnsResolver) lookupTXT() string {
222 ss, err := lookupTXT(d.ctx, d.host)
224 grpclog.Warningf("grpc: failed dns TXT record lookup due to %v.\n", err)
228 for _, s := range ss {
232 // TXT record must have "grpc_config=" attribute in order to be used as service config.
233 if !strings.HasPrefix(res, txtAttribute) {
234 grpclog.Warningf("grpc: TXT record %v missing %v attribute", res, txtAttribute)
237 return strings.TrimPrefix(res, txtAttribute)
240 func (d *dnsResolver) lookupHost() []resolver.Address {
241 var newAddrs []resolver.Address
242 addrs, err := lookupHost(d.ctx, d.host)
244 grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err)
247 for _, a := range addrs {
250 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
253 addr := a + ":" + d.port
254 newAddrs = append(newAddrs, resolver.Address{Addr: addr})
259 func (d *dnsResolver) lookup() ([]resolver.Address, string) {
260 var newAddrs []resolver.Address
261 newAddrs = d.lookupSRV()
262 // Support fallback to non-balancer address.
263 newAddrs = append(newAddrs, d.lookupHost()...)
265 return newAddrs, canaryingSC(sc)
268 // formatIP returns ok = false if addr is not a valid textual representation of an IP address.
269 // If addr is an IPv4 address, return the addr and ok = true.
270 // If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true.
271 func formatIP(addr string) (addrIP string, ok bool) {
272 ip := net.ParseIP(addr)
279 return "[" + addr + "]", true
282 // parseTarget takes the user input target string, returns formatted host and port info.
283 // If target doesn't specify a port, set the port to be the defaultPort.
284 // If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets
285 // are strippd when setting the host.
287 // target: "www.google.com" returns host: "www.google.com", port: "443"
288 // target: "ipv4-host:80" returns host: "ipv4-host", port: "80"
289 // target: "[ipv6-host]" returns host: "ipv6-host", port: "443"
290 // target: ":80" returns host: "localhost", port: "80"
291 // target: ":" returns host: "localhost", port: "443"
292 func parseTarget(target string) (host, port string, err error) {
294 return "", "", errMissingAddr
296 if ip := net.ParseIP(target); ip != nil {
297 // target is an IPv4 or IPv6(without brackets) address
298 return target, defaultPort, nil
300 if host, port, err = net.SplitHostPort(target); err == nil {
301 // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port
303 // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.
307 // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used.
310 return host, port, nil
312 if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {
313 // target doesn't have port
314 return host, port, nil
316 return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)
319 type rawChoice struct {
320 ClientLanguage *[]string `json:"clientLanguage,omitempty"`
321 Percentage *int `json:"percentage,omitempty"`
322 ClientHostName *[]string `json:"clientHostName,omitempty"`
323 ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"`
326 func containsString(a *[]string, b string) bool {
330 for _, c := range *a {
338 func chosenByPercentage(a *int) bool {
342 s := rand.NewSource(time.Now().UnixNano())
344 if r.Intn(100)+1 > *a {
350 func canaryingSC(js string) string {
355 err := json.Unmarshal([]byte(js), &rcs)
357 grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err)
360 cliHostname, err := os.Hostname()
362 grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err)
366 for _, c := range rcs {
367 if !containsString(c.ClientLanguage, golang) ||
368 !chosenByPercentage(c.Percentage) ||
369 !containsString(c.ClientHostName, cliHostname) ||
370 c.ServiceConfig == nil {
373 sc = string(*c.ServiceConfig)