pipeline_test.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. p := newPipeline(tr, picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), fs, &fakeRaft{}, nil)
  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. fs.Lock()
  44. defer fs.Unlock()
  45. if fs.Counts.Success != 1 {
  46. t.Errorf("success = %d, want 1", fs.Counts.Success)
  47. }
  48. }
  49. // TestPipelineKeepSendingWhenPostError tests that pipeline can keep
  50. // sending messages if previous messages meet post error.
  51. func TestPipelineKeepSendingWhenPostError(t *testing.T) {
  52. tr := &respRoundTripper{err: fmt.Errorf("roundtrip error")}
  53. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  54. fs := &stats.FollowerStats{}
  55. p := newPipeline(tr, picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), fs, &fakeRaft{}, nil)
  56. for i := 0; i < 50; i++ {
  57. p.msgc <- raftpb.Message{Type: raftpb.MsgApp}
  58. }
  59. testutil.WaitSchedule()
  60. p.stop()
  61. // check it send out 50 requests
  62. tr.mu.Lock()
  63. defer tr.mu.Unlock()
  64. if tr.reqCount != 50 {
  65. t.Errorf("request count = %d, want 50", tr.reqCount)
  66. }
  67. }
  68. func TestPipelineExceedMaximumServing(t *testing.T) {
  69. tr := newRoundTripperBlocker()
  70. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  71. fs := &stats.FollowerStats{}
  72. p := newPipeline(tr, 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. p := newPipeline(newRespRoundTripper(0, errors.New("blah")), picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), fs, &fakeRaft{}, nil)
  108. p.msgc <- raftpb.Message{Type: raftpb.MsgApp}
  109. testutil.WaitSchedule()
  110. p.stop()
  111. fs.Lock()
  112. defer fs.Unlock()
  113. if fs.Counts.Fail != 1 {
  114. t.Errorf("fail = %d, want 1", fs.Counts.Fail)
  115. }
  116. }
  117. func TestPipelinePost(t *testing.T) {
  118. tr := &roundTripperRecorder{}
  119. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  120. p := newPipeline(tr, picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), nil, &fakeRaft{}, nil)
  121. if err := p.post([]byte("some data")); err != nil {
  122. t.Fatalf("unexpect post error: %v", err)
  123. }
  124. p.stop()
  125. if g := tr.Request().Method; g != "POST" {
  126. t.Errorf("method = %s, want %s", g, "POST")
  127. }
  128. if g := tr.Request().URL.String(); g != "http://localhost:2380/raft" {
  129. t.Errorf("url = %s, want %s", g, "http://localhost:2380/raft")
  130. }
  131. if g := tr.Request().Header.Get("Content-Type"); g != "application/protobuf" {
  132. t.Errorf("content type = %s, want %s", g, "application/protobuf")
  133. }
  134. if g := tr.Request().Header.Get("X-Server-Version"); g != version.Version {
  135. t.Errorf("version = %s, want %s", g, version.Version)
  136. }
  137. if g := tr.Request().Header.Get("X-Min-Cluster-Version"); g != version.MinClusterVersion {
  138. t.Errorf("min version = %s, want %s", g, version.MinClusterVersion)
  139. }
  140. if g := tr.Request().Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  141. t.Errorf("cluster id = %s, want %s", g, "1")
  142. }
  143. b, err := ioutil.ReadAll(tr.Request().Body)
  144. if err != nil {
  145. t.Fatalf("unexpected ReadAll error: %v", err)
  146. }
  147. if string(b) != "some data" {
  148. t.Errorf("body = %s, want %s", b, "some data")
  149. }
  150. }
  151. func TestPipelinePostBad(t *testing.T) {
  152. tests := []struct {
  153. u string
  154. code int
  155. err error
  156. }{
  157. // RoundTrip returns error
  158. {"http://localhost:2380", 0, errors.New("blah")},
  159. // unexpected response status code
  160. {"http://localhost:2380", http.StatusOK, nil},
  161. {"http://localhost:2380", http.StatusCreated, nil},
  162. }
  163. for i, tt := range tests {
  164. picker := mustNewURLPicker(t, []string{tt.u})
  165. p := newPipeline(newRespRoundTripper(tt.code, tt.err), picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), nil, &fakeRaft{}, make(chan error))
  166. err := p.post([]byte("some data"))
  167. p.stop()
  168. if err == nil {
  169. t.Errorf("#%d: err = nil, want not nil", i)
  170. }
  171. }
  172. }
  173. func TestPipelinePostErrorc(t *testing.T) {
  174. tests := []struct {
  175. u string
  176. code int
  177. err error
  178. }{
  179. {"http://localhost:2380", http.StatusForbidden, nil},
  180. }
  181. for i, tt := range tests {
  182. picker := mustNewURLPicker(t, []string{tt.u})
  183. errorc := make(chan error, 1)
  184. p := newPipeline(newRespRoundTripper(tt.code, tt.err), picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), nil, &fakeRaft{}, errorc)
  185. p.post([]byte("some data"))
  186. p.stop()
  187. select {
  188. case <-errorc:
  189. default:
  190. t.Fatalf("#%d: cannot receive from errorc", i)
  191. }
  192. }
  193. }
  194. func TestStopBlockedPipeline(t *testing.T) {
  195. picker := mustNewURLPicker(t, []string{"http://localhost:2380"})
  196. p := newPipeline(newRoundTripperBlocker(), picker, types.ID(2), types.ID(1), types.ID(1), newPeerStatus(types.ID(1)), nil, &fakeRaft{}, nil)
  197. // send many messages that most of them will be blocked in buffer
  198. for i := 0; i < connPerPipeline*10; i++ {
  199. p.msgc <- raftpb.Message{}
  200. }
  201. done := make(chan struct{})
  202. go func() {
  203. p.stop()
  204. done <- struct{}{}
  205. }()
  206. select {
  207. case <-done:
  208. case <-time.After(time.Second):
  209. t.Fatalf("failed to stop pipeline in 1s")
  210. }
  211. }
  212. type roundTripperBlocker struct {
  213. unblockc chan struct{}
  214. mu sync.Mutex
  215. cancel map[*http.Request]chan struct{}
  216. }
  217. func newRoundTripperBlocker() *roundTripperBlocker {
  218. return &roundTripperBlocker{
  219. unblockc: make(chan struct{}),
  220. cancel: make(map[*http.Request]chan struct{}),
  221. }
  222. }
  223. func (t *roundTripperBlocker) unblock() {
  224. close(t.unblockc)
  225. }
  226. func (t *roundTripperBlocker) CancelRequest(req *http.Request) {
  227. t.mu.Lock()
  228. defer t.mu.Unlock()
  229. if c, ok := t.cancel[req]; ok {
  230. c <- struct{}{}
  231. delete(t.cancel, req)
  232. }
  233. }
  234. type respRoundTripper struct {
  235. mu sync.Mutex
  236. reqCount int
  237. code int
  238. header http.Header
  239. err error
  240. }
  241. func newRespRoundTripper(code int, err error) *respRoundTripper {
  242. return &respRoundTripper{code: code, err: err}
  243. }
  244. func (t *respRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  245. t.mu.Lock()
  246. defer t.mu.Unlock()
  247. t.reqCount++
  248. return &http.Response{StatusCode: t.code, Header: t.header, Body: &nopReadCloser{}}, t.err
  249. }
  250. type roundTripperRecorder struct {
  251. req *http.Request
  252. sync.Mutex
  253. }
  254. func (t *roundTripperRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
  255. t.Lock()
  256. defer t.Unlock()
  257. t.req = req
  258. return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil
  259. }
  260. func (t *roundTripperRecorder) Request() *http.Request {
  261. t.Lock()
  262. defer t.Unlock()
  263. return t.req
  264. }
  265. type nopReadCloser struct{}
  266. func (n *nopReadCloser) Read(p []byte) (int, error) { return 0, io.EOF }
  267. func (n *nopReadCloser) Close() error { return nil }