server_test.go 35 KB

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