server_test.go 34 KB

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