netutil.go 4.9 KB

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