server_test.go 35 KB

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