server_test.go 30 KB

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