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