stream_test.go 9.7 KB

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