server_test.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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 TestApply(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.apply(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 int64) {
  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([]int64, ns)
  368. for i := int64(0); i < ns; i++ {
  369. members[i] = i + 1
  370. }
  371. for i := int64(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, []int64{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, []int64{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, []int64{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, []int64{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()
  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, []int64{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; int64(i) < s.SnapCount; 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. // Nop + SnapCount * Puts + Cut + SaveSnap = Save + SnapCount * Save + Cut + SaveSnap
  673. if len(gaction) != 3+int(s.SnapCount) {
  674. t.Fatalf("len(action) = %d, want %d", len(gaction), 3+int(s.SnapCount))
  675. }
  676. if !reflect.DeepEqual(gaction[12], action{name: "SaveSnap"}) {
  677. t.Errorf("action = %s, want SaveSnap", gaction[12])
  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. // TestAddNode tests AddNode can propose and perform node addition.
  731. func TestAddNode(t *testing.T) {
  732. n := newNodeConfChangeCommitterRecorder()
  733. s := &EtcdServer{
  734. Node: n,
  735. Store: &storeRecorder{},
  736. Send: func(_ []raftpb.Message) {},
  737. Storage: &storageRecorder{},
  738. }
  739. s.start()
  740. s.AddNode(context.TODO(), 1, []byte("foo"))
  741. gaction := n.Action()
  742. s.Stop()
  743. wactions := []action{action{name: "ProposeConfChange:ConfChangeAddNode"}, action{name: "ApplyConfChange:ConfChangeAddNode"}}
  744. if !reflect.DeepEqual(gaction, wactions) {
  745. t.Errorf("action = %v, want %v", gaction, wactions)
  746. }
  747. }
  748. // TestRemoveNode tests RemoveNode can propose and perform node removal.
  749. func TestRemoveNode(t *testing.T) {
  750. n := newNodeConfChangeCommitterRecorder()
  751. s := &EtcdServer{
  752. Node: n,
  753. Store: &storeRecorder{},
  754. Send: func(_ []raftpb.Message) {},
  755. Storage: &storageRecorder{},
  756. }
  757. s.start()
  758. s.RemoveNode(context.TODO(), 1)
  759. gaction := n.Action()
  760. s.Stop()
  761. wactions := []action{action{name: "ProposeConfChange:ConfChangeRemoveNode"}, action{name: "ApplyConfChange:ConfChangeRemoveNode"}}
  762. if !reflect.DeepEqual(gaction, wactions) {
  763. t.Errorf("action = %v, want %v", gaction, wactions)
  764. }
  765. }
  766. // TODO: test wait trigger correctness in multi-server case
  767. func TestPublish(t *testing.T) {
  768. n := &nodeProposeDataRecorder{}
  769. ch := make(chan interface{}, 1)
  770. // simulate that request has gone through consensus
  771. ch <- Response{}
  772. w := &waitWithResponse{ch: ch}
  773. srv := &EtcdServer{
  774. Node: n,
  775. w: w,
  776. }
  777. m := Member{ID: 1, Name: "node1"}
  778. srv.publish(m, time.Hour)
  779. data := n.data()
  780. if len(data) != 1 {
  781. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  782. }
  783. var r pb.Request
  784. if err := r.Unmarshal(data[0]); err != nil {
  785. t.Fatalf("unmarshal request error: %v", err)
  786. }
  787. if r.Method != "PUT" {
  788. t.Errorf("method = %s, want PUT", r.Method)
  789. }
  790. if r.Path != m.storeKey() {
  791. t.Errorf("path = %s, want %s", r.Path, m.storeKey())
  792. }
  793. var gm Member
  794. if err := json.Unmarshal([]byte(r.Val), &gm); err != nil {
  795. t.Fatalf("unmarshal val error: %v", err)
  796. }
  797. if !reflect.DeepEqual(gm, m) {
  798. t.Errorf("member = %v, want %v", gm, m)
  799. }
  800. }
  801. // TestPublishStopped tests that publish will be stopped if server is stopped.
  802. func TestPublishStopped(t *testing.T) {
  803. srv := &EtcdServer{
  804. Node: &nodeRecorder{},
  805. w: &waitRecorder{},
  806. done: make(chan struct{}),
  807. }
  808. srv.Stop()
  809. srv.publish(Member{ID: 1, Name: "node1"}, time.Hour)
  810. }
  811. // TestPublishRetry tests that publish will keep retry until success.
  812. func TestPublishRetry(t *testing.T) {
  813. n := &nodeRecorder{}
  814. srv := &EtcdServer{
  815. Node: n,
  816. w: &waitRecorder{},
  817. done: make(chan struct{}),
  818. }
  819. time.AfterFunc(500*time.Microsecond, srv.Stop)
  820. srv.publish(Member{ID: 1, Name: "node1"}, 10*time.Nanosecond)
  821. action := n.Action()
  822. // multiple Propose + Stop
  823. if len(action) < 3 {
  824. t.Errorf("len(action) = %d, want >= 3", action)
  825. }
  826. }
  827. func TestGetBool(t *testing.T) {
  828. tests := []struct {
  829. b *bool
  830. wb bool
  831. wset bool
  832. }{
  833. {nil, false, false},
  834. {boolp(true), true, true},
  835. {boolp(false), false, true},
  836. }
  837. for i, tt := range tests {
  838. b, set := getBool(tt.b)
  839. if b != tt.wb {
  840. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  841. }
  842. if set != tt.wset {
  843. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  844. }
  845. }
  846. }
  847. func TestGenID(t *testing.T) {
  848. // Sanity check that the GenID function has been seeded appropriately
  849. // (math/rand is seeded with 1 by default)
  850. r := rand.NewSource(int64(1))
  851. var n int64
  852. for n == 0 {
  853. n = r.Int63()
  854. }
  855. if n == GenID() {
  856. t.Fatalf("GenID's rand seeded with 1!")
  857. }
  858. }
  859. type action struct {
  860. name string
  861. params []interface{}
  862. }
  863. type recorder struct {
  864. sync.Mutex
  865. actions []action
  866. }
  867. func (r *recorder) record(a action) {
  868. r.Lock()
  869. r.actions = append(r.actions, a)
  870. r.Unlock()
  871. }
  872. func (r *recorder) Action() []action {
  873. r.Lock()
  874. cpy := make([]action, len(r.actions))
  875. copy(cpy, r.actions)
  876. r.Unlock()
  877. return cpy
  878. }
  879. type storeRecorder struct {
  880. recorder
  881. }
  882. func (s *storeRecorder) Version() int { return 0 }
  883. func (s *storeRecorder) Index() uint64 { return 0 }
  884. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  885. s.record(action{
  886. name: "Get",
  887. params: []interface{}{path, recursive, sorted},
  888. })
  889. return &store.Event{}, nil
  890. }
  891. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  892. s.record(action{
  893. name: "Set",
  894. params: []interface{}{path, dir, val, expr},
  895. })
  896. return &store.Event{}, nil
  897. }
  898. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  899. s.record(action{
  900. name: "Update",
  901. params: []interface{}{path, val, expr},
  902. })
  903. return &store.Event{}, nil
  904. }
  905. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  906. s.record(action{
  907. name: "Create",
  908. params: []interface{}{path, dir, val, uniq, exp},
  909. })
  910. return &store.Event{}, nil
  911. }
  912. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  913. s.record(action{
  914. name: "CompareAndSwap",
  915. params: []interface{}{path, prevVal, prevIdx, val, expr},
  916. })
  917. return &store.Event{}, nil
  918. }
  919. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  920. s.record(action{
  921. name: "Delete",
  922. params: []interface{}{path, dir, recursive},
  923. })
  924. return &store.Event{}, nil
  925. }
  926. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  927. s.record(action{
  928. name: "CompareAndDelete",
  929. params: []interface{}{path, prevVal, prevIdx},
  930. })
  931. return &store.Event{}, nil
  932. }
  933. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  934. s.record(action{name: "Watch"})
  935. return &stubWatcher{}, nil
  936. }
  937. func (s *storeRecorder) Save() ([]byte, error) {
  938. s.record(action{name: "Save"})
  939. return nil, nil
  940. }
  941. func (s *storeRecorder) Recovery(b []byte) error {
  942. s.record(action{name: "Recovery"})
  943. return nil
  944. }
  945. func (s *storeRecorder) TotalTransactions() uint64 { return 0 }
  946. func (s *storeRecorder) JsonStats() []byte { return nil }
  947. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  948. s.record(action{
  949. name: "DeleteExpiredKeys",
  950. params: []interface{}{cutoff},
  951. })
  952. }
  953. type stubWatcher struct{}
  954. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  955. func (w *stubWatcher) Remove() {}
  956. // errStoreRecorder returns an store error on Get, Watch request
  957. type errStoreRecorder struct {
  958. storeRecorder
  959. err error
  960. }
  961. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  962. s.record(action{name: "Get"})
  963. return nil, s.err
  964. }
  965. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  966. s.record(action{name: "Watch"})
  967. return nil, s.err
  968. }
  969. type waitRecorder struct {
  970. action []action
  971. }
  972. func (w *waitRecorder) Register(id int64) <-chan interface{} {
  973. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  974. return nil
  975. }
  976. func (w *waitRecorder) Trigger(id int64, x interface{}) {
  977. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  978. }
  979. func boolp(b bool) *bool { return &b }
  980. func stringp(s string) *string { return &s }
  981. type storageRecorder struct {
  982. recorder
  983. }
  984. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) {
  985. p.record(action{name: "Save"})
  986. }
  987. func (p *storageRecorder) Cut() error {
  988. p.record(action{name: "Cut"})
  989. return nil
  990. }
  991. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
  992. if raft.IsEmptySnap(st) {
  993. return
  994. }
  995. p.record(action{name: "SaveSnap"})
  996. }
  997. type readyNode struct {
  998. readyc chan raft.Ready
  999. }
  1000. func newReadyNode() *readyNode {
  1001. readyc := make(chan raft.Ready, 1)
  1002. return &readyNode{readyc: readyc}
  1003. }
  1004. func (n *readyNode) Tick() {}
  1005. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1006. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1007. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1008. return nil
  1009. }
  1010. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1011. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1012. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) {}
  1013. func (n *readyNode) Stop() {}
  1014. func (n *readyNode) Compact(d []byte) {}
  1015. type nodeRecorder struct {
  1016. recorder
  1017. }
  1018. func (n *nodeRecorder) Tick() {
  1019. n.record(action{name: "Tick"})
  1020. }
  1021. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1022. n.record(action{name: "Campaign"})
  1023. return nil
  1024. }
  1025. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1026. n.record(action{name: "Propose"})
  1027. return nil
  1028. }
  1029. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1030. n.record(action{name: "ProposeConfChange"})
  1031. return nil
  1032. }
  1033. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1034. n.record(action{name: "Step"})
  1035. return nil
  1036. }
  1037. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1038. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1039. n.record(action{name: "ApplyConfChange"})
  1040. }
  1041. func (n *nodeRecorder) Stop() {
  1042. n.record(action{name: "Stop"})
  1043. }
  1044. func (n *nodeRecorder) Compact(d []byte) {
  1045. n.record(action{name: "Compact"})
  1046. }
  1047. type nodeProposeDataRecorder struct {
  1048. nodeRecorder
  1049. sync.Mutex
  1050. d [][]byte
  1051. }
  1052. func (n *nodeProposeDataRecorder) data() [][]byte {
  1053. n.Lock()
  1054. d := n.d
  1055. n.Unlock()
  1056. return d
  1057. }
  1058. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1059. n.nodeRecorder.Propose(ctx, data)
  1060. n.Lock()
  1061. n.d = append(n.d, data)
  1062. n.Unlock()
  1063. return nil
  1064. }
  1065. type nodeProposalBlockerRecorder struct {
  1066. nodeRecorder
  1067. }
  1068. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1069. <-ctx.Done()
  1070. n.record(action{name: "Propose blocked"})
  1071. return nil
  1072. }
  1073. type nodeConfChangeCommitterRecorder struct {
  1074. nodeRecorder
  1075. readyc chan raft.Ready
  1076. }
  1077. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1078. readyc := make(chan raft.Ready, 1)
  1079. readyc <- raft.Ready{SoftState: &raft.SoftState{RaftState: raft.StateLeader}}
  1080. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1081. }
  1082. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1083. data, err := conf.Marshal()
  1084. if err != nil {
  1085. return err
  1086. }
  1087. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1088. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1089. return nil
  1090. }
  1091. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1092. return n.readyc
  1093. }
  1094. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1095. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1096. }
  1097. type waitWithResponse struct {
  1098. ch <-chan interface{}
  1099. }
  1100. func (w *waitWithResponse) Register(id int64) <-chan interface{} {
  1101. return w.ch
  1102. }
  1103. func (w *waitWithResponse) Trigger(id int64, x interface{}) {}