pipeline.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. "bytes"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "strings"
  22. "sync"
  23. "time"
  24. "github.com/coreos/etcd/etcdserver/stats"
  25. "github.com/coreos/etcd/pkg/httputil"
  26. "github.com/coreos/etcd/pkg/pbutil"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft"
  29. "github.com/coreos/etcd/raft/raftpb"
  30. "github.com/coreos/etcd/version"
  31. )
  32. const (
  33. connPerPipeline = 4
  34. // pipelineBufSize is the size of pipeline buffer, which helps hold the
  35. // temporary network latency.
  36. // The size ensures that pipeline does not drop messages when the network
  37. // is out of work for less than 1 second in good path.
  38. pipelineBufSize = 64
  39. )
  40. var errStopped = errors.New("stopped")
  41. type pipeline struct {
  42. from, to types.ID
  43. cid types.ID
  44. tr http.RoundTripper
  45. picker *urlPicker
  46. status *peerStatus
  47. fs *stats.FollowerStats
  48. r Raft
  49. errorc chan error
  50. msgc chan raftpb.Message
  51. // wait for the handling routines
  52. wg sync.WaitGroup
  53. stopc chan struct{}
  54. }
  55. func newPipeline(tr http.RoundTripper, picker *urlPicker, from, to, cid types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft, errorc chan error) *pipeline {
  56. p := &pipeline{
  57. from: from,
  58. to: to,
  59. cid: cid,
  60. tr: tr,
  61. picker: picker,
  62. status: status,
  63. fs: fs,
  64. r: r,
  65. errorc: errorc,
  66. stopc: make(chan struct{}),
  67. msgc: make(chan raftpb.Message, pipelineBufSize),
  68. }
  69. p.wg.Add(connPerPipeline)
  70. for i := 0; i < connPerPipeline; i++ {
  71. go p.handle()
  72. }
  73. return p
  74. }
  75. func (p *pipeline) stop() {
  76. close(p.msgc)
  77. close(p.stopc)
  78. p.wg.Wait()
  79. }
  80. func (p *pipeline) handle() {
  81. defer p.wg.Done()
  82. for m := range p.msgc {
  83. start := time.Now()
  84. err := p.post(pbutil.MustMarshal(&m))
  85. if err == errStopped {
  86. return
  87. }
  88. end := time.Now()
  89. if err != nil {
  90. reportSentFailure(pipelineMsg, m)
  91. p.status.deactivate(failureType{source: pipelineMsg, action: "write"}, err.Error())
  92. if m.Type == raftpb.MsgApp && p.fs != nil {
  93. p.fs.Fail()
  94. }
  95. p.r.ReportUnreachable(m.To)
  96. if isMsgSnap(m) {
  97. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  98. }
  99. } else {
  100. p.status.activate()
  101. if m.Type == raftpb.MsgApp && p.fs != nil {
  102. p.fs.Succ(end.Sub(start))
  103. }
  104. if isMsgSnap(m) {
  105. p.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  106. }
  107. reportSentDuration(pipelineMsg, m, time.Since(start))
  108. }
  109. }
  110. }
  111. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  112. // error on any failure.
  113. func (p *pipeline) post(data []byte) (err error) {
  114. u := p.picker.pick()
  115. uu := u
  116. uu.Path = RaftPrefix
  117. req, err := http.NewRequest("POST", uu.String(), bytes.NewBuffer(data))
  118. if err != nil {
  119. p.picker.unreachable(u)
  120. return err
  121. }
  122. req.Header.Set("Content-Type", "application/protobuf")
  123. req.Header.Set("X-Server-From", p.from.String())
  124. req.Header.Set("X-Server-Version", version.Version)
  125. req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
  126. req.Header.Set("X-Etcd-Cluster-ID", p.cid.String())
  127. var stopped bool
  128. defer func() {
  129. if stopped {
  130. // rewrite to errStopped so the caller goroutine can stop itself
  131. err = errStopped
  132. }
  133. }()
  134. done := make(chan struct{}, 1)
  135. cancel := httputil.RequestCanceler(p.tr, req)
  136. go func() {
  137. select {
  138. case <-done:
  139. case <-p.stopc:
  140. waitSchedule()
  141. stopped = true
  142. cancel()
  143. }
  144. }()
  145. resp, err := p.tr.RoundTrip(req)
  146. done <- struct{}{}
  147. if err != nil {
  148. p.picker.unreachable(u)
  149. return err
  150. }
  151. b, err := ioutil.ReadAll(resp.Body)
  152. if err != nil {
  153. p.picker.unreachable(u)
  154. return err
  155. }
  156. resp.Body.Close()
  157. switch resp.StatusCode {
  158. case http.StatusPreconditionFailed:
  159. switch strings.TrimSuffix(string(b), "\n") {
  160. case errIncompatibleVersion.Error():
  161. plog.Errorf("request sent was ignored by peer %s (server version incompatible)", p.to)
  162. return errIncompatibleVersion
  163. case errClusterIDMismatch.Error():
  164. plog.Errorf("request sent was ignored (cluster ID mismatch: remote[%s]=%s, local=%s)",
  165. p.to, resp.Header.Get("X-Etcd-Cluster-ID"), p.cid)
  166. return errClusterIDMismatch
  167. default:
  168. return fmt.Errorf("unhandled error %q when precondition failed", string(b))
  169. }
  170. case http.StatusForbidden:
  171. err := fmt.Errorf("the member has been permanently removed from the cluster")
  172. select {
  173. case p.errorc <- err:
  174. default:
  175. }
  176. return nil
  177. case http.StatusNoContent:
  178. return nil
  179. default:
  180. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  181. }
  182. }
  183. // waitSchedule waits other goroutines to be scheduled for a while
  184. func waitSchedule() { time.Sleep(time.Millisecond) }