server_test.go 31 KB

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