server_test.go 35 KB

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