stream_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. // 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. 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: 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: 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. sr := startStreamReader(&http.Transport{}, picker, tt.t, types.ID(1), types.ID(2), types.ID(1), newPeerStatus(types.ID(1)), recvc, propc, nil)
  237. defer sr.stop()
  238. // wait for stream to work
  239. var writec chan<- raftpb.Message
  240. for {
  241. var ok bool
  242. if writec, ok = sw.writec(); ok {
  243. break
  244. }
  245. time.Sleep(time.Millisecond)
  246. }
  247. writec <- tt.m
  248. var m raftpb.Message
  249. select {
  250. case m = <-tt.wc:
  251. case <-time.After(time.Second):
  252. t.Fatalf("#%d: failed to receive message from the channel", i)
  253. }
  254. if !reflect.DeepEqual(m, tt.m) {
  255. t.Fatalf("#%d: message = %+v, want %+v", i, m, tt.m)
  256. }
  257. }
  258. }
  259. func TestCheckStreamSupport(t *testing.T) {
  260. tests := []struct {
  261. v *semver.Version
  262. t streamType
  263. w bool
  264. }{
  265. // support
  266. {
  267. semver.Must(semver.NewVersion("2.1.0")),
  268. streamTypeMsgAppV2,
  269. true,
  270. },
  271. // ignore patch
  272. {
  273. semver.Must(semver.NewVersion("2.1.9")),
  274. streamTypeMsgAppV2,
  275. true,
  276. },
  277. // ignore prerelease
  278. {
  279. semver.Must(semver.NewVersion("2.1.0-alpha")),
  280. streamTypeMsgAppV2,
  281. true,
  282. },
  283. }
  284. for i, tt := range tests {
  285. if g := checkStreamSupport(tt.v, tt.t); g != tt.w {
  286. t.Errorf("#%d: check = %v, want %v", i, g, tt.w)
  287. }
  288. }
  289. }
  290. type fakeWriteFlushCloser struct {
  291. mu sync.Mutex
  292. err error
  293. written int
  294. closed bool
  295. }
  296. func (wfc *fakeWriteFlushCloser) Write(p []byte) (n int, err error) {
  297. wfc.mu.Lock()
  298. defer wfc.mu.Unlock()
  299. wfc.written += len(p)
  300. return len(p), wfc.err
  301. }
  302. func (wfc *fakeWriteFlushCloser) Flush() {}
  303. func (wfc *fakeWriteFlushCloser) Close() error {
  304. wfc.mu.Lock()
  305. defer wfc.mu.Unlock()
  306. wfc.closed = true
  307. return wfc.err
  308. }
  309. func (wfc *fakeWriteFlushCloser) Written() int {
  310. wfc.mu.Lock()
  311. defer wfc.mu.Unlock()
  312. return wfc.written
  313. }
  314. func (wfc *fakeWriteFlushCloser) Closed() bool {
  315. wfc.mu.Lock()
  316. defer wfc.mu.Unlock()
  317. return wfc.closed
  318. }
  319. type fakeStreamHandler struct {
  320. t streamType
  321. sw *streamWriter
  322. }
  323. func (h *fakeStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  324. w.Header().Add("X-Server-Version", version.Version)
  325. w.(http.Flusher).Flush()
  326. c := newCloseNotifier()
  327. h.sw.attach(&outgoingConn{
  328. t: h.t,
  329. Writer: w,
  330. Flusher: w.(http.Flusher),
  331. Closer: c,
  332. })
  333. <-c.closeNotify()
  334. }