25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

439 lines
12 KiB

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