PageRenderTime 57ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/go/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go

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