server_test.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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. }
  932. srv.Stop()
  933. srv.publish(time.Hour)
  934. }
  935. // TestPublishRetry tests that publish will keep retry until success.
  936. func TestPublishRetry(t *testing.T) {
  937. n := &nodeRecorder{}
  938. srv := &EtcdServer{
  939. node: n,
  940. w: &waitRecorder{},
  941. done: make(chan struct{}),
  942. }
  943. time.AfterFunc(500*time.Microsecond, srv.Stop)
  944. srv.publish(10 * time.Nanosecond)
  945. action := n.Action()
  946. // multiple Proposes
  947. if len(action) < 2 {
  948. t.Errorf("len(action) = %d, want >= 2", action)
  949. }
  950. }
  951. func TestGetBool(t *testing.T) {
  952. tests := []struct {
  953. b *bool
  954. wb bool
  955. wset bool
  956. }{
  957. {nil, false, false},
  958. {boolp(true), true, true},
  959. {boolp(false), false, true},
  960. }
  961. for i, tt := range tests {
  962. b, set := getBool(tt.b)
  963. if b != tt.wb {
  964. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  965. }
  966. if set != tt.wset {
  967. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  968. }
  969. }
  970. }
  971. func TestGenID(t *testing.T) {
  972. // Sanity check that the GenID function has been seeded appropriately
  973. // (math/rand is seeded with 1 by default)
  974. r := rand.NewSource(int64(1))
  975. var n uint64
  976. for n == 0 {
  977. n = uint64(r.Int63())
  978. }
  979. if n == GenID() {
  980. t.Fatalf("GenID's rand seeded with 1!")
  981. }
  982. }
  983. type action struct {
  984. name string
  985. params []interface{}
  986. }
  987. type recorder struct {
  988. sync.Mutex
  989. actions []action
  990. }
  991. func (r *recorder) record(a action) {
  992. r.Lock()
  993. r.actions = append(r.actions, a)
  994. r.Unlock()
  995. }
  996. func (r *recorder) Action() []action {
  997. r.Lock()
  998. cpy := make([]action, len(r.actions))
  999. copy(cpy, r.actions)
  1000. r.Unlock()
  1001. return cpy
  1002. }
  1003. type storeRecorder struct {
  1004. recorder
  1005. }
  1006. func (s *storeRecorder) Version() int { return 0 }
  1007. func (s *storeRecorder) Index() uint64 { return 0 }
  1008. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1009. s.record(action{
  1010. name: "Get",
  1011. params: []interface{}{path, recursive, sorted},
  1012. })
  1013. return &store.Event{}, nil
  1014. }
  1015. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1016. s.record(action{
  1017. name: "Set",
  1018. params: []interface{}{path, dir, val, expr},
  1019. })
  1020. return &store.Event{}, nil
  1021. }
  1022. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1023. s.record(action{
  1024. name: "Update",
  1025. params: []interface{}{path, val, expr},
  1026. })
  1027. return &store.Event{}, nil
  1028. }
  1029. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1030. s.record(action{
  1031. name: "Create",
  1032. params: []interface{}{path, dir, val, uniq, exp},
  1033. })
  1034. return &store.Event{}, nil
  1035. }
  1036. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1037. s.record(action{
  1038. name: "CompareAndSwap",
  1039. params: []interface{}{path, prevVal, prevIdx, val, expr},
  1040. })
  1041. return &store.Event{}, nil
  1042. }
  1043. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1044. s.record(action{
  1045. name: "Delete",
  1046. params: []interface{}{path, dir, recursive},
  1047. })
  1048. return &store.Event{}, nil
  1049. }
  1050. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1051. s.record(action{
  1052. name: "CompareAndDelete",
  1053. params: []interface{}{path, prevVal, prevIdx},
  1054. })
  1055. return &store.Event{}, nil
  1056. }
  1057. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1058. s.record(action{name: "Watch"})
  1059. return &stubWatcher{}, nil
  1060. }
  1061. func (s *storeRecorder) Save() ([]byte, error) {
  1062. s.record(action{name: "Save"})
  1063. return nil, nil
  1064. }
  1065. func (s *storeRecorder) Recovery(b []byte) error {
  1066. s.record(action{name: "Recovery"})
  1067. return nil
  1068. }
  1069. func (s *storeRecorder) JsonStats() []byte { return nil }
  1070. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1071. s.record(action{
  1072. name: "DeleteExpiredKeys",
  1073. params: []interface{}{cutoff},
  1074. })
  1075. }
  1076. type stubWatcher struct{}
  1077. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  1078. func (w *stubWatcher) StartIndex() uint64 { return 0 }
  1079. func (w *stubWatcher) Remove() {}
  1080. // errStoreRecorder returns an store error on Get, Watch request
  1081. type errStoreRecorder struct {
  1082. storeRecorder
  1083. err error
  1084. }
  1085. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  1086. s.record(action{name: "Get"})
  1087. return nil, s.err
  1088. }
  1089. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1090. s.record(action{name: "Watch"})
  1091. return nil, s.err
  1092. }
  1093. type waitRecorder struct {
  1094. action []action
  1095. }
  1096. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1097. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  1098. return nil
  1099. }
  1100. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1101. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  1102. }
  1103. func boolp(b bool) *bool { return &b }
  1104. func stringp(s string) *string { return &s }
  1105. type storageRecorder struct {
  1106. recorder
  1107. }
  1108. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) {
  1109. p.record(action{name: "Save"})
  1110. }
  1111. func (p *storageRecorder) Cut() error {
  1112. p.record(action{name: "Cut"})
  1113. return nil
  1114. }
  1115. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
  1116. if raft.IsEmptySnap(st) {
  1117. return
  1118. }
  1119. p.record(action{name: "SaveSnap"})
  1120. }
  1121. type readyNode struct {
  1122. readyc chan raft.Ready
  1123. }
  1124. func newReadyNode() *readyNode {
  1125. readyc := make(chan raft.Ready, 1)
  1126. return &readyNode{readyc: readyc}
  1127. }
  1128. func (n *readyNode) Tick() {}
  1129. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1130. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1131. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1132. return nil
  1133. }
  1134. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1135. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1136. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) {}
  1137. func (n *readyNode) Stop() {}
  1138. func (n *readyNode) Compact(index uint64, nodes []uint64, d []byte) {}
  1139. type nodeRecorder struct {
  1140. recorder
  1141. }
  1142. func (n *nodeRecorder) Tick() {
  1143. n.record(action{name: "Tick"})
  1144. }
  1145. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1146. n.record(action{name: "Campaign"})
  1147. return nil
  1148. }
  1149. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1150. n.record(action{name: "Propose"})
  1151. return nil
  1152. }
  1153. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1154. n.record(action{name: "ProposeConfChange"})
  1155. return nil
  1156. }
  1157. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1158. n.record(action{name: "Step"})
  1159. return nil
  1160. }
  1161. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1162. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1163. n.record(action{name: "ApplyConfChange", params: []interface{}{conf}})
  1164. }
  1165. func (n *nodeRecorder) Stop() {
  1166. n.record(action{name: "Stop"})
  1167. }
  1168. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1169. n.record(action{name: "Compact"})
  1170. }
  1171. type nodeProposeDataRecorder struct {
  1172. nodeRecorder
  1173. sync.Mutex
  1174. d [][]byte
  1175. }
  1176. func (n *nodeProposeDataRecorder) data() [][]byte {
  1177. n.Lock()
  1178. d := n.d
  1179. n.Unlock()
  1180. return d
  1181. }
  1182. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1183. n.nodeRecorder.Propose(ctx, data)
  1184. n.Lock()
  1185. n.d = append(n.d, data)
  1186. n.Unlock()
  1187. return nil
  1188. }
  1189. type nodeProposalBlockerRecorder struct {
  1190. nodeRecorder
  1191. }
  1192. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1193. <-ctx.Done()
  1194. n.record(action{name: "Propose blocked"})
  1195. return nil
  1196. }
  1197. type nodeConfChangeCommitterRecorder struct {
  1198. nodeRecorder
  1199. readyc chan raft.Ready
  1200. }
  1201. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1202. readyc := make(chan raft.Ready, 1)
  1203. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1204. }
  1205. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1206. data, err := conf.Marshal()
  1207. if err != nil {
  1208. return err
  1209. }
  1210. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1211. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1212. return nil
  1213. }
  1214. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1215. return n.readyc
  1216. }
  1217. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1218. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1219. }
  1220. type waitWithResponse struct {
  1221. ch <-chan interface{}
  1222. }
  1223. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1224. return w.ch
  1225. }
  1226. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1227. type clusterStoreRecorder struct {
  1228. recorder
  1229. }
  1230. func (cs *clusterStoreRecorder) Add(m Member) {
  1231. cs.record(action{name: "Add", params: []interface{}{m}})
  1232. }
  1233. func (cs *clusterStoreRecorder) Get() Cluster {
  1234. cs.record(action{name: "Get"})
  1235. return nil
  1236. }
  1237. func (cs *clusterStoreRecorder) Remove(id uint64) {
  1238. cs.record(action{name: "Remove", params: []interface{}{id}})
  1239. }
  1240. func mustMakePeerSlice(t *testing.T, ids ...uint64) []raft.Peer {
  1241. peers := make([]raft.Peer, len(ids))
  1242. for i, id := range ids {
  1243. m := Member{ID: id}
  1244. b, err := json.Marshal(m)
  1245. if err != nil {
  1246. t.Fatal(err)
  1247. }
  1248. peers[i] = raft.Peer{ID: id, Context: b}
  1249. }
  1250. return peers
  1251. }