server_test.go 33 KB

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