cubefs
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.
21package dns22
23import (24"context"25"encoding/json"26"errors"27"fmt"28"net"29"os"30"strconv"31"strings"32"sync"33"time"34
35grpclbstate "google.golang.org/grpc/balancer/grpclb/state"36"google.golang.org/grpc/grpclog"37"google.golang.org/grpc/internal/envconfig"38"google.golang.org/grpc/internal/grpcrand"39"google.golang.org/grpc/resolver"40"google.golang.org/grpc/serviceconfig"41)
42
43// EnableSRVLookups controls whether the DNS resolver attempts to fetch gRPCLB
44// addresses from SRV records. Must not be changed after init time.
45var EnableSRVLookups = false46
47var logger = grpclog.Component("dns")48
49func init() {50resolver.Register(NewBuilder())51}
52
53const (54defaultPort = "443"55defaultDNSSvrPort = "53"56golang = "GO"57// txtPrefix is the prefix string to be prepended to the host name for txt record lookup.58txtPrefix = "_grpc_config."59// In DNS, service config is encoded in a TXT record via the mechanism60// described in RFC-1464 using the attribute name grpc_config.61txtAttribute = "grpc_config="62)
63
64var (65errMissingAddr = errors.New("dns resolver: missing address")66
67// Addresses ending with a colon that is supposed to be the separator68// between host and port is not allowed. E.g. "::" is a valid address as69// it is an IPv6 address (host only) and "[::]:" is invalid as it ends with70// a colon as the host and port separator71errEndsWithColon = errors.New("dns resolver: missing port after port-separator colon")72)
73
74var (75defaultResolver netResolver = net.DefaultResolver76// To prevent excessive re-resolution, we enforce a rate limit on DNS77// resolution requests.78minDNSResRate = 30 * time.Second79)
80
81var customAuthorityDialler = func(authority string) func(ctx context.Context, network, address string) (net.Conn, error) {82return func(ctx context.Context, network, address string) (net.Conn, error) {83var dialer net.Dialer84return dialer.DialContext(ctx, network, authority)85}86}
87
88var customAuthorityResolver = func(authority string) (netResolver, error) {89host, port, err := parseTarget(authority, defaultDNSSvrPort)90if err != nil {91return nil, err92}93
94authorityWithPort := net.JoinHostPort(host, port)95
96return &net.Resolver{97PreferGo: true,98Dial: customAuthorityDialler(authorityWithPort),99}, nil100}
101
102// NewBuilder creates a dnsBuilder which is used to factory DNS resolvers.
103func NewBuilder() resolver.Builder {104return &dnsBuilder{}105}
106
107type dnsBuilder struct{}108
109// Build creates and starts a DNS resolver that watches the name resolution of the target.
110func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {111host, port, err := parseTarget(target.Endpoint, defaultPort)112if err != nil {113return nil, err114}115
116// IP address.117if ipAddr, ok := formatIP(host); ok {118addr := []resolver.Address{{Addr: ipAddr + ":" + port}}119cc.UpdateState(resolver.State{Addresses: addr})120return deadResolver{}, nil121}122
123// DNS address (non-IP).124ctx, cancel := context.WithCancel(context.Background())125d := &dnsResolver{126host: host,127port: port,128ctx: ctx,129cancel: cancel,130cc: cc,131rn: make(chan struct{}, 1),132disableServiceConfig: opts.DisableServiceConfig,133}134
135if target.Authority == "" {136d.resolver = defaultResolver137} else {138d.resolver, err = customAuthorityResolver(target.Authority)139if err != nil {140return nil, err141}142}143
144d.wg.Add(1)145go d.watcher()146d.ResolveNow(resolver.ResolveNowOptions{})147return d, nil148}
149
150// Scheme returns the naming scheme of this resolver builder, which is "dns".
151func (b *dnsBuilder) Scheme() string {152return "dns"153}
154
155type netResolver interface {156LookupHost(ctx context.Context, host string) (addrs []string, err error)157LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*net.SRV, err error)158LookupTXT(ctx context.Context, name string) (txts []string, err error)159}
160
161// deadResolver is a resolver that does nothing.
162type deadResolver struct{}163
164func (deadResolver) ResolveNow(resolver.ResolveNowOptions) {}165
166func (deadResolver) Close() {}167
168// dnsResolver watches for the name resolution update for a non-IP target.
169type dnsResolver struct {170host string171port string172resolver netResolver
173ctx context.Context174cancel context.CancelFunc175cc resolver.ClientConn176// rn channel is used by ResolveNow() to force an immediate resolution of the target.177rn chan struct{}178// wg is used to enforce Close() to return after the watcher() goroutine has finished.179// Otherwise, data race will be possible. [Race Example] in dns_resolver_test we180// replace the real lookup functions with mocked ones to facilitate testing.181// If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes182// will warns lookup (READ the lookup function pointers) inside watcher() goroutine183// has data race with replaceNetFunc (WRITE the lookup function pointers).184wg sync.WaitGroup185disableServiceConfig bool186}
187
188// ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
189func (d *dnsResolver) ResolveNow(resolver.ResolveNowOptions) {190select {191case d.rn <- struct{}{}:192default:193}194}
195
196// Close closes the dnsResolver.
197func (d *dnsResolver) Close() {198d.cancel()199d.wg.Wait()200}
201
202func (d *dnsResolver) watcher() {203defer d.wg.Done()204for {205select {206case <-d.ctx.Done():207return208case <-d.rn:209}210
211state, err := d.lookup()212if err != nil {213d.cc.ReportError(err)214} else {215d.cc.UpdateState(*state)216}217
218// Sleep to prevent excessive re-resolutions. Incoming resolution requests219// will be queued in d.rn.220t := time.NewTimer(minDNSResRate)221select {222case <-t.C:223case <-d.ctx.Done():224t.Stop()225return226}227}228}
229
230func (d *dnsResolver) lookupSRV() ([]resolver.Address, error) {231if !EnableSRVLookups {232return nil, nil233}234var newAddrs []resolver.Address235_, srvs, err := d.resolver.LookupSRV(d.ctx, "grpclb", "tcp", d.host)236if err != nil {237err = handleDNSError(err, "SRV") // may become nil238return nil, err239}240for _, s := range srvs {241lbAddrs, err := d.resolver.LookupHost(d.ctx, s.Target)242if err != nil {243err = handleDNSError(err, "A") // may become nil244if err == nil {245// If there are other SRV records, look them up and ignore this246// one that does not exist.247continue248}249return nil, err250}251for _, a := range lbAddrs {252ip, ok := formatIP(a)253if !ok {254return nil, fmt.Errorf("dns: error parsing A record IP address %v", a)255}256addr := ip + ":" + strconv.Itoa(int(s.Port))257newAddrs = append(newAddrs, resolver.Address{Addr: addr, ServerName: s.Target})258}259}260return newAddrs, nil261}
262
263var filterError = func(err error) error {264if dnsErr, ok := err.(*net.DNSError); ok && !dnsErr.IsTimeout && !dnsErr.IsTemporary {265// Timeouts and temporary errors should be communicated to gRPC to266// attempt another DNS query (with backoff). Other errors should be267// suppressed (they may represent the absence of a TXT record).268return nil269}270return err271}
272
273func handleDNSError(err error, lookupType string) error {274err = filterError(err)275if err != nil {276err = fmt.Errorf("dns: %v record lookup error: %v", lookupType, err)277logger.Info(err)278}279return err280}
281
282func (d *dnsResolver) lookupTXT() *serviceconfig.ParseResult {283ss, err := d.resolver.LookupTXT(d.ctx, txtPrefix+d.host)284if err != nil {285if envconfig.TXTErrIgnore {286return nil287}288if err = handleDNSError(err, "TXT"); err != nil {289return &serviceconfig.ParseResult{Err: err}290}291return nil292}293var res string294for _, s := range ss {295res += s296}297
298// TXT record must have "grpc_config=" attribute in order to be used as service config.299if !strings.HasPrefix(res, txtAttribute) {300logger.Warningf("dns: TXT record %v missing %v attribute", res, txtAttribute)301// This is not an error; it is the equivalent of not having a service config.302return nil303}304sc := canaryingSC(strings.TrimPrefix(res, txtAttribute))305return d.cc.ParseServiceConfig(sc)306}
307
308func (d *dnsResolver) lookupHost() ([]resolver.Address, error) {309var newAddrs []resolver.Address310addrs, err := d.resolver.LookupHost(d.ctx, d.host)311if err != nil {312err = handleDNSError(err, "A")313return nil, err314}315for _, a := range addrs {316ip, ok := formatIP(a)317if !ok {318return nil, fmt.Errorf("dns: error parsing A record IP address %v", a)319}320addr := ip + ":" + d.port321newAddrs = append(newAddrs, resolver.Address{Addr: addr})322}323return newAddrs, nil324}
325
326func (d *dnsResolver) lookup() (*resolver.State, error) {327srv, srvErr := d.lookupSRV()328addrs, hostErr := d.lookupHost()329if hostErr != nil && (srvErr != nil || len(srv) == 0) {330return nil, hostErr331}332
333state := resolver.State{Addresses: addrs}334if len(srv) > 0 {335state = grpclbstate.Set(state, &grpclbstate.State{BalancerAddresses: srv})336}337if !d.disableServiceConfig {338state.ServiceConfig = d.lookupTXT()339}340return &state, nil341}
342
343// formatIP returns ok = false if addr is not a valid textual representation of an IP address.
344// If addr is an IPv4 address, return the addr and ok = true.
345// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true.
346func formatIP(addr string) (addrIP string, ok bool) {347ip := net.ParseIP(addr)348if ip == nil {349return "", false350}351if ip.To4() != nil {352return addr, true353}354return "[" + addr + "]", true355}
356
357// parseTarget takes the user input target string and default port, returns formatted host and port info.
358// If target doesn't specify a port, set the port to be the defaultPort.
359// If target is in IPv6 format and host-name is enclosed in square brackets, brackets
360// are stripped when setting the host.
361// examples:
362// target: "www.google.com" defaultPort: "443" returns host: "www.google.com", port: "443"
363// target: "ipv4-host:80" defaultPort: "443" returns host: "ipv4-host", port: "80"
364// target: "[ipv6-host]" defaultPort: "443" returns host: "ipv6-host", port: "443"
365// target: ":80" defaultPort: "443" returns host: "localhost", port: "80"
366func parseTarget(target, defaultPort string) (host, port string, err error) {367if target == "" {368return "", "", errMissingAddr369}370if ip := net.ParseIP(target); ip != nil {371// target is an IPv4 or IPv6(without brackets) address372return target, defaultPort, nil373}374if host, port, err = net.SplitHostPort(target); err == nil {375if port == "" {376// If the port field is empty (target ends with colon), e.g. "[::1]:", this is an error.377return "", "", errEndsWithColon378}379// target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port380if host == "" {381// Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.382host = "localhost"383}384return host, port, nil385}386if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {387// target doesn't have port388return host, port, nil389}390return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)391}
392
393type rawChoice struct {394ClientLanguage *[]string `json:"clientLanguage,omitempty"`395Percentage *int `json:"percentage,omitempty"`396ClientHostName *[]string `json:"clientHostName,omitempty"`397ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"`398}
399
400func containsString(a *[]string, b string) bool {401if a == nil {402return true403}404for _, c := range *a {405if c == b {406return true407}408}409return false410}
411
412func chosenByPercentage(a *int) bool {413if a == nil {414return true415}416return grpcrand.Intn(100)+1 <= *a417}
418
419func canaryingSC(js string) string {420if js == "" {421return ""422}423var rcs []rawChoice424err := json.Unmarshal([]byte(js), &rcs)425if err != nil {426logger.Warningf("dns: error parsing service config json: %v", err)427return ""428}429cliHostname, err := os.Hostname()430if err != nil {431logger.Warningf("dns: error getting client hostname: %v", err)432return ""433}434var sc string435for _, c := range rcs {436if !containsString(c.ClientLanguage, golang) ||437!chosenByPercentage(c.Percentage) ||438!containsString(c.ClientHostName, cliHostname) ||439c.ServiceConfig == nil {440continue441}442sc = string(*c.ServiceConfig)443break444}445return sc446}
447