stream_test.go 10 KB

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