netutil.go 5.4 KB

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