dns_resolver.go 11 KB

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