dns_resolver.go 11 KB

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