stream_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. "net/http"
  20. "net/http/httptest"
  21. "reflect"
  22. "sync"
  23. "testing"
  24. "time"
  25. "github.com/coreos/etcd/etcdserver/stats"
  26. "github.com/coreos/etcd/pkg/testutil"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. "github.com/coreos/etcd/version"
  30. "github.com/coreos/go-semver/semver"
  31. )
  32. // TestStreamWriterAttachOutgoingConn tests that outgoingConn can be attached
  33. // to streamWriter. After that, streamWriter can use it to send messages
  34. // continuously, and closes it when stopped.
  35. func TestStreamWriterAttachOutgoingConn(t *testing.T) {
  36. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  37. // the expected initial state of streamWriter is not working
  38. if _, ok := sw.writec(); ok {
  39. t.Errorf("initial working status = %v, want false", ok)
  40. }
  41. // repeat tests to ensure streamWriter can use last attached connection
  42. var wfc *fakeWriteFlushCloser
  43. for i := 0; i < 3; i++ {
  44. prevwfc := wfc
  45. wfc = newFakeWriteFlushCloser(nil)
  46. sw.attach(&outgoingConn{t: streamTypeMessage, Writer: wfc, Flusher: wfc, Closer: wfc})
  47. // previous attached connection should be closed
  48. if prevwfc != nil {
  49. select {
  50. case <-prevwfc.closed:
  51. case <-time.After(time.Second):
  52. t.Errorf("#%d: close of previous connection timed out", i)
  53. }
  54. }
  55. // if prevwfc != nil, the new msgc is ready since prevwfc has closed
  56. // if prevwfc == nil, the first connection may be pending, but the first
  57. // msgc is already available since it's set on calling startStreamwriter
  58. msgc, _ := sw.writec()
  59. msgc <- raftpb.Message{}
  60. select {
  61. case <-wfc.writec:
  62. case <-time.After(time.Second):
  63. t.Errorf("#%d: failed to write to the underlying connection", i)
  64. }
  65. // write chan is still available
  66. if _, ok := sw.writec(); !ok {
  67. t.Errorf("#%d: working status = %v, want true", i, ok)
  68. }
  69. }
  70. sw.stop()
  71. // write chan is unavailable since the writer is stopped.
  72. if _, ok := sw.writec(); ok {
  73. t.Errorf("working status after stop = %v, want false", ok)
  74. }
  75. if !wfc.Closed() {
  76. t.Errorf("failed to close the underlying connection")
  77. }
  78. }
  79. // TestStreamWriterAttachBadOutgoingConn tests that streamWriter with bad
  80. // outgoingConn will close the outgoingConn and fall back to non-working status.
  81. func TestStreamWriterAttachBadOutgoingConn(t *testing.T) {
  82. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  83. defer sw.stop()
  84. wfc := newFakeWriteFlushCloser(errors.New("blah"))
  85. sw.attach(&outgoingConn{t: streamTypeMessage, Writer: wfc, Flusher: wfc, Closer: wfc})
  86. sw.msgc <- raftpb.Message{}
  87. select {
  88. case <-wfc.closed:
  89. case <-time.After(time.Second):
  90. t.Errorf("failed to close the underlying connection in time")
  91. }
  92. // no longer working
  93. if _, ok := sw.writec(); ok {
  94. t.Errorf("working = %v, want false", ok)
  95. }
  96. }
  97. func TestStreamReaderDialRequest(t *testing.T) {
  98. for i, tt := range []streamType{streamTypeMessage, streamTypeMsgAppV2} {
  99. tr := &roundTripperRecorder{rec: &testutil.RecorderBuffered{}}
  100. sr := &streamReader{
  101. peerID: types.ID(2),
  102. tr: &Transport{streamRt: tr, ClusterID: types.ID(1), ID: types.ID(1)},
  103. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  104. }
  105. sr.dial(tt)
  106. act, err := tr.rec.Wait(1)
  107. if err != nil {
  108. t.Fatal(err)
  109. }
  110. req := act[0].Params[0].(*http.Request)
  111. wurl := fmt.Sprintf("http://localhost:2380" + tt.endpoint() + "/1")
  112. if req.URL.String() != wurl {
  113. t.Errorf("#%d: url = %s, want %s", i, req.URL.String(), wurl)
  114. }
  115. if w := "GET"; req.Method != w {
  116. t.Errorf("#%d: method = %s, want %s", i, req.Method, w)
  117. }
  118. if g := req.Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  119. t.Errorf("#%d: header X-Etcd-Cluster-ID = %s, want 1", i, g)
  120. }
  121. if g := req.Header.Get("X-Raft-To"); g != "2" {
  122. t.Errorf("#%d: header X-Raft-To = %s, want 2", i, g)
  123. }
  124. }
  125. }
  126. // TestStreamReaderDialResult tests the result of the dial func call meets the
  127. // HTTP response received.
  128. func TestStreamReaderDialResult(t *testing.T) {
  129. tests := []struct {
  130. code int
  131. err error
  132. wok bool
  133. whalt bool
  134. }{
  135. {0, errors.New("blah"), false, false},
  136. {http.StatusOK, nil, true, false},
  137. {http.StatusMethodNotAllowed, nil, false, false},
  138. {http.StatusNotFound, nil, false, false},
  139. {http.StatusPreconditionFailed, nil, false, false},
  140. {http.StatusGone, nil, false, true},
  141. }
  142. for i, tt := range tests {
  143. h := http.Header{}
  144. h.Add("X-Server-Version", version.Version)
  145. tr := &respRoundTripper{
  146. code: tt.code,
  147. header: h,
  148. err: tt.err,
  149. }
  150. sr := &streamReader{
  151. peerID: types.ID(2),
  152. tr: &Transport{streamRt: tr, ClusterID: types.ID(1)},
  153. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  154. errorc: make(chan error, 1),
  155. }
  156. _, err := sr.dial(streamTypeMessage)
  157. if ok := err == nil; ok != tt.wok {
  158. t.Errorf("#%d: ok = %v, want %v", i, ok, tt.wok)
  159. }
  160. if halt := len(sr.errorc) > 0; halt != tt.whalt {
  161. t.Errorf("#%d: halt = %v, want %v", i, halt, tt.whalt)
  162. }
  163. }
  164. }
  165. // TestStreamReaderStopOnDial tests a stream reader closes the connection on stop.
  166. func TestStreamReaderStopOnDial(t *testing.T) {
  167. defer testutil.AfterTest(t)
  168. h := http.Header{}
  169. h.Add("X-Server-Version", version.Version)
  170. tr := &respWaitRoundTripper{rrt: &respRoundTripper{code: http.StatusOK, header: h}}
  171. sr := &streamReader{
  172. peerID: types.ID(2),
  173. tr: &Transport{streamRt: tr, ClusterID: types.ID(1)},
  174. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  175. errorc: make(chan error, 1),
  176. typ: streamTypeMessage,
  177. status: newPeerStatus(types.ID(2)),
  178. }
  179. tr.onResp = func() {
  180. // stop() waits for the run() goroutine to exit, but that exit
  181. // needs a response from RoundTrip() first; use goroutine
  182. go sr.stop()
  183. // wait so that stop() is blocked on run() exiting
  184. time.Sleep(10 * time.Millisecond)
  185. // sr.run() completes dialing then begins decoding while stopped
  186. }
  187. sr.start()
  188. select {
  189. case <-sr.done:
  190. case <-time.After(time.Second):
  191. t.Fatal("streamReader did not stop in time")
  192. }
  193. }
  194. type respWaitRoundTripper struct {
  195. rrt *respRoundTripper
  196. onResp func()
  197. }
  198. func (t *respWaitRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  199. resp, err := t.rrt.RoundTrip(req)
  200. resp.Body = newWaitReadCloser()
  201. t.onResp()
  202. return resp, err
  203. }
  204. type waitReadCloser struct{ closec chan struct{} }
  205. func newWaitReadCloser() *waitReadCloser { return &waitReadCloser{make(chan struct{})} }
  206. func (wrc *waitReadCloser) Read(p []byte) (int, error) {
  207. <-wrc.closec
  208. return 0, io.EOF
  209. }
  210. func (wrc *waitReadCloser) Close() error {
  211. close(wrc.closec)
  212. return nil
  213. }
  214. // TestStreamReaderDialDetectUnsupport tests that dial func could find
  215. // out that the stream type is not supported by the remote.
  216. func TestStreamReaderDialDetectUnsupport(t *testing.T) {
  217. for i, typ := range []streamType{streamTypeMsgAppV2, streamTypeMessage} {
  218. // the response from etcd 2.0
  219. tr := &respRoundTripper{
  220. code: http.StatusNotFound,
  221. header: http.Header{},
  222. }
  223. sr := &streamReader{
  224. peerID: types.ID(2),
  225. tr: &Transport{streamRt: tr, ClusterID: types.ID(1)},
  226. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  227. }
  228. _, err := sr.dial(typ)
  229. if err != errUnsupportedStreamType {
  230. t.Errorf("#%d: error = %v, want %v", i, err, errUnsupportedStreamType)
  231. }
  232. }
  233. }
  234. // TestStream tests that streamReader and streamWriter can build stream to
  235. // send messages between each other.
  236. func TestStream(t *testing.T) {
  237. recvc := make(chan raftpb.Message, streamBufSize)
  238. propc := make(chan raftpb.Message, streamBufSize)
  239. msgapp := raftpb.Message{
  240. Type: raftpb.MsgApp,
  241. From: 2,
  242. To: 1,
  243. Term: 1,
  244. LogTerm: 1,
  245. Index: 3,
  246. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  247. }
  248. tests := []struct {
  249. t streamType
  250. m raftpb.Message
  251. wc chan raftpb.Message
  252. }{
  253. {
  254. streamTypeMessage,
  255. raftpb.Message{Type: raftpb.MsgProp, To: 2},
  256. propc,
  257. },
  258. {
  259. streamTypeMessage,
  260. msgapp,
  261. recvc,
  262. },
  263. {
  264. streamTypeMsgAppV2,
  265. msgapp,
  266. recvc,
  267. },
  268. }
  269. for i, tt := range tests {
  270. h := &fakeStreamHandler{t: tt.t}
  271. srv := httptest.NewServer(h)
  272. defer srv.Close()
  273. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  274. defer sw.stop()
  275. h.sw = sw
  276. picker := mustNewURLPicker(t, []string{srv.URL})
  277. tr := &Transport{streamRt: &http.Transport{}, ClusterID: types.ID(1)}
  278. sr := &streamReader{
  279. peerID: types.ID(2),
  280. typ: tt.t,
  281. tr: tr,
  282. picker: picker,
  283. status: newPeerStatus(types.ID(2)),
  284. recvc: recvc,
  285. propc: propc,
  286. }
  287. sr.start()
  288. // wait for stream to work
  289. var writec chan<- raftpb.Message
  290. for {
  291. var ok bool
  292. if writec, ok = sw.writec(); ok {
  293. break
  294. }
  295. time.Sleep(time.Millisecond)
  296. }
  297. writec <- tt.m
  298. var m raftpb.Message
  299. select {
  300. case m = <-tt.wc:
  301. case <-time.After(time.Second):
  302. t.Fatalf("#%d: failed to receive message from the channel", i)
  303. }
  304. if !reflect.DeepEqual(m, tt.m) {
  305. t.Fatalf("#%d: message = %+v, want %+v", i, m, tt.m)
  306. }
  307. sr.stop()
  308. }
  309. }
  310. func TestCheckStreamSupport(t *testing.T) {
  311. tests := []struct {
  312. v *semver.Version
  313. t streamType
  314. w bool
  315. }{
  316. // support
  317. {
  318. semver.Must(semver.NewVersion("2.1.0")),
  319. streamTypeMsgAppV2,
  320. true,
  321. },
  322. // ignore patch
  323. {
  324. semver.Must(semver.NewVersion("2.1.9")),
  325. streamTypeMsgAppV2,
  326. true,
  327. },
  328. // ignore prerelease
  329. {
  330. semver.Must(semver.NewVersion("2.1.0-alpha")),
  331. streamTypeMsgAppV2,
  332. true,
  333. },
  334. }
  335. for i, tt := range tests {
  336. if g := checkStreamSupport(tt.v, tt.t); g != tt.w {
  337. t.Errorf("#%d: check = %v, want %v", i, g, tt.w)
  338. }
  339. }
  340. }
  341. type fakeWriteFlushCloser struct {
  342. mu sync.Mutex
  343. err error
  344. written int
  345. closed chan struct{}
  346. writec chan struct{}
  347. }
  348. func newFakeWriteFlushCloser(err error) *fakeWriteFlushCloser {
  349. return &fakeWriteFlushCloser{
  350. err: err,
  351. closed: make(chan struct{}),
  352. writec: make(chan struct{}, 1),
  353. }
  354. }
  355. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  356. wfc.mu.Lock()
  357. defer wfc.mu.Unlock()
  358. select {
  359. case wfc.writec <- struct{}{}:
  360. default:
  361. }
  362. wfc.written += len(p)
  363. return len(p), wfc.err
  364. }
  365. func (wfc *fakeWriteFlushCloser) Flush() {}
  366. func (wfc *fakeWriteFlushCloser) Close() error {
  367. close(wfc.closed)
  368. return wfc.err
  369. }
  370. func (wfc *fakeWriteFlushCloser) Written() int {
  371. wfc.mu.Lock()
  372. defer wfc.mu.Unlock()
  373. return wfc.written
  374. }
  375. func (wfc *fakeWriteFlushCloser) Closed() bool {
  376. select {
  377. case <-wfc.closed:
  378. return true
  379. default:
  380. return false
  381. }
  382. }
  383. type fakeStreamHandler struct {
  384. t streamType
  385. sw *streamWriter
  386. }
  387. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  388. w.Header().Add("X-Server-Version", version.Version)
  389. w.(http.Flusher).Flush()
  390. c := newCloseNotifier()
  391. h.sw.attach(&outgoingConn{
  392. t: h.t,
  393. Writer: w,
  394. Flusher: w.(http.Flusher),
  395. Closer: c,
  396. })
  397. <-c.closeNotify()
  398. }