server_test.go 37 KB

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