pipeline_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. "errors"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net/http"
  21. "sync"
  22. "testing"
  23. "time"
  24. "github.com/coreos/etcd/etcdserver/stats"
  25. "github.com/coreos/etcd/pkg/testutil"
  26. "github.com/coreos/etcd/pkg/types"
  27. "github.com/coreos/etcd/raft/raftpb"
  28. "github.com/coreos/etcd/version"
  29. )
  30. // TestPipelineSend tests that pipeline could send data using roundtripper
  31. // and increase success count in stats.
  32. func TestPipelineSend(t *testing.T) {
  33. tr := &roundTripperRecorder{rec: testutil.NewRecorderStream()}
  34. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  35. tp := &Transport{pipelineRt: tr}
  36. p := startTestPipeline(tp, picker)
  37. p.msgc <- raftpb.Message{Type: raftpb.MsgApp}
  38. tr.rec.Wait(1)
  39. p.stop()
  40. if p.followerStats.Counts.Success != 1 {
  41. t.Errorf("success = %d, want 1", p.followerStats.Counts.Success)
  42. }
  43. }
  44. // TestPipelineKeepSendingWhenPostError tests that pipeline can keep
  45. // sending messages if previous messages meet post error.
  46. func TestPipelineKeepSendingWhenPostError(t *testing.T) {
  47. tr := &respRoundTripper{rec: testutil.NewRecorderStream(), err: fmt.Errorf("roundtrip error")}
  48. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  49. tp := &Transport{pipelineRt: tr}
  50. p := startTestPipeline(tp, picker)
  51. defer p.stop()
  52. for i := 0; i < 50; i++ {
  53. p.msgc <- raftpb.Message{Type: raftpb.MsgApp}
  54. }
  55. _, err := tr.rec.Wait(50)
  56. if err != nil {
  57. t.Errorf("unexpected wait error %v", err)
  58. }
  59. }
  60. func TestPipelineExceedMaximumServing(t *testing.T) {
  61. rt := newRoundTripperBlocker()
  62. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  63. tp := &Transport{pipelineRt: rt}
  64. p := startTestPipeline(tp, picker)
  65. defer p.stop()
  66. // keep the sender busy and make the buffer full
  67. // nothing can go out as we block the sender
  68. for i := 0; i < connPerPipeline+pipelineBufSize; i++ {
  69. select {
  70. case p.msgc <- raftpb.Message{}:
  71. case <-time.After(time.Second):
  72. t.Errorf("failed to send out message")
  73. }
  74. }
  75. // try to send a data when we are sure the buffer is full
  76. select {
  77. case p.msgc <- raftpb.Message{}:
  78. t.Errorf("unexpected message sendout")
  79. default:
  80. }
  81. // unblock the senders and force them to send out the data
  82. rt.unblock()
  83. // It could send new data after previous ones succeed
  84. select {
  85. case p.msgc <- raftpb.Message{}:
  86. case <-time.After(time.Second):
  87. t.Errorf("failed to send out message")
  88. }
  89. }
  90. // TestPipelineSendFailed tests that when send func meets the post error,
  91. // it increases fail count in stats.
  92. func TestPipelineSendFailed(t *testing.T) {
  93. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  94. rt := newRespRoundTripper(0, errors.New("blah"))
  95. rt.rec = testutil.NewRecorderStream()
  96. tp := &Transport{pipelineRt: rt}
  97. p := startTestPipeline(tp, picker)
  98. p.msgc <- raftpb.Message{Type: raftpb.MsgApp}
  99. if _, err := rt.rec.Wait(1); err != nil {
  100. t.Fatal(err)
  101. }
  102. p.stop()
  103. if p.followerStats.Counts.Fail != 1 {
  104. t.Errorf("fail = %d, want 1", p.followerStats.Counts.Fail)
  105. }
  106. }
  107. func TestPipelinePost(t *testing.T) {
  108. tr := &roundTripperRecorder{rec: &testutil.RecorderBuffered{}}
  109. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  110. tp := &Transport{ClusterID: types.ID(1), pipelineRt: tr}
  111. p := startTestPipeline(tp, picker)
  112. if err := p.post([]byte("some data")); err != nil {
  113. t.Fatalf("unexpected post error: %v", err)
  114. }
  115. act, err := tr.rec.Wait(1)
  116. if err != nil {
  117. t.Fatal(err)
  118. }
  119. p.stop()
  120. req := act[0].Params[0].(*http.Request)
  121. if g := req.Method; g != "POST" {
  122. t.Errorf("method = %s, want %s", g, "POST")
  123. }
  124. if g := req.URL.String(); g != "http://localhost:2380/raft" {
  125. t.Errorf("url = %s, want %s", g, "http://localhost:2380/raft")
  126. }
  127. if g := req.Header.Get("Content-Type"); g != "application/protobuf" {
  128. t.Errorf("content type = %s, want %s", g, "application/protobuf")
  129. }
  130. if g := req.Header.Get("X-Server-Version"); g != version.Version {
  131. t.Errorf("version = %s, want %s", g, version.Version)
  132. }
  133. if g := req.Header.Get("X-Min-Cluster-Version"); g != version.MinClusterVersion {
  134. t.Errorf("min version = %s, want %s", g, version.MinClusterVersion)
  135. }
  136. if g := req.Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  137. t.Errorf("cluster id = %s, want %s", g, "1")
  138. }
  139. b, err := ioutil.ReadAll(req.Body)
  140. if err != nil {
  141. t.Fatalf("unexpected ReadAll error: %v", err)
  142. }
  143. if string(b) != "some data" {
  144. t.Errorf("body = %s, want %s", b, "some data")
  145. }
  146. }
  147. func TestPipelinePostBad(t *testing.T) {
  148. tests := []struct {
  149. u string
  150. code int
  151. err error
  152. }{
  153. // RoundTrip returns error
  154. {"http://localhost:2380", 0, errors.New("blah")},
  155. // unexpected response status code
  156. {"http://localhost:2380", http.StatusOK, nil},
  157. {"http://localhost:2380", http.StatusCreated, nil},
  158. }
  159. for i, tt := range tests {
  160. picker := mustNewURLPicker(t, []string{tt.u})
  161. tp := &Transport{pipelineRt: newRespRoundTripper(tt.code, tt.err)}
  162. p := startTestPipeline(tp, picker)
  163. err := p.post([]byte("some data"))
  164. p.stop()
  165. if err == nil {
  166. t.Errorf("#%d: err = nil, want not nil", i)
  167. }
  168. }
  169. }
  170. func TestPipelinePostErrorc(t *testing.T) {
  171. tests := []struct {
  172. u string
  173. code int
  174. err error
  175. }{
  176. {"http://localhost:2380", http.StatusForbidden, nil},
  177. }
  178. for i, tt := range tests {
  179. picker := mustNewURLPicker(t, []string{tt.u})
  180. tp := &Transport{pipelineRt: newRespRoundTripper(tt.code, tt.err)}
  181. p := startTestPipeline(tp, picker)
  182. p.post([]byte("some data"))
  183. p.stop()
  184. select {
  185. case <-p.errorc:
  186. default:
  187. t.Fatalf("#%d: cannot receive from errorc", i)
  188. }
  189. }
  190. }
  191. func TestStopBlockedPipeline(t *testing.T) {
  192. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  193. tp := &Transport{pipelineRt: newRoundTripperBlocker()}
  194. p := startTestPipeline(tp, picker)
  195. // send many messages that most of them will be blocked in buffer
  196. for i := 0; i < connPerPipeline*10; i++ {
  197. p.msgc <- raftpb.Message{}
  198. }
  199. done := make(chan struct{})
  200. go func() {
  201. p.stop()
  202. done <- struct{}{}
  203. }()
  204. select {
  205. case <-done:
  206. case <-time.After(time.Second):
  207. t.Fatalf("failed to stop pipeline in 1s")
  208. }
  209. }
  210. type roundTripperBlocker struct {
  211. unblockc chan struct{}
  212. mu sync.Mutex
  213. cancel map[*http.Request]chan struct{}
  214. }
  215. func newRoundTripperBlocker() *roundTripperBlocker {
  216. return &roundTripperBlocker{
  217. unblockc: make(chan struct{}),
  218. cancel: make(map[*http.Request]chan struct{}),
  219. }
  220. }
  221. func (t *roundTripperBlocker) unblock() {
  222. close(t.unblockc)
  223. }
  224. func (t *roundTripperBlocker) CancelRequest(req *http.Request) {
  225. t.mu.Lock()
  226. defer t.mu.Unlock()
  227. if c, ok := t.cancel[req]; ok {
  228. c <- struct{}{}
  229. delete(t.cancel, req)
  230. }
  231. }
  232. type respRoundTripper struct {
  233. mu sync.Mutex
  234. rec testutil.Recorder
  235. code int
  236. header http.Header
  237. err error
  238. }
  239. func newRespRoundTripper(code int, err error) *respRoundTripper {
  240. return &respRoundTripper{code: code, err: err}
  241. }
  242. func (t *respRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  243. t.mu.Lock()
  244. defer t.mu.Unlock()
  245. if t.rec != nil {
  246. t.rec.Record(testutil.Action{Name: "req", Params: []interface{}{req}})
  247. }
  248. return &http.Response{StatusCode: t.code, Header: t.header, Body: &nopReadCloser{}}, t.err
  249. }
  250. type roundTripperRecorder struct {
  251. rec testutil.Recorder
  252. }
  253. func (t *roundTripperRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
  254. if t.rec != nil {
  255. t.rec.Record(testutil.Action{Name: "req", Params: []interface{}{req}})
  256. }
  257. return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil
  258. }
  259. type nopReadCloser struct{}
  260. func (n *nopReadCloser) Read(p []byte) (int, error) { return 0, io.EOF }
  261. func (n *nopReadCloser) Close() error { return nil }
  262. func startTestPipeline(tr *Transport, picker *urlPicker) *pipeline {
  263. p := &pipeline{
  264. peerID: types.ID(1),
  265. tr: tr,
  266. picker: picker,
  267. status: newPeerStatus(types.ID(1)),
  268. raft: &fakeRaft{},
  269. followerStats: &stats.FollowerStats{},
  270. errorc: make(chan error, 1),
  271. }
  272. p.start()
  273. return p
  274. }