http_test.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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, &fakeCluster{}, 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. cluster := &fakeCluster{
  583. members: []etcdserver.Member{
  584. {ID: 0xBEEF0, PeerURLs: []string{"localhost:8080"}},
  585. {ID: 0xBEEF1, PeerURLs: []string{"localhost:8081"}},
  586. {ID: 0xBEEF2, PeerURLs: []string{"localhost:8082"}},
  587. },
  588. }
  589. writer := httptest.NewRecorder()
  590. req, err := http.NewRequest("GET", "", nil)
  591. if err != nil {
  592. t.Fatal(err)
  593. }
  594. h := &serverHandler{clusterStore: cluster}
  595. h.serveMachines(writer, req)
  596. w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
  597. if g := writer.Body.String(); g != w {
  598. t.Errorf("body = %s, want %s", g, w)
  599. }
  600. if writer.Code != http.StatusOK {
  601. t.Errorf("header = %d, want %d", writer.Code, http.StatusOK)
  602. }
  603. }
  604. func TestClusterGetEndpoints(t *testing.T) {
  605. tests := []struct {
  606. clusterStore etcdserver.ClusterStore
  607. endpoints []string
  608. }{
  609. // single peer with a single address
  610. {
  611. clusterStore: &fakeCluster{
  612. members: []etcdserver.Member{
  613. {ID: 1, PeerURLs: []string{"192.0.2.1"}},
  614. },
  615. },
  616. endpoints: []string{"http://192.0.2.1"},
  617. },
  618. // single peer with a single address with a port
  619. {
  620. clusterStore: &fakeCluster{
  621. members: []etcdserver.Member{
  622. {ID: 1, PeerURLs: []string{"192.0.2.1:8001"}},
  623. },
  624. },
  625. endpoints: []string{"http://192.0.2.1:8001"},
  626. },
  627. // several members explicitly unsorted
  628. {
  629. clusterStore: &fakeCluster{
  630. members: []etcdserver.Member{
  631. {ID: 2, PeerURLs: []string{"192.0.2.3", "192.0.2.4"}},
  632. {ID: 3, PeerURLs: []string{"192.0.2.5", "192.0.2.6"}},
  633. {ID: 1, PeerURLs: []string{"192.0.2.1", "192.0.2.2"}},
  634. },
  635. },
  636. 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"},
  637. },
  638. // no members
  639. {
  640. clusterStore: &fakeCluster{members: []etcdserver.Member{}},
  641. endpoints: []string{},
  642. },
  643. // peer with no endpoints
  644. {
  645. clusterStore: &fakeCluster{
  646. members: []etcdserver.Member{
  647. {ID: 3, PeerURLs: []string{}},
  648. },
  649. },
  650. endpoints: []string{},
  651. },
  652. }
  653. for i, tt := range tests {
  654. endpoints := tt.clusterStore.Get().Endpoints()
  655. if !reflect.DeepEqual(tt.endpoints, endpoints) {
  656. t.Errorf("#%d: members.Endpoints() incorrect: want=%#v got=%#v", i, tt.endpoints, endpoints)
  657. }
  658. }
  659. }
  660. func TestAllowMethod(t *testing.T) {
  661. tests := []struct {
  662. m string
  663. ms []string
  664. w bool
  665. wh string
  666. }{
  667. // Accepted methods
  668. {
  669. m: "GET",
  670. ms: []string{"GET", "POST", "PUT"},
  671. w: true,
  672. },
  673. {
  674. m: "POST",
  675. ms: []string{"POST"},
  676. w: true,
  677. },
  678. // Made-up methods no good
  679. {
  680. m: "FAKE",
  681. ms: []string{"GET", "POST", "PUT"},
  682. w: false,
  683. wh: "GET,POST,PUT",
  684. },
  685. // Empty methods no good
  686. {
  687. m: "",
  688. ms: []string{"GET", "POST"},
  689. w: false,
  690. wh: "GET,POST",
  691. },
  692. // Empty accepted methods no good
  693. {
  694. m: "GET",
  695. ms: []string{""},
  696. w: false,
  697. wh: "",
  698. },
  699. // No methods accepted
  700. {
  701. m: "GET",
  702. ms: []string{},
  703. w: false,
  704. wh: "",
  705. },
  706. }
  707. for i, tt := range tests {
  708. rw := httptest.NewRecorder()
  709. g := allowMethod(rw, tt.m, tt.ms...)
  710. if g != tt.w {
  711. t.Errorf("#%d: got allowMethod()=%t, want %t", i, g, tt.w)
  712. }
  713. if !tt.w {
  714. if rw.Code != http.StatusMethodNotAllowed {
  715. t.Errorf("#%d: code=%d, want %d", i, rw.Code, http.StatusMethodNotAllowed)
  716. }
  717. gh := rw.Header().Get("Allow")
  718. if gh != tt.wh {
  719. t.Errorf("#%d: Allow header=%q, want %q", i, gh, tt.wh)
  720. }
  721. }
  722. }
  723. }
  724. // errServer implements the etcd.Server interface for testing.
  725. // It returns the given error from any Do/Process calls.
  726. type errServer struct {
  727. err error
  728. }
  729. func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
  730. return etcdserver.Response{}, fs.err
  731. }
  732. func (fs *errServer) Process(ctx context.Context, m raftpb.Message) error {
  733. return fs.err
  734. }
  735. func (fs *errServer) Start() {}
  736. func (fs *errServer) Stop() {}
  737. // errReader implements io.Reader to facilitate a broken request.
  738. type errReader struct{}
  739. func (er *errReader) Read(_ []byte) (int, error) { return 0, errors.New("some error") }
  740. func mustMarshalMsg(t *testing.T, m raftpb.Message) []byte {
  741. json, err := m.Marshal()
  742. if err != nil {
  743. t.Fatalf("error marshalling raft Message: %#v", err)
  744. }
  745. return json
  746. }
  747. func TestServeRaft(t *testing.T) {
  748. testCases := []struct {
  749. method string
  750. body io.Reader
  751. serverErr error
  752. wcode int
  753. }{
  754. {
  755. // bad method
  756. "GET",
  757. bytes.NewReader(
  758. mustMarshalMsg(
  759. t,
  760. raftpb.Message{},
  761. ),
  762. ),
  763. nil,
  764. http.StatusMethodNotAllowed,
  765. },
  766. {
  767. // bad method
  768. "PUT",
  769. bytes.NewReader(
  770. mustMarshalMsg(
  771. t,
  772. raftpb.Message{},
  773. ),
  774. ),
  775. nil,
  776. http.StatusMethodNotAllowed,
  777. },
  778. {
  779. // bad method
  780. "DELETE",
  781. bytes.NewReader(
  782. mustMarshalMsg(
  783. t,
  784. raftpb.Message{},
  785. ),
  786. ),
  787. nil,
  788. http.StatusMethodNotAllowed,
  789. },
  790. {
  791. // bad request body
  792. "POST",
  793. &errReader{},
  794. nil,
  795. http.StatusBadRequest,
  796. },
  797. {
  798. // bad request protobuf
  799. "POST",
  800. strings.NewReader("malformed garbage"),
  801. nil,
  802. http.StatusBadRequest,
  803. },
  804. {
  805. // good request, etcdserver.Server error
  806. "POST",
  807. bytes.NewReader(
  808. mustMarshalMsg(
  809. t,
  810. raftpb.Message{},
  811. ),
  812. ),
  813. errors.New("some error"),
  814. http.StatusInternalServerError,
  815. },
  816. {
  817. // good request
  818. "POST",
  819. bytes.NewReader(
  820. mustMarshalMsg(
  821. t,
  822. raftpb.Message{},
  823. ),
  824. ),
  825. nil,
  826. http.StatusNoContent,
  827. },
  828. }
  829. for i, tt := range testCases {
  830. req, err := http.NewRequest(tt.method, "foo", tt.body)
  831. if err != nil {
  832. t.Fatalf("#%d: could not create request: %#v", i, err)
  833. }
  834. h := &serverHandler{
  835. timeout: time.Hour,
  836. server: &errServer{tt.serverErr},
  837. }
  838. rw := httptest.NewRecorder()
  839. h.serveRaft(rw, req)
  840. if rw.Code != tt.wcode {
  841. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  842. }
  843. }
  844. }
  845. // resServer implements the etcd.Server interface for testing.
  846. // It returns the given responsefrom any Do calls, and nil error
  847. type resServer struct {
  848. res etcdserver.Response
  849. }
  850. func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
  851. return rs.res, nil
  852. }
  853. func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
  854. func (rs *resServer) Start() {}
  855. func (rs *resServer) Stop() {}
  856. func mustMarshalEvent(t *testing.T, ev *store.Event) string {
  857. b := new(bytes.Buffer)
  858. if err := json.NewEncoder(b).Encode(ev); err != nil {
  859. t.Fatalf("error marshalling event %#v: %v", ev, err)
  860. }
  861. return b.String()
  862. }
  863. func TestBadServeKeys(t *testing.T) {
  864. testBadCases := []struct {
  865. req *http.Request
  866. server etcdserver.Server
  867. wcode int
  868. }{
  869. {
  870. // bad method
  871. &http.Request{
  872. Method: "CONNECT",
  873. },
  874. &resServer{},
  875. http.StatusMethodNotAllowed,
  876. },
  877. {
  878. // bad method
  879. &http.Request{
  880. Method: "TRACE",
  881. },
  882. &resServer{},
  883. http.StatusMethodNotAllowed,
  884. },
  885. {
  886. // parseRequest error
  887. &http.Request{
  888. Body: nil,
  889. Method: "PUT",
  890. },
  891. &resServer{},
  892. http.StatusBadRequest,
  893. },
  894. {
  895. // etcdserver.Server error
  896. mustNewRequest(t, "foo"),
  897. &errServer{
  898. errors.New("blah"),
  899. },
  900. http.StatusInternalServerError,
  901. },
  902. {
  903. // non-event/watcher response from etcdserver.Server
  904. mustNewRequest(t, "foo"),
  905. &resServer{
  906. etcdserver.Response{},
  907. },
  908. http.StatusInternalServerError,
  909. },
  910. }
  911. for i, tt := range testBadCases {
  912. h := &serverHandler{
  913. timeout: 0, // context times out immediately
  914. server: tt.server,
  915. }
  916. rw := httptest.NewRecorder()
  917. h.serveKeys(rw, tt.req)
  918. if rw.Code != tt.wcode {
  919. t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
  920. }
  921. }
  922. }
  923. func TestServeKeysEvent(t *testing.T) {
  924. req := mustNewRequest(t, "foo")
  925. server := &resServer{
  926. etcdserver.Response{
  927. Event: &store.Event{
  928. Action: store.Get,
  929. Node: &store.NodeExtern{},
  930. },
  931. },
  932. }
  933. h := &serverHandler{
  934. timeout: time.Hour,
  935. server: server,
  936. timer: &dummyRaftTimer{},
  937. }
  938. rw := httptest.NewRecorder()
  939. h.serveKeys(rw, req)
  940. wcode := http.StatusOK
  941. wbody := mustMarshalEvent(
  942. t,
  943. &store.Event{
  944. Action: store.Get,
  945. Node: &store.NodeExtern{},
  946. },
  947. )
  948. if rw.Code != wcode {
  949. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  950. }
  951. g := rw.Body.String()
  952. if g != wbody {
  953. t.Errorf("got body=%#v, want %#v", g, wbody)
  954. }
  955. }
  956. func TestServeKeysWatch(t *testing.T) {
  957. req := mustNewRequest(t, "/foo/bar")
  958. ec := make(chan *store.Event)
  959. dw := &dummyWatcher{
  960. echan: ec,
  961. }
  962. server := &resServer{
  963. etcdserver.Response{
  964. Watcher: dw,
  965. },
  966. }
  967. h := &serverHandler{
  968. timeout: time.Hour,
  969. server: server,
  970. timer: &dummyRaftTimer{},
  971. }
  972. go func() {
  973. ec <- &store.Event{
  974. Action: store.Get,
  975. Node: &store.NodeExtern{},
  976. }
  977. }()
  978. rw := httptest.NewRecorder()
  979. h.serveKeys(rw, req)
  980. wcode := http.StatusOK
  981. wbody := mustMarshalEvent(
  982. t,
  983. &store.Event{
  984. Action: store.Get,
  985. Node: &store.NodeExtern{},
  986. },
  987. )
  988. if rw.Code != wcode {
  989. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  990. }
  991. g := rw.Body.String()
  992. if g != wbody {
  993. t.Errorf("got body=%#v, want %#v", g, wbody)
  994. }
  995. }
  996. func TestHandleWatch(t *testing.T) {
  997. rw := httptest.NewRecorder()
  998. wa := &dummyWatcher{
  999. echan: make(chan *store.Event, 1),
  1000. }
  1001. wa.echan <- &store.Event{
  1002. Action: store.Get,
  1003. Node: &store.NodeExtern{},
  1004. }
  1005. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  1006. wcode := http.StatusOK
  1007. wct := "application/json"
  1008. wri := "100"
  1009. wrt := "5"
  1010. wbody := mustMarshalEvent(
  1011. t,
  1012. &store.Event{
  1013. Action: store.Get,
  1014. Node: &store.NodeExtern{},
  1015. },
  1016. )
  1017. if rw.Code != wcode {
  1018. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1019. }
  1020. h := rw.Header()
  1021. if ct := h.Get("Content-Type"); ct != wct {
  1022. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1023. }
  1024. if ri := h.Get("X-Raft-Index"); ri != wri {
  1025. t.Errorf("X-Raft-Index=%q, want %q", ri, wri)
  1026. }
  1027. if rt := h.Get("X-Raft-Term"); rt != wrt {
  1028. t.Errorf("X-Raft-Term=%q, want %q", rt, wrt)
  1029. }
  1030. g := rw.Body.String()
  1031. if g != wbody {
  1032. t.Errorf("got body=%#v, want %#v", g, wbody)
  1033. }
  1034. }
  1035. func TestHandleWatchNoEvent(t *testing.T) {
  1036. rw := httptest.NewRecorder()
  1037. wa := &dummyWatcher{
  1038. echan: make(chan *store.Event, 1),
  1039. }
  1040. close(wa.echan)
  1041. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  1042. wcode := http.StatusOK
  1043. wct := "application/json"
  1044. wbody := ""
  1045. if rw.Code != wcode {
  1046. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1047. }
  1048. h := rw.Header()
  1049. if ct := h.Get("Content-Type"); ct != wct {
  1050. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1051. }
  1052. g := rw.Body.String()
  1053. if g != wbody {
  1054. t.Errorf("got body=%#v, want %#v", g, wbody)
  1055. }
  1056. }
  1057. type recordingCloseNotifier struct {
  1058. *httptest.ResponseRecorder
  1059. cn chan bool
  1060. }
  1061. func (rcn *recordingCloseNotifier) CloseNotify() <-chan bool {
  1062. return rcn.cn
  1063. }
  1064. func TestHandleWatchCloseNotified(t *testing.T) {
  1065. rw := &recordingCloseNotifier{
  1066. ResponseRecorder: httptest.NewRecorder(),
  1067. cn: make(chan bool, 1),
  1068. }
  1069. rw.cn <- true
  1070. wa := &dummyWatcher{}
  1071. handleWatch(context.Background(), rw, wa, false, dummyRaftTimer{})
  1072. wcode := http.StatusOK
  1073. wct := "application/json"
  1074. wbody := ""
  1075. if rw.Code != wcode {
  1076. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1077. }
  1078. h := rw.Header()
  1079. if ct := h.Get("Content-Type"); ct != wct {
  1080. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1081. }
  1082. g := rw.Body.String()
  1083. if g != wbody {
  1084. t.Errorf("got body=%#v, want %#v", g, wbody)
  1085. }
  1086. }
  1087. func TestHandleWatchTimeout(t *testing.T) {
  1088. rw := httptest.NewRecorder()
  1089. wa := &dummyWatcher{}
  1090. // Simulate a timed-out context
  1091. ctx, cancel := context.WithCancel(context.Background())
  1092. cancel()
  1093. handleWatch(ctx, rw, wa, false, dummyRaftTimer{})
  1094. wcode := http.StatusOK
  1095. wct := "application/json"
  1096. wbody := ""
  1097. if rw.Code != wcode {
  1098. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1099. }
  1100. h := rw.Header()
  1101. if ct := h.Get("Content-Type"); ct != wct {
  1102. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1103. }
  1104. g := rw.Body.String()
  1105. if g != wbody {
  1106. t.Errorf("got body=%#v, want %#v", g, wbody)
  1107. }
  1108. }
  1109. // flushingRecorder provides a channel to allow users to block until the Recorder is Flushed()
  1110. type flushingRecorder struct {
  1111. *httptest.ResponseRecorder
  1112. ch chan struct{}
  1113. }
  1114. func (fr *flushingRecorder) Flush() {
  1115. fr.ResponseRecorder.Flush()
  1116. fr.ch <- struct{}{}
  1117. }
  1118. func TestHandleWatchStreaming(t *testing.T) {
  1119. rw := &flushingRecorder{
  1120. httptest.NewRecorder(),
  1121. make(chan struct{}, 1),
  1122. }
  1123. wa := &dummyWatcher{
  1124. echan: make(chan *store.Event),
  1125. }
  1126. // Launch the streaming handler in the background with a cancellable context
  1127. ctx, cancel := context.WithCancel(context.Background())
  1128. done := make(chan struct{})
  1129. go func() {
  1130. handleWatch(ctx, rw, wa, true, dummyRaftTimer{})
  1131. close(done)
  1132. }()
  1133. // Expect one Flush for the headers etc.
  1134. select {
  1135. case <-rw.ch:
  1136. case <-time.After(time.Second):
  1137. t.Fatalf("timed out waiting for flush")
  1138. }
  1139. // Expect headers but no body
  1140. wcode := http.StatusOK
  1141. wct := "application/json"
  1142. wbody := ""
  1143. if rw.Code != wcode {
  1144. t.Errorf("got code=%d, want %d", rw.Code, wcode)
  1145. }
  1146. h := rw.Header()
  1147. if ct := h.Get("Content-Type"); ct != wct {
  1148. t.Errorf("Content-Type=%q, want %q", ct, wct)
  1149. }
  1150. g := rw.Body.String()
  1151. if g != wbody {
  1152. t.Errorf("got body=%#v, want %#v", g, wbody)
  1153. }
  1154. // Now send the first event
  1155. select {
  1156. case wa.echan <- &store.Event{
  1157. Action: store.Get,
  1158. Node: &store.NodeExtern{},
  1159. }:
  1160. case <-time.After(time.Second):
  1161. t.Fatal("timed out waiting for send")
  1162. }
  1163. // Wait for it to be flushed...
  1164. select {
  1165. case <-rw.ch:
  1166. case <-time.After(time.Second):
  1167. t.Fatalf("timed out waiting for flush")
  1168. }
  1169. // And check the body is as expected
  1170. wbody = mustMarshalEvent(
  1171. t,
  1172. &store.Event{
  1173. Action: store.Get,
  1174. Node: &store.NodeExtern{},
  1175. },
  1176. )
  1177. g = rw.Body.String()
  1178. if g != wbody {
  1179. t.Errorf("got body=%#v, want %#v", g, wbody)
  1180. }
  1181. // Rinse and repeat
  1182. select {
  1183. case wa.echan <- &store.Event{
  1184. Action: store.Get,
  1185. Node: &store.NodeExtern{},
  1186. }:
  1187. case <-time.After(time.Second):
  1188. t.Fatal("timed out waiting for send")
  1189. }
  1190. select {
  1191. case <-rw.ch:
  1192. case <-time.After(time.Second):
  1193. t.Fatalf("timed out waiting for flush")
  1194. }
  1195. // This time, we expect to see both events
  1196. wbody = wbody + wbody
  1197. g = rw.Body.String()
  1198. if g != wbody {
  1199. t.Errorf("got body=%#v, want %#v", g, wbody)
  1200. }
  1201. // Finally, time out the connection and ensure the serving goroutine returns
  1202. cancel()
  1203. select {
  1204. case <-done:
  1205. case <-time.After(time.Second):
  1206. t.Fatalf("timed out waiting for done")
  1207. }
  1208. }
  1209. type fakeCluster struct {
  1210. members []etcdserver.Member
  1211. }
  1212. func (c *fakeCluster) Get() etcdserver.Cluster {
  1213. cl := &etcdserver.Cluster{}
  1214. cl.AddSlice(c.members)
  1215. return *cl
  1216. }
  1217. func (c *fakeCluster) Delete(id int64) { return }