server_test.go 35 KB

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