util.go 6.4 KB

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