util.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 rafthttp
  15. import (
  16. "fmt"
  17. "io"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "strings"
  22. "time"
  23. "github.com/coreos/etcd/pkg/transport"
  24. "github.com/coreos/etcd/pkg/types"
  25. "github.com/coreos/etcd/version"
  26. "github.com/coreos/go-semver/semver"
  27. )
  28. var (
  29. errMemberRemoved = fmt.Errorf("the member has been permanently removed from the cluster")
  30. errMemberNotFound = fmt.Errorf("member not found")
  31. )
  32. // NewListener returns a listener for raft message transfer between peers.
  33. // It uses timeout listener to identify broken streams promptly.
  34. func NewListener(u url.URL, tlsinfo *transport.TLSInfo) (net.Listener, error) {
  35. return transport.NewTimeoutListener(u.Host, u.Scheme, tlsinfo, ConnReadTimeout, ConnWriteTimeout)
  36. }
  37. // NewRoundTripper returns a roundTripper used to send requests
  38. // to rafthttp listener of remote peers.
  39. func NewRoundTripper(tlsInfo transport.TLSInfo, dialTimeout time.Duration) (http.RoundTripper, error) {
  40. // It uses timeout transport to pair with remote timeout listeners.
  41. // It sets no read/write timeout, because message in requests may
  42. // take long time to write out before reading out the response.
  43. return transport.NewTimeoutTransport(tlsInfo, dialTimeout, 0, 0)
  44. }
  45. // newStreamRoundTripper returns a roundTripper used to send stream requests
  46. // to rafthttp listener of remote peers.
  47. // Read/write timeout is set for stream roundTripper to promptly
  48. // find out broken status, which minimizes the number of messages
  49. // sent on broken connection.
  50. func newStreamRoundTripper(tlsInfo transport.TLSInfo, dialTimeout time.Duration) (http.RoundTripper, error) {
  51. return transport.NewTimeoutTransport(tlsInfo, dialTimeout, ConnReadTimeout, ConnWriteTimeout)
  52. }
  53. // createPostRequest creates a HTTP POST request that sends raft message.
  54. func createPostRequest(u url.URL, path string, body io.Reader, ct string, urls types.URLs, from, cid types.ID) *http.Request {
  55. uu := u
  56. uu.Path = path
  57. req, err := http.NewRequest("POST", uu.String(), body)
  58. if err != nil {
  59. plog.Panicf("unexpected new request error (%v)", err)
  60. }
  61. req.Header.Set("Content-Type", ct)
  62. req.Header.Set("X-Server-From", from.String())
  63. req.Header.Set("X-Server-Version", version.Version)
  64. req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
  65. req.Header.Set("X-Etcd-Cluster-ID", cid.String())
  66. setPeerURLsHeader(req, urls)
  67. return req
  68. }
  69. // checkPostResponse checks the response of the HTTP POST request that sends
  70. // raft message.
  71. func checkPostResponse(resp *http.Response, body []byte, req *http.Request, to types.ID) error {
  72. switch resp.StatusCode {
  73. case http.StatusPreconditionFailed:
  74. switch strings.TrimSuffix(string(body), "\n") {
  75. case errIncompatibleVersion.Error():
  76. plog.Errorf("request sent was ignored by peer %s (server version incompatible)", to)
  77. return errIncompatibleVersion
  78. case errClusterIDMismatch.Error():
  79. plog.Errorf("request sent was ignored (cluster ID mismatch: remote[%s]=%s, local=%s)",
  80. to, resp.Header.Get("X-Etcd-Cluster-ID"), req.Header.Get("X-Etcd-Cluster-ID"))
  81. return errClusterIDMismatch
  82. default:
  83. return fmt.Errorf("unhandled error %q when precondition failed", string(body))
  84. }
  85. case http.StatusForbidden:
  86. return errMemberRemoved
  87. case http.StatusNoContent:
  88. return nil
  89. default:
  90. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  91. }
  92. }
  93. // reportCriticalError reports the given error through sending it into
  94. // the given error channel.
  95. // If the error channel is filled up when sending error, it drops the error
  96. // because the fact that error has happened is reported, which is
  97. // good enough.
  98. func reportCriticalError(err error, errc chan<- error) {
  99. select {
  100. case errc <- err:
  101. default:
  102. }
  103. }
  104. // compareMajorMinorVersion returns an integer comparing two versions based on
  105. // their major and minor version. The result will be 0 if a==b, -1 if a < b,
  106. // and 1 if a > b.
  107. func compareMajorMinorVersion(a, b *semver.Version) int {
  108. na := &semver.Version{Major: a.Major, Minor: a.Minor}
  109. nb := &semver.Version{Major: b.Major, Minor: b.Minor}
  110. switch {
  111. case na.LessThan(*nb):
  112. return -1
  113. case nb.LessThan(*na):
  114. return 1
  115. default:
  116. return 0
  117. }
  118. }
  119. // serverVersion returns the server version from the given header.
  120. func serverVersion(h http.Header) *semver.Version {
  121. verStr := h.Get("X-Server-Version")
  122. // backward compatibility with etcd 2.0
  123. if verStr == "" {
  124. verStr = "2.0.0"
  125. }
  126. return semver.Must(semver.NewVersion(verStr))
  127. }
  128. // serverVersion returns the min cluster version from the given header.
  129. func minClusterVersion(h http.Header) *semver.Version {
  130. verStr := h.Get("X-Min-Cluster-Version")
  131. // backward compatibility with etcd 2.0
  132. if verStr == "" {
  133. verStr = "2.0.0"
  134. }
  135. return semver.Must(semver.NewVersion(verStr))
  136. }
  137. // checkVersionCompability checks whether the given version is compatible
  138. // with the local version.
  139. func checkVersionCompability(name string, server, minCluster *semver.Version) error {
  140. localServer := semver.Must(semver.NewVersion(version.Version))
  141. localMinCluster := semver.Must(semver.NewVersion(version.MinClusterVersion))
  142. if compareMajorMinorVersion(server, localMinCluster) == -1 {
  143. return fmt.Errorf("remote version is too low: remote[%s]=%s, local=%s", name, server, localServer)
  144. }
  145. if compareMajorMinorVersion(minCluster, localServer) == 1 {
  146. return fmt.Errorf("local version is too low: remote[%s]=%s, local=%s", name, server, localServer)
  147. }
  148. return nil
  149. }
  150. // setPeerURLsHeader reports local urls for peer discovery
  151. func setPeerURLsHeader(req *http.Request, urls types.URLs) {
  152. if urls == nil {
  153. // often not set in unit tests
  154. return
  155. }
  156. peerURLs := make([]string, urls.Len())
  157. for i := range urls {
  158. peerURLs[i] = urls[i].String()
  159. }
  160. req.Header.Set("X-PeerURLs", strings.Join(peerURLs, ","))
  161. }