stream_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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: &Transport{streamRt: tr},
  108. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  109. local: types.ID(1),
  110. remote: types.ID(2),
  111. cid: types.ID(1),
  112. }
  113. sr.dial(tt)
  114. req := tr.Request()
  115. wurl := fmt.Sprintf("http://localhost:2380" + tt.endpoint() + "/1")
  116. if req.URL.String() != wurl {
  117. t.Errorf("#%d: url = %s, want %s", i, req.URL.String(), wurl)
  118. }
  119. if w := "GET"; req.Method != w {
  120. t.Errorf("#%d: method = %s, want %s", i, req.Method, w)
  121. }
  122. if g := req.Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  123. t.Errorf("#%d: header X-Etcd-Cluster-ID = %s, want 1", i, g)
  124. }
  125. if g := req.Header.Get("X-Raft-To"); g != "2" {
  126. t.Errorf("#%d: header X-Raft-To = %s, want 2", i, g)
  127. }
  128. }
  129. }
  130. // TestStreamReaderDialResult tests the result of the dial func call meets the
  131. // HTTP response received.
  132. func TestStreamReaderDialResult(t *testing.T) {
  133. tests := []struct {
  134. code int
  135. err error
  136. wok bool
  137. whalt bool
  138. }{
  139. {0, errors.New("blah"), false, false},
  140. {http.StatusOK, nil, true, false},
  141. {http.StatusMethodNotAllowed, nil, false, false},
  142. {http.StatusNotFound, nil, false, false},
  143. {http.StatusPreconditionFailed, nil, false, false},
  144. {http.StatusGone, nil, false, true},
  145. }
  146. for i, tt := range tests {
  147. h := http.Header{}
  148. h.Add("X-Server-Version", version.Version)
  149. tr := &respRoundTripper{
  150. code: tt.code,
  151. header: h,
  152. err: tt.err,
  153. }
  154. sr := &streamReader{
  155. tr: &Transport{streamRt: tr},
  156. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  157. local: types.ID(1),
  158. remote: types.ID(2),
  159. cid: types.ID(1),
  160. errorc: make(chan error, 1),
  161. }
  162. _, err := sr.dial(streamTypeMessage)
  163. if ok := err == nil; ok != tt.wok {
  164. t.Errorf("#%d: ok = %v, want %v", i, ok, tt.wok)
  165. }
  166. if halt := len(sr.errorc) > 0; halt != tt.whalt {
  167. t.Errorf("#%d: halt = %v, want %v", i, halt, tt.whalt)
  168. }
  169. }
  170. }
  171. // TestStreamReaderDialDetectUnsupport tests that dial func could find
  172. // out that the stream type is not supported by the remote.
  173. func TestStreamReaderDialDetectUnsupport(t *testing.T) {
  174. for i, typ := range []streamType{streamTypeMsgAppV2, streamTypeMessage} {
  175. // the response from etcd 2.0
  176. tr := &respRoundTripper{
  177. code: http.StatusNotFound,
  178. header: http.Header{},
  179. }
  180. sr := &streamReader{
  181. tr: &Transport{streamRt: tr},
  182. picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
  183. local: types.ID(1),
  184. remote: types.ID(2),
  185. cid: types.ID(1),
  186. }
  187. _, err := sr.dial(typ)
  188. if err != errUnsupportedStreamType {
  189. t.Errorf("#%d: error = %v, want %v", i, err, errUnsupportedStreamType)
  190. }
  191. }
  192. }
  193. // TestStream tests that streamReader and streamWriter can build stream to
  194. // send messages between each other.
  195. func TestStream(t *testing.T) {
  196. recvc := make(chan raftpb.Message, streamBufSize)
  197. propc := make(chan raftpb.Message, streamBufSize)
  198. msgapp := raftpb.Message{
  199. Type: raftpb.MsgApp,
  200. From: 2,
  201. To: 1,
  202. Term: 1,
  203. LogTerm: 1,
  204. Index: 3,
  205. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  206. }
  207. tests := []struct {
  208. t streamType
  209. m raftpb.Message
  210. wc chan raftpb.Message
  211. }{
  212. {
  213. streamTypeMessage,
  214. raftpb.Message{Type: raftpb.MsgProp, To: 2},
  215. propc,
  216. },
  217. {
  218. streamTypeMessage,
  219. msgapp,
  220. recvc,
  221. },
  222. {
  223. streamTypeMsgAppV2,
  224. msgapp,
  225. recvc,
  226. },
  227. }
  228. for i, tt := range tests {
  229. h := &fakeStreamHandler{t: tt.t}
  230. srv := httptest.NewServer(h)
  231. defer srv.Close()
  232. sw := startStreamWriter(types.ID(1), newPeerStatus(types.ID(1)), &stats.FollowerStats{}, &fakeRaft{})
  233. defer sw.stop()
  234. h.sw = sw
  235. picker := mustNewURLPicker(t, []string{srv.URL})
  236. tr := &Transport{streamRt: &http.Transport{}}
  237. sr := startStreamReader(tr, picker, tt.t, types.ID(1), types.ID(2), types.ID(1), newPeerStatus(types.ID(1)), recvc, propc, nil)
  238. defer sr.stop()
  239. // wait for stream to work
  240. var writec chan<- raftpb.Message
  241. for {
  242. var ok bool
  243. if writec, ok = sw.writec(); ok {
  244. break
  245. }
  246. time.Sleep(time.Millisecond)
  247. }
  248. writec <- tt.m
  249. var m raftpb.Message
  250. select {
  251. case m = <-tt.wc:
  252. case <-time.After(time.Second):
  253. t.Fatalf("#%d: failed to receive message from the channel", i)
  254. }
  255. if !reflect.DeepEqual(m, tt.m) {
  256. t.Fatalf("#%d: message = %+v, want %+v", i, m, tt.m)
  257. }
  258. }
  259. }
  260. func TestCheckStreamSupport(t *testing.T) {
  261. tests := []struct {
  262. v *semver.Version
  263. t streamType
  264. w bool
  265. }{
  266. // support
  267. {
  268. semver.Must(semver.NewVersion("2.1.0")),
  269. streamTypeMsgAppV2,
  270. true,
  271. },
  272. // ignore patch
  273. {
  274. semver.Must(semver.NewVersion("2.1.9")),
  275. streamTypeMsgAppV2,
  276. true,
  277. },
  278. // ignore prerelease
  279. {
  280. semver.Must(semver.NewVersion("2.1.0-alpha")),
  281. streamTypeMsgAppV2,
  282. true,
  283. },
  284. }
  285. for i, tt := range tests {
  286. if g := checkStreamSupport(tt.v, tt.t); g != tt.w {
  287. t.Errorf("#%d: check = %v, want %v", i, g, tt.w)
  288. }
  289. }
  290. }
  291. type fakeWriteFlushCloser struct {
  292. mu sync.Mutex
  293. err error
  294. written int
  295. closed bool
  296. }
  297. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  298. wfc.mu.Lock()
  299. defer wfc.mu.Unlock()
  300. wfc.written += len(p)
  301. return len(p), wfc.err
  302. }
  303. func (wfc *fakeWriteFlushCloser) Flush() {}
  304. func (wfc *fakeWriteFlushCloser) Close() error {
  305. wfc.mu.Lock()
  306. defer wfc.mu.Unlock()
  307. wfc.closed = true
  308. return wfc.err
  309. }
  310. func (wfc *fakeWriteFlushCloser) Written() int {
  311. wfc.mu.Lock()
  312. defer wfc.mu.Unlock()
  313. return wfc.written
  314. }
  315. func (wfc *fakeWriteFlushCloser) Closed() bool {
  316. wfc.mu.Lock()
  317. defer wfc.mu.Unlock()
  318. return wfc.closed
  319. }
  320. type fakeStreamHandler struct {
  321. t streamType
  322. sw *streamWriter
  323. }
  324. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  325. w.Header().Add("X-Server-Version", version.Version)
  326. w.(http.Flusher).Flush()
  327. c := newCloseNotifier()
  328. h.sw.attach(&outgoingConn{
  329. t: h.t,
  330. Writer: w,
  331. Flusher: w.(http.Flusher),
  332. Closer: c,
  333. })
  334. <-c.closeNotify()
  335. }