pipeline_test.go 8.8 KB

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