util.go 6.9 KB

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