pipeline_test.go 8.4 KB

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