stream_test.go 11 KB

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