http_test.go 8.3 KB

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