util.go 6.2 KB

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