server_test.go 34 KB

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