stream_test.go 9.1 KB

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