server_test.go 35 KB

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