stream_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
  11. "github.com/coreos/etcd/etcdserver/stats"
  12. "github.com/coreos/etcd/pkg/testutil"
  13. "github.com/coreos/etcd/pkg/types"
  14. "github.com/coreos/etcd/raft/raftpb"
  15. "github.com/coreos/etcd/version"
  16. )
  17. // TestStreamWriterAttachOutgoingConn tests that outgoingConn can be attached
  18. // to streamWriter. After that, streamWriter can use it to send messages
  19. // continuously, and closes it when stopped.
  20. func TestStreamWriterAttachOutgoingConn(t *testing.T) {
  21. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  22. // the expected initial state of streamWrite is not working
  23. if _, ok := sw.writec(); ok != false {
  24. t.Errorf("initial working status = %v, want false", ok)
  25. }
  26. // repeatitive tests to ensure it can use latest connection
  27. var wfc *fakeWriteFlushCloser
  28. for i := 0; i < 3; i++ {
  29. prevwfc := wfc
  30. wfc = &fakeWriteFlushCloser{}
  31. sw.attach(&outgoingConn{t: streamTypeMessage, Writer: wfc, Flusher: wfc, Closer: wfc})
  32. testutil.WaitSchedule()
  33. // previous attached connection should be closed
  34. if prevwfc != nil && prevwfc.closed != true {
  35. t.Errorf("#%d: close of previous connection = %v, want true", i, prevwfc.closed)
  36. }
  37. // starts working
  38. if _, ok := sw.writec(); ok != true {
  39. t.Errorf("#%d: working status = %v, want true", i, ok)
  40. }
  41. sw.msgc <- raftpb.Message{}
  42. testutil.WaitSchedule()
  43. // still working
  44. if _, ok := sw.writec(); ok != true {
  45. t.Errorf("#%d: working status = %v, want true", i, ok)
  46. }
  47. if wfc.written == 0 {
  48. t.Errorf("#%d: failed to write to the underlying connection", i)
  49. }
  50. }
  51. sw.stop()
  52. // no longer in working status now
  53. if _, ok := sw.writec(); ok != false {
  54. t.Errorf("working status after stop = %v, want false", ok)
  55. }
  56. if wfc.closed != true {
  57. t.Errorf("failed to close the underlying connection")
  58. }
  59. }
  60. // TestStreamWriterAttachBadOutgoingConn tests that streamWriter with bad
  61. // outgoingConn will close the outgoingConn and fall back to non-working status.
  62. func TestStreamWriterAttachBadOutgoingConn(t *testing.T) {
  63. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  64. defer sw.stop()
  65. wfc := &fakeWriteFlushCloser{err: errors.New("blah")}
  66. sw.attach(&outgoingConn{t: streamTypeMessage, Writer: wfc, Flusher: wfc, Closer: wfc})
  67. sw.msgc <- raftpb.Message{}
  68. testutil.WaitSchedule()
  69. // no longer working
  70. if _, ok := sw.writec(); ok != false {
  71. t.Errorf("working = %v, want false", ok)
  72. }
  73. if wfc.closed != true {
  74. t.Errorf("failed to close the underlying connection")
  75. }
  76. }
  77. func TestStreamReaderDialRequest(t *testing.T) {
  78. for i, tt := range []streamType{streamTypeMsgApp, streamTypeMessage, streamTypeMsgAppV2} {
  79. tr := &roundTripperRecorder{}
  80. sr := &streamReader{
  81. tr: tr,
  82. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  83. local: types.ID(1),
  84. remote: types.ID(2),
  85. cid: types.ID(1),
  86. msgAppTerm: 1,
  87. }
  88. sr.dial(tt)
  89. req := tr.Request()
  90. wurl := fmt.Sprintf("http://localhost:2380" + tt.endpoint() + "/1")
  91. if req.URL.String() != wurl {
  92. t.Errorf("#%d: url = %s, want %s", i, req.URL.String(), wurl)
  93. }
  94. if w := "GET"; req.Method != w {
  95. t.Errorf("#%d: method = %s, want %s", i, req.Method, w)
  96. }
  97. if g := req.Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  98. t.Errorf("#%d: header X-Etcd-Cluster-ID = %s, want 1", i, g)
  99. }
  100. if g := req.Header.Get("X-Raft-To"); g != "2" {
  101. t.Errorf("#%d: header X-Raft-To = %s, want 2", i, g)
  102. }
  103. if g := req.Header.Get("X-Raft-Term"); tt == streamTypeMsgApp && g != "1" {
  104. t.Errorf("#%d: header X-Raft-Term = %s, want 1", i, g)
  105. }
  106. }
  107. }
  108. // TestStreamReaderDialResult tests the result of the dial func call meets the
  109. // HTTP response received.
  110. func TestStreamReaderDialResult(t *testing.T) {
  111. tests := []struct {
  112. code int
  113. err error
  114. wok bool
  115. whalt bool
  116. }{
  117. {0, errors.New("blah"), false, false},
  118. {http.StatusOK, nil, true, false},
  119. {http.StatusMethodNotAllowed, nil, false, false},
  120. {http.StatusNotFound, nil, false, false},
  121. {http.StatusPreconditionFailed, nil, false, false},
  122. {http.StatusGone, nil, false, true},
  123. }
  124. for i, tt := range tests {
  125. h := http.Header{}
  126. h.Add("X-Server-Version", version.Version)
  127. tr := &respRoundTripper{
  128. code: tt.code,
  129. header: h,
  130. err: tt.err,
  131. }
  132. sr := &streamReader{
  133. tr: tr,
  134. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  135. local: types.ID(1),
  136. remote: types.ID(2),
  137. cid: types.ID(1),
  138. errorc: make(chan error, 1),
  139. }
  140. _, err := sr.dial(streamTypeMessage)
  141. if ok := err == nil; ok != tt.wok {
  142. t.Errorf("#%d: ok = %v, want %v", i, ok, tt.wok)
  143. }
  144. if halt := len(sr.errorc) > 0; halt != tt.whalt {
  145. t.Errorf("#%d: halt = %v, want %v", i, halt, tt.whalt)
  146. }
  147. }
  148. }
  149. func TestStreamReaderUpdateMsgAppTerm(t *testing.T) {
  150. term := uint64(2)
  151. tests := []struct {
  152. term uint64
  153. typ streamType
  154. wterm uint64
  155. wclose bool
  156. }{
  157. // lower term
  158. {1, streamTypeMsgApp, 2, false},
  159. // unchanged term
  160. {2, streamTypeMsgApp, 2, false},
  161. // higher term
  162. {3, streamTypeMessage, 3, false},
  163. {3, streamTypeMsgAppV2, 3, false},
  164. // higher term, reset closer
  165. {3, streamTypeMsgApp, 3, true},
  166. }
  167. for i, tt := range tests {
  168. closer := &fakeWriteFlushCloser{}
  169. cr := &streamReader{
  170. msgAppTerm: term,
  171. t: tt.typ,
  172. closer: closer,
  173. }
  174. cr.updateMsgAppTerm(tt.term)
  175. if cr.msgAppTerm != tt.wterm {
  176. t.Errorf("#%d: term = %d, want %d", i, cr.msgAppTerm, tt.wterm)
  177. }
  178. if closer.closed != tt.wclose {
  179. t.Errorf("#%d: closed = %v, want %v", i, closer.closed, tt.wclose)
  180. }
  181. }
  182. }
  183. // TestStreamReaderDialDetectUnsupport tests that dial func could find
  184. // out that the stream type is not supported by the remote.
  185. func TestStreamReaderDialDetectUnsupport(t *testing.T) {
  186. for i, typ := range []streamType{streamTypeMsgAppV2, streamTypeMessage} {
  187. // the response from etcd 2.0
  188. tr := &respRoundTripper{
  189. code: http.StatusNotFound,
  190. header: http.Header{},
  191. }
  192. sr := &streamReader{
  193. tr: tr,
  194. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  195. local: types.ID(1),
  196. remote: types.ID(2),
  197. cid: types.ID(1),
  198. }
  199. _, err := sr.dial(typ)
  200. if err != errUnsupportedStreamType {
  201. t.Errorf("#%d: error = %v, want %v", i, err, errUnsupportedStreamType)
  202. }
  203. }
  204. }
  205. // TestStream tests that streamReader and streamWriter can build stream to
  206. // send messages between each other.
  207. func TestStream(t *testing.T) {
  208. recvc := make(chan raftpb.Message, streamBufSize)
  209. propc := make(chan raftpb.Message, streamBufSize)
  210. msgapp := raftpb.Message{
  211. Type: raftpb.MsgApp,
  212. From: 2,
  213. To: 1,
  214. Term: 1,
  215. LogTerm: 1,
  216. Index: 3,
  217. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  218. }
  219. tests := []struct {
  220. t streamType
  221. term uint64
  222. m raftpb.Message
  223. wc chan raftpb.Message
  224. }{
  225. {
  226. streamTypeMessage,
  227. 0,
  228. raftpb.Message{Type: raftpb.MsgProp, To: 2},
  229. propc,
  230. },
  231. {
  232. streamTypeMessage,
  233. 0,
  234. msgapp,
  235. recvc,
  236. },
  237. {
  238. streamTypeMsgApp,
  239. 1,
  240. msgapp,
  241. recvc,
  242. },
  243. {
  244. streamTypeMsgAppV2,
  245. 0,
  246. msgapp,
  247. recvc,
  248. },
  249. }
  250. for i, tt := range tests {
  251. h := &fakeStreamHandler{t: tt.t}
  252. srv := httptest.NewServer(h)
  253. defer srv.Close()
  254. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  255. defer sw.stop()
  256. h.sw = sw
  257. picker := mustNewURLPicker(t, []string{srv.URL})
  258. sr := startStreamReader(&http.Transport{}, picker, tt.t, types.ID(1), types.ID(2), types.ID(1), newPeerStatus(types.ID(1)), recvc, propc, nil, tt.term)
  259. defer sr.stop()
  260. // wait for stream to work
  261. var writec chan<- raftpb.Message
  262. for {
  263. var ok bool
  264. if writec, ok = sw.writec(); ok {
  265. break
  266. }
  267. time.Sleep(time.Millisecond)
  268. }
  269. writec <- tt.m
  270. var m raftpb.Message
  271. select {
  272. case m = <-tt.wc:
  273. case <-time.After(time.Second):
  274. t.Fatalf("#%d: failed to receive message from the channel", i)
  275. }
  276. if !reflect.DeepEqual(m, tt.m) {
  277. t.Fatalf("#%d: message = %+v, want %+v", i, m, tt.m)
  278. }
  279. }
  280. }
  281. func TestCheckStreamSupport(t *testing.T) {
  282. tests := []struct {
  283. v *semver.Version
  284. t streamType
  285. w bool
  286. }{
  287. // support
  288. {
  289. semver.Must(semver.NewVersion("2.0.0")),
  290. streamTypeMsgApp,
  291. true,
  292. },
  293. // ignore patch
  294. {
  295. semver.Must(semver.NewVersion("2.0.9")),
  296. streamTypeMsgApp,
  297. true,
  298. },
  299. // ignore prerelease
  300. {
  301. semver.Must(semver.NewVersion("2.0.0-alpha")),
  302. streamTypeMsgApp,
  303. true,
  304. },
  305. // not support
  306. {
  307. semver.Must(semver.NewVersion("2.0.0")),
  308. streamTypeMsgAppV2,
  309. false,
  310. },
  311. }
  312. for i, tt := range tests {
  313. if g := checkStreamSupport(tt.v, tt.t); g != tt.w {
  314. t.Errorf("#%d: check = %v, want %v", i, g, tt.w)
  315. }
  316. }
  317. }
  318. type fakeWriteFlushCloser struct {
  319. err error
  320. written int
  321. closed bool
  322. }
  323. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  324. wfc.written += len(p)
  325. return len(p), wfc.err
  326. }
  327. func (wfc *fakeWriteFlushCloser) Flush() {}
  328. func (wfc *fakeWriteFlushCloser) Close() error {
  329. wfc.closed = true
  330. return wfc.err
  331. }
  332. type fakeStreamHandler struct {
  333. t streamType
  334. sw *streamWriter
  335. }
  336. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  337. w.Header().Add("X-Server-Version", version.Version)
  338. w.(http.Flusher).Flush()
  339. c := newCloseNotifier()
  340. h.sw.attach(&outgoingConn{
  341. t: h.t,
  342. termStr: r.Header.Get("X-Raft-Term"),
  343. Writer: w,
  344. Flusher: w.(http.Flusher),
  345. Closer: c,
  346. })
  347. <-c.closeNotify()
  348. }