http_test.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. package etcdhttp
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "net/url"
  10. "path"
  11. "reflect"
  12. "strings"
  13. "testing"
  14. "time"
  15. etcdErr "github.com/coreos/etcd/error"
  16. "github.com/coreos/etcd/etcdserver"
  17. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  18. "github.com/coreos/etcd/raft/raftpb"
  19. "github.com/coreos/etcd/store"
  20. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  21. )
  22. func boolp(b bool) *bool { return &b }
  23. func mustNewURL(t *testing.T, s string) *url.URL {
  24. u, err := url.Parse(s)
  25. if err != nil {
  26. t.Fatalf("error creating URL from %q: %v", s, err)
  27. }
  28. return u
  29. }
  30. // mustNewRequest takes a path, appends it to the standard keysPrefix, and constructs
  31. // a GET *http.Request referencing the resulting URL
  32. func mustNewRequest(t *testing.T, p string) *http.Request {
  33. return mustNewMethodRequest(t, "GET", p)
  34. }
  35. func mustNewMethodRequest(t *testing.T, m, p string) *http.Request {
  36. return &http.Request{
  37. Method: m,
  38. URL: mustNewURL(t, path.Join(keysPrefix, p)),
  39. }
  40. }
  41. // mustNewForm takes a set of Values and constructs a PUT *http.Request,
  42. // with a URL constructed from appending the given path to the standard keysPrefix
  43. func mustNewForm(t *testing.T, p string, vals url.Values) *http.Request {
  44. u := mustNewURL(t, path.Join(keysPrefix, p))
  45. req, err := http.NewRequest("PUT", u.String(), strings.NewReader(vals.Encode()))
  46. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  47. if err != nil {
  48. t.Fatalf("error creating new request: %v", err)
  49. }
  50. return req
  51. }
  52. func TestBadParseRequest(t *testing.T) {
  53. tests := []struct {
  54. in *http.Request
  55. wcode int
  56. }{
  57. {
  58. // parseForm failure
  59. &http.Request{
  60. Body: nil,
  61. Method: "PUT",
  62. },
  63. etcdErr.EcodeInvalidForm,
  64. },
  65. {
  66. // bad key prefix
  67. &http.Request{
  68. URL: mustNewURL(t, "/badprefix/"),
  69. },
  70. etcdErr.EcodeInvalidForm,
  71. },
  72. // bad values for prevIndex, waitIndex, ttl
  73. {
  74. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"garbage"}}),
  75. etcdErr.EcodeIndexNaN,
  76. },
  77. {
  78. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"1.5"}}),
  79. etcdErr.EcodeIndexNaN,
  80. },
  81. {
  82. mustNewForm(t, "foo", url.Values{"prevIndex": []string{"-1"}}),
  83. etcdErr.EcodeIndexNaN,
  84. },
  85. {
  86. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"garbage"}}),
  87. etcdErr.EcodeIndexNaN,
  88. },
  89. {
  90. mustNewForm(t, "foo", url.Values{"waitIndex": []string{"??"}}),
  91. etcdErr.EcodeIndexNaN,
  92. },
  93. {
  94. mustNewForm(t, "foo", url.Values{"ttl": []string{"-1"}}),
  95. etcdErr.EcodeTTLNaN,
  96. },
  97. // bad values for recursive, sorted, wait, prevExist, dir, stream
  98. {
  99. mustNewForm(t, "foo", url.Values{"recursive": []string{"hahaha"}}),
  100. etcdErr.EcodeInvalidField,
  101. },
  102. {
  103. mustNewForm(t, "foo", url.Values{"recursive": []string{"1234"}}),
  104. etcdErr.EcodeInvalidField,
  105. },
  106. {
  107. mustNewForm(t, "foo", url.Values{"recursive": []string{"?"}}),
  108. etcdErr.EcodeInvalidField,
  109. },
  110. {
  111. mustNewForm(t, "foo", url.Values{"sorted": []string{"?"}}),
  112. etcdErr.EcodeInvalidField,
  113. },
  114. {
  115. mustNewForm(t, "foo", url.Values{"sorted": []string{"x"}}),
  116. etcdErr.EcodeInvalidField,
  117. },
  118. {
  119. mustNewForm(t, "foo", url.Values{"wait": []string{"?!"}}),
  120. etcdErr.EcodeInvalidField,
  121. },
  122. {
  123. mustNewForm(t, "foo", url.Values{"wait": []string{"yes"}}),
  124. etcdErr.EcodeInvalidField,
  125. },
  126. {
  127. mustNewForm(t, "foo", url.Values{"prevExist": []string{"yes"}}),
  128. etcdErr.EcodeInvalidField,
  129. },
  130. {
  131. mustNewForm(t, "foo", url.Values{"prevExist": []string{"#2"}}),
  132. etcdErr.EcodeInvalidField,
  133. },
  134. {
  135. mustNewForm(t, "foo", url.Values{"dir": []string{"no"}}),
  136. etcdErr.EcodeInvalidField,
  137. },
  138. {
  139. mustNewForm(t, "foo", url.Values{"dir": []string{"file"}}),
  140. etcdErr.EcodeInvalidField,
  141. },
  142. {
  143. mustNewForm(t, "foo", url.Values{"stream": []string{"zzz"}}),
  144. etcdErr.EcodeInvalidField,
  145. },
  146. {
  147. mustNewForm(t, "foo", url.Values{"stream": []string{"something"}}),
  148. etcdErr.EcodeInvalidField,
  149. },
  150. // prevValue cannot be empty
  151. {
  152. mustNewForm(t, "foo", url.Values{"prevValue": []string{""}}),
  153. etcdErr.EcodeInvalidField,
  154. },
  155. // wait is only valid with GET requests
  156. {
  157. mustNewMethodRequest(t, "HEAD", "foo?wait=true"),
  158. etcdErr.EcodeInvalidField,
  159. },
  160. // query values are considered
  161. {
  162. mustNewRequest(t, "foo?prevExist=wrong"),
  163. etcdErr.EcodeInvalidField,
  164. },
  165. {
  166. mustNewRequest(t, "foo?ttl=wrong"),
  167. etcdErr.EcodeTTLNaN,
  168. },
  169. // but body takes precedence if both are specified
  170. {
  171. mustNewForm(
  172. t,
  173. "foo?ttl=12",
  174. url.Values{"ttl": []string{"garbage"}},
  175. ),
  176. etcdErr.EcodeTTLNaN,
  177. },
  178. {
  179. mustNewForm(
  180. t,
  181. "foo?prevExist=false",
  182. url.Values{"prevExist": []string{"yes"}},
  183. ),
  184. etcdErr.EcodeInvalidField,
  185. },
  186. }
  187. for i, tt := range tests {
  188. got, err := parseRequest(tt.in, 1234)
  189. if err == nil {
  190. t.Errorf("#%d: unexpected nil error!", i)
  191. continue
  192. }
  193. ee, ok := err.(*etcdErr.Error)
  194. if !ok {
  195. t.Errorf("#%d: err is not etcd.Error!", i)
  196. continue
  197. }
  198. if ee.ErrorCode != tt.wcode {
  199. t.Errorf("#%d: code=%d, want %v", i, ee.ErrorCode, tt.wcode)
  200. t.Logf("cause: %#v", ee.Cause)
  201. }
  202. if !reflect.DeepEqual(got, etcdserverpb.Request{}) {
  203. t.Errorf("#%d: unexpected non-empty Request: %#v", i, got)
  204. }
  205. }
  206. }
  207. func TestGoodParseRequest(t *testing.T) {
  208. tests := []struct {
  209. in *http.Request
  210. w etcdserverpb.Request
  211. }{
  212. {
  213. // good prefix, all other values default
  214. mustNewRequest(t, "foo"),
  215. etcdserverpb.Request{
  216. Id: 1234,
  217. Method: "GET",
  218. Path: "/foo",
  219. },
  220. },
  221. {
  222. // value specified
  223. mustNewForm(
  224. t,
  225. "foo",
  226. url.Values{"value": []string{"some_value"}},
  227. ),
  228. etcdserverpb.Request{
  229. Id: 1234,
  230. Method: "PUT",
  231. Val: "some_value",
  232. Path: "/foo",
  233. },
  234. },
  235. {
  236. // prevIndex specified
  237. mustNewForm(
  238. t,
  239. "foo",
  240. url.Values{"prevIndex": []string{"98765"}},
  241. ),
  242. etcdserverpb.Request{
  243. Id: 1234,
  244. Method: "PUT",
  245. PrevIndex: 98765,
  246. Path: "/foo",
  247. },
  248. },
  249. {
  250. // recursive specified
  251. mustNewForm(
  252. t,
  253. "foo",
  254. url.Values{"recursive": []string{"true"}},
  255. ),
  256. etcdserverpb.Request{
  257. Id: 1234,
  258. Method: "PUT",
  259. Recursive: true,
  260. Path: "/foo",
  261. },
  262. },
  263. {
  264. // sorted specified
  265. mustNewForm(
  266. t,
  267. "foo",
  268. url.Values{"sorted": []string{"true"}},
  269. ),
  270. etcdserverpb.Request{
  271. Id: 1234,
  272. Method: "PUT",
  273. Sorted: true,
  274. Path: "/foo",
  275. },
  276. },
  277. {
  278. // wait specified
  279. mustNewRequest(t, "foo?wait=true"),
  280. etcdserverpb.Request{
  281. Id: 1234,
  282. Method: "GET",
  283. Wait: true,
  284. Path: "/foo",
  285. },
  286. },
  287. {
  288. // empty TTL specified
  289. mustNewRequest(t, "foo?ttl="),
  290. etcdserverpb.Request{
  291. Id: 1234,
  292. Method: "GET",
  293. Path: "/foo",
  294. Expiration: 0,
  295. },
  296. },
  297. {
  298. // dir specified
  299. mustNewRequest(t, "foo?dir=true"),
  300. etcdserverpb.Request{
  301. Id: 1234,
  302. Method: "GET",
  303. Dir: true,
  304. Path: "/foo",
  305. },
  306. },
  307. {
  308. // dir specified negatively
  309. mustNewRequest(t, "foo?dir=false"),
  310. etcdserverpb.Request{
  311. Id: 1234,
  312. Method: "GET",
  313. Dir: false,
  314. Path: "/foo",
  315. },
  316. },
  317. {
  318. // prevExist should be non-null if specified
  319. mustNewForm(
  320. t,
  321. "foo",
  322. url.Values{"prevExist": []string{"true"}},
  323. ),
  324. etcdserverpb.Request{
  325. Id: 1234,
  326. Method: "PUT",
  327. PrevExist: boolp(true),
  328. Path: "/foo",
  329. },
  330. },
  331. {
  332. // prevExist should be non-null if specified
  333. mustNewForm(
  334. t,
  335. "foo",
  336. url.Values{"prevExist": []string{"false"}},
  337. ),
  338. etcdserverpb.Request{
  339. Id: 1234,
  340. Method: "PUT",
  341. PrevExist: boolp(false),
  342. Path: "/foo",
  343. },
  344. },
  345. // mix various fields
  346. {
  347. mustNewForm(
  348. t,
  349. "foo",
  350. url.Values{
  351. "value": []string{"some value"},
  352. "prevExist": []string{"true"},
  353. "prevValue": []string{"previous value"},
  354. },
  355. ),
  356. etcdserverpb.Request{
  357. Id: 1234,
  358. Method: "PUT",
  359. PrevExist: boolp(true),
  360. PrevValue: "previous value",
  361. Val: "some value",
  362. Path: "/foo",
  363. },
  364. },
  365. // query parameters should be used if given
  366. {
  367. mustNewForm(
  368. t,
  369. "foo?prevValue=woof",
  370. url.Values{},
  371. ),
  372. etcdserverpb.Request{
  373. Id: 1234,
  374. Method: "PUT",
  375. PrevValue: "woof",
  376. Path: "/foo",
  377. },
  378. },
  379. // but form values should take precedence over query parameters
  380. {
  381. mustNewForm(
  382. t,
  383. "foo?prevValue=woof",
  384. url.Values{
  385. "prevValue": []string{"miaow"},
  386. },
  387. ),
  388. etcdserverpb.Request{
  389. Id: 1234,
  390. Method: "PUT",
  391. PrevValue: "miaow",
  392. Path: "/foo",
  393. },
  394. },
  395. }
  396. for i, tt := range tests {
  397. got, err := parseRequest(tt.in, 1234)
  398. if err != nil {
  399. t.Errorf("#%d: err = %v, want %v", i, err, nil)
  400. }
  401. if !reflect.DeepEqual(got, tt.w) {
  402. t.Errorf("#%d: request=%#v, want %#v", i, got, tt.w)
  403. }
  404. }
  405. // Test TTL separately until we don't rely on the time module...
  406. now := time.Now().UnixNano()
  407. req := mustNewForm(t, "foo", url.Values{"ttl": []string{"100"}})
  408. got, err := parseRequest(req, 1234)
  409. if err != nil {
  410. t.Fatalf("err = %v, want nil", err)
  411. }
  412. if got.Expiration <= now {
  413. t.Fatalf("expiration = %v, wanted > %v", got.Expiration, now)
  414. }
  415. // ensure TTL=0 results in an expiration time
  416. req = mustNewForm(t, "foo", url.Values{"ttl": []string{"0"}})
  417. got, err = parseRequest(req, 1234)
  418. if err != nil {
  419. t.Fatalf("err = %v, want nil", err)
  420. }
  421. if got.Expiration <= now {
  422. t.Fatalf("expiration = %v, wanted > %v", got.Expiration, now)
  423. }
  424. }
  425. // eventingWatcher immediately returns a simple event of the given action on its channel
  426. type eventingWatcher struct {
  427. action string
  428. }
  429. func (w *eventingWatcher) EventChan() chan *store.Event {
  430. ch := make(chan *store.Event)
  431. go func() {
  432. ch <- &store.Event{
  433. Action: w.action,
  434. Node: &store.NodeExtern{},
  435. }
  436. }()
  437. return ch
  438. }
  439. func (w *eventingWatcher) Remove() {}
  440. func TestWriteError(t *testing.T) {
  441. // nil error should not panic
  442. rw := httptest.NewRecorder()
  443. writeError(rw, nil)
  444. h := rw.Header()
  445. if len(h) > 0 {
  446. t.Fatalf("unexpected non-empty headers: %#v", h)
  447. }
  448. b := rw.Body.String()
  449. if len(b) > 0 {
  450. t.Fatalf("unexpected non-empty body: %q", b)
  451. }
  452. tests := []struct {
  453. err error
  454. wcode int
  455. wi string
  456. }{
  457. {
  458. etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/foo/bar", 123),
  459. http.StatusNotFound,
  460. "123",
  461. },
  462. {
  463. etcdErr.NewError(etcdErr.EcodeTestFailed, "/foo/bar", 456),
  464. http.StatusPreconditionFailed,
  465. "456",
  466. },
  467. {
  468. err: errors.New("something went wrong"),
  469. wcode: http.StatusInternalServerError,
  470. },
  471. }
  472. for i, tt := range tests {
  473. rw := httptest.NewRecorder()
  474. writeError(rw, tt.err)
  475. if code := rw.Code; code != tt.wcode {
  476. t.Errorf("#%d: code=%d, want %d", i, code, tt.wcode)
  477. }
  478. if idx := rw.Header().Get("X-Etcd-Index"); idx != tt.wi {
  479. t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, idx, tt.wi)
  480. }
  481. }
  482. }
  483. type dummyRaftTimer struct{}
  484. func (drt dummyRaftTimer) Index() int64 { return int64(100) }
  485. func (drt dummyRaftTimer) Term() int64 { return int64(5) }
  486. func TestWriteEvent(t *testing.T) {
  487. // nil event should not panic
  488. rw := httptest.NewRecorder()
  489. writeEvent(rw, nil, dummyRaftTimer{})
  490. h := rw.Header()
  491. if len(h) > 0 {
  492. t.Fatalf("unexpected non-empty headers: %#v", h)
  493. }
  494. b := rw.Body.String()
  495. if len(b) > 0 {
  496. t.Fatalf("unexpected non-empty body: %q", b)
  497. }
  498. tests := []struct {
  499. ev *store.Event
  500. idx string
  501. // TODO(jonboulle): check body as well as just status code
  502. code int
  503. err error
  504. }{
  505. // standard case, standard 200 response
  506. {
  507. &store.Event{
  508. Action: store.Get,
  509. Node: &store.NodeExtern{},
  510. PrevNode: &store.NodeExtern{},
  511. },
  512. "0",
  513. http.StatusOK,
  514. nil,
  515. },
  516. // check new nodes return StatusCreated
  517. {
  518. &store.Event{
  519. Action: store.Create,
  520. Node: &store.NodeExtern{},
  521. PrevNode: &store.NodeExtern{},
  522. },
  523. "0",
  524. http.StatusCreated,
  525. nil,
  526. },
  527. }
  528. for i, tt := range tests {
  529. rw := httptest.NewRecorder()
  530. writeEvent(rw, tt.ev, dummyRaftTimer{})
  531. if gct := rw.Header().Get("Content-Type"); gct != "application/json" {
  532. t.Errorf("case %d: bad Content-Type: got %q, want application/json", i, gct)
  533. }
  534. if gri := rw.Header().Get("X-Raft-Index"); gri != "100" {
  535. t.Errorf("case %d: bad X-Raft-Index header: got %s, want %s", i, gri, "100")
  536. }
  537. if grt := rw.Header().Get("X-Raft-Term"); grt != "5" {
  538. t.Errorf("case %d: bad X-Raft-Term header: got %s, want %s", i, grt, "5")
  539. }
  540. if gei := rw.Header().Get("X-Etcd-Index"); gei != tt.idx {
  541. t.Errorf("case %d: bad X-Etcd-Index header: got %s, want %s", i, gei, tt.idx)
  542. }
  543. if rw.Code != tt.code {
  544. t.Errorf("case %d: bad response code: got %d, want %v", i, rw.Code, tt.code)
  545. }
  546. }
  547. }
  548. type dummyWatcher struct {
  549. echan chan *store.Event
  550. }
  551. func (w *dummyWatcher) EventChan() chan *store.Event {
  552. return w.echan
  553. }
  554. func (w *dummyWatcher) Remove() {}
  555. func TestV2MachinesEndpoint(t *testing.T) {
  556. tests := []struct {
  557. method string
  558. wcode int
  559. }{
  560. {"GET", http.StatusOK},
  561. {"HEAD", http.StatusOK},
  562. {"POST", http.StatusMethodNotAllowed},
  563. }
  564. m := NewClientHandler(nil, Peers{}, time.Hour)
  565. s := httptest.NewServer(m)
  566. defer s.Close()
  567. for _, tt := range tests {
  568. req, err := http.NewRequest(tt.method, s.URL+machinesPrefix, nil)
  569. if err != nil {
  570. t.Fatal(err)
  571. }
  572. resp, err := http.DefaultClient.Do(req)
  573. if err != nil {
  574. t.Fatal(err)
  575. }
  576. if resp.StatusCode != tt.wcode {
  577. t.Errorf("StatusCode = %d, expected %d", resp.StatusCode, tt.wcode)
  578. }
  579. }
  580. }
  581. func TestServeMachines(t *testing.T) {
  582. peers := Peers{}
  583. peers.Set("0xBEEF0=localhost:8080&0xBEEF1=localhost:8081&0xBEEF2=localhost:8082")
  584. writer := httptest.NewRecorder()
  585. req, err := http.NewRequest("GET", "", nil)
  586. if err != nil {
  587. t.Fatal(err)
  588. }
  589. h := &serverHandler{peers: peers}
  590. h.serveMachines(writer, req)
  591. w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
  592. if g := writer.Body.String(); g != w {
  593. t.Errorf("body = %s, want %s", g, w)
  594. }
  595. if writer.Code != http.StatusOK {
  596. t.Errorf("header = %d, want %d", writer.Code, http.StatusOK)
  597. }
  598. }
  599. func TestPeersEndpoints(t *testing.T) {
  600. tests := []struct {
  601. peers Peers
  602. endpoints []string
  603. }{
  604. // single peer with a single address
  605. {
  606. peers: Peers(map[int64][]string{
  607. 1: []string{"192.0.2.1"},
  608. }),
  609. endpoints: []string{"http://192.0.2.1"},
  610. },
  611. // single peer with a single address with a port
  612. {
  613. peers: Peers(map[int64][]string{
  614. 1: []string{"192.0.2.1:8001"},
  615. }),
  616. endpoints: []string{"http://192.0.2.1:8001"},
  617. },
  618. // several peers explicitly unsorted
  619. {
  620. peers: Peers(map[int64][]string{
  621. 2: []string{"192.0.2.3", "192.0.2.4"},
  622. 3: []string{"192.0.2.5", "192.0.2.6"},
  623. 1: []string{"192.0.2.1", "192.0.2.2"},
  624. }),
  625. endpoints: []string{"http://192.0.2.1", "http://192.0.2.2", "http://192.0.2.3", "http://192.0.2.4", "http://192.0.2.5", "http://192.0.2.6"},
  626. },
  627. // no peers
  628. {
  629. peers: Peers(map[int64][]string{}),
  630. endpoints: []string{},
  631. },
  632. // peer with no endpoints
  633. {
  634. peers: Peers(map[int64][]string{
  635. 3: []string{},
  636. }),
  637. endpoints: []string{},
  638. },
  639. }
  640. for i, tt := range tests {
  641. endpoints := tt.peers.Endpoints()
  642. if !reflect.DeepEqual(tt.endpoints, endpoints) {
  643. t.Errorf("#%d: peers.Endpoints() incorrect: want=%#v got=%#v", i, tt.endpoints, endpoints)
  644. }
  645. }
  646. }
  647. func TestAllowMethod(t *testing.T) {
  648. tests := []struct {
  649. m string
  650. ms []string
  651. w bool
  652. wh string
  653. }{
  654. // Accepted methods
  655. {
  656. m: "GET",
  657. ms: []string{"GET", "POST", "PUT"},
  658. w: true,
  659. },
  660. {
  661. m: "POST",
  662. ms: []string{"POST"},
  663. w: true,
  664. },
  665. // Made-up methods no good
  666. {
  667. m: "FAKE",
  668. ms: []string{"GET", "POST", "PUT"},
  669. w: false,
  670. wh: "GET,POST,PUT",
  671. },
  672. // Empty methods no good
  673. {
  674. m: "",
  675. ms: []string{"GET", "POST"},
  676. w: false,
  677. wh: "GET,POST",
  678. },
  679. // Empty accepted methods no good
  680. {
  681. m: "GET",
  682. ms: []string{""},
  683. w: false,
  684. wh: "",
  685. },
  686. // No methods accepted
  687. {
  688. m: "GET",
  689. ms: []string{},
  690. w: false,
  691. wh: "",
  692. },
  693. }
  694. for i, tt := range tests {
  695. rw := httptest.NewRecorder()
  696. g := allowMethod(rw, tt.m, tt.ms...)
  697. if g != tt.w {
  698. t.Errorf("#%d: got allowMethod()=%t, want %t", i, g, tt.w)
  699. }
  700. if !tt.w {
  701. if rw.Code != http.StatusMethodNotAllowed {
  702. t.Errorf("#%d: code=%d, want %d", i, rw.Code, http.StatusMethodNotAllowed)
  703. }
  704. gh := rw.Header().Get("Allow")
  705. if gh != tt.wh {
  706. t.Errorf("#%d: Allow header=%q, want %q", i, gh, tt.wh)
  707. }
  708. }
  709. }
  710. }
  711. // errServer implements the etcd.Server interface for testing.
  712. // It returns the given error from any Do/Process calls.
  713. type errServer struct {
  714. err error
  715. }
  716. func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  717. return etcdserver.Response{}, fs.err
  718. }
  719. func (fs *errServer) Process(ctx context.Context, m raftpb.Message) error {
  720. return fs.err
  721. }
  722. func (fs *errServer) Start() {}
  723. func (fs *errServer) Stop() {}
  724. // errReader implements io.Reader to facilitate a broken request.
  725. type errReader struct{}
  726. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  727. func mustMarshalMsg(t *testing.T, m raftpb.Message) []byte {
  728. json, err := m.Marshal()
  729. if err != nil {
  730. t.Fatalf("error marshalling raft Message: %#v", err)
  731. }
  732. return json
  733. }
  734. func TestServeRaft(t *testing.T) {
  735. testCases := []struct {
  736. method string
  737. body io.Reader
  738. serverErr error
  739. wcode int
  740. }{
  741. {
  742. // bad method
  743. "GET",
  744. bytes.NewReader(
  745. mustMarshalMsg(
  746. t,
  747. raftpb.Message{},
  748. ),
  749. ),
  750. nil,
  751. http.StatusMethodNotAllowed,
  752. },
  753. {
  754. // bad method
  755. "PUT",
  756. bytes.NewReader(
  757. mustMarshalMsg(
  758. t,
  759. raftpb.Message{},
  760. ),
  761. ),
  762. nil,
  763. http.StatusMethodNotAllowed,
  764. },
  765. {
  766. // bad method
  767. "DELETE",
  768. bytes.NewReader(
  769. mustMarshalMsg(
  770. t,
  771. raftpb.Message{},
  772. ),
  773. ),
  774. nil,
  775. http.StatusMethodNotAllowed,
  776. },
  777. {
  778. // bad request body
  779. "POST",
  780. &errReader{},
  781. nil,
  782. http.StatusBadRequest,
  783. },
  784. {
  785. // bad request protobuf
  786. "POST",
  787. strings.NewReader("malformed garbage"),
  788. nil,
  789. http.StatusBadRequest,
  790. },
  791. {
  792. // good request, etcdserver.Server error
  793. "POST",
  794. bytes.NewReader(
  795. mustMarshalMsg(
  796. t,
  797. raftpb.Message{},
  798. ),
  799. ),
  800. errors.New("some error"),
  801. http.StatusInternalServerError,
  802. },
  803. {
  804. // good request
  805. "POST",
  806. bytes.NewReader(
  807. mustMarshalMsg(
  808. t,
  809. raftpb.Message{},
  810. ),
  811. ),
  812. nil,
  813. http.StatusNoContent,
  814. },
  815. }
  816. for i, tt := range testCases {
  817. req, err := http.NewRequest(tt.method, "foo", tt.body)
  818. if err != nil {
  819. t.Fatalf("#%d: could not create request: %#v", i, err)
  820. }
  821. h := &serverHandler{
  822. timeout: time.Hour,
  823. server: &errServer{tt.serverErr},
  824. peers: nil,
  825. }
  826. rw := httptest.NewRecorder()
  827. h.serveRaft(rw, req)
  828. if rw.Code != tt.wcode {
  829. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  830. }
  831. }
  832. }
  833. // resServer implements the etcd.Server interface for testing.
  834. // It returns the given responsefrom any Do calls, and nil error
  835. type resServer struct {
  836. res etcdserver.Response
  837. }
  838. func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
  839. return rs.res, nil
  840. }
  841. func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
  842. func (rs *resServer) Start() {}
  843. func (rs *resServer) Stop() {}
  844. func mustMarshalEvent(t *testing.T, ev *store.Event) string {
  845. b := new(bytes.Buffer)
  846. if err := json.NewEncoder(b).Encode(ev); err != nil {
  847. t.Fatalf("error marshalling event %#v: %v", ev, err)
  848. }
  849. return b.String()
  850. }
  851. func TestBadServeKeys(t *testing.T) {
  852. testBadCases := []struct {
  853. req *http.Request
  854. server etcdserver.Server
  855. wcode int
  856. }{
  857. {
  858. // bad method
  859. &http.Request{
  860. Method: "CONNECT",
  861. },
  862. &resServer{},
  863. http.StatusMethodNotAllowed,
  864. },
  865. {
  866. // bad method
  867. &http.Request{
  868. Method: "TRACE",
  869. },
  870. &resServer{},
  871. http.StatusMethodNotAllowed,
  872. },
  873. {
  874. // parseRequest error
  875. &http.Request{
  876. Body: nil,
  877. Method: "PUT",
  878. },
  879. &resServer{},
  880. http.StatusBadRequest,
  881. },
  882. {
  883. // etcdserver.Server error
  884. mustNewRequest(t, "foo"),
  885. &errServer{
  886. errors.New("blah"),
  887. },
  888. http.StatusInternalServerError,
  889. },
  890. {
  891. // non-event/watcher response from etcdserver.Server
  892. mustNewRequest(t, "foo"),
  893. &resServer{
  894. etcdserver.Response{},
  895. },
  896. http.StatusInternalServerError,
  897. },
  898. }
  899. for i, tt := range testBadCases {
  900. h := &serverHandler{
  901. timeout: 0, // context times out immediately
  902. server: tt.server,
  903. peers: nil,
  904. }
  905. rw := httptest.NewRecorder()
  906. h.serveKeys(rw, tt.req)
  907. if rw.Code != tt.wcode {
  908. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  909. }
  910. }
  911. }
  912. func TestServeKeysEvent(t *testing.T) {
  913. req := mustNewRequest(t, "foo")
  914. server := &resServer{
  915. etcdserver.Response{
  916. Event: &store.Event{
  917. Action: store.Get,
  918. Node: &store.NodeExtern{},
  919. },
  920. },
  921. }
  922. h := &serverHandler{
  923. timeout: time.Hour,
  924. server: server,
  925. peers: nil,
  926. timer: &dummyRaftTimer{},
  927. }
  928. rw := httptest.NewRecorder()
  929. h.serveKeys(rw, req)
  930. wcode := http.StatusOK
  931. wbody := mustMarshalEvent(
  932. t,
  933. &store.Event{
  934. Action: store.Get,
  935. Node: &store.NodeExtern{},
  936. },
  937. )
  938. if rw.Code != wcode {
  939. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  940. }
  941. g := rw.Body.String()
  942. if g != wbody {
  943. t.Errorf("got body=%#v, want %#v", g, wbody)
  944. }
  945. }
  946. func TestServeKeysWatch(t *testing.T) {
  947. req := mustNewRequest(t, "/foo/bar")
  948. ec := make(chan *store.Event)
  949. dw := &dummyWatcher{
  950. echan: ec,
  951. }
  952. server := &resServer{
  953. etcdserver.Response{
  954. Watcher: dw,
  955. },
  956. }
  957. h := &serverHandler{
  958. timeout: time.Hour,
  959. server: server,
  960. peers: nil,
  961. timer: &dummyRaftTimer{},
  962. }
  963. go func() {
  964. ec <- &store.Event{
  965. Action: store.Get,
  966. Node: &store.NodeExtern{},
  967. }
  968. }()
  969. rw := httptest.NewRecorder()
  970. h.serveKeys(rw, req)
  971. wcode := http.StatusOK
  972. wbody := mustMarshalEvent(
  973. t,
  974. &store.Event{
  975. Action: store.Get,
  976. Node: &store.NodeExtern{},
  977. },
  978. )
  979. if rw.Code != wcode {
  980. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  981. }
  982. g := rw.Body.String()
  983. if g != wbody {
  984. t.Errorf("got body=%#v, want %#v", g, wbody)
  985. }
  986. }
  987. func TestHandleWatch(t *testing.T) {
  988. rw := httptest.NewRecorder()
  989. wa := &dummyWatcher{
  990. echan: make(chan *store.Event, 1),
  991. }
  992. wa.echan <- &store.Event{
  993. Action: store.Get,
  994. Node: &store.NodeExtern{},
  995. }
  996. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  997. wcode := http.StatusOK
  998. wct := "application/json"
  999. wri := "100"
  1000. wrt := "5"
  1001. wbody := mustMarshalEvent(
  1002. t,
  1003. &store.Event{
  1004. Action: store.Get,
  1005. Node: &store.NodeExtern{},
  1006. },
  1007. )
  1008. if rw.Code != wcode {
  1009. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1010. }
  1011. h := rw.Header()
  1012. if ct := h.Get("Content-Type"); ct != wct {
  1013. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1014. }
  1015. if ri := h.Get("X-Raft-Index"); ri != wri {
  1016. t.Errorf("X-Raft-Index=%q, want %q", ri, wri)
  1017. }
  1018. if rt := h.Get("X-Raft-Term"); rt != wrt {
  1019. t.Errorf("X-Raft-Term=%q, want %q", rt, wrt)
  1020. }
  1021. g := rw.Body.String()
  1022. if g != wbody {
  1023. t.Errorf("got body=%#v, want %#v", g, wbody)
  1024. }
  1025. }
  1026. func TestHandleWatchNoEvent(t *testing.T) {
  1027. rw := httptest.NewRecorder()
  1028. wa := &dummyWatcher{
  1029. echan: make(chan *store.Event, 1),
  1030. }
  1031. close(wa.echan)
  1032. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  1033. wcode := http.StatusOK
  1034. wct := "application/json"
  1035. wbody := ""
  1036. if rw.Code != wcode {
  1037. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1038. }
  1039. h := rw.Header()
  1040. if ct := h.Get("Content-Type"); ct != wct {
  1041. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1042. }
  1043. g := rw.Body.String()
  1044. if g != wbody {
  1045. t.Errorf("got body=%#v, want %#v", g, wbody)
  1046. }
  1047. }
  1048. type recordingCloseNotifier struct {
  1049. *httptest.ResponseRecorder
  1050. cn chan bool
  1051. }
  1052. func (rcn *recordingCloseNotifier) CloseNotify() <-chan bool {
  1053. return rcn.cn
  1054. }
  1055. func TestHandleWatchCloseNotified(t *testing.T) {
  1056. rw := &recordingCloseNotifier{
  1057. ResponseRecorder: httptest.NewRecorder(),
  1058. cn: make(chan bool, 1),
  1059. }
  1060. rw.cn <- true
  1061. wa := &dummyWatcher{}
  1062. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  1063. wcode := http.StatusOK
  1064. wct := "application/json"
  1065. wbody := ""
  1066. if rw.Code != wcode {
  1067. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1068. }
  1069. h := rw.Header()
  1070. if ct := h.Get("Content-Type"); ct != wct {
  1071. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1072. }
  1073. g := rw.Body.String()
  1074. if g != wbody {
  1075. t.Errorf("got body=%#v, want %#v", g, wbody)
  1076. }
  1077. }
  1078. func TestHandleWatchTimeout(t *testing.T) {
  1079. rw := httptest.NewRecorder()
  1080. wa := &dummyWatcher{}
  1081. // Simulate a timed-out context
  1082. ctx, cancel := context.WithCancel(context.Background())
  1083. cancel()
  1084. handleWatch(ctx, rw, wa, false, dummyRaftTimer{})
  1085. wcode := http.StatusOK
  1086. wct := "application/json"
  1087. wbody := ""
  1088. if rw.Code != wcode {
  1089. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1090. }
  1091. h := rw.Header()
  1092. if ct := h.Get("Content-Type"); ct != wct {
  1093. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1094. }
  1095. g := rw.Body.String()
  1096. if g != wbody {
  1097. t.Errorf("got body=%#v, want %#v", g, wbody)
  1098. }
  1099. }
  1100. // flushingRecorder provides a channel to allow users to block until the Recorder is Flushed()
  1101. type flushingRecorder struct {
  1102. *httptest.ResponseRecorder
  1103. ch chan struct{}
  1104. }
  1105. func (fr *flushingRecorder) Flush() {
  1106. fr.ResponseRecorder.Flush()
  1107. fr.ch <- struct{}{}
  1108. }
  1109. func TestHandleWatchStreaming(t *testing.T) {
  1110. rw := &flushingRecorder{
  1111. httptest.NewRecorder(),
  1112. make(chan struct{}, 1),
  1113. }
  1114. wa := &dummyWatcher{
  1115. echan: make(chan *store.Event),
  1116. }
  1117. // Launch the streaming handler in the background with a cancellable context
  1118. ctx, cancel := context.WithCancel(context.Background())
  1119. done := make(chan struct{})
  1120. go func() {
  1121. handleWatch(ctx, rw, wa, true, dummyRaftTimer{})
  1122. close(done)
  1123. }()
  1124. // Expect one Flush for the headers etc.
  1125. select {
  1126. case <-rw.ch:
  1127. case <-time.After(time.Second):
  1128. t.Fatalf("timed out waiting for flush")
  1129. }
  1130. // Expect headers but no body
  1131. wcode := http.StatusOK
  1132. wct := "application/json"
  1133. wbody := ""
  1134. if rw.Code != wcode {
  1135. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1136. }
  1137. h := rw.Header()
  1138. if ct := h.Get("Content-Type"); ct != wct {
  1139. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1140. }
  1141. g := rw.Body.String()
  1142. if g != wbody {
  1143. t.Errorf("got body=%#v, want %#v", g, wbody)
  1144. }
  1145. // Now send the first event
  1146. select {
  1147. case wa.echan <- &store.Event{
  1148. Action: store.Get,
  1149. Node: &store.NodeExtern{},
  1150. }:
  1151. case <-time.After(time.Second):
  1152. t.Fatal("timed out waiting for send")
  1153. }
  1154. // Wait for it to be flushed...
  1155. select {
  1156. case <-rw.ch:
  1157. case <-time.After(time.Second):
  1158. t.Fatalf("timed out waiting for flush")
  1159. }
  1160. // And check the body is as expected
  1161. wbody = mustMarshalEvent(
  1162. t,
  1163. &store.Event{
  1164. Action: store.Get,
  1165. Node: &store.NodeExtern{},
  1166. },
  1167. )
  1168. g = rw.Body.String()
  1169. if g != wbody {
  1170. t.Errorf("got body=%#v, want %#v", g, wbody)
  1171. }
  1172. // Rinse and repeat
  1173. select {
  1174. case wa.echan <- &store.Event{
  1175. Action: store.Get,
  1176. Node: &store.NodeExtern{},
  1177. }:
  1178. case <-time.After(time.Second):
  1179. t.Fatal("timed out waiting for send")
  1180. }
  1181. select {
  1182. case <-rw.ch:
  1183. case <-time.After(time.Second):
  1184. t.Fatalf("timed out waiting for flush")
  1185. }
  1186. // This time, we expect to see both events
  1187. wbody = wbody + wbody
  1188. g = rw.Body.String()
  1189. if g != wbody {
  1190. t.Errorf("got body=%#v, want %#v", g, wbody)
  1191. }
  1192. // Finally, time out the connection and ensure the serving goroutine returns
  1193. cancel()
  1194. select {
  1195. case <-done:
  1196. case <-time.After(time.Second):
  1197. t.Fatalf("timed out waiting for done")
  1198. }
  1199. }