pipeline.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. "io/ioutil"
  19. "net/http"
  20. "sync"
  21. "time"
  22. "github.com/coreos/etcd/etcdserver/stats"
  23. "github.com/coreos/etcd/pkg/httputil"
  24. "github.com/coreos/etcd/pkg/pbutil"
  25. "github.com/coreos/etcd/pkg/types"
  26. "github.com/coreos/etcd/raft"
  27. "github.com/coreos/etcd/raft/raftpb"
  28. )
  29. const (
  30. connPerPipeline = 4
  31. // pipelineBufSize is the size of pipeline buffer, which helps hold the
  32. // temporary network latency.
  33. // The size ensures that pipeline does not drop messages when the network
  34. // is out of work for less than 1 second in good path.
  35. pipelineBufSize = 64
  36. )
  37. var errStopped = errors.New("stopped")
  38. type pipeline struct {
  39. from, to types.ID
  40. cid types.ID
  41. tr http.RoundTripper
  42. picker *urlPicker
  43. status *peerStatus
  44. fs *stats.FollowerStats
  45. r Raft
  46. errorc chan error
  47. msgc chan raftpb.Message
  48. // wait for the handling routines
  49. wg sync.WaitGroup
  50. stopc chan struct{}
  51. }
  52. func newPipeline(tr http.RoundTripper, picker *urlPicker, from, to, cid types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft, errorc chan error) *pipeline {
  53. p := &pipeline{
  54. from: from,
  55. to: to,
  56. cid: cid,
  57. tr: tr,
  58. picker: picker,
  59. status: status,
  60. fs: fs,
  61. r: r,
  62. errorc: errorc,
  63. stopc: make(chan struct{}),
  64. msgc: make(chan raftpb.Message, pipelineBufSize),
  65. }
  66. p.wg.Add(connPerPipeline)
  67. for i := 0; i < connPerPipeline; i++ {
  68. go p.handle()
  69. }
  70. return p
  71. }
  72. func (p *pipeline) stop() {
  73. close(p.stopc)
  74. p.wg.Wait()
  75. }
  76. func (p *pipeline) handle() {
  77. defer p.wg.Done()
  78. for {
  79. select {
  80. case m := <-p.msgc:
  81. start := time.Now()
  82. err := p.post(pbutil.MustMarshal(&m))
  83. end := time.Now()
  84. if err != nil {
  85. p.status.deactivate(failureType{source: pipelineMsg, action: "write"}, err.Error())
  86. reportSentFailure(pipelineMsg, m)
  87. if m.Type == raftpb.MsgApp && p.fs != nil {
  88. p.fs.Fail()
  89. }
  90. p.r.ReportUnreachable(m.To)
  91. if isMsgSnap(m) {
  92. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  93. }
  94. continue
  95. }
  96. p.status.activate()
  97. if m.Type == raftpb.MsgApp && p.fs != nil {
  98. p.fs.Succ(end.Sub(start))
  99. }
  100. if isMsgSnap(m) {
  101. p.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  102. }
  103. reportSentDuration(pipelineMsg, m, time.Since(start))
  104. case <-p.stopc:
  105. return
  106. }
  107. }
  108. }
  109. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  110. // error on any failure.
  111. func (p *pipeline) post(data []byte) (err error) {
  112. u := p.picker.pick()
  113. req := createPostRequest(u, RaftPrefix, bytes.NewBuffer(data), "application/protobuf", p.from, p.cid)
  114. done := make(chan struct{}, 1)
  115. cancel := httputil.RequestCanceler(p.tr, req)
  116. go func() {
  117. select {
  118. case <-done:
  119. case <-p.stopc:
  120. waitSchedule()
  121. cancel()
  122. }
  123. }()
  124. resp, err := p.tr.RoundTrip(req)
  125. done <- struct{}{}
  126. if err != nil {
  127. p.picker.unreachable(u)
  128. return err
  129. }
  130. b, err := ioutil.ReadAll(resp.Body)
  131. if err != nil {
  132. p.picker.unreachable(u)
  133. return err
  134. }
  135. resp.Body.Close()
  136. err = checkPostResponse(resp, b, req, p.to)
  137. if err != nil {
  138. p.picker.unreachable(u)
  139. // errMemberRemoved is a critical error since a removed member should
  140. // always be stopped. So we use reportCriticalError to report it to errorc.
  141. if err == errMemberRemoved {
  142. reportCriticalError(err, p.errorc)
  143. }
  144. return err
  145. }
  146. return nil
  147. }
  148. // waitSchedule waits other goroutines to be scheduled for a while
  149. func waitSchedule() { time.Sleep(time.Millisecond) }