server_test.go 37 KB

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