stream_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package rafthttp
  2. import (
  3. "errors"
  4. "net/http"
  5. "net/http/httptest"
  6. "reflect"
  7. "testing"
  8. "time"
  9. "github.com/coreos/etcd/etcdserver/stats"
  10. "github.com/coreos/etcd/pkg/testutil"
  11. "github.com/coreos/etcd/pkg/types"
  12. "github.com/coreos/etcd/raft/raftpb"
  13. )
  14. // TestStreamWriterAttachOutgoingConn tests that outgoingConn can be attached
  15. // to streamWriter. After that, streamWriter can use it to send messages
  16. // continuously, and closes it when stopped.
  17. func TestStreamWriterAttachOutgoingConn(t *testing.T) {
  18. sw := startStreamWriter(types.ID(1), &stats.FollowerStats{}, &fakeRaft{})
  19. // the expected initial state of streamWrite is not working
  20. if _, ok := sw.writec(); ok != false {
  21. t.Errorf("initial working status = %v, want false", ok)
  22. }
  23. // repeatitive tests to ensure it can use latest connection
  24. var wfc *fakeWriteFlushCloser
  25. for i := 0; i < 3; i++ {
  26. prevwfc := wfc
  27. wfc = &fakeWriteFlushCloser{}
  28. sw.attach(&outgoingConn{t: streamTypeMessage, Writer: wfc, Flusher: wfc, Closer: wfc})
  29. testutil.ForceGosched()
  30. // previous attached connection should be closed
  31. if prevwfc != nil && prevwfc.closed != true {
  32. t.Errorf("#%d: close of previous connection = %v, want true", i, prevwfc.closed)
  33. }
  34. // starts working
  35. if _, ok := sw.writec(); ok != true {
  36. t.Errorf("#%d: working status = %v, want true", i, ok)
  37. }
  38. sw.msgc <- raftpb.Message{}
  39. testutil.ForceGosched()
  40. // still working
  41. if _, ok := sw.writec(); ok != true {
  42. t.Errorf("#%d: working status = %v, want true", i, ok)
  43. }
  44. if wfc.written == 0 {
  45. t.Errorf("#%d: failed to write to the underlying connection", i)
  46. }
  47. }
  48. sw.stop()
  49. // no longer in working status now
  50. if _, ok := sw.writec(); ok != false {
  51. t.Errorf("working status after stop = %v, want false", ok)
  52. }
  53. if wfc.closed != true {
  54. t.Errorf("failed to close the underlying connection")
  55. }
  56. }
  57. // TestStreamWriterAttachBadOutgoingConn tests that streamWriter with bad
  58. // outgoingConn will close the outgoingConn and fall back to non-working status.
  59. func TestStreamWriterAttachBadOutgoingConn(t *testing.T) {
  60. sw := startStreamWriter(types.ID(1), &stats.FollowerStats{}, &fakeRaft{})
  61. defer sw.stop()
  62. wfc := &fakeWriteFlushCloser{err: errors.New("blah")}
  63. sw.attach(&outgoingConn{t: streamTypeMessage, Writer: wfc, Flusher: wfc, Closer: wfc})
  64. sw.msgc <- raftpb.Message{}
  65. testutil.ForceGosched()
  66. // no longer working
  67. if _, ok := sw.writec(); ok != false {
  68. t.Errorf("working = %v, want false", ok)
  69. }
  70. if wfc.closed != true {
  71. t.Errorf("failed to close the underlying connection")
  72. }
  73. }
  74. func TestStreamReaderDialRequest(t *testing.T) {
  75. for i, tt := range []streamType{streamTypeMsgApp, streamTypeMessage} {
  76. tr := &roundTripperRecorder{}
  77. sr := &streamReader{
  78. tr: tr,
  79. picker: mustNewURLPicker(t, []string{"http://localhost:7001"}),
  80. t: tt,
  81. from: types.ID(1),
  82. to: types.ID(2),
  83. cid: types.ID(1),
  84. msgAppTerm: 1,
  85. }
  86. sr.dial()
  87. req := tr.Request()
  88. var wurl string
  89. switch tt {
  90. case streamTypeMsgApp:
  91. wurl = "http://localhost:7001/raft/stream/1"
  92. case streamTypeMessage:
  93. wurl = "http://localhost:7001/raft/stream/message/1"
  94. }
  95. if req.URL.String() != wurl {
  96. t.Errorf("#%d: url = %s, want %s", i, req.URL.String(), wurl)
  97. }
  98. if w := "GET"; req.Method != w {
  99. t.Errorf("#%d: method = %s, want %s", i, req.Method, w)
  100. }
  101. if g := req.Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  102. t.Errorf("#%d: header X-Etcd-Cluster-ID = %s, want 1", i, g)
  103. }
  104. if g := req.Header.Get("X-Raft-To"); g != "2" {
  105. t.Errorf("#%d: header X-Raft-To = %s, want 2", i, g)
  106. }
  107. if g := req.Header.Get("X-Raft-Term"); tt == streamTypeMsgApp && g != "1" {
  108. t.Errorf("#%d: header X-Raft-Term = %s, want 1", i, g)
  109. }
  110. }
  111. }
  112. // TestStreamReaderDialResult tests the result of the dial func call meets the
  113. // HTTP response received.
  114. func TestStreamReaderDialResult(t *testing.T) {
  115. tests := []struct {
  116. code int
  117. err error
  118. wok bool
  119. }{
  120. {0, errors.New("blah"), false},
  121. {http.StatusOK, nil, true},
  122. {http.StatusMethodNotAllowed, nil, false},
  123. {http.StatusNotFound, nil, false},
  124. {http.StatusPreconditionFailed, nil, false},
  125. }
  126. for i, tt := range tests {
  127. tr := newRespRoundTripper(tt.code, tt.err)
  128. sr := &streamReader{
  129. tr: tr,
  130. picker: mustNewURLPicker(t, []string{"http://localhost:7001"}),
  131. t: streamTypeMessage,
  132. from: types.ID(1),
  133. to: types.ID(2),
  134. cid: types.ID(1),
  135. }
  136. _, err := sr.dial()
  137. if ok := err == nil; ok != tt.wok {
  138. t.Errorf("#%d: ok = %v, want %v", i, ok, tt.wok)
  139. }
  140. }
  141. }
  142. // TestStream tests that streamReader and streamWriter can build stream to
  143. // send messages between each other.
  144. func TestStream(t *testing.T) {
  145. recvc := make(chan raftpb.Message)
  146. propc := make(chan raftpb.Message)
  147. msgapp := raftpb.Message{
  148. Type: raftpb.MsgApp,
  149. From: 2,
  150. To: 1,
  151. Term: 1,
  152. LogTerm: 1,
  153. Index: 3,
  154. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  155. }
  156. tests := []struct {
  157. t streamType
  158. term uint64
  159. m raftpb.Message
  160. wc chan raftpb.Message
  161. }{
  162. {
  163. streamTypeMessage,
  164. 0,
  165. raftpb.Message{Type: raftpb.MsgProp, To: 2},
  166. propc,
  167. },
  168. {
  169. streamTypeMessage,
  170. 0,
  171. msgapp,
  172. recvc,
  173. },
  174. {
  175. streamTypeMsgApp,
  176. 1,
  177. msgapp,
  178. recvc,
  179. },
  180. }
  181. for i, tt := range tests {
  182. h := &fakeStreamHandler{t: tt.t}
  183. srv := httptest.NewServer(h)
  184. defer srv.Close()
  185. sw := startStreamWriter(types.ID(1), &stats.FollowerStats{}, &fakeRaft{})
  186. defer sw.stop()
  187. h.sw = sw
  188. picker := mustNewURLPicker(t, []string{srv.URL})
  189. sr := startStreamReader(&http.Transport{}, picker, tt.t, types.ID(1), types.ID(2), types.ID(1), recvc, propc)
  190. defer sr.stop()
  191. if tt.t == streamTypeMsgApp {
  192. sr.updateMsgAppTerm(tt.term)
  193. }
  194. // wait for stream to work
  195. var writec chan<- raftpb.Message
  196. for {
  197. var ok bool
  198. if writec, ok = sw.writec(); ok {
  199. break
  200. }
  201. time.Sleep(time.Millisecond)
  202. }
  203. writec <- tt.m
  204. var m raftpb.Message
  205. select {
  206. case m = <-tt.wc:
  207. case <-time.After(time.Second):
  208. t.Errorf("#%d: failed to receive message from the channel", i)
  209. }
  210. if !reflect.DeepEqual(m, tt.m) {
  211. t.Errorf("#%d: message = %+v, want %+v", i, m, tt.m)
  212. }
  213. }
  214. }
  215. type fakeWriteFlushCloser struct {
  216. err error
  217. written int
  218. closed bool
  219. }
  220. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  221. wfc.written += len(p)
  222. return len(p), wfc.err
  223. }
  224. func (wfc *fakeWriteFlushCloser) Flush() {}
  225. func (wfc *fakeWriteFlushCloser) Close() error {
  226. wfc.closed = true
  227. return wfc.err
  228. }
  229. type fakeStreamHandler struct {
  230. t streamType
  231. sw *streamWriter
  232. }
  233. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  234. w.(http.Flusher).Flush()
  235. c := newCloseNotifier()
  236. h.sw.attach(&outgoingConn{
  237. t: h.t,
  238. termStr: r.Header.Get("X-Raft-Term"),
  239. Writer: w,
  240. Flusher: w.(http.Flusher),
  241. Closer: c,
  242. })
  243. <-c.closeNotify()
  244. }