server_test.go 35 KB

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