dns_resolver.go 13 KB

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