stream_test.go 8.8 KB

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