server_test.go 35 KB

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