pipeline.go 3.9 KB

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