server_test.go 37 KB

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