stream_test.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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:2380"}),
  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:2380" + 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. whalt bool
  115. }{
  116. {0, errors.New("blah"), false, false},
  117. {http.StatusOK, nil, true, false},
  118. {http.StatusMethodNotAllowed, nil, false, false},
  119. {http.StatusNotFound, nil, false, false},
  120. {http.StatusPreconditionFailed, nil, false, false},
  121. {http.StatusGone, nil, false, true},
  122. }
  123. for i, tt := range tests {
  124. tr := newRespRoundTripper(tt.code, tt.err)
  125. sr := &streamReader{
  126. tr: tr,
  127. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  128. t: streamTypeMessage,
  129. from: types.ID(1),
  130. to: types.ID(2),
  131. cid: types.ID(1),
  132. errorc: make(chan error, 1),
  133. }
  134. _, err := sr.dial()
  135. if ok := err == nil; ok != tt.wok {
  136. t.Errorf("#%d: ok = %v, want %v", i, ok, tt.wok)
  137. }
  138. if halt := len(sr.errorc) > 0; halt != tt.whalt {
  139. t.Errorf("#%d: halt = %v, want %v", i, halt, tt.whalt)
  140. }
  141. }
  142. }
  143. // TestStream tests that streamReader and streamWriter can build stream to
  144. // send messages between each other.
  145. func TestStream(t *testing.T) {
  146. recvc := make(chan raftpb.Message)
  147. propc := make(chan raftpb.Message)
  148. msgapp := raftpb.Message{
  149. Type: raftpb.MsgApp,
  150. From: 2,
  151. To: 1,
  152. Term: 1,
  153. LogTerm: 1,
  154. Index: 3,
  155. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  156. }
  157. tests := []struct {
  158. t streamType
  159. term uint64
  160. m raftpb.Message
  161. wc chan raftpb.Message
  162. }{
  163. {
  164. streamTypeMessage,
  165. 0,
  166. raftpb.Message{Type: raftpb.MsgProp, To: 2},
  167. propc,
  168. },
  169. {
  170. streamTypeMessage,
  171. 0,
  172. msgapp,
  173. recvc,
  174. },
  175. {
  176. streamTypeMsgApp,
  177. 1,
  178. msgapp,
  179. recvc,
  180. },
  181. {
  182. streamTypeMsgAppV2,
  183. 0,
  184. msgapp,
  185. recvc,
  186. },
  187. }
  188. for i, tt := range tests {
  189. h := &fakeStreamHandler{t: tt.t}
  190. srv := httptest.NewServer(h)
  191. defer srv.Close()
  192. sw := startStreamWriter(types.ID(1), &stats.FollowerStats{}, &fakeRaft{})
  193. defer sw.stop()
  194. h.sw = sw
  195. picker := mustNewURLPicker(t, []string{srv.URL})
  196. sr := startStreamReader(&http.Transport{}, picker, tt.t, types.ID(1), types.ID(2), types.ID(1), recvc, propc, nil)
  197. defer sr.stop()
  198. if tt.t == streamTypeMsgApp {
  199. sr.updateMsgAppTerm(tt.term)
  200. }
  201. // wait for stream to work
  202. var writec chan<- raftpb.Message
  203. for {
  204. var ok bool
  205. if writec, ok = sw.writec(); ok {
  206. break
  207. }
  208. time.Sleep(time.Millisecond)
  209. }
  210. writec <- tt.m
  211. var m raftpb.Message
  212. select {
  213. case m = <-tt.wc:
  214. case <-time.After(time.Second):
  215. t.Errorf("#%d: failed to receive message from the channel", i)
  216. }
  217. if !reflect.DeepEqual(m, tt.m) {
  218. t.Errorf("#%d: message = %+v, want %+v", i, m, tt.m)
  219. }
  220. }
  221. }
  222. type fakeWriteFlushCloser struct {
  223. err error
  224. written int
  225. closed bool
  226. }
  227. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  228. wfc.written += len(p)
  229. return len(p), wfc.err
  230. }
  231. func (wfc *fakeWriteFlushCloser) Flush() {}
  232. func (wfc *fakeWriteFlushCloser) Close() error {
  233. wfc.closed = true
  234. return wfc.err
  235. }
  236. type fakeStreamHandler struct {
  237. t streamType
  238. sw *streamWriter
  239. }
  240. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  241. w.(http.Flusher).Flush()
  242. c := newCloseNotifier()
  243. h.sw.attach(&outgoingConn{
  244. t: h.t,
  245. termStr: r.Header.Get("X-Raft-Term"),
  246. Writer: w,
  247. Flusher: w.(http.Flusher),
  248. Closer: c,
  249. })
  250. <-c.closeNotify()
  251. }