util.go 6.8 KB

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