pipeline.go 3.9 KB

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