server_test.go 35 KB

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