stream_test.go 12 KB

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