server_test.go 35 KB

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