http_test.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. h.ServeHTTP(rw, req)
  151. if rw.Code != tt.wcode {
  152. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  153. }
  154. }
  155. }
  156. func TestServeRaftStreamPrefix(t *testing.T) {
  157. tests := []struct {
  158. path string
  159. wtype streamType
  160. }{
  161. {
  162. RaftStreamPrefix + "/message/1",
  163. streamTypeMessage,
  164. },
  165. {
  166. RaftStreamPrefix + "/msgapp/1",
  167. streamTypeMsgAppV2,
  168. },
  169. }
  170. for i, tt := range tests {
  171. req, err := http.NewRequest("GET", "http://localhost:2380"+tt.path, nil)
  172. if err != nil {
  173. t.Fatalf("#%d: could not create request: %#v", i, err)
  174. }
  175. req.Header.Set("X-Etcd-Cluster-ID", "1")
  176. req.Header.Set("X-Server-Version", version.Version)
  177. req.Header.Set("X-Raft-To", "2")
  178. peer := newFakePeer()
  179. peerGetter := &fakePeerGetter{peers: map[types.ID]Peer{types.ID(1): peer}}
  180. tr := &Transport{}
  181. h := newStreamHandler(tr, peerGetter, &fakeRaft{}, types.ID(2), types.ID(1))
  182. rw := httptest.NewRecorder()
  183. go h.ServeHTTP(rw, req)
  184. var conn *outgoingConn
  185. select {
  186. case conn = <-peer.connc:
  187. case <-time.After(time.Second):
  188. t.Fatalf("#%d: failed to attach outgoingConn", i)
  189. }
  190. if g := rw.Header().Get("X-Server-Version"); g != version.Version {
  191. t.Errorf("#%d: X-Server-Version = %s, want %s", i, g, version.Version)
  192. }
  193. if conn.t != tt.wtype {
  194. t.Errorf("#%d: type = %s, want %s", i, conn.t, tt.wtype)
  195. }
  196. conn.Close()
  197. }
  198. }
  199. func TestServeRaftStreamPrefixBad(t *testing.T) {
  200. removedID := uint64(5)
  201. tests := []struct {
  202. method string
  203. path string
  204. clusterID string
  205. remote string
  206. wcode int
  207. }{
  208. // bad method
  209. {
  210. "PUT",
  211. RaftStreamPrefix + "/message/1",
  212. "1",
  213. "1",
  214. http.StatusMethodNotAllowed,
  215. },
  216. // bad method
  217. {
  218. "POST",
  219. RaftStreamPrefix + "/message/1",
  220. "1",
  221. "1",
  222. http.StatusMethodNotAllowed,
  223. },
  224. // bad method
  225. {
  226. "DELETE",
  227. RaftStreamPrefix + "/message/1",
  228. "1",
  229. "1",
  230. http.StatusMethodNotAllowed,
  231. },
  232. // bad path
  233. {
  234. "GET",
  235. RaftStreamPrefix + "/strange/1",
  236. "1",
  237. "1",
  238. http.StatusNotFound,
  239. },
  240. // bad path
  241. {
  242. "GET",
  243. RaftStreamPrefix + "/strange",
  244. "1",
  245. "1",
  246. http.StatusNotFound,
  247. },
  248. // non-existent peer
  249. {
  250. "GET",
  251. RaftStreamPrefix + "/message/2",
  252. "1",
  253. "1",
  254. http.StatusNotFound,
  255. },
  256. // removed peer
  257. {
  258. "GET",
  259. RaftStreamPrefix + "/message/" + fmt.Sprint(removedID),
  260. "1",
  261. "1",
  262. http.StatusGone,
  263. },
  264. // wrong cluster ID
  265. {
  266. "GET",
  267. RaftStreamPrefix + "/message/1",
  268. "2",
  269. "1",
  270. http.StatusPreconditionFailed,
  271. },
  272. // wrong remote id
  273. {
  274. "GET",
  275. RaftStreamPrefix + "/message/1",
  276. "1",
  277. "2",
  278. http.StatusPreconditionFailed,
  279. },
  280. }
  281. for i, tt := range tests {
  282. req, err := http.NewRequest(tt.method, "http://localhost:2380"+tt.path, nil)
  283. if err != nil {
  284. t.Fatalf("#%d: could not create request: %#v", i, err)
  285. }
  286. req.Header.Set("X-Etcd-Cluster-ID", tt.clusterID)
  287. req.Header.Set("X-Server-Version", version.Version)
  288. req.Header.Set("X-Raft-To", tt.remote)
  289. rw := httptest.NewRecorder()
  290. tr := &Transport{}
  291. peerGetter := &fakePeerGetter{peers: map[types.ID]Peer{types.ID(1): newFakePeer()}}
  292. r := &fakeRaft{removedID: removedID}
  293. h := newStreamHandler(tr, peerGetter, r, types.ID(1), types.ID(1))
  294. h.ServeHTTP(rw, req)
  295. if rw.Code != tt.wcode {
  296. t.Errorf("#%d: code = %d, want %d", i, rw.Code, tt.wcode)
  297. }
  298. }
  299. }
  300. func TestCloseNotifier(t *testing.T) {
  301. c := newCloseNotifier()
  302. select {
  303. case <-c.closeNotify():
  304. t.Fatalf("received unexpected close notification")
  305. default:
  306. }
  307. c.Close()
  308. select {
  309. case <-c.closeNotify():
  310. default:
  311. t.Fatalf("failed to get close notification")
  312. }
  313. }
  314. // errReader implements io.Reader to facilitate a broken request.
  315. type errReader struct{}
  316. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  317. type resWriterToError struct {
  318. code int
  319. }
  320. func (e *resWriterToError) Error() string { return "" }
  321. func (e *resWriterToError) WriteTo(w http.ResponseWriter) { w.WriteHeader(e.code) }
  322. type fakePeerGetter struct {
  323. peers map[types.ID]Peer
  324. }
  325. func (pg *fakePeerGetter) Get(id types.ID) Peer { return pg.peers[id] }
  326. type fakePeer struct {
  327. msgs []raftpb.Message
  328. snapMsgs []snap.Message
  329. peerURLs types.URLs
  330. connc chan *outgoingConn
  331. }
  332. func newFakePeer() *fakePeer {
  333. fakeURL, _ := url.Parse("http://localhost")
  334. return &fakePeer{
  335. connc: make(chan *outgoingConn, 1),
  336. peerURLs: types.URLs{*fakeURL},
  337. }
  338. }
  339. func (pr *fakePeer) send(m raftpb.Message) { pr.msgs = append(pr.msgs, m) }
  340. func (pr *fakePeer) sendSnap(m snap.Message) { pr.snapMsgs = append(pr.snapMsgs, m) }
  341. func (pr *fakePeer) update(urls types.URLs) { pr.peerURLs = urls }
  342. func (pr *fakePeer) attachOutgoingConn(conn *outgoingConn) { pr.connc <- conn }
  343. func (pr *fakePeer) activeSince() time.Time { return time.Time{} }
  344. func (pr *fakePeer) stop() {}