pipeline.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. "fmt"
  18. "log"
  19. "net/http"
  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. type pipeline struct {
  37. id types.ID
  38. cid types.ID
  39. tr http.RoundTripper
  40. // the url this pipeline sends to
  41. u string
  42. fs *stats.FollowerStats
  43. r Raft
  44. errorc chan error
  45. msgc chan raftpb.Message
  46. // wait for the handling routines
  47. wg sync.WaitGroup
  48. sync.Mutex
  49. // if the last send was successful, the pipeline is active.
  50. // Or it is inactive
  51. active bool
  52. errored error
  53. }
  54. func newPipeline(tr http.RoundTripper, u string, id, cid types.ID, fs *stats.FollowerStats, r Raft, errorc chan error) *pipeline {
  55. p := &pipeline{
  56. id: id,
  57. cid: cid,
  58. tr: tr,
  59. u: u,
  60. fs: fs,
  61. r: r,
  62. errorc: errorc,
  63. msgc: make(chan raftpb.Message, pipelineBufSize),
  64. active: true,
  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) update(u string) { p.u = u }
  73. func (p *pipeline) stop() {
  74. close(p.msgc)
  75. p.wg.Wait()
  76. }
  77. func (p *pipeline) handle() {
  78. defer p.wg.Done()
  79. for m := range p.msgc {
  80. start := time.Now()
  81. err := p.post(pbutil.MustMarshal(&m))
  82. end := time.Now()
  83. p.Lock()
  84. if err != nil {
  85. reportMessageFailure(pipelineMsg, m)
  86. if p.errored == nil || p.errored.Error() != err.Error() {
  87. log.Printf("pipeline: error posting to %s: %v", p.id, err)
  88. p.errored = err
  89. }
  90. if p.active {
  91. log.Printf("pipeline: the connection with %s became inactive", p.id)
  92. p.active = false
  93. }
  94. if m.Type == raftpb.MsgApp {
  95. p.fs.Fail()
  96. }
  97. p.r.ReportUnreachable(m.To)
  98. if isMsgSnap(m) {
  99. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  100. }
  101. } else {
  102. if !p.active {
  103. log.Printf("pipeline: the connection with %s became active", p.id)
  104. p.active = true
  105. p.errored = nil
  106. }
  107. if m.Type == raftpb.MsgApp {
  108. p.fs.Succ(end.Sub(start))
  109. }
  110. if isMsgSnap(m) {
  111. p.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  112. }
  113. reportSendingDuration(pipelineMsg, m, time.Since(start))
  114. }
  115. p.Unlock()
  116. }
  117. }
  118. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  119. // error on any failure.
  120. func (p *pipeline) post(data []byte) error {
  121. p.Lock()
  122. req, err := http.NewRequest("POST", p.u, bytes.NewBuffer(data))
  123. p.Unlock()
  124. if err != nil {
  125. return err
  126. }
  127. req.Header.Set("Content-Type", "application/protobuf")
  128. req.Header.Set("X-Etcd-Cluster-ID", p.cid.String())
  129. resp, err := p.tr.RoundTrip(req)
  130. if err != nil {
  131. return err
  132. }
  133. resp.Body.Close()
  134. switch resp.StatusCode {
  135. case http.StatusPreconditionFailed:
  136. err := fmt.Errorf("conflicting cluster ID with the target cluster (%s != %s)", resp.Header.Get("X-Etcd-Cluster-ID"), p.cid)
  137. select {
  138. case p.errorc <- err:
  139. default:
  140. }
  141. return nil
  142. case http.StatusForbidden:
  143. err := fmt.Errorf("the member has been permanently removed from the cluster")
  144. select {
  145. case p.errorc <- err:
  146. default:
  147. }
  148. return nil
  149. case http.StatusNoContent:
  150. return nil
  151. default:
  152. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  153. }
  154. }