pipeline.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. if p.errored == nil || p.errored.Error() != err.Error() {
  86. log.Printf("pipeline: error posting to %s: %v", p.id, err)
  87. p.errored = err
  88. }
  89. if p.active {
  90. log.Printf("pipeline: the connection with %s became inactive", p.id)
  91. p.active = false
  92. }
  93. if m.Type == raftpb.MsgApp {
  94. p.fs.Fail()
  95. }
  96. p.r.ReportUnreachable(m.To)
  97. if isMsgSnap(m) {
  98. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  99. }
  100. } else {
  101. if !p.active {
  102. log.Printf("pipeline: the connection with %s became active", p.id)
  103. p.active = true
  104. p.errored = nil
  105. }
  106. if m.Type == raftpb.MsgApp {
  107. p.fs.Succ(end.Sub(start))
  108. }
  109. if isMsgSnap(m) {
  110. p.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  111. }
  112. reportSendingDuration(pipelineMsg, m, time.Since(start))
  113. }
  114. p.Unlock()
  115. }
  116. }
  117. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  118. // error on any failure.
  119. func (p *pipeline) post(data []byte) error {
  120. p.Lock()
  121. req, err := http.NewRequest("POST", p.u, bytes.NewBuffer(data))
  122. p.Unlock()
  123. if err != nil {
  124. return err
  125. }
  126. req.Header.Set("Content-Type", "application/protobuf")
  127. req.Header.Set("X-Etcd-Cluster-ID", p.cid.String())
  128. resp, err := p.tr.RoundTrip(req)
  129. if err != nil {
  130. return err
  131. }
  132. resp.Body.Close()
  133. switch resp.StatusCode {
  134. case http.StatusPreconditionFailed:
  135. err := fmt.Errorf("conflicting cluster ID with the target cluster (%s != %s)", resp.Header.Get("X-Etcd-Cluster-ID"), p.cid)
  136. select {
  137. case p.errorc <- err:
  138. default:
  139. }
  140. return nil
  141. case http.StatusForbidden:
  142. err := fmt.Errorf("the member has been permanently removed from the cluster")
  143. select {
  144. case p.errorc <- err:
  145. default:
  146. }
  147. return nil
  148. case http.StatusNoContent:
  149. return nil
  150. default:
  151. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  152. }
  153. }