http_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. "bytes"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net/http"
  21. "net/http/httptest"
  22. "net/url"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/coreos/etcd/pkg/pbutil"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. "github.com/coreos/etcd/snap"
  30. "github.com/coreos/etcd/version"
  31. )
  32. func TestServeRaftPrefix(t *testing.T) {
  33. testCases := []struct {
  34. method string
  35. body io.Reader
  36. p Raft
  37. clusterID string
  38. wcode int
  39. }{
  40. {
  41. // bad method
  42. "GET",
  43. bytes.NewReader(
  44. pbutil.MustMarshal(&raftpb.Message{}),
  45. ),
  46. &fakeRaft{},
  47. "0",
  48. http.StatusMethodNotAllowed,
  49. },
  50. {
  51. // bad method
  52. "PUT",
  53. bytes.NewReader(
  54. pbutil.MustMarshal(&raftpb.Message{}),
  55. ),
  56. &fakeRaft{},
  57. "0",
  58. http.StatusMethodNotAllowed,
  59. },
  60. {
  61. // bad method
  62. "DELETE",
  63. bytes.NewReader(
  64. pbutil.MustMarshal(&raftpb.Message{}),
  65. ),
  66. &fakeRaft{},
  67. "0",
  68. http.StatusMethodNotAllowed,
  69. },
  70. {
  71. // bad request body
  72. "POST",
  73. &errReader{},
  74. &fakeRaft{},
  75. "0",
  76. http.StatusBadRequest,
  77. },
  78. {
  79. // bad request protobuf
  80. "POST",
  81. strings.NewReader("malformed garbage"),
  82. &fakeRaft{},
  83. "0",
  84. http.StatusBadRequest,
  85. },
  86. {
  87. // good request, wrong cluster ID
  88. "POST",
  89. bytes.NewReader(
  90. pbutil.MustMarshal(&raftpb.Message{}),
  91. ),
  92. &fakeRaft{},
  93. "1",
  94. http.StatusPreconditionFailed,
  95. },
  96. {
  97. // good request, Processor failure
  98. "POST",
  99. bytes.NewReader(
  100. pbutil.MustMarshal(&raftpb.Message{}),
  101. ),
  102. &fakeRaft{
  103. err: &resWriterToError{code: http.StatusForbidden},
  104. },
  105. "0",
  106. http.StatusForbidden,
  107. },
  108. {
  109. // good request, Processor failure
  110. "POST",
  111. bytes.NewReader(
  112. pbutil.MustMarshal(&raftpb.Message{}),
  113. ),
  114. &fakeRaft{
  115. err: &resWriterToError{code: http.StatusInternalServerError},
  116. },
  117. "0",
  118. http.StatusInternalServerError,
  119. },
  120. {
  121. // good request, Processor failure
  122. "POST",
  123. bytes.NewReader(
  124. pbutil.MustMarshal(&raftpb.Message{}),
  125. ),
  126. &fakeRaft{err: errors.New("blah")},
  127. "0",
  128. http.StatusInternalServerError,
  129. },
  130. {
  131. // good request
  132. "POST",
  133. bytes.NewReader(
  134. pbutil.MustMarshal(&raftpb.Message{}),
  135. ),
  136. &fakeRaft{},
  137. "0",
  138. http.StatusNoContent,
  139. },
  140. }
  141. for i, tt := range testCases {
  142. req, err := http.NewRequest(tt.method, "foo", tt.body)
  143. if err != nil {
  144. t.Fatalf("#%d: could not create request: %#v", i, err)
  145. }
  146. req.Header.Set("X-Etcd-Cluster-ID", tt.clusterID)
  147. req.Header.Set("X-Server-Version", version.Version)
  148. rw := httptest.NewRecorder()
  149. h := newPipelineHandler(NewNopTransporter(), tt.p, types.ID(0))
  150. // goroutine because the handler panics to disconnect on raft error
  151. donec := make(chan struct{})
  152. go func() {
  153. defer func() {
  154. recover()
  155. close(donec)
  156. }()
  157. h.ServeHTTP(rw, req)
  158. }()
  159. <-donec
  160. if rw.Code != tt.wcode {
  161. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  162. }
  163. }
  164. }
  165. func TestServeRaftStreamPrefix(t *testing.T) {
  166. tests := []struct {
  167. path string
  168. wtype streamType
  169. }{
  170. {
  171. RaftStreamPrefix + "/message/1",
  172. streamTypeMessage,
  173. },
  174. {
  175. RaftStreamPrefix + "/msgapp/1",
  176. streamTypeMsgAppV2,
  177. },
  178. }
  179. for i, tt := range tests {
  180. req, err := http.NewRequest("GET", "http://localhost:2380"+tt.path, nil)
  181. if err != nil {
  182. t.Fatalf("#%d: could not create request: %#v", i, err)
  183. }
  184. req.Header.Set("X-Etcd-Cluster-ID", "1")
  185. req.Header.Set("X-Server-Version", version.Version)
  186. req.Header.Set("X-Raft-To", "2")
  187. peer := newFakePeer()
  188. peerGetter := &fakePeerGetter{peers: map[types.ID]Peer{types.ID(1): peer}}
  189. tr := &Transport{}
  190. h := newStreamHandler(tr, peerGetter, &fakeRaft{}, types.ID(2), types.ID(1))
  191. rw := httptest.NewRecorder()
  192. go h.ServeHTTP(rw, req)
  193. var conn *outgoingConn
  194. select {
  195. case conn = <-peer.connc:
  196. case <-time.After(time.Second):
  197. t.Fatalf("#%d: failed to attach outgoingConn", i)
  198. }
  199. if g := rw.Header().Get("X-Server-Version"); g != version.Version {
  200. t.Errorf("#%d: X-Server-Version = %s, want %s", i, g, version.Version)
  201. }
  202. if conn.t != tt.wtype {
  203. t.Errorf("#%d: type = %s, want %s", i, conn.t, tt.wtype)
  204. }
  205. conn.Close()
  206. }
  207. }
  208. func TestServeRaftStreamPrefixBad(t *testing.T) {
  209. removedID := uint64(5)
  210. tests := []struct {
  211. method string
  212. path string
  213. clusterID string
  214. remote string
  215. wcode int
  216. }{
  217. // bad method
  218. {
  219. "PUT",
  220. RaftStreamPrefix + "/message/1",
  221. "1",
  222. "1",
  223. http.StatusMethodNotAllowed,
  224. },
  225. // bad method
  226. {
  227. "POST",
  228. RaftStreamPrefix + "/message/1",
  229. "1",
  230. "1",
  231. http.StatusMethodNotAllowed,
  232. },
  233. // bad method
  234. {
  235. "DELETE",
  236. RaftStreamPrefix + "/message/1",
  237. "1",
  238. "1",
  239. http.StatusMethodNotAllowed,
  240. },
  241. // bad path
  242. {
  243. "GET",
  244. RaftStreamPrefix + "/strange/1",
  245. "1",
  246. "1",
  247. http.StatusNotFound,
  248. },
  249. // bad path
  250. {
  251. "GET",
  252. RaftStreamPrefix + "/strange",
  253. "1",
  254. "1",
  255. http.StatusNotFound,
  256. },
  257. // non-existent peer
  258. {
  259. "GET",
  260. RaftStreamPrefix + "/message/2",
  261. "1",
  262. "1",
  263. http.StatusNotFound,
  264. },
  265. // removed peer
  266. {
  267. "GET",
  268. RaftStreamPrefix + "/message/" + fmt.Sprint(removedID),
  269. "1",
  270. "1",
  271. http.StatusGone,
  272. },
  273. // wrong cluster ID
  274. {
  275. "GET",
  276. RaftStreamPrefix + "/message/1",
  277. "2",
  278. "1",
  279. http.StatusPreconditionFailed,
  280. },
  281. // wrong remote id
  282. {
  283. "GET",
  284. RaftStreamPrefix + "/message/1",
  285. "1",
  286. "2",
  287. http.StatusPreconditionFailed,
  288. },
  289. }
  290. for i, tt := range tests {
  291. req, err := http.NewRequest(tt.method, "http://localhost:2380"+tt.path, nil)
  292. if err != nil {
  293. t.Fatalf("#%d: could not create request: %#v", i, err)
  294. }
  295. req.Header.Set("X-Etcd-Cluster-ID", tt.clusterID)
  296. req.Header.Set("X-Server-Version", version.Version)
  297. req.Header.Set("X-Raft-To", tt.remote)
  298. rw := httptest.NewRecorder()
  299. tr := &Transport{}
  300. peerGetter := &fakePeerGetter{peers: map[types.ID]Peer{types.ID(1): newFakePeer()}}
  301. r := &fakeRaft{removedID: removedID}
  302. h := newStreamHandler(tr, peerGetter, r, types.ID(1), types.ID(1))
  303. h.ServeHTTP(rw, req)
  304. if rw.Code != tt.wcode {
  305. t.Errorf("#%d: code = %d, want %d", i, rw.Code, tt.wcode)
  306. }
  307. }
  308. }
  309. func TestCloseNotifier(t *testing.T) {
  310. c := newCloseNotifier()
  311. select {
  312. case <-c.closeNotify():
  313. t.Fatalf("received unexpected close notification")
  314. default:
  315. }
  316. c.Close()
  317. select {
  318. case <-c.closeNotify():
  319. default:
  320. t.Fatalf("failed to get close notification")
  321. }
  322. }
  323. // errReader implements io.Reader to facilitate a broken request.
  324. type errReader struct{}
  325. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  326. type resWriterToError struct {
  327. code int
  328. }
  329. func (e *resWriterToError) Error() string { return "" }
  330. func (e *resWriterToError) WriteTo(w http.ResponseWriter) { w.WriteHeader(e.code) }
  331. type fakePeerGetter struct {
  332. peers map[types.ID]Peer
  333. }
  334. func (pg *fakePeerGetter) Get(id types.ID) Peer { return pg.peers[id] }
  335. type fakePeer struct {
  336. msgs []raftpb.Message
  337. snapMsgs []snap.Message
  338. peerURLs types.URLs
  339. connc chan *outgoingConn
  340. paused bool
  341. }
  342. func newFakePeer() *fakePeer {
  343. fakeURL, _ := url.Parse("http://localhost")
  344. return &fakePeer{
  345. connc: make(chan *outgoingConn, 1),
  346. peerURLs: types.URLs{*fakeURL},
  347. }
  348. }
  349. func (pr *fakePeer) send(m raftpb.Message) {
  350. if pr.paused {
  351. return
  352. }
  353. pr.msgs = append(pr.msgs, m)
  354. }
  355. func (pr *fakePeer) sendSnap(m snap.Message) {
  356. if pr.paused {
  357. return
  358. }
  359. pr.snapMsgs = append(pr.snapMsgs, m)
  360. }
  361. func (pr *fakePeer) update(urls types.URLs) { pr.peerURLs = urls }
  362. func (pr *fakePeer) attachOutgoingConn(conn *outgoingConn) { pr.connc <- conn }
  363. func (pr *fakePeer) activeSince() time.Time { return time.Time{} }
  364. func (pr *fakePeer) stop() {}
  365. func (pr *fakePeer) Pause() { pr.paused = true }
  366. func (pr *fakePeer) Resume() { pr.paused = false }