netutil.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package netutil
  15. import (
  16. "context"
  17. "fmt"
  18. "net"
  19. "net/url"
  20. "reflect"
  21. "sort"
  22. "time"
  23. "go.etcd.io/etcd/pkg/types"
  24. "go.uber.org/zap"
  25. )
  26. // indirection for testing
  27. var resolveTCPAddr = resolveTCPAddrDefault
  28. const retryInterval = time.Second
  29. // taken from go's ResolveTCP code but uses configurable ctx
  30. func resolveTCPAddrDefault(ctx context.Context, addr string) (*net.TCPAddr, error) {
  31. host, port, serr := net.SplitHostPort(addr)
  32. if serr != nil {
  33. return nil, serr
  34. }
  35. portnum, perr := net.DefaultResolver.LookupPort(ctx, "tcp", port)
  36. if perr != nil {
  37. return nil, perr
  38. }
  39. var ips []net.IPAddr
  40. if ip := net.ParseIP(host); ip != nil {
  41. ips = []net.IPAddr{{IP: ip}}
  42. } else {
  43. // Try as a DNS name.
  44. ipss, err := net.DefaultResolver.LookupIPAddr(ctx, host)
  45. if err != nil {
  46. return nil, err
  47. }
  48. ips = ipss
  49. }
  50. // randomize?
  51. ip := ips[0]
  52. return &net.TCPAddr{IP: ip.IP, Port: portnum, Zone: ip.Zone}, nil
  53. }
  54. // resolveTCPAddrs is a convenience wrapper for net.ResolveTCPAddr.
  55. // resolveTCPAddrs return a new set of url.URLs, in which all DNS hostnames
  56. // are resolved.
  57. func resolveTCPAddrs(ctx context.Context, lg *zap.Logger, urls [][]url.URL) ([][]url.URL, error) {
  58. newurls := make([][]url.URL, 0)
  59. for _, us := range urls {
  60. nus := make([]url.URL, len(us))
  61. for i, u := range us {
  62. nu, err := url.Parse(u.String())
  63. if err != nil {
  64. return nil, fmt.Errorf("failed to parse %q (%v)", u.String(), err)
  65. }
  66. nus[i] = *nu
  67. }
  68. for i, u := range nus {
  69. h, err := resolveURL(ctx, lg, u)
  70. if err != nil {
  71. return nil, fmt.Errorf("failed to resolve %q (%v)", u.String(), err)
  72. }
  73. if h != "" {
  74. nus[i].Host = h
  75. }
  76. }
  77. newurls = append(newurls, nus)
  78. }
  79. return newurls, nil
  80. }
  81. func resolveURL(ctx context.Context, lg *zap.Logger, u url.URL) (string, error) {
  82. if u.Scheme == "unix" || u.Scheme == "unixs" {
  83. // unix sockets don't resolve over TCP
  84. return "", nil
  85. }
  86. host, _, err := net.SplitHostPort(u.Host)
  87. if err != nil {
  88. lg.Warn(
  89. "failed to parse URL Host while resolving URL",
  90. zap.String("url", u.String()),
  91. zap.String("host", u.Host),
  92. zap.Error(err),
  93. )
  94. return "", err
  95. }
  96. if host == "localhost" || net.ParseIP(host) != nil {
  97. return "", nil
  98. }
  99. for ctx.Err() == nil {
  100. tcpAddr, err := resolveTCPAddr(ctx, u.Host)
  101. if err == nil {
  102. lg.Info(
  103. "resolved URL Host",
  104. zap.String("url", u.String()),
  105. zap.String("host", u.Host),
  106. zap.String("resolved-addr", tcpAddr.String()),
  107. )
  108. return tcpAddr.String(), nil
  109. }
  110. lg.Warn(
  111. "failed to resolve URL Host",
  112. zap.String("url", u.String()),
  113. zap.String("host", u.Host),
  114. zap.Duration("retry-interval", retryInterval),
  115. zap.Error(err),
  116. )
  117. select {
  118. case <-ctx.Done():
  119. lg.Warn(
  120. "failed to resolve URL Host; returning",
  121. zap.String("url", u.String()),
  122. zap.String("host", u.Host),
  123. zap.Duration("retry-interval", retryInterval),
  124. zap.Error(err),
  125. )
  126. return "", err
  127. case <-time.After(retryInterval):
  128. }
  129. }
  130. return "", ctx.Err()
  131. }
  132. // urlsEqual checks equality of url.URLS between two arrays.
  133. // This check pass even if an URL is in hostname and opposite is in IP address.
  134. func urlsEqual(ctx context.Context, lg *zap.Logger, a []url.URL, b []url.URL) (bool, error) {
  135. if len(a) != len(b) {
  136. return false, fmt.Errorf("len(%q) != len(%q)", urlsToStrings(a), urlsToStrings(b))
  137. }
  138. urls, err := resolveTCPAddrs(ctx, lg, [][]url.URL{a, b})
  139. if err != nil {
  140. return false, err
  141. }
  142. preva, prevb := a, b
  143. a, b = urls[0], urls[1]
  144. sort.Sort(types.URLs(a))
  145. sort.Sort(types.URLs(b))
  146. for i := range a {
  147. if !reflect.DeepEqual(a[i], b[i]) {
  148. return false, fmt.Errorf("%q(resolved from %q) != %q(resolved from %q)",
  149. a[i].String(), preva[i].String(),
  150. b[i].String(), prevb[i].String(),
  151. )
  152. }
  153. }
  154. return true, nil
  155. }
  156. // URLStringsEqual returns "true" if given URLs are valid
  157. // and resolved to same IP addresses. Otherwise, return "false"
  158. // and error, if any.
  159. func URLStringsEqual(ctx context.Context, lg *zap.Logger, a []string, b []string) (bool, error) {
  160. if len(a) != len(b) {
  161. return false, fmt.Errorf("len(%q) != len(%q)", a, b)
  162. }
  163. urlsA := make([]url.URL, 0)
  164. for _, str := range a {
  165. u, err := url.Parse(str)
  166. if err != nil {
  167. return false, fmt.Errorf("failed to parse %q", str)
  168. }
  169. urlsA = append(urlsA, *u)
  170. }
  171. urlsB := make([]url.URL, 0)
  172. for _, str := range b {
  173. u, err := url.Parse(str)
  174. if err != nil {
  175. return false, fmt.Errorf("failed to parse %q", str)
  176. }
  177. urlsB = append(urlsB, *u)
  178. }
  179. if lg == nil {
  180. lg, _ = zap.NewProduction()
  181. if lg == nil {
  182. lg = zap.NewExample()
  183. }
  184. }
  185. return urlsEqual(ctx, lg, urlsA, urlsB)
  186. }
  187. func urlsToStrings(us []url.URL) []string {
  188. rs := make([]string, len(us))
  189. for i := range us {
  190. rs[i] = us[i].String()
  191. }
  192. return rs
  193. }
  194. func IsNetworkTimeoutError(err error) bool {
  195. nerr, ok := err.(net.Error)
  196. return ok && nerr.Timeout()
  197. }