http_test.go 7.7 KB

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