server_test.go 31 KB

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