server_test.go 34 KB

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