stream_test.go 9.5 KB

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