dns_resolver.go 12 KB

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