server_test.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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. cs := &removedClusterStore{removed: removed}
  408. srv := &EtcdServer{
  409. node: n,
  410. ClusterStore: cs,
  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. srv := &EtcdServer{
  451. node: n,
  452. store: store.New(),
  453. send: send,
  454. storage: &storageRecorder{},
  455. Ticker: tk.C,
  456. ClusterStore: &clusterStoreRecorder{},
  457. }
  458. srv.start()
  459. ss[i] = srv
  460. }
  461. for i := 1; i <= 10; i++ {
  462. r := pb.Request{
  463. Method: "PUT",
  464. ID: uint64(i),
  465. Path: "/foo",
  466. Val: "bar",
  467. }
  468. j := rand.Intn(len(ss))
  469. t.Logf("ss = %d", j)
  470. resp, err := ss[j].Do(ctx, r)
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. g, w := resp.Event.Node, &store.NodeExtern{
  475. Key: "/foo",
  476. ModifiedIndex: uint64(i),
  477. CreatedIndex: uint64(i),
  478. Value: stringp("bar"),
  479. }
  480. if !reflect.DeepEqual(g, w) {
  481. t.Error("value:", *g.Value)
  482. t.Errorf("g = %+v, w %+v", g, w)
  483. }
  484. }
  485. time.Sleep(10 * time.Millisecond)
  486. var last interface{}
  487. for i, sv := range ss {
  488. sv.Stop()
  489. g, _ := sv.store.Get("/", true, true)
  490. if last != nil && !reflect.DeepEqual(last, g) {
  491. t.Errorf("server %d: Root = %#v, want %#v", i, g, last)
  492. }
  493. last = g
  494. }
  495. }
  496. func TestDoProposal(t *testing.T) {
  497. tests := []pb.Request{
  498. pb.Request{Method: "POST", ID: 1},
  499. pb.Request{Method: "PUT", ID: 1},
  500. pb.Request{Method: "DELETE", ID: 1},
  501. pb.Request{Method: "GET", ID: 1, Quorum: true},
  502. }
  503. for i, tt := range tests {
  504. ctx, _ := context.WithCancel(context.Background())
  505. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1)
  506. st := &storeRecorder{}
  507. tk := make(chan time.Time)
  508. // this makes <-tk always successful, which accelerates internal clock
  509. close(tk)
  510. srv := &EtcdServer{
  511. node: n,
  512. store: st,
  513. send: func(_ []raftpb.Message) {},
  514. storage: &storageRecorder{},
  515. Ticker: tk,
  516. ClusterStore: &clusterStoreRecorder{},
  517. }
  518. srv.start()
  519. resp, err := srv.Do(ctx, tt)
  520. srv.Stop()
  521. action := st.Action()
  522. if len(action) != 1 {
  523. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  524. }
  525. if err != nil {
  526. t.Fatalf("#%d: err = %v, want nil", i, err)
  527. }
  528. wresp := Response{Event: &store.Event{}}
  529. if !reflect.DeepEqual(resp, wresp) {
  530. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  531. }
  532. }
  533. }
  534. func TestDoProposalCancelled(t *testing.T) {
  535. ctx, cancel := context.WithCancel(context.Background())
  536. // node cannot make any progress because there are two nodes
  537. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0, 0xBAD1), 10, 1)
  538. st := &storeRecorder{}
  539. wait := &waitRecorder{}
  540. srv := &EtcdServer{
  541. // TODO: use fake node for better testability
  542. node: n,
  543. store: st,
  544. w: wait,
  545. }
  546. done := make(chan struct{})
  547. var err error
  548. go func() {
  549. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  550. close(done)
  551. }()
  552. cancel()
  553. <-done
  554. gaction := st.Action()
  555. if len(gaction) != 0 {
  556. t.Errorf("len(action) = %v, want 0", len(gaction))
  557. }
  558. if err != context.Canceled {
  559. t.Fatalf("err = %v, want %v", err, context.Canceled)
  560. }
  561. w := []action{action{name: "Register1"}, action{name: "Trigger1"}}
  562. if !reflect.DeepEqual(wait.action, w) {
  563. t.Errorf("wait.action = %+v, want %+v", wait.action, w)
  564. }
  565. }
  566. func TestDoProposalStopped(t *testing.T) {
  567. ctx, cancel := context.WithCancel(context.Background())
  568. defer cancel()
  569. // node cannot make any progress because there are two nodes
  570. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0, 0xBAD1), 10, 1)
  571. st := &storeRecorder{}
  572. tk := make(chan time.Time)
  573. // this makes <-tk always successful, which accelarates internal clock
  574. close(tk)
  575. srv := &EtcdServer{
  576. // TODO: use fake node for better testability
  577. node: n,
  578. store: st,
  579. send: func(_ []raftpb.Message) {},
  580. storage: &storageRecorder{},
  581. Ticker: tk,
  582. }
  583. srv.start()
  584. done := make(chan struct{})
  585. var err error
  586. go func() {
  587. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  588. close(done)
  589. }()
  590. srv.Stop()
  591. <-done
  592. action := st.Action()
  593. if len(action) != 0 {
  594. t.Errorf("len(action) = %v, want 0", len(action))
  595. }
  596. if err != ErrStopped {
  597. t.Errorf("err = %v, want %v", err, ErrStopped)
  598. }
  599. }
  600. // TestSync tests sync 1. is nonblocking 2. sends out SYNC request.
  601. func TestSync(t *testing.T) {
  602. n := &nodeProposeDataRecorder{}
  603. srv := &EtcdServer{
  604. node: n,
  605. }
  606. start := time.Now()
  607. srv.sync(defaultSyncTimeout)
  608. // check that sync is non-blocking
  609. if d := time.Since(start); d > time.Millisecond {
  610. t.Errorf("CallSyncTime = %v, want < %v", d, time.Millisecond)
  611. }
  612. pkg.ForceGosched()
  613. data := n.data()
  614. if len(data) != 1 {
  615. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  616. }
  617. var r pb.Request
  618. if err := r.Unmarshal(data[0]); err != nil {
  619. t.Fatalf("unmarshal request error: %v", err)
  620. }
  621. if r.Method != "SYNC" {
  622. t.Errorf("method = %s, want SYNC", r.Method)
  623. }
  624. }
  625. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  626. // after timeout
  627. func TestSyncTimeout(t *testing.T) {
  628. n := &nodeProposalBlockerRecorder{}
  629. srv := &EtcdServer{
  630. node: n,
  631. }
  632. start := time.Now()
  633. srv.sync(0)
  634. // check that sync is non-blocking
  635. if d := time.Since(start); d > time.Millisecond {
  636. t.Errorf("CallSyncTime = %v, want < %v", d, time.Millisecond)
  637. }
  638. // give time for goroutine in sync to cancel
  639. // TODO: use fake clock
  640. pkg.ForceGosched()
  641. w := []action{action{name: "Propose blocked"}}
  642. if g := n.Action(); !reflect.DeepEqual(g, w) {
  643. t.Errorf("action = %v, want %v", g, w)
  644. }
  645. }
  646. // TODO: TestNoSyncWhenNoLeader
  647. // blockingNodeProposer implements the node interface to allow users to
  648. // block until Propose has been called and then verify the Proposed data
  649. type blockingNodeProposer struct {
  650. ch chan []byte
  651. readyNode
  652. }
  653. func (n *blockingNodeProposer) Propose(_ context.Context, data []byte) error {
  654. n.ch <- data
  655. return nil
  656. }
  657. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  658. func TestSyncTrigger(t *testing.T) {
  659. n := &blockingNodeProposer{
  660. ch: make(chan []byte),
  661. readyNode: *newReadyNode(),
  662. }
  663. st := make(chan time.Time, 1)
  664. srv := &EtcdServer{
  665. node: n,
  666. store: &storeRecorder{},
  667. send: func(_ []raftpb.Message) {},
  668. storage: &storageRecorder{},
  669. SyncTicker: st,
  670. }
  671. srv.start()
  672. // trigger the server to become a leader and accept sync requests
  673. n.readyc <- raft.Ready{
  674. SoftState: &raft.SoftState{
  675. RaftState: raft.StateLeader,
  676. },
  677. }
  678. // trigger a sync request
  679. st <- time.Time{}
  680. var data []byte
  681. select {
  682. case <-time.After(time.Second):
  683. t.Fatalf("did not receive proposed request as expected!")
  684. case data = <-n.ch:
  685. }
  686. srv.Stop()
  687. var req pb.Request
  688. if err := req.Unmarshal(data); err != nil {
  689. t.Fatalf("error unmarshalling data: %v", err)
  690. }
  691. if req.Method != "SYNC" {
  692. t.Fatalf("unexpected proposed request: %#v", req.Method)
  693. }
  694. }
  695. // snapshot should snapshot the store and cut the persistent
  696. // TODO: node.Compact is called... we need to make the node an interface
  697. func TestSnapshot(t *testing.T) {
  698. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1)
  699. defer n.Stop()
  700. st := &storeRecorder{}
  701. p := &storageRecorder{}
  702. s := &EtcdServer{
  703. store: st,
  704. storage: p,
  705. node: n,
  706. }
  707. s.snapshot(0, []uint64{1})
  708. gaction := st.Action()
  709. if len(gaction) != 1 {
  710. t.Fatalf("len(action) = %d, want 1", len(gaction))
  711. }
  712. if !reflect.DeepEqual(gaction[0], action{name: "Save"}) {
  713. t.Errorf("action = %s, want Save", gaction[0])
  714. }
  715. gaction = p.Action()
  716. if len(gaction) != 1 {
  717. t.Fatalf("len(action) = %d, want 1", len(gaction))
  718. }
  719. if !reflect.DeepEqual(gaction[0], action{name: "Cut"}) {
  720. t.Errorf("action = %s, want Cut", gaction[0])
  721. }
  722. }
  723. // Applied > SnapCount should trigger a SaveSnap event
  724. func TestTriggerSnap(t *testing.T) {
  725. ctx := context.Background()
  726. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1)
  727. <-n.Ready()
  728. n.ApplyConfChange(raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 0xBAD0})
  729. n.Campaign(ctx)
  730. st := &storeRecorder{}
  731. p := &storageRecorder{}
  732. s := &EtcdServer{
  733. store: st,
  734. send: func(_ []raftpb.Message) {},
  735. storage: p,
  736. node: n,
  737. snapCount: 10,
  738. ClusterStore: &clusterStoreRecorder{},
  739. }
  740. s.start()
  741. for i := 0; uint64(i) < s.snapCount-1; i++ {
  742. s.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  743. }
  744. time.Sleep(time.Millisecond)
  745. s.Stop()
  746. gaction := p.Action()
  747. // each operation is recorded as a Save
  748. // BootstrapConfig/Nop + (SnapCount - 1) * Puts + Cut + SaveSnap = Save + (SnapCount - 1) * Save + Cut + SaveSnap
  749. wcnt := 2 + int(s.snapCount)
  750. if len(gaction) != wcnt {
  751. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  752. }
  753. if !reflect.DeepEqual(gaction[wcnt-1], action{name: "SaveSnap"}) {
  754. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  755. }
  756. }
  757. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  758. // it should trigger storage.SaveSnap and also store.Recover.
  759. func TestRecvSnapshot(t *testing.T) {
  760. n := newReadyNode()
  761. st := &storeRecorder{}
  762. p := &storageRecorder{}
  763. s := &EtcdServer{
  764. store: st,
  765. send: func(_ []raftpb.Message) {},
  766. storage: p,
  767. node: n,
  768. }
  769. s.start()
  770. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  771. // make goroutines move forward to receive snapshot
  772. pkg.ForceGosched()
  773. s.Stop()
  774. wactions := []action{action{name: "Recovery"}}
  775. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  776. t.Errorf("store action = %v, want %v", g, wactions)
  777. }
  778. wactions = []action{action{name: "Save"}, action{name: "SaveSnap"}}
  779. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  780. t.Errorf("storage action = %v, want %v", g, wactions)
  781. }
  782. }
  783. // TestRecvSlowSnapshot tests that slow snapshot will not be applied
  784. // to store.
  785. func TestRecvSlowSnapshot(t *testing.T) {
  786. n := newReadyNode()
  787. st := &storeRecorder{}
  788. s := &EtcdServer{
  789. store: st,
  790. send: func(_ []raftpb.Message) {},
  791. storage: &storageRecorder{},
  792. node: n,
  793. }
  794. s.start()
  795. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  796. // make goroutines move forward to receive snapshot
  797. pkg.ForceGosched()
  798. action := st.Action()
  799. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  800. // make goroutines move forward to receive snapshot
  801. pkg.ForceGosched()
  802. s.Stop()
  803. if g := st.Action(); !reflect.DeepEqual(g, action) {
  804. t.Errorf("store action = %v, want %v", g, action)
  805. }
  806. }
  807. // TestAddMember tests AddMember can propose and perform node addition.
  808. func TestAddMember(t *testing.T) {
  809. n := newNodeConfChangeCommitterRecorder()
  810. n.readyc <- raft.Ready{
  811. SoftState: &raft.SoftState{
  812. RaftState: raft.StateLeader,
  813. Nodes: []uint64{2, 3},
  814. },
  815. }
  816. cs := &clusterStoreRecorder{}
  817. s := &EtcdServer{
  818. node: n,
  819. store: &storeRecorder{},
  820. send: func(_ []raftpb.Message) {},
  821. storage: &storageRecorder{},
  822. ClusterStore: cs,
  823. }
  824. s.start()
  825. m := Member{ID: 1, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  826. err := s.AddMember(context.TODO(), m)
  827. gaction := n.Action()
  828. s.Stop()
  829. if err != nil {
  830. t.Fatalf("AddMember error: %v", err)
  831. }
  832. wactions := []action{action{name: "ProposeConfChange:ConfChangeAddNode"}, action{name: "ApplyConfChange:ConfChangeAddNode"}}
  833. if !reflect.DeepEqual(gaction, wactions) {
  834. t.Errorf("action = %v, want %v", gaction, wactions)
  835. }
  836. wcsactions := []action{{name: "Add", params: []interface{}{m}}}
  837. if g := cs.Action(); !reflect.DeepEqual(g, wcsactions) {
  838. t.Errorf("csaction = %v, want %v", g, wcsactions)
  839. }
  840. }
  841. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  842. func TestRemoveMember(t *testing.T) {
  843. n := newNodeConfChangeCommitterRecorder()
  844. n.readyc <- raft.Ready{
  845. SoftState: &raft.SoftState{
  846. RaftState: raft.StateLeader,
  847. Nodes: []uint64{1, 2, 3},
  848. },
  849. }
  850. cs := &clusterStoreRecorder{}
  851. s := &EtcdServer{
  852. node: n,
  853. store: &storeRecorder{},
  854. send: func(_ []raftpb.Message) {},
  855. storage: &storageRecorder{},
  856. ClusterStore: cs,
  857. }
  858. s.start()
  859. id := uint64(1)
  860. err := s.RemoveMember(context.TODO(), id)
  861. gaction := n.Action()
  862. s.Stop()
  863. if err != nil {
  864. t.Fatalf("RemoveMember error: %v", err)
  865. }
  866. wactions := []action{action{name: "ProposeConfChange:ConfChangeRemoveNode"}, action{name: "ApplyConfChange:ConfChangeRemoveNode"}}
  867. if !reflect.DeepEqual(gaction, wactions) {
  868. t.Errorf("action = %v, want %v", gaction, wactions)
  869. }
  870. wcsactions := []action{{name: "Remove", params: []interface{}{id}}}
  871. if g := cs.Action(); !reflect.DeepEqual(g, wcsactions) {
  872. t.Errorf("csaction = %v, want %v", g, wcsactions)
  873. }
  874. }
  875. // TODO: test server could stop itself when being removed
  876. // TODO: test wait trigger correctness in multi-server case
  877. func TestPublish(t *testing.T) {
  878. n := &nodeProposeDataRecorder{}
  879. ch := make(chan interface{}, 1)
  880. // simulate that request has gone through consensus
  881. ch <- Response{}
  882. w := &waitWithResponse{ch: ch}
  883. srv := &EtcdServer{
  884. id: 1,
  885. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  886. node: n,
  887. w: w,
  888. }
  889. srv.publish(time.Hour)
  890. data := n.data()
  891. if len(data) != 1 {
  892. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  893. }
  894. var r pb.Request
  895. if err := r.Unmarshal(data[0]); err != nil {
  896. t.Fatalf("unmarshal request error: %v", err)
  897. }
  898. if r.Method != "PUT" {
  899. t.Errorf("method = %s, want PUT", r.Method)
  900. }
  901. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  902. if w := path.Join(memberStoreKey(wm.ID), attributesSuffix); r.Path != w {
  903. t.Errorf("path = %s, want %s", r.Path, w)
  904. }
  905. var gattr Attributes
  906. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  907. t.Fatalf("unmarshal val error: %v", err)
  908. }
  909. if !reflect.DeepEqual(gattr, wm.Attributes) {
  910. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  911. }
  912. }
  913. // TestPublishStopped tests that publish will be stopped if server is stopped.
  914. func TestPublishStopped(t *testing.T) {
  915. srv := &EtcdServer{
  916. node: &nodeRecorder{},
  917. w: &waitRecorder{},
  918. done: make(chan struct{}),
  919. stopped: make(chan struct{}),
  920. }
  921. close(srv.stopped)
  922. srv.Stop()
  923. srv.publish(time.Hour)
  924. }
  925. // TestPublishRetry tests that publish will keep retry until success.
  926. func TestPublishRetry(t *testing.T) {
  927. n := &nodeRecorder{}
  928. srv := &EtcdServer{
  929. node: n,
  930. w: &waitRecorder{},
  931. done: make(chan struct{}),
  932. }
  933. time.AfterFunc(500*time.Microsecond, srv.Stop)
  934. srv.publish(10 * time.Nanosecond)
  935. action := n.Action()
  936. // multiple Proposes
  937. if n := len(action); n < 2 {
  938. t.Errorf("len(action) = %d, want >= 2", n)
  939. }
  940. }
  941. func TestGetBool(t *testing.T) {
  942. tests := []struct {
  943. b *bool
  944. wb bool
  945. wset bool
  946. }{
  947. {nil, false, false},
  948. {boolp(true), true, true},
  949. {boolp(false), false, true},
  950. }
  951. for i, tt := range tests {
  952. b, set := getBool(tt.b)
  953. if b != tt.wb {
  954. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  955. }
  956. if set != tt.wset {
  957. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  958. }
  959. }
  960. }
  961. func TestGenID(t *testing.T) {
  962. // Sanity check that the GenID function has been seeded appropriately
  963. // (math/rand is seeded with 1 by default)
  964. r := rand.NewSource(int64(1))
  965. var n uint64
  966. for n == 0 {
  967. n = uint64(r.Int63())
  968. }
  969. if n == GenID() {
  970. t.Fatalf("GenID's rand seeded with 1!")
  971. }
  972. }
  973. type action struct {
  974. name string
  975. params []interface{}
  976. }
  977. type recorder struct {
  978. sync.Mutex
  979. actions []action
  980. }
  981. func (r *recorder) record(a action) {
  982. r.Lock()
  983. r.actions = append(r.actions, a)
  984. r.Unlock()
  985. }
  986. func (r *recorder) Action() []action {
  987. r.Lock()
  988. cpy := make([]action, len(r.actions))
  989. copy(cpy, r.actions)
  990. r.Unlock()
  991. return cpy
  992. }
  993. type storeRecorder struct {
  994. recorder
  995. }
  996. func (s *storeRecorder) Version() int { return 0 }
  997. func (s *storeRecorder) Index() uint64 { return 0 }
  998. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  999. s.record(action{
  1000. name: "Get",
  1001. params: []interface{}{path, recursive, sorted},
  1002. })
  1003. return &store.Event{}, nil
  1004. }
  1005. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1006. s.record(action{
  1007. name: "Set",
  1008. params: []interface{}{path, dir, val, expr},
  1009. })
  1010. return &store.Event{}, nil
  1011. }
  1012. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1013. s.record(action{
  1014. name: "Update",
  1015. params: []interface{}{path, val, expr},
  1016. })
  1017. return &store.Event{}, nil
  1018. }
  1019. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1020. s.record(action{
  1021. name: "Create",
  1022. params: []interface{}{path, dir, val, uniq, exp},
  1023. })
  1024. return &store.Event{}, nil
  1025. }
  1026. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1027. s.record(action{
  1028. name: "CompareAndSwap",
  1029. params: []interface{}{path, prevVal, prevIdx, val, expr},
  1030. })
  1031. return &store.Event{}, nil
  1032. }
  1033. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1034. s.record(action{
  1035. name: "Delete",
  1036. params: []interface{}{path, dir, recursive},
  1037. })
  1038. return &store.Event{}, nil
  1039. }
  1040. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1041. s.record(action{
  1042. name: "CompareAndDelete",
  1043. params: []interface{}{path, prevVal, prevIdx},
  1044. })
  1045. return &store.Event{}, nil
  1046. }
  1047. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1048. s.record(action{name: "Watch"})
  1049. return &stubWatcher{}, nil
  1050. }
  1051. func (s *storeRecorder) Save() ([]byte, error) {
  1052. s.record(action{name: "Save"})
  1053. return nil, nil
  1054. }
  1055. func (s *storeRecorder) Recovery(b []byte) error {
  1056. s.record(action{name: "Recovery"})
  1057. return nil
  1058. }
  1059. func (s *storeRecorder) JsonStats() []byte { return nil }
  1060. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1061. s.record(action{
  1062. name: "DeleteExpiredKeys",
  1063. params: []interface{}{cutoff},
  1064. })
  1065. }
  1066. type stubWatcher struct{}
  1067. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  1068. func (w *stubWatcher) StartIndex() uint64 { return 0 }
  1069. func (w *stubWatcher) Remove() {}
  1070. // errStoreRecorder returns an store error on Get, Watch request
  1071. type errStoreRecorder struct {
  1072. storeRecorder
  1073. err error
  1074. }
  1075. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  1076. s.record(action{name: "Get"})
  1077. return nil, s.err
  1078. }
  1079. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1080. s.record(action{name: "Watch"})
  1081. return nil, s.err
  1082. }
  1083. type waitRecorder struct {
  1084. action []action
  1085. }
  1086. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1087. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  1088. return nil
  1089. }
  1090. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1091. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  1092. }
  1093. func boolp(b bool) *bool { return &b }
  1094. func stringp(s string) *string { return &s }
  1095. type storageRecorder struct {
  1096. recorder
  1097. }
  1098. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) {
  1099. p.record(action{name: "Save"})
  1100. }
  1101. func (p *storageRecorder) Cut() error {
  1102. p.record(action{name: "Cut"})
  1103. return nil
  1104. }
  1105. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
  1106. if raft.IsEmptySnap(st) {
  1107. return
  1108. }
  1109. p.record(action{name: "SaveSnap"})
  1110. }
  1111. type readyNode struct {
  1112. readyc chan raft.Ready
  1113. }
  1114. func newReadyNode() *readyNode {
  1115. readyc := make(chan raft.Ready, 1)
  1116. return &readyNode{readyc: readyc}
  1117. }
  1118. func (n *readyNode) Tick() {}
  1119. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1120. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1121. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1122. return nil
  1123. }
  1124. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1125. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1126. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) {}
  1127. func (n *readyNode) Stop() {}
  1128. func (n *readyNode) Compact(index uint64, nodes []uint64, d []byte) {}
  1129. type nodeRecorder struct {
  1130. recorder
  1131. }
  1132. func (n *nodeRecorder) Tick() {
  1133. n.record(action{name: "Tick"})
  1134. }
  1135. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1136. n.record(action{name: "Campaign"})
  1137. return nil
  1138. }
  1139. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1140. n.record(action{name: "Propose"})
  1141. return nil
  1142. }
  1143. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1144. n.record(action{name: "ProposeConfChange"})
  1145. return nil
  1146. }
  1147. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1148. n.record(action{name: "Step"})
  1149. return nil
  1150. }
  1151. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1152. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1153. n.record(action{name: "ApplyConfChange", params: []interface{}{conf}})
  1154. }
  1155. func (n *nodeRecorder) Stop() {
  1156. n.record(action{name: "Stop"})
  1157. }
  1158. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1159. n.record(action{name: "Compact"})
  1160. }
  1161. type nodeProposeDataRecorder struct {
  1162. nodeRecorder
  1163. sync.Mutex
  1164. d [][]byte
  1165. }
  1166. func (n *nodeProposeDataRecorder) data() [][]byte {
  1167. n.Lock()
  1168. d := n.d
  1169. n.Unlock()
  1170. return d
  1171. }
  1172. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1173. n.nodeRecorder.Propose(ctx, data)
  1174. n.Lock()
  1175. n.d = append(n.d, data)
  1176. n.Unlock()
  1177. return nil
  1178. }
  1179. type nodeProposalBlockerRecorder struct {
  1180. nodeRecorder
  1181. }
  1182. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1183. <-ctx.Done()
  1184. n.record(action{name: "Propose blocked"})
  1185. return nil
  1186. }
  1187. type nodeConfChangeCommitterRecorder struct {
  1188. nodeRecorder
  1189. readyc chan raft.Ready
  1190. }
  1191. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1192. readyc := make(chan raft.Ready, 1)
  1193. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1194. }
  1195. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1196. data, err := conf.Marshal()
  1197. if err != nil {
  1198. return err
  1199. }
  1200. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1201. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1202. return nil
  1203. }
  1204. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1205. return n.readyc
  1206. }
  1207. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1208. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1209. }
  1210. type waitWithResponse struct {
  1211. ch <-chan interface{}
  1212. }
  1213. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1214. return w.ch
  1215. }
  1216. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1217. type clusterStoreRecorder struct {
  1218. recorder
  1219. }
  1220. func (cs *clusterStoreRecorder) Add(m Member) {
  1221. cs.record(action{name: "Add", params: []interface{}{m}})
  1222. }
  1223. func (cs *clusterStoreRecorder) Get() Cluster {
  1224. cs.record(action{name: "Get"})
  1225. return Cluster{}
  1226. }
  1227. func (cs *clusterStoreRecorder) Remove(id uint64) {
  1228. cs.record(action{name: "Remove", params: []interface{}{id}})
  1229. }
  1230. func (cs *clusterStoreRecorder) IsRemoved(id uint64) bool { return false }
  1231. type removedClusterStore struct {
  1232. removed map[uint64]bool
  1233. }
  1234. func (cs *removedClusterStore) Add(m Member) {}
  1235. func (cs *removedClusterStore) Get() Cluster { return Cluster{} }
  1236. func (cs *removedClusterStore) Remove(id uint64) {}
  1237. func (cs *removedClusterStore) IsRemoved(id uint64) bool { return cs.removed[id] }
  1238. func mustMakePeerSlice(t *testing.T, ids ...uint64) []raft.Peer {
  1239. peers := make([]raft.Peer, len(ids))
  1240. for i, id := range ids {
  1241. m := Member{ID: id}
  1242. b, err := json.Marshal(m)
  1243. if err != nil {
  1244. t.Fatal(err)
  1245. }
  1246. peers[i] = raft.Peer{ID: id, Context: b}
  1247. }
  1248. return peers
  1249. }