stream_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. func TestStreamReaderUpdateMsgAppTerm(t *testing.T) {
  144. term := uint64(2)
  145. tests := []struct {
  146. term uint64
  147. typ streamType
  148. wterm uint64
  149. wclose bool
  150. }{
  151. // lower term
  152. {1, streamTypeMsgApp, 2, false},
  153. // unchanged term
  154. {2, streamTypeMsgApp, 2, false},
  155. // higher term
  156. {3, streamTypeMessage, 3, false},
  157. {3, streamTypeMsgAppV2, 3, false},
  158. // higher term, reset closer
  159. {3, streamTypeMsgApp, 3, true},
  160. }
  161. for i, tt := range tests {
  162. closer := &fakeWriteFlushCloser{}
  163. cr := &streamReader{
  164. msgAppTerm: term,
  165. t: tt.typ,
  166. closer: closer,
  167. }
  168. cr.updateMsgAppTerm(tt.term)
  169. if cr.msgAppTerm != tt.wterm {
  170. t.Errorf("#%d: term = %d, want %d", i, cr.msgAppTerm, tt.wterm)
  171. }
  172. if closer.closed != tt.wclose {
  173. t.Errorf("#%d: closed = %v, want %v", i, closer.closed, tt.wclose)
  174. }
  175. }
  176. }
  177. // TestStream tests that streamReader and streamWriter can build stream to
  178. // send messages between each other.
  179. func TestStream(t *testing.T) {
  180. recvc := make(chan raftpb.Message)
  181. propc := make(chan raftpb.Message)
  182. msgapp := raftpb.Message{
  183. Type: raftpb.MsgApp,
  184. From: 2,
  185. To: 1,
  186. Term: 1,
  187. LogTerm: 1,
  188. Index: 3,
  189. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  190. }
  191. tests := []struct {
  192. t streamType
  193. term uint64
  194. m raftpb.Message
  195. wc chan raftpb.Message
  196. }{
  197. {
  198. streamTypeMessage,
  199. 0,
  200. raftpb.Message{Type: raftpb.MsgProp, To: 2},
  201. propc,
  202. },
  203. {
  204. streamTypeMessage,
  205. 0,
  206. msgapp,
  207. recvc,
  208. },
  209. {
  210. streamTypeMsgApp,
  211. 1,
  212. msgapp,
  213. recvc,
  214. },
  215. {
  216. streamTypeMsgAppV2,
  217. 0,
  218. msgapp,
  219. recvc,
  220. },
  221. }
  222. for i, tt := range tests {
  223. h := &fakeStreamHandler{t: tt.t}
  224. srv := httptest.NewServer(h)
  225. defer srv.Close()
  226. sw := startStreamWriter(types.ID(1), &stats.FollowerStats{}, &fakeRaft{})
  227. defer sw.stop()
  228. h.sw = sw
  229. picker := mustNewURLPicker(t, []string{srv.URL})
  230. sr := startStreamReader(&http.Transport{}, picker, tt.t, types.ID(1), types.ID(2), types.ID(1), recvc, propc, nil)
  231. defer sr.stop()
  232. if tt.t == streamTypeMsgApp {
  233. sr.updateMsgAppTerm(tt.term)
  234. }
  235. // wait for stream to work
  236. var writec chan<- raftpb.Message
  237. for {
  238. var ok bool
  239. if writec, ok = sw.writec(); ok {
  240. break
  241. }
  242. time.Sleep(time.Millisecond)
  243. }
  244. writec <- tt.m
  245. var m raftpb.Message
  246. select {
  247. case m = <-tt.wc:
  248. case <-time.After(time.Second):
  249. t.Errorf("#%d: failed to receive message from the channel", i)
  250. }
  251. if !reflect.DeepEqual(m, tt.m) {
  252. t.Errorf("#%d: message = %+v, want %+v", i, m, tt.m)
  253. }
  254. }
  255. }
  256. type fakeWriteFlushCloser struct {
  257. err error
  258. written int
  259. closed bool
  260. }
  261. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  262. wfc.written += len(p)
  263. return len(p), wfc.err
  264. }
  265. func (wfc *fakeWriteFlushCloser) Flush() {}
  266. func (wfc *fakeWriteFlushCloser) Close() error {
  267. wfc.closed = true
  268. return wfc.err
  269. }
  270. type fakeStreamHandler struct {
  271. t streamType
  272. sw *streamWriter
  273. }
  274. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  275. w.(http.Flusher).Flush()
  276. c := newCloseNotifier()
  277. h.sw.attach(&outgoingConn{
  278. t: h.t,
  279. termStr: r.Header.Get("X-Raft-Term"),
  280. Writer: w,
  281. Flusher: w.(http.Flusher),
  282. Closer: c,
  283. })
  284. <-c.closeNotify()
  285. }