util.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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/http"
  20. "net/url"
  21. "strings"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
  23. "github.com/coreos/etcd/pkg/types"
  24. "github.com/coreos/etcd/raft/raftpb"
  25. "github.com/coreos/etcd/version"
  26. )
  27. var errMemberRemoved = fmt.Errorf("the member has been permanently removed from the cluster")
  28. func writeEntryTo(w io.Writer, ent *raftpb.Entry) error {
  29. size := ent.Size()
  30. if err := binary.Write(w, binary.BigEndian, uint64(size)); err != nil {
  31. return err
  32. }
  33. b, err := ent.Marshal()
  34. if err != nil {
  35. return err
  36. }
  37. _, err = w.Write(b)
  38. return err
  39. }
  40. func readEntryFrom(r io.Reader, ent *raftpb.Entry) error {
  41. var l uint64
  42. if err := binary.Read(r, binary.BigEndian, &l); err != nil {
  43. return err
  44. }
  45. buf := make([]byte, int(l))
  46. if _, err := io.ReadFull(r, buf); err != nil {
  47. return err
  48. }
  49. return ent.Unmarshal(buf)
  50. }
  51. // createPostRequest creates a HTTP POST request that sends raft message.
  52. func createPostRequest(u url.URL, path string, body io.Reader, ct string, from, cid types.ID) *http.Request {
  53. uu := u
  54. uu.Path = path
  55. req, err := http.NewRequest("POST", uu.String(), body)
  56. if err != nil {
  57. plog.Panicf("unexpected new request error (%v)", err)
  58. }
  59. req.Header.Set("Content-Type", ct)
  60. req.Header.Set("X-Server-From", from.String())
  61. req.Header.Set("X-Server-Version", version.Version)
  62. req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
  63. req.Header.Set("X-Etcd-Cluster-ID", cid.String())
  64. return req
  65. }
  66. // checkPostResponse checks the response of the HTTP POST request that sends
  67. // raft message.
  68. func checkPostResponse(resp *http.Response, body []byte, req *http.Request, to types.ID) error {
  69. switch resp.StatusCode {
  70. case http.StatusPreconditionFailed:
  71. switch strings.TrimSuffix(string(body), "\n") {
  72. case errIncompatibleVersion.Error():
  73. plog.Errorf("request sent was ignored by peer %s (server version incompatible)", to)
  74. return errIncompatibleVersion
  75. case errClusterIDMismatch.Error():
  76. plog.Errorf("request sent was ignored (cluster ID mismatch: remote[%s]=%s, local=%s)",
  77. to, resp.Header.Get("X-Etcd-Cluster-ID"), req.Header.Get("X-Etcd-Cluster-ID"))
  78. return errClusterIDMismatch
  79. default:
  80. return fmt.Errorf("unhandled error %q when precondition failed", string(body))
  81. }
  82. case http.StatusForbidden:
  83. return errMemberRemoved
  84. case http.StatusNoContent:
  85. return nil
  86. default:
  87. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  88. }
  89. }
  90. // reportErr reports the given error through sending it into
  91. // the given error channel.
  92. // If the error channel is filled up when sending error, it drops the error
  93. // because the fact that error has happened is reported, which is
  94. // good enough.
  95. func reportCriticalError(err error, errc chan<- error) {
  96. select {
  97. case errc <- err:
  98. default:
  99. }
  100. }
  101. // compareMajorMinorVersion returns an integer comparing two versions based on
  102. // their major and minor version. The result will be 0 if a==b, -1 if a < b,
  103. // and 1 if a > b.
  104. func compareMajorMinorVersion(a, b *semver.Version) int {
  105. na := &semver.Version{Major: a.Major, Minor: a.Minor}
  106. nb := &semver.Version{Major: b.Major, Minor: b.Minor}
  107. switch {
  108. case na.LessThan(*nb):
  109. return -1
  110. case nb.LessThan(*na):
  111. return 1
  112. default:
  113. return 0
  114. }
  115. }
  116. // serverVersion returns the server version from the given header.
  117. func serverVersion(h http.Header) *semver.Version {
  118. verStr := h.Get("X-Server-Version")
  119. // backward compatibility with etcd 2.0
  120. if verStr == "" {
  121. verStr = "2.0.0"
  122. }
  123. return semver.Must(semver.NewVersion(verStr))
  124. }
  125. // serverVersion returns the min cluster version from the given header.
  126. func minClusterVersion(h http.Header) *semver.Version {
  127. verStr := h.Get("X-Min-Cluster-Version")
  128. // backward compatibility with etcd 2.0
  129. if verStr == "" {
  130. verStr = "2.0.0"
  131. }
  132. return semver.Must(semver.NewVersion(verStr))
  133. }
  134. // checkVersionCompability checks whether the given version is compatible
  135. // with the local version.
  136. func checkVersionCompability(name string, server, minCluster *semver.Version) error {
  137. localServer := semver.Must(semver.NewVersion(version.Version))
  138. localMinCluster := semver.Must(semver.NewVersion(version.MinClusterVersion))
  139. if compareMajorMinorVersion(server, localMinCluster) == -1 {
  140. return fmt.Errorf("remote version is too low: remote[%s]=%s, local=%s", name, server, localServer)
  141. }
  142. if compareMajorMinorVersion(minCluster, localServer) == 1 {
  143. return fmt.Errorf("local version is too low: remote[%s]=%s, local=%s", name, server, localServer)
  144. }
  145. return nil
  146. }