server_test.go 38 KB

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