stream_test.go 6.7 KB

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