server_test.go 37 KB

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