http_test.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. "io"
  19. "net/http"
  20. "net/http/httptest"
  21. "strings"
  22. "testing"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. "github.com/coreos/etcd/pkg/pbutil"
  26. "github.com/coreos/etcd/pkg/types"
  27. "github.com/coreos/etcd/raft"
  28. "github.com/coreos/etcd/raft/raftpb"
  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. &nopProcessor{},
  45. "0",
  46. http.StatusMethodNotAllowed,
  47. },
  48. {
  49. // bad method
  50. "PUT",
  51. bytes.NewReader(
  52. pbutil.MustMarshal(&raftpb.Message{}),
  53. ),
  54. &nopProcessor{},
  55. "0",
  56. http.StatusMethodNotAllowed,
  57. },
  58. {
  59. // bad method
  60. "DELETE",
  61. bytes.NewReader(
  62. pbutil.MustMarshal(&raftpb.Message{}),
  63. ),
  64. &nopProcessor{},
  65. "0",
  66. http.StatusMethodNotAllowed,
  67. },
  68. {
  69. // bad request body
  70. "POST",
  71. &errReader{},
  72. &nopProcessor{},
  73. "0",
  74. http.StatusBadRequest,
  75. },
  76. {
  77. // bad request protobuf
  78. "POST",
  79. strings.NewReader("malformed garbage"),
  80. &nopProcessor{},
  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. &nopProcessor{},
  91. "1",
  92. http.StatusPreconditionFailed,
  93. },
  94. {
  95. // good request, Processor failure
  96. "POST",
  97. bytes.NewReader(
  98. pbutil.MustMarshal(&raftpb.Message{}),
  99. ),
  100. &errProcessor{
  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. &errProcessor{
  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. &errProcessor{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. &nopProcessor{},
  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. streamTypeMsgApp,
  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:7001"+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, 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 conn.t != tt.wtype {
  193. t.Errorf("$%d: type = %s, want %s", i, conn.t, tt.wtype)
  194. }
  195. if conn.termStr != wterm {
  196. t.Errorf("$%d: term = %s, want %s", i, conn.termStr, wterm)
  197. }
  198. conn.Close()
  199. }
  200. }
  201. func TestServeRaftStreamPrefixBad(t *testing.T) {
  202. tests := []struct {
  203. method string
  204. path string
  205. clusterID string
  206. remote string
  207. wcode int
  208. }{
  209. // bad method
  210. {
  211. "PUT",
  212. RaftStreamPrefix + "/message/1",
  213. "1",
  214. "1",
  215. http.StatusMethodNotAllowed,
  216. },
  217. // bad method
  218. {
  219. "POST",
  220. RaftStreamPrefix + "/message/1",
  221. "1",
  222. "1",
  223. http.StatusMethodNotAllowed,
  224. },
  225. // bad method
  226. {
  227. "DELETE",
  228. RaftStreamPrefix + "/message/1",
  229. "1",
  230. "1",
  231. http.StatusMethodNotAllowed,
  232. },
  233. // bad path
  234. {
  235. "GET",
  236. RaftStreamPrefix + "/strange/1",
  237. "1",
  238. "1",
  239. http.StatusNotFound,
  240. },
  241. // bad path
  242. {
  243. "GET",
  244. RaftStreamPrefix + "/strange",
  245. "1",
  246. "1",
  247. http.StatusNotFound,
  248. },
  249. // non-existant peer
  250. {
  251. "GET",
  252. RaftStreamPrefix + "/message/2",
  253. "1",
  254. "1",
  255. http.StatusNotFound,
  256. },
  257. // wrong cluster ID
  258. {
  259. "GET",
  260. RaftStreamPrefix + "/message/1",
  261. "2",
  262. "1",
  263. http.StatusPreconditionFailed,
  264. },
  265. // wrong remote id
  266. {
  267. "GET",
  268. RaftStreamPrefix + "/message/1",
  269. "1",
  270. "2",
  271. http.StatusPreconditionFailed,
  272. },
  273. }
  274. for i, tt := range tests {
  275. req, err := http.NewRequest(tt.method, "http://localhost:7001"+tt.path, nil)
  276. if err != nil {
  277. t.Fatalf("#%d: could not create request: %#v", i, err)
  278. }
  279. req.Header.Set("X-Etcd-Cluster-ID", tt.clusterID)
  280. req.Header.Set("X-Raft-To", tt.remote)
  281. rw := httptest.NewRecorder()
  282. peerGetter := &fakePeerGetter{peers: map[types.ID]Peer{types.ID(1): newFakePeer()}}
  283. h := newStreamHandler(peerGetter, types.ID(1), types.ID(1))
  284. h.ServeHTTP(rw, req)
  285. if rw.Code != tt.wcode {
  286. t.Errorf("#%d: code = %d, want %d", i, rw.Code, tt.wcode)
  287. }
  288. }
  289. }
  290. func TestCloseNotifier(t *testing.T) {
  291. c := newCloseNotifier()
  292. select {
  293. case <-c.closeNotify():
  294. t.Fatalf("received unexpected close notification")
  295. default:
  296. }
  297. c.Close()
  298. select {
  299. case <-c.closeNotify():
  300. default:
  301. t.Fatalf("failed to get close notification")
  302. }
  303. }
  304. // errReader implements io.Reader to facilitate a broken request.
  305. type errReader struct{}
  306. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  307. type nopProcessor struct{}
  308. func (p *nopProcessor) Process(ctx context.Context, m raftpb.Message) error { return nil }
  309. func (p *nopProcessor) ReportUnreachable(id uint64) {}
  310. func (p *nopProcessor) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  311. type errProcessor struct {
  312. err error
  313. }
  314. func (p *errProcessor) Process(ctx context.Context, m raftpb.Message) error { return p.err }
  315. func (p *errProcessor) ReportUnreachable(id uint64) {}
  316. func (p *errProcessor) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  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. u string
  329. connc chan *outgoingConn
  330. }
  331. func newFakePeer() *fakePeer {
  332. return &fakePeer{
  333. connc: make(chan *outgoingConn, 1),
  334. }
  335. }
  336. func (pr *fakePeer) Send(m raftpb.Message) { pr.msgs = append(pr.msgs, m) }
  337. func (pr *fakePeer) Update(u string) { pr.u = u }
  338. func (pr *fakePeer) attachOutgoingConn(conn *outgoingConn) { pr.connc <- conn }
  339. func (pr *fakePeer) Stop() {}