stream_test.go 12 KB

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