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