server_test.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. package etcdserver
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/rand"
  6. "net/url"
  7. "reflect"
  8. "sync"
  9. "testing"
  10. "time"
  11. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  12. "github.com/coreos/etcd/pkg"
  13. "github.com/coreos/etcd/raft"
  14. "github.com/coreos/etcd/raft/raftpb"
  15. "github.com/coreos/etcd/store"
  16. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  17. )
  18. func TestGetExpirationTime(t *testing.T) {
  19. tests := []struct {
  20. r pb.Request
  21. want time.Time
  22. }{
  23. {
  24. pb.Request{Expiration: 0},
  25. time.Time{},
  26. },
  27. {
  28. pb.Request{Expiration: 60000},
  29. time.Unix(0, 60000),
  30. },
  31. {
  32. pb.Request{Expiration: -60000},
  33. time.Unix(0, -60000),
  34. },
  35. }
  36. for i, tt := range tests {
  37. got := getExpirationTime(&tt.r)
  38. if !reflect.DeepEqual(tt.want, got) {
  39. t.Errorf("#%d: incorrect expiration time: want=%v got=%v", i, tt.want, got)
  40. }
  41. }
  42. }
  43. // TestDoLocalAction tests requests which do not need to go through raft to be applied,
  44. // and are served through local data.
  45. func TestDoLocalAction(t *testing.T) {
  46. tests := []struct {
  47. req pb.Request
  48. wresp Response
  49. werr error
  50. wactions []action
  51. }{
  52. {
  53. pb.Request{Method: "GET", ID: 1, Wait: true},
  54. Response{Watcher: &stubWatcher{}}, nil, []action{action{name: "Watch"}},
  55. },
  56. {
  57. pb.Request{Method: "GET", ID: 1},
  58. Response{Event: &store.Event{}}, nil,
  59. []action{
  60. action{
  61. name: "Get",
  62. params: []interface{}{"", false, false},
  63. },
  64. },
  65. },
  66. {
  67. pb.Request{Method: "BADMETHOD", ID: 1},
  68. Response{}, ErrUnknownMethod, []action{},
  69. },
  70. }
  71. for i, tt := range tests {
  72. st := &storeRecorder{}
  73. srv := &EtcdServer{store: st}
  74. resp, err := srv.Do(context.TODO(), tt.req)
  75. if err != tt.werr {
  76. t.Fatalf("#%d: err = %+v, want %+v", i, err, tt.werr)
  77. }
  78. if !reflect.DeepEqual(resp, tt.wresp) {
  79. t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp)
  80. }
  81. gaction := st.Action()
  82. if !reflect.DeepEqual(gaction, tt.wactions) {
  83. t.Errorf("#%d: action = %+v, want %+v", i, gaction, tt.wactions)
  84. }
  85. }
  86. }
  87. // TestDoBadLocalAction tests server requests which do not need to go through consensus,
  88. // and return errors when they fetch from local data.
  89. func TestDoBadLocalAction(t *testing.T) {
  90. storeErr := fmt.Errorf("bah")
  91. tests := []struct {
  92. req pb.Request
  93. wactions []action
  94. }{
  95. {
  96. pb.Request{Method: "GET", ID: 1, Wait: true},
  97. []action{action{name: "Watch"}},
  98. },
  99. {
  100. pb.Request{Method: "GET", ID: 1},
  101. []action{action{name: "Get"}},
  102. },
  103. }
  104. for i, tt := range tests {
  105. st := &errStoreRecorder{err: storeErr}
  106. srv := &EtcdServer{store: st}
  107. resp, err := srv.Do(context.Background(), tt.req)
  108. if err != storeErr {
  109. t.Fatalf("#%d: err = %+v, want %+v", i, err, storeErr)
  110. }
  111. if !reflect.DeepEqual(resp, Response{}) {
  112. t.Errorf("#%d: resp = %+v, want %+v", i, resp, Response{})
  113. }
  114. gaction := st.Action()
  115. if !reflect.DeepEqual(gaction, tt.wactions) {
  116. t.Errorf("#%d: action = %+v, want %+v", i, gaction, tt.wactions)
  117. }
  118. }
  119. }
  120. func TestApply(t *testing.T) {
  121. tests := []struct {
  122. req pb.Request
  123. wresp Response
  124. wactions []action
  125. }{
  126. // POST ==> Create
  127. {
  128. pb.Request{Method: "POST", ID: 1},
  129. Response{Event: &store.Event{}},
  130. []action{
  131. action{
  132. name: "Create",
  133. params: []interface{}{"", false, "", true, time.Time{}},
  134. },
  135. },
  136. },
  137. // POST ==> Create, with expiration
  138. {
  139. pb.Request{Method: "POST", ID: 1, Expiration: 1337},
  140. Response{Event: &store.Event{}},
  141. []action{
  142. action{
  143. name: "Create",
  144. params: []interface{}{"", false, "", true, time.Unix(0, 1337)},
  145. },
  146. },
  147. },
  148. // POST ==> Create, with dir
  149. {
  150. pb.Request{Method: "POST", ID: 1, Dir: true},
  151. Response{Event: &store.Event{}},
  152. []action{
  153. action{
  154. name: "Create",
  155. params: []interface{}{"", true, "", true, time.Time{}},
  156. },
  157. },
  158. },
  159. // PUT ==> Set
  160. {
  161. pb.Request{Method: "PUT", ID: 1},
  162. Response{Event: &store.Event{}},
  163. []action{
  164. action{
  165. name: "Set",
  166. params: []interface{}{"", false, "", time.Time{}},
  167. },
  168. },
  169. },
  170. // PUT ==> Set, with dir
  171. {
  172. pb.Request{Method: "PUT", ID: 1, Dir: true},
  173. Response{Event: &store.Event{}},
  174. []action{
  175. action{
  176. name: "Set",
  177. params: []interface{}{"", true, "", time.Time{}},
  178. },
  179. },
  180. },
  181. // PUT with PrevExist=true ==> Update
  182. {
  183. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(true)},
  184. Response{Event: &store.Event{}},
  185. []action{
  186. action{
  187. name: "Update",
  188. params: []interface{}{"", "", time.Time{}},
  189. },
  190. },
  191. },
  192. // PUT with PrevExist=false ==> Create
  193. {
  194. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(false)},
  195. Response{Event: &store.Event{}},
  196. []action{
  197. action{
  198. name: "Create",
  199. params: []interface{}{"", false, "", false, time.Time{}},
  200. },
  201. },
  202. },
  203. // PUT with PrevExist=true *and* PrevIndex set ==> Update
  204. // TODO(jonboulle): is this expected?!
  205. {
  206. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(true), PrevIndex: 1},
  207. Response{Event: &store.Event{}},
  208. []action{
  209. action{
  210. name: "Update",
  211. params: []interface{}{"", "", time.Time{}},
  212. },
  213. },
  214. },
  215. // PUT with PrevExist=false *and* PrevIndex set ==> Create
  216. // TODO(jonboulle): is this expected?!
  217. {
  218. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(false), PrevIndex: 1},
  219. Response{Event: &store.Event{}},
  220. []action{
  221. action{
  222. name: "Create",
  223. params: []interface{}{"", false, "", false, time.Time{}},
  224. },
  225. },
  226. },
  227. // PUT with PrevIndex set ==> CompareAndSwap
  228. {
  229. pb.Request{Method: "PUT", ID: 1, PrevIndex: 1},
  230. Response{Event: &store.Event{}},
  231. []action{
  232. action{
  233. name: "CompareAndSwap",
  234. params: []interface{}{"", "", uint64(1), "", time.Time{}},
  235. },
  236. },
  237. },
  238. // PUT with PrevValue set ==> CompareAndSwap
  239. {
  240. pb.Request{Method: "PUT", ID: 1, PrevValue: "bar"},
  241. Response{Event: &store.Event{}},
  242. []action{
  243. action{
  244. name: "CompareAndSwap",
  245. params: []interface{}{"", "bar", uint64(0), "", time.Time{}},
  246. },
  247. },
  248. },
  249. // PUT with PrevIndex and PrevValue set ==> CompareAndSwap
  250. {
  251. pb.Request{Method: "PUT", ID: 1, PrevIndex: 1, PrevValue: "bar"},
  252. Response{Event: &store.Event{}},
  253. []action{
  254. action{
  255. name: "CompareAndSwap",
  256. params: []interface{}{"", "bar", uint64(1), "", time.Time{}},
  257. },
  258. },
  259. },
  260. // DELETE ==> Delete
  261. {
  262. pb.Request{Method: "DELETE", ID: 1},
  263. Response{Event: &store.Event{}},
  264. []action{
  265. action{
  266. name: "Delete",
  267. params: []interface{}{"", false, false},
  268. },
  269. },
  270. },
  271. // DELETE with PrevIndex set ==> CompareAndDelete
  272. {
  273. pb.Request{Method: "DELETE", ID: 1, PrevIndex: 1},
  274. Response{Event: &store.Event{}},
  275. []action{
  276. action{
  277. name: "CompareAndDelete",
  278. params: []interface{}{"", "", uint64(1)},
  279. },
  280. },
  281. },
  282. // DELETE with PrevValue set ==> CompareAndDelete
  283. {
  284. pb.Request{Method: "DELETE", ID: 1, PrevValue: "bar"},
  285. Response{Event: &store.Event{}},
  286. []action{
  287. action{
  288. name: "CompareAndDelete",
  289. params: []interface{}{"", "bar", uint64(0)},
  290. },
  291. },
  292. },
  293. // DELETE with PrevIndex *and* PrevValue set ==> CompareAndDelete
  294. {
  295. pb.Request{Method: "DELETE", ID: 1, PrevIndex: 5, PrevValue: "bar"},
  296. Response{Event: &store.Event{}},
  297. []action{
  298. action{
  299. name: "CompareAndDelete",
  300. params: []interface{}{"", "bar", uint64(5)},
  301. },
  302. },
  303. },
  304. // QGET ==> Get
  305. {
  306. pb.Request{Method: "QGET", ID: 1},
  307. Response{Event: &store.Event{}},
  308. []action{
  309. action{
  310. name: "Get",
  311. params: []interface{}{"", false, false},
  312. },
  313. },
  314. },
  315. // SYNC ==> DeleteExpiredKeys
  316. {
  317. pb.Request{Method: "SYNC", ID: 1},
  318. Response{},
  319. []action{
  320. action{
  321. name: "DeleteExpiredKeys",
  322. params: []interface{}{time.Unix(0, 0)},
  323. },
  324. },
  325. },
  326. {
  327. pb.Request{Method: "SYNC", ID: 1, Time: 12345},
  328. Response{},
  329. []action{
  330. action{
  331. name: "DeleteExpiredKeys",
  332. params: []interface{}{time.Unix(0, 12345)},
  333. },
  334. },
  335. },
  336. // Unknown method - error
  337. {
  338. pb.Request{Method: "BADMETHOD", ID: 1},
  339. Response{err: ErrUnknownMethod},
  340. []action{},
  341. },
  342. }
  343. for i, tt := range tests {
  344. st := &storeRecorder{}
  345. srv := &EtcdServer{store: st}
  346. resp := srv.apply(tt.req)
  347. if !reflect.DeepEqual(resp, tt.wresp) {
  348. t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp)
  349. }
  350. gaction := st.Action()
  351. if !reflect.DeepEqual(gaction, tt.wactions) {
  352. t.Errorf("#%d: action = %#v, want %#v", i, gaction, tt.wactions)
  353. }
  354. }
  355. }
  356. func TestClusterOf1(t *testing.T) { testServer(t, 1) }
  357. func TestClusterOf3(t *testing.T) { testServer(t, 3) }
  358. func testServer(t *testing.T, ns int64) {
  359. ctx, cancel := context.WithCancel(context.Background())
  360. defer cancel()
  361. ss := make([]*EtcdServer, ns)
  362. send := func(msgs []raftpb.Message) {
  363. for _, m := range msgs {
  364. t.Logf("m = %+v\n", m)
  365. ss[m.To-1].node.Step(ctx, m)
  366. }
  367. }
  368. members := make([]int64, ns)
  369. for i := int64(0); i < ns; i++ {
  370. members[i] = i + 1
  371. }
  372. for i := int64(0); i < ns; i++ {
  373. id := i + 1
  374. n := raft.StartNode(id, members, 10, 1)
  375. tk := time.NewTicker(10 * time.Millisecond)
  376. defer tk.Stop()
  377. srv := &EtcdServer{
  378. node: n,
  379. store: store.New(),
  380. send: send,
  381. storage: &storageRecorder{},
  382. ticker: tk.C,
  383. }
  384. srv.start()
  385. // TODO(xiangli): randomize election timeout
  386. // then remove this sleep.
  387. time.Sleep(1 * time.Millisecond)
  388. ss[i] = srv
  389. }
  390. for i := 1; i <= 10; i++ {
  391. r := pb.Request{
  392. Method: "PUT",
  393. ID: int64(i),
  394. Path: "/foo",
  395. Val: "bar",
  396. }
  397. j := rand.Intn(len(ss))
  398. t.Logf("ss = %d", j)
  399. resp, err := ss[j].Do(ctx, r)
  400. if err != nil {
  401. t.Fatal(err)
  402. }
  403. g, w := resp.Event.Node, &store.NodeExtern{
  404. Key: "/foo",
  405. ModifiedIndex: uint64(i),
  406. CreatedIndex: uint64(i),
  407. Value: stringp("bar"),
  408. }
  409. if !reflect.DeepEqual(g, w) {
  410. t.Error("value:", *g.Value)
  411. t.Errorf("g = %+v, w %+v", g, w)
  412. }
  413. }
  414. time.Sleep(10 * time.Millisecond)
  415. var last interface{}
  416. for i, sv := range ss {
  417. sv.Stop()
  418. g, _ := sv.store.Get("/", true, true)
  419. if last != nil && !reflect.DeepEqual(last, g) {
  420. t.Errorf("server %d: Root = %#v, want %#v", i, g, last)
  421. }
  422. last = g
  423. }
  424. }
  425. func TestDoProposal(t *testing.T) {
  426. tests := []pb.Request{
  427. pb.Request{Method: "POST", ID: 1},
  428. pb.Request{Method: "PUT", ID: 1},
  429. pb.Request{Method: "DELETE", ID: 1},
  430. pb.Request{Method: "GET", ID: 1, Quorum: true},
  431. }
  432. for i, tt := range tests {
  433. ctx, _ := context.WithCancel(context.Background())
  434. n := raft.StartNode(0xBAD0, []int64{0xBAD0}, 10, 1)
  435. st := &storeRecorder{}
  436. tk := make(chan time.Time)
  437. // this makes <-tk always successful, which accelerates internal clock
  438. close(tk)
  439. srv := &EtcdServer{
  440. node: n,
  441. store: st,
  442. send: func(_ []raftpb.Message) {},
  443. storage: &storageRecorder{},
  444. ticker: tk,
  445. }
  446. srv.start()
  447. resp, err := srv.Do(ctx, tt)
  448. srv.Stop()
  449. action := st.Action()
  450. if len(action) != 1 {
  451. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  452. }
  453. if err != nil {
  454. t.Fatalf("#%d: err = %v, want nil", i, err)
  455. }
  456. wresp := Response{Event: &store.Event{}}
  457. if !reflect.DeepEqual(resp, wresp) {
  458. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  459. }
  460. }
  461. }
  462. func TestDoProposalCancelled(t *testing.T) {
  463. ctx, cancel := context.WithCancel(context.Background())
  464. // node cannot make any progress because there are two nodes
  465. n := raft.StartNode(0xBAD0, []int64{0xBAD0, 0xBAD1}, 10, 1)
  466. st := &storeRecorder{}
  467. wait := &waitRecorder{}
  468. srv := &EtcdServer{
  469. // TODO: use fake node for better testability
  470. node: n,
  471. store: st,
  472. w: wait,
  473. }
  474. done := make(chan struct{})
  475. var err error
  476. go func() {
  477. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  478. close(done)
  479. }()
  480. cancel()
  481. <-done
  482. gaction := st.Action()
  483. if len(gaction) != 0 {
  484. t.Errorf("len(action) = %v, want 0", len(gaction))
  485. }
  486. if err != context.Canceled {
  487. t.Fatalf("err = %v, want %v", err, context.Canceled)
  488. }
  489. w := []action{action{name: "Register1"}, action{name: "Trigger1"}}
  490. if !reflect.DeepEqual(wait.action, w) {
  491. t.Errorf("wait.action = %+v, want %+v", wait.action, w)
  492. }
  493. }
  494. func TestDoProposalStopped(t *testing.T) {
  495. ctx, cancel := context.WithCancel(context.Background())
  496. defer cancel()
  497. // node cannot make any progress because there are two nodes
  498. n := raft.StartNode(0xBAD0, []int64{0xBAD0, 0xBAD1}, 10, 1)
  499. st := &storeRecorder{}
  500. tk := make(chan time.Time)
  501. // this makes <-tk always successful, which accelarates internal clock
  502. close(tk)
  503. srv := &EtcdServer{
  504. // TODO: use fake node for better testability
  505. node: n,
  506. store: st,
  507. send: func(_ []raftpb.Message) {},
  508. storage: &storageRecorder{},
  509. ticker: tk,
  510. }
  511. srv.start()
  512. done := make(chan struct{})
  513. var err error
  514. go func() {
  515. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  516. close(done)
  517. }()
  518. srv.Stop()
  519. <-done
  520. action := st.Action()
  521. if len(action) != 0 {
  522. t.Errorf("len(action) = %v, want 0", len(action))
  523. }
  524. if err != ErrStopped {
  525. t.Errorf("err = %v, want %v", err, ErrStopped)
  526. }
  527. }
  528. // TestSync tests sync 1. is nonblocking 2. sends out SYNC request.
  529. func TestSync(t *testing.T) {
  530. n := &nodeProposeDataRecorder{}
  531. srv := &EtcdServer{
  532. node: n,
  533. }
  534. start := time.Now()
  535. srv.sync(defaultSyncTimeout)
  536. // check that sync is non-blocking
  537. if d := time.Since(start); d > time.Millisecond {
  538. t.Errorf("CallSyncTime = %v, want < %v", d, time.Millisecond)
  539. }
  540. pkg.ForceGosched()
  541. data := n.data()
  542. if len(data) != 1 {
  543. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  544. }
  545. var r pb.Request
  546. if err := r.Unmarshal(data[0]); err != nil {
  547. t.Fatalf("unmarshal request error: %v", err)
  548. }
  549. if r.Method != "SYNC" {
  550. t.Errorf("method = %s, want SYNC", r.Method)
  551. }
  552. }
  553. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  554. // after timeout
  555. func TestSyncTimeout(t *testing.T) {
  556. n := &nodeProposalBlockerRecorder{}
  557. srv := &EtcdServer{
  558. node: n,
  559. }
  560. start := time.Now()
  561. srv.sync(0)
  562. // check that sync is non-blocking
  563. if d := time.Since(start); d > time.Millisecond {
  564. t.Errorf("CallSyncTime = %v, want < %v", d, time.Millisecond)
  565. }
  566. // give time for goroutine in sync to cancel
  567. // TODO: use fake clock
  568. pkg.ForceGosched()
  569. w := []action{action{name: "Propose blocked"}}
  570. if g := n.Action(); !reflect.DeepEqual(g, w) {
  571. t.Errorf("action = %v, want %v", g, w)
  572. }
  573. }
  574. // TODO: TestNoSyncWhenNoLeader
  575. // blockingNodeProposer implements the node interface to allow users to
  576. // block until Propose has been called and then verify the Proposed data
  577. type blockingNodeProposer struct {
  578. ch chan []byte
  579. readyNode
  580. }
  581. func (n *blockingNodeProposer) Propose(_ context.Context, data []byte) error {
  582. n.ch <- data
  583. return nil
  584. }
  585. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  586. func TestSyncTrigger(t *testing.T) {
  587. n := &blockingNodeProposer{
  588. ch: make(chan []byte),
  589. readyNode: *newReadyNode(),
  590. }
  591. st := make(chan time.Time, 1)
  592. srv := &EtcdServer{
  593. node: n,
  594. store: &storeRecorder{},
  595. send: func(_ []raftpb.Message) {},
  596. storage: &storageRecorder{},
  597. syncTicker: st,
  598. }
  599. srv.start()
  600. // trigger the server to become a leader and accept sync requests
  601. n.readyc <- raft.Ready{
  602. SoftState: &raft.SoftState{
  603. RaftState: raft.StateLeader,
  604. },
  605. }
  606. // trigger a sync request
  607. st <- time.Time{}
  608. var data []byte
  609. select {
  610. case <-time.After(time.Second):
  611. t.Fatalf("did not receive proposed request as expected!")
  612. case data = <-n.ch:
  613. }
  614. srv.Stop()
  615. var req pb.Request
  616. if err := req.Unmarshal(data); err != nil {
  617. t.Fatalf("error unmarshalling data: %v", err)
  618. }
  619. if req.Method != "SYNC" {
  620. t.Fatalf("unexpected proposed request: %#v", req.Method)
  621. }
  622. }
  623. // snapshot should snapshot the store and cut the persistent
  624. // TODO: node.Compact is called... we need to make the node an interface
  625. func TestSnapshot(t *testing.T) {
  626. n := raft.StartNode(0xBAD0, []int64{0xBAD0}, 10, 1)
  627. defer n.Stop()
  628. st := &storeRecorder{}
  629. p := &storageRecorder{}
  630. s := &EtcdServer{
  631. store: st,
  632. storage: p,
  633. node: n,
  634. }
  635. s.snapshot(0, []int64{1})
  636. gaction := st.Action()
  637. if len(gaction) != 1 {
  638. t.Fatalf("len(action) = %d, want 1", len(gaction))
  639. }
  640. if !reflect.DeepEqual(gaction[0], action{name: "Save"}) {
  641. t.Errorf("action = %s, want Save", gaction[0])
  642. }
  643. gaction = p.Action()
  644. if len(gaction) != 1 {
  645. t.Fatalf("len(action) = %d, want 1", len(gaction))
  646. }
  647. if !reflect.DeepEqual(gaction[0], action{name: "Cut"}) {
  648. t.Errorf("action = %s, want Cut", gaction[0])
  649. }
  650. }
  651. // Applied > SnapCount should trigger a SaveSnap event
  652. func TestTriggerSnap(t *testing.T) {
  653. ctx := context.Background()
  654. n := raft.StartNode(0xBAD0, []int64{0xBAD0}, 10, 1)
  655. n.Campaign(ctx)
  656. st := &storeRecorder{}
  657. p := &storageRecorder{}
  658. s := &EtcdServer{
  659. store: st,
  660. send: func(_ []raftpb.Message) {},
  661. storage: p,
  662. node: n,
  663. snapCount: 10,
  664. }
  665. s.start()
  666. for i := 0; int64(i) < s.snapCount-1; i++ {
  667. s.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  668. }
  669. time.Sleep(time.Millisecond)
  670. s.Stop()
  671. gaction := p.Action()
  672. // each operation is recorded as a Save
  673. // BootstrapConfig/Nop + (SnapCount - 1) * Puts + Cut + SaveSnap = Save + (SnapCount - 1) * Save + Cut + SaveSnap
  674. if len(gaction) != 2+int(s.snapCount) {
  675. t.Fatalf("len(action) = %d, want %d", len(gaction), 2+int(s.snapCount))
  676. }
  677. if !reflect.DeepEqual(gaction[11], action{name: "SaveSnap"}) {
  678. t.Errorf("action = %s, want SaveSnap", gaction[11])
  679. }
  680. }
  681. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  682. // it should trigger storage.SaveSnap and also store.Recover.
  683. func TestRecvSnapshot(t *testing.T) {
  684. n := newReadyNode()
  685. st := &storeRecorder{}
  686. p := &storageRecorder{}
  687. s := &EtcdServer{
  688. store: st,
  689. send: func(_ []raftpb.Message) {},
  690. storage: p,
  691. node: n,
  692. }
  693. s.start()
  694. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  695. // make goroutines move forward to receive snapshot
  696. pkg.ForceGosched()
  697. s.Stop()
  698. wactions := []action{action{name: "Recovery"}}
  699. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  700. t.Errorf("store action = %v, want %v", g, wactions)
  701. }
  702. wactions = []action{action{name: "Save"}, action{name: "SaveSnap"}}
  703. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  704. t.Errorf("storage action = %v, want %v", g, wactions)
  705. }
  706. }
  707. // TestRecvSlowSnapshot tests that slow snapshot will not be applied
  708. // to store.
  709. func TestRecvSlowSnapshot(t *testing.T) {
  710. n := newReadyNode()
  711. st := &storeRecorder{}
  712. s := &EtcdServer{
  713. store: st,
  714. send: func(_ []raftpb.Message) {},
  715. storage: &storageRecorder{},
  716. node: n,
  717. }
  718. s.start()
  719. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  720. // make goroutines move forward to receive snapshot
  721. pkg.ForceGosched()
  722. action := st.Action()
  723. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  724. // make goroutines move forward to receive snapshot
  725. pkg.ForceGosched()
  726. s.Stop()
  727. if g := st.Action(); !reflect.DeepEqual(g, action) {
  728. t.Errorf("store action = %v, want %v", g, action)
  729. }
  730. }
  731. // TestAddNode tests AddNode can propose and perform node addition.
  732. func TestAddNode(t *testing.T) {
  733. n := newNodeConfChangeCommitterRecorder()
  734. s := &EtcdServer{
  735. node: n,
  736. store: &storeRecorder{},
  737. send: func(_ []raftpb.Message) {},
  738. storage: &storageRecorder{},
  739. }
  740. s.start()
  741. s.AddNode(context.TODO(), 1, []byte("foo"))
  742. gaction := n.Action()
  743. s.Stop()
  744. wactions := []action{action{name: "ProposeConfChange:ConfChangeAddNode"}, action{name: "ApplyConfChange:ConfChangeAddNode"}}
  745. if !reflect.DeepEqual(gaction, wactions) {
  746. t.Errorf("action = %v, want %v", gaction, wactions)
  747. }
  748. }
  749. // TestRemoveNode tests RemoveNode can propose and perform node removal.
  750. func TestRemoveNode(t *testing.T) {
  751. n := newNodeConfChangeCommitterRecorder()
  752. s := &EtcdServer{
  753. node: n,
  754. store: &storeRecorder{},
  755. send: func(_ []raftpb.Message) {},
  756. storage: &storageRecorder{},
  757. }
  758. s.start()
  759. s.RemoveNode(context.TODO(), 1)
  760. gaction := n.Action()
  761. s.Stop()
  762. wactions := []action{action{name: "ProposeConfChange:ConfChangeRemoveNode"}, action{name: "ApplyConfChange:ConfChangeRemoveNode"}}
  763. if !reflect.DeepEqual(gaction, wactions) {
  764. t.Errorf("action = %v, want %v", gaction, wactions)
  765. }
  766. }
  767. // TestServerStopItself tests that if node sends out Ready with ShouldStop,
  768. // server will stop.
  769. func TestServerStopItself(t *testing.T) {
  770. n := newReadyNode()
  771. s := &EtcdServer{
  772. node: n,
  773. store: &storeRecorder{},
  774. send: func(_ []raftpb.Message) {},
  775. storage: &storageRecorder{},
  776. }
  777. s.start()
  778. n.readyc <- raft.Ready{SoftState: &raft.SoftState{ShouldStop: true}}
  779. select {
  780. case <-s.done:
  781. case <-time.After(time.Millisecond):
  782. t.Errorf("did not receive from closed done channel as expected")
  783. }
  784. }
  785. // TODO: test wait trigger correctness in multi-server case
  786. func TestPublish(t *testing.T) {
  787. n := &nodeProposeDataRecorder{}
  788. cs := mustClusterStore(t, []Member{{ID: 1, Name: "node1"}})
  789. ch := make(chan interface{}, 1)
  790. // simulate that request has gone through consensus
  791. ch <- Response{}
  792. w := &waitWithResponse{ch: ch}
  793. srv := &EtcdServer{
  794. name: "node1",
  795. clientURLs: []url.URL{{Scheme: "http", Host: "a"}, {Scheme: "http", Host: "b"}},
  796. node: n,
  797. ClusterStore: cs,
  798. w: w,
  799. }
  800. srv.publish(time.Hour)
  801. data := n.data()
  802. if len(data) != 1 {
  803. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  804. }
  805. var r pb.Request
  806. if err := r.Unmarshal(data[0]); err != nil {
  807. t.Fatalf("unmarshal request error: %v", err)
  808. }
  809. if r.Method != "PUT" {
  810. t.Errorf("method = %s, want PUT", r.Method)
  811. }
  812. wm := Member{ID: 1, Name: "node1", ClientURLs: []string{"http://a", "http://b"}}
  813. if r.Path != wm.storeKey() {
  814. t.Errorf("path = %s, want %s", r.Path, wm.storeKey())
  815. }
  816. var gm Member
  817. if err := json.Unmarshal([]byte(r.Val), &gm); err != nil {
  818. t.Fatalf("unmarshal val error: %v", err)
  819. }
  820. if !reflect.DeepEqual(gm, wm) {
  821. t.Errorf("member = %v, want %v", gm, wm)
  822. }
  823. }
  824. // TestPublishStopped tests that publish will be stopped if server is stopped.
  825. func TestPublishStopped(t *testing.T) {
  826. cs := mustClusterStore(t, []Member{{ID: 1, Name: "node1"}})
  827. srv := &EtcdServer{
  828. name: "node1",
  829. node: &nodeRecorder{},
  830. ClusterStore: cs,
  831. w: &waitRecorder{},
  832. done: make(chan struct{}),
  833. }
  834. srv.Stop()
  835. srv.publish(time.Hour)
  836. }
  837. // TestPublishRetry tests that publish will keep retry until success.
  838. func TestPublishRetry(t *testing.T) {
  839. n := &nodeRecorder{}
  840. cs := mustClusterStore(t, []Member{{ID: 1, Name: "node1"}})
  841. srv := &EtcdServer{
  842. name: "node1",
  843. node: n,
  844. ClusterStore: cs,
  845. w: &waitRecorder{},
  846. done: make(chan struct{}),
  847. }
  848. time.AfterFunc(500*time.Microsecond, srv.Stop)
  849. srv.publish(10 * time.Nanosecond)
  850. action := n.Action()
  851. // multiple Propose + Stop
  852. if len(action) < 3 {
  853. t.Errorf("len(action) = %d, want >= 3", action)
  854. }
  855. }
  856. func TestGetBool(t *testing.T) {
  857. tests := []struct {
  858. b *bool
  859. wb bool
  860. wset bool
  861. }{
  862. {nil, false, false},
  863. {boolp(true), true, true},
  864. {boolp(false), false, true},
  865. }
  866. for i, tt := range tests {
  867. b, set := getBool(tt.b)
  868. if b != tt.wb {
  869. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  870. }
  871. if set != tt.wset {
  872. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  873. }
  874. }
  875. }
  876. func TestGenID(t *testing.T) {
  877. // Sanity check that the GenID function has been seeded appropriately
  878. // (math/rand is seeded with 1 by default)
  879. r := rand.NewSource(int64(1))
  880. var n int64
  881. for n == 0 {
  882. n = r.Int63()
  883. }
  884. if n == GenID() {
  885. t.Fatalf("GenID's rand seeded with 1!")
  886. }
  887. }
  888. type action struct {
  889. name string
  890. params []interface{}
  891. }
  892. type recorder struct {
  893. sync.Mutex
  894. actions []action
  895. }
  896. func (r *recorder) record(a action) {
  897. r.Lock()
  898. r.actions = append(r.actions, a)
  899. r.Unlock()
  900. }
  901. func (r *recorder) Action() []action {
  902. r.Lock()
  903. cpy := make([]action, len(r.actions))
  904. copy(cpy, r.actions)
  905. r.Unlock()
  906. return cpy
  907. }
  908. type storeRecorder struct {
  909. recorder
  910. }
  911. func (s *storeRecorder) Version() int { return 0 }
  912. func (s *storeRecorder) Index() uint64 { return 0 }
  913. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  914. s.record(action{
  915. name: "Get",
  916. params: []interface{}{path, recursive, sorted},
  917. })
  918. return &store.Event{}, nil
  919. }
  920. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  921. s.record(action{
  922. name: "Set",
  923. params: []interface{}{path, dir, val, expr},
  924. })
  925. return &store.Event{}, nil
  926. }
  927. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  928. s.record(action{
  929. name: "Update",
  930. params: []interface{}{path, val, expr},
  931. })
  932. return &store.Event{}, nil
  933. }
  934. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  935. s.record(action{
  936. name: "Create",
  937. params: []interface{}{path, dir, val, uniq, exp},
  938. })
  939. return &store.Event{}, nil
  940. }
  941. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  942. s.record(action{
  943. name: "CompareAndSwap",
  944. params: []interface{}{path, prevVal, prevIdx, val, expr},
  945. })
  946. return &store.Event{}, nil
  947. }
  948. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  949. s.record(action{
  950. name: "Delete",
  951. params: []interface{}{path, dir, recursive},
  952. })
  953. return &store.Event{}, nil
  954. }
  955. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  956. s.record(action{
  957. name: "CompareAndDelete",
  958. params: []interface{}{path, prevVal, prevIdx},
  959. })
  960. return &store.Event{}, nil
  961. }
  962. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  963. s.record(action{name: "Watch"})
  964. return &stubWatcher{}, nil
  965. }
  966. func (s *storeRecorder) Save() ([]byte, error) {
  967. s.record(action{name: "Save"})
  968. return nil, nil
  969. }
  970. func (s *storeRecorder) Recovery(b []byte) error {
  971. s.record(action{name: "Recovery"})
  972. return nil
  973. }
  974. func (s *storeRecorder) TotalTransactions() uint64 { return 0 }
  975. func (s *storeRecorder) JsonStats() []byte { return nil }
  976. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  977. s.record(action{
  978. name: "DeleteExpiredKeys",
  979. params: []interface{}{cutoff},
  980. })
  981. }
  982. type stubWatcher struct{}
  983. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  984. func (w *stubWatcher) StartIndex() uint64 { return 0 }
  985. func (w *stubWatcher) Remove() {}
  986. // errStoreRecorder returns an store error on Get, Watch request
  987. type errStoreRecorder struct {
  988. storeRecorder
  989. err error
  990. }
  991. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  992. s.record(action{name: "Get"})
  993. return nil, s.err
  994. }
  995. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  996. s.record(action{name: "Watch"})
  997. return nil, s.err
  998. }
  999. type waitRecorder struct {
  1000. action []action
  1001. }
  1002. func (w *waitRecorder) Register(id int64) <-chan interface{} {
  1003. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  1004. return nil
  1005. }
  1006. func (w *waitRecorder) Trigger(id int64, x interface{}) {
  1007. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  1008. }
  1009. func boolp(b bool) *bool { return &b }
  1010. func stringp(s string) *string { return &s }
  1011. type storageRecorder struct {
  1012. recorder
  1013. }
  1014. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) {
  1015. p.record(action{name: "Save"})
  1016. }
  1017. func (p *storageRecorder) Cut() error {
  1018. p.record(action{name: "Cut"})
  1019. return nil
  1020. }
  1021. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
  1022. if raft.IsEmptySnap(st) {
  1023. return
  1024. }
  1025. p.record(action{name: "SaveSnap"})
  1026. }
  1027. type readyNode struct {
  1028. readyc chan raft.Ready
  1029. }
  1030. func newReadyNode() *readyNode {
  1031. readyc := make(chan raft.Ready, 1)
  1032. return &readyNode{readyc: readyc}
  1033. }
  1034. func (n *readyNode) Tick() {}
  1035. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1036. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1037. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1038. return nil
  1039. }
  1040. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1041. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1042. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) {}
  1043. func (n *readyNode) Stop() {}
  1044. func (n *readyNode) Compact(index int64, nodes []int64, d []byte) {}
  1045. type nodeRecorder struct {
  1046. recorder
  1047. }
  1048. func (n *nodeRecorder) Tick() {
  1049. n.record(action{name: "Tick"})
  1050. }
  1051. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1052. n.record(action{name: "Campaign"})
  1053. return nil
  1054. }
  1055. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1056. n.record(action{name: "Propose"})
  1057. return nil
  1058. }
  1059. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1060. n.record(action{name: "ProposeConfChange"})
  1061. return nil
  1062. }
  1063. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1064. n.record(action{name: "Step"})
  1065. return nil
  1066. }
  1067. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1068. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1069. n.record(action{name: "ApplyConfChange"})
  1070. }
  1071. func (n *nodeRecorder) Stop() {
  1072. n.record(action{name: "Stop"})
  1073. }
  1074. func (n *nodeRecorder) Compact(index int64, nodes []int64, d []byte) {
  1075. n.record(action{name: "Compact"})
  1076. }
  1077. type nodeProposeDataRecorder struct {
  1078. nodeRecorder
  1079. sync.Mutex
  1080. d [][]byte
  1081. }
  1082. func (n *nodeProposeDataRecorder) data() [][]byte {
  1083. n.Lock()
  1084. d := n.d
  1085. n.Unlock()
  1086. return d
  1087. }
  1088. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1089. n.nodeRecorder.Propose(ctx, data)
  1090. n.Lock()
  1091. n.d = append(n.d, data)
  1092. n.Unlock()
  1093. return nil
  1094. }
  1095. type nodeProposalBlockerRecorder struct {
  1096. nodeRecorder
  1097. }
  1098. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1099. <-ctx.Done()
  1100. n.record(action{name: "Propose blocked"})
  1101. return nil
  1102. }
  1103. type nodeConfChangeCommitterRecorder struct {
  1104. nodeRecorder
  1105. readyc chan raft.Ready
  1106. }
  1107. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1108. readyc := make(chan raft.Ready, 1)
  1109. readyc <- raft.Ready{SoftState: &raft.SoftState{RaftState: raft.StateLeader}}
  1110. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1111. }
  1112. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1113. data, err := conf.Marshal()
  1114. if err != nil {
  1115. return err
  1116. }
  1117. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1118. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1119. return nil
  1120. }
  1121. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1122. return n.readyc
  1123. }
  1124. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1125. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1126. }
  1127. type waitWithResponse struct {
  1128. ch <-chan interface{}
  1129. }
  1130. func (w *waitWithResponse) Register(id int64) <-chan interface{} {
  1131. return w.ch
  1132. }
  1133. func (w *waitWithResponse) Trigger(id int64, x interface{}) {}
  1134. func mustClusterStore(t *testing.T, membs []Member) ClusterStore {
  1135. c := Cluster{}
  1136. if err := c.AddSlice(membs); err != nil {
  1137. t.Fatalf("error creating cluster from %v: %v", membs, err)
  1138. }
  1139. return NewClusterStore(&getAllStore{}, c)
  1140. }