server_test.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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:2379"]}`,
  391. }
  392. srv.applyRequest(req)
  393. w := Attributes{Name: "abc", ClientURLs: []string{"http://127.0.0.1:2379"}}
  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. cl.SetTransport(&nopTransporter{})
  402. for i := 1; i <= 4; i++ {
  403. cl.AddMember(&Member{ID: types.ID(i)}, uint64(i))
  404. }
  405. cl.RemoveMember(4, 5)
  406. tests := []struct {
  407. cc raftpb.ConfChange
  408. werr error
  409. }{
  410. {
  411. raftpb.ConfChange{
  412. Type: raftpb.ConfChangeAddNode,
  413. NodeID: 4,
  414. },
  415. ErrIDRemoved,
  416. },
  417. {
  418. raftpb.ConfChange{
  419. Type: raftpb.ConfChangeUpdateNode,
  420. NodeID: 4,
  421. },
  422. ErrIDRemoved,
  423. },
  424. {
  425. raftpb.ConfChange{
  426. Type: raftpb.ConfChangeAddNode,
  427. NodeID: 1,
  428. },
  429. ErrIDExists,
  430. },
  431. {
  432. raftpb.ConfChange{
  433. Type: raftpb.ConfChangeRemoveNode,
  434. NodeID: 5,
  435. },
  436. ErrIDNotFound,
  437. },
  438. }
  439. for i, tt := range tests {
  440. n := &nodeRecorder{}
  441. srv := &EtcdServer{
  442. r: raftNode{Node: n},
  443. Cluster: cl,
  444. }
  445. _, err := srv.applyConfChange(tt.cc, nil, 10)
  446. if err != tt.werr {
  447. t.Errorf("#%d: applyConfChange error = %v, want %v", i, err, tt.werr)
  448. }
  449. cc := raftpb.ConfChange{Type: tt.cc.Type, NodeID: raft.None}
  450. w := []testutil.Action{
  451. {
  452. Name: "ApplyConfChange",
  453. Params: []interface{}{cc},
  454. },
  455. }
  456. if g := n.Action(); !reflect.DeepEqual(g, w) {
  457. t.Errorf("#%d: action = %+v, want %+v", i, g, w)
  458. }
  459. }
  460. }
  461. func TestApplyConfChangeShouldStop(t *testing.T) {
  462. cl := newCluster("")
  463. cl.SetStore(store.New())
  464. cl.SetTransport(&nopTransporter{})
  465. for i := 1; i <= 3; i++ {
  466. cl.AddMember(&Member{ID: types.ID(i)}, uint64(i))
  467. }
  468. srv := &EtcdServer{
  469. id: 1,
  470. r: raftNode{
  471. Node: &nodeRecorder{},
  472. transport: &nopTransporter{},
  473. },
  474. Cluster: cl,
  475. }
  476. cc := raftpb.ConfChange{
  477. Type: raftpb.ConfChangeRemoveNode,
  478. NodeID: 2,
  479. }
  480. // remove non-local member
  481. shouldStop, err := srv.applyConfChange(cc, &raftpb.ConfState{}, 10)
  482. if err != nil {
  483. t.Fatalf("unexpected error %v", err)
  484. }
  485. if shouldStop != false {
  486. t.Errorf("shouldStop = %t, want %t", shouldStop, false)
  487. }
  488. // remove local member
  489. cc.NodeID = 1
  490. shouldStop, err = srv.applyConfChange(cc, &raftpb.ConfState{}, 10)
  491. if err != nil {
  492. t.Fatalf("unexpected error %v", err)
  493. }
  494. if shouldStop != true {
  495. t.Errorf("shouldStop = %t, want %t", shouldStop, true)
  496. }
  497. }
  498. func TestDoProposal(t *testing.T) {
  499. tests := []pb.Request{
  500. pb.Request{Method: "POST", ID: 1},
  501. pb.Request{Method: "PUT", ID: 1},
  502. pb.Request{Method: "DELETE", ID: 1},
  503. pb.Request{Method: "GET", ID: 1, Quorum: true},
  504. }
  505. for i, tt := range tests {
  506. st := &storeRecorder{}
  507. srv := &EtcdServer{
  508. r: raftNode{
  509. Node: newNodeCommitter(),
  510. storage: &storageRecorder{},
  511. raftStorage: raft.NewMemoryStorage(),
  512. transport: &nopTransporter{},
  513. },
  514. store: st,
  515. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  516. }
  517. srv.start()
  518. resp, err := srv.Do(context.Background(), tt)
  519. srv.Stop()
  520. action := st.Action()
  521. if len(action) != 1 {
  522. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  523. }
  524. if err != nil {
  525. t.Fatalf("#%d: err = %v, want nil", i, err)
  526. }
  527. wresp := Response{Event: &store.Event{}}
  528. if !reflect.DeepEqual(resp, wresp) {
  529. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  530. }
  531. }
  532. }
  533. func TestDoProposalCancelled(t *testing.T) {
  534. wait := &waitRecorder{}
  535. srv := &EtcdServer{
  536. r: raftNode{Node: &nodeRecorder{}},
  537. w: wait,
  538. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  539. }
  540. ctx, cancel := context.WithCancel(context.Background())
  541. cancel()
  542. _, err := srv.Do(ctx, pb.Request{Method: "PUT"})
  543. if err != ErrCanceled {
  544. t.Fatalf("err = %v, want %v", err, ErrCanceled)
  545. }
  546. w := []testutil.Action{{Name: "Register"}, {Name: "Trigger"}}
  547. if !reflect.DeepEqual(wait.action, w) {
  548. t.Errorf("wait.action = %+v, want %+v", wait.action, w)
  549. }
  550. }
  551. func TestDoProposalTimeout(t *testing.T) {
  552. srv := &EtcdServer{
  553. r: raftNode{Node: &nodeRecorder{}},
  554. w: &waitRecorder{},
  555. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  556. }
  557. ctx, _ := context.WithTimeout(context.Background(), 0)
  558. _, err := srv.Do(ctx, pb.Request{Method: "PUT"})
  559. if err != ErrTimeout {
  560. t.Fatalf("err = %v, want %v", err, ErrTimeout)
  561. }
  562. }
  563. func TestDoProposalStopped(t *testing.T) {
  564. srv := &EtcdServer{
  565. r: raftNode{Node: &nodeRecorder{}},
  566. w: &waitRecorder{},
  567. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  568. }
  569. srv.done = make(chan struct{})
  570. close(srv.done)
  571. _, err := srv.Do(context.Background(), pb.Request{Method: "PUT", ID: 1})
  572. if err != ErrStopped {
  573. t.Errorf("err = %v, want %v", err, ErrStopped)
  574. }
  575. }
  576. // TestSync tests sync 1. is nonblocking 2. proposes SYNC request.
  577. func TestSync(t *testing.T) {
  578. n := &nodeRecorder{}
  579. srv := &EtcdServer{
  580. r: raftNode{Node: n},
  581. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  582. }
  583. // check that sync is non-blocking
  584. timer := time.AfterFunc(time.Second, func() {
  585. t.Fatalf("sync should be non-blocking but did not return after 1s!")
  586. })
  587. srv.sync(10 * time.Second)
  588. timer.Stop()
  589. testutil.ForceGosched()
  590. action := n.Action()
  591. if len(action) != 1 {
  592. t.Fatalf("len(action) = %d, want 1", len(action))
  593. }
  594. if action[0].Name != "Propose" {
  595. t.Fatalf("action = %s, want Propose", action[0].Name)
  596. }
  597. data := action[0].Params[0].([]byte)
  598. var r pb.Request
  599. if err := r.Unmarshal(data); err != nil {
  600. t.Fatalf("unmarshal request error: %v", err)
  601. }
  602. if r.Method != "SYNC" {
  603. t.Errorf("method = %s, want SYNC", r.Method)
  604. }
  605. }
  606. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  607. // after timeout
  608. func TestSyncTimeout(t *testing.T) {
  609. n := &nodeProposalBlockerRecorder{}
  610. srv := &EtcdServer{
  611. r: raftNode{Node: n},
  612. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  613. }
  614. // check that sync is non-blocking
  615. timer := time.AfterFunc(time.Second, func() {
  616. t.Fatalf("sync should be non-blocking but did not return after 1s!")
  617. })
  618. srv.sync(0)
  619. timer.Stop()
  620. // give time for goroutine in sync to cancel
  621. testutil.ForceGosched()
  622. w := []testutil.Action{{Name: "Propose blocked"}}
  623. if g := n.Action(); !reflect.DeepEqual(g, w) {
  624. t.Errorf("action = %v, want %v", g, w)
  625. }
  626. }
  627. // TODO: TestNoSyncWhenNoLeader
  628. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  629. func TestSyncTrigger(t *testing.T) {
  630. n := newReadyNode()
  631. st := make(chan time.Time, 1)
  632. srv := &EtcdServer{
  633. r: raftNode{
  634. Node: n,
  635. raftStorage: raft.NewMemoryStorage(),
  636. transport: &nopTransporter{},
  637. storage: &storageRecorder{},
  638. },
  639. store: &storeRecorder{},
  640. SyncTicker: st,
  641. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  642. }
  643. srv.start()
  644. defer srv.Stop()
  645. // trigger the server to become a leader and accept sync requests
  646. n.readyc <- raft.Ready{
  647. SoftState: &raft.SoftState{
  648. RaftState: raft.StateLeader,
  649. },
  650. }
  651. // trigger a sync request
  652. st <- time.Time{}
  653. testutil.ForceGosched()
  654. action := n.Action()
  655. if len(action) != 1 {
  656. t.Fatalf("len(action) = %d, want 1", len(action))
  657. }
  658. if action[0].Name != "Propose" {
  659. t.Fatalf("action = %s, want Propose", action[0].Name)
  660. }
  661. data := action[0].Params[0].([]byte)
  662. var req pb.Request
  663. if err := req.Unmarshal(data); err != nil {
  664. t.Fatalf("error unmarshalling data: %v", err)
  665. }
  666. if req.Method != "SYNC" {
  667. t.Fatalf("unexpected proposed request: %#v", req.Method)
  668. }
  669. }
  670. // snapshot should snapshot the store and cut the persistent
  671. func TestSnapshot(t *testing.T) {
  672. s := raft.NewMemoryStorage()
  673. s.Append([]raftpb.Entry{{Index: 1}})
  674. st := &storeRecorder{}
  675. p := &storageRecorder{}
  676. srv := &EtcdServer{
  677. r: raftNode{
  678. Node: &nodeRecorder{},
  679. raftStorage: s,
  680. storage: p,
  681. },
  682. store: st,
  683. }
  684. srv.snapshot(1, raftpb.ConfState{Nodes: []uint64{1}})
  685. testutil.ForceGosched()
  686. gaction := st.Action()
  687. if len(gaction) != 2 {
  688. t.Fatalf("len(action) = %d, want 1", len(gaction))
  689. }
  690. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "Clone"}) {
  691. t.Errorf("action = %s, want Clone", gaction[0])
  692. }
  693. if !reflect.DeepEqual(gaction[1], testutil.Action{Name: "SaveNoCopy"}) {
  694. t.Errorf("action = %s, want SaveNoCopy", gaction[1])
  695. }
  696. gaction = p.Action()
  697. if len(gaction) != 1 {
  698. t.Fatalf("len(action) = %d, want 1", len(gaction))
  699. }
  700. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "SaveSnap"}) {
  701. t.Errorf("action = %s, want SaveSnap", gaction[0])
  702. }
  703. }
  704. // Applied > SnapCount should trigger a SaveSnap event
  705. func TestTriggerSnap(t *testing.T) {
  706. snapc := 10
  707. st := &storeRecorder{}
  708. p := &storageRecorder{}
  709. srv := &EtcdServer{
  710. snapCount: uint64(snapc),
  711. r: raftNode{
  712. Node: newNodeCommitter(),
  713. raftStorage: raft.NewMemoryStorage(),
  714. storage: p,
  715. transport: &nopTransporter{},
  716. },
  717. store: st,
  718. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  719. }
  720. srv.start()
  721. for i := 0; i < snapc+1; i++ {
  722. srv.Do(context.Background(), pb.Request{Method: "PUT"})
  723. }
  724. srv.Stop()
  725. gaction := p.Action()
  726. // each operation is recorded as a Save
  727. // (SnapCount+1) * Puts + SaveSnap = (SnapCount+1) * Save + SaveSnap
  728. wcnt := 2 + snapc
  729. if len(gaction) != wcnt {
  730. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  731. }
  732. if !reflect.DeepEqual(gaction[wcnt-1], testutil.Action{Name: "SaveSnap"}) {
  733. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  734. }
  735. }
  736. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  737. // it should trigger storage.SaveSnap and also store.Recover.
  738. func TestRecvSnapshot(t *testing.T) {
  739. n := newReadyNode()
  740. st := &storeRecorder{}
  741. p := &storageRecorder{}
  742. cl := newCluster("abc")
  743. cl.SetStore(store.New())
  744. cl.SetTransport(&nopTransporter{})
  745. s := &EtcdServer{
  746. r: raftNode{
  747. Node: n,
  748. transport: &nopTransporter{},
  749. storage: p,
  750. raftStorage: raft.NewMemoryStorage(),
  751. },
  752. store: st,
  753. Cluster: cl,
  754. }
  755. s.start()
  756. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
  757. // make goroutines move forward to receive snapshot
  758. testutil.ForceGosched()
  759. s.Stop()
  760. wactions := []testutil.Action{{Name: "Recovery"}}
  761. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  762. t.Errorf("store action = %v, want %v", g, wactions)
  763. }
  764. wactions = []testutil.Action{{Name: "SaveSnap"}, {Name: "Save"}}
  765. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  766. t.Errorf("storage action = %v, want %v", g, wactions)
  767. }
  768. }
  769. // TestApplySnapshotAndCommittedEntries tests that server applies snapshot
  770. // first and then committed entries.
  771. func TestApplySnapshotAndCommittedEntries(t *testing.T) {
  772. n := newReadyNode()
  773. st := &storeRecorder{}
  774. cl := newCluster("abc")
  775. cl.SetStore(store.New())
  776. cl.SetTransport(&nopTransporter{})
  777. storage := raft.NewMemoryStorage()
  778. s := &EtcdServer{
  779. r: raftNode{
  780. Node: n,
  781. storage: &storageRecorder{},
  782. raftStorage: storage,
  783. transport: &nopTransporter{},
  784. },
  785. store: st,
  786. Cluster: cl,
  787. }
  788. s.start()
  789. req := &pb.Request{Method: "QGET"}
  790. n.readyc <- raft.Ready{
  791. Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}},
  792. CommittedEntries: []raftpb.Entry{
  793. {Index: 2, Data: pbutil.MustMarshal(req)},
  794. },
  795. }
  796. // make goroutines move forward to receive snapshot
  797. testutil.ForceGosched()
  798. s.Stop()
  799. actions := st.Action()
  800. if len(actions) != 2 {
  801. t.Fatalf("len(action) = %d, want 2", len(actions))
  802. }
  803. if actions[0].Name != "Recovery" {
  804. t.Errorf("actions[0] = %s, want %s", actions[0].Name, "Recovery")
  805. }
  806. if actions[1].Name != "Get" {
  807. t.Errorf("actions[1] = %s, want %s", actions[1].Name, "Get")
  808. }
  809. }
  810. // TestAddMember tests AddMember can propose and perform node addition.
  811. func TestAddMember(t *testing.T) {
  812. n := newNodeConfChangeCommitterRecorder()
  813. n.readyc <- raft.Ready{
  814. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  815. }
  816. cl := newTestCluster(nil)
  817. st := store.New()
  818. cl.SetStore(st)
  819. cl.SetTransport(&nopTransporter{})
  820. s := &EtcdServer{
  821. r: raftNode{
  822. Node: n,
  823. raftStorage: raft.NewMemoryStorage(),
  824. storage: &storageRecorder{},
  825. transport: &nopTransporter{},
  826. },
  827. store: st,
  828. Cluster: cl,
  829. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  830. }
  831. s.start()
  832. m := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  833. err := s.AddMember(context.TODO(), m)
  834. gaction := n.Action()
  835. s.Stop()
  836. if err != nil {
  837. t.Fatalf("AddMember error: %v", err)
  838. }
  839. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeAddNode"}, {Name: "ApplyConfChange:ConfChangeAddNode"}}
  840. if !reflect.DeepEqual(gaction, wactions) {
  841. t.Errorf("action = %v, want %v", gaction, wactions)
  842. }
  843. if cl.Member(1234) == nil {
  844. t.Errorf("member with id 1234 is not added")
  845. }
  846. }
  847. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  848. func TestRemoveMember(t *testing.T) {
  849. n := newNodeConfChangeCommitterRecorder()
  850. n.readyc <- raft.Ready{
  851. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  852. }
  853. cl := newTestCluster(nil)
  854. st := store.New()
  855. cl.SetStore(store.New())
  856. cl.SetTransport(&nopTransporter{})
  857. s := &EtcdServer{
  858. r: raftNode{
  859. Node: n,
  860. raftStorage: raft.NewMemoryStorage(),
  861. storage: &storageRecorder{},
  862. transport: &nopTransporter{},
  863. },
  864. store: st,
  865. Cluster: cl,
  866. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  867. }
  868. s.start()
  869. s.AddMember(context.TODO(), Member{ID: 1234})
  870. err := s.RemoveMember(context.TODO(), 1234)
  871. gaction := n.Action()
  872. s.Stop()
  873. if err != nil {
  874. t.Fatalf("RemoveMember error: %v", err)
  875. }
  876. wactions := []testutil.Action{
  877. {Name: "ProposeConfChange:ConfChangeAddNode"},
  878. {Name: "ApplyConfChange:ConfChangeAddNode"},
  879. {Name: "ProposeConfChange:ConfChangeRemoveNode"},
  880. {Name: "ApplyConfChange:ConfChangeRemoveNode"},
  881. }
  882. if !reflect.DeepEqual(gaction, wactions) {
  883. t.Errorf("action = %v, want %v", gaction, wactions)
  884. }
  885. if cl.Member(1234) != nil {
  886. t.Errorf("member with id 1234 is not removed")
  887. }
  888. }
  889. // TestUpdateMember tests RemoveMember can propose and perform node update.
  890. func TestUpdateMember(t *testing.T) {
  891. n := newNodeConfChangeCommitterRecorder()
  892. n.readyc <- raft.Ready{
  893. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  894. }
  895. cl := newTestCluster(nil)
  896. st := store.New()
  897. cl.SetStore(st)
  898. cl.SetTransport(&nopTransporter{})
  899. s := &EtcdServer{
  900. r: raftNode{
  901. Node: n,
  902. raftStorage: raft.NewMemoryStorage(),
  903. storage: &storageRecorder{},
  904. transport: &nopTransporter{},
  905. },
  906. store: st,
  907. Cluster: cl,
  908. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  909. }
  910. s.start()
  911. s.AddMember(context.TODO(), Member{ID: 1234})
  912. wm := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  913. err := s.UpdateMember(context.TODO(), wm)
  914. gaction := n.Action()
  915. s.Stop()
  916. if err != nil {
  917. t.Fatalf("UpdateMember error: %v", err)
  918. }
  919. wactions := []testutil.Action{
  920. {Name: "ProposeConfChange:ConfChangeAddNode"},
  921. {Name: "ApplyConfChange:ConfChangeAddNode"},
  922. {Name: "ProposeConfChange:ConfChangeUpdateNode"},
  923. {Name: "ApplyConfChange:ConfChangeUpdateNode"},
  924. }
  925. if !reflect.DeepEqual(gaction, wactions) {
  926. t.Errorf("action = %v, want %v", gaction, wactions)
  927. }
  928. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  929. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  930. }
  931. }
  932. // TODO: test server could stop itself when being removed
  933. func TestPublish(t *testing.T) {
  934. n := &nodeRecorder{}
  935. ch := make(chan interface{}, 1)
  936. // simulate that request has gone through consensus
  937. ch <- Response{}
  938. w := &waitWithResponse{ch: ch}
  939. srv := &EtcdServer{
  940. id: 1,
  941. r: raftNode{Node: n},
  942. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  943. Cluster: &Cluster{},
  944. w: w,
  945. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  946. }
  947. srv.publish(time.Hour)
  948. action := n.Action()
  949. if len(action) != 1 {
  950. t.Fatalf("len(action) = %d, want 1", len(action))
  951. }
  952. if action[0].Name != "Propose" {
  953. t.Fatalf("action = %s, want Propose", action[0].Name)
  954. }
  955. data := action[0].Params[0].([]byte)
  956. var r pb.Request
  957. if err := r.Unmarshal(data); err != nil {
  958. t.Fatalf("unmarshal request error: %v", err)
  959. }
  960. if r.Method != "PUT" {
  961. t.Errorf("method = %s, want PUT", r.Method)
  962. }
  963. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  964. if wpath := path.Join(memberStoreKey(wm.ID), attributesSuffix); r.Path != wpath {
  965. t.Errorf("path = %s, want %s", r.Path, wpath)
  966. }
  967. var gattr Attributes
  968. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  969. t.Fatalf("unmarshal val error: %v", err)
  970. }
  971. if !reflect.DeepEqual(gattr, wm.Attributes) {
  972. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  973. }
  974. }
  975. // TestPublishStopped tests that publish will be stopped if server is stopped.
  976. func TestPublishStopped(t *testing.T) {
  977. srv := &EtcdServer{
  978. r: raftNode{
  979. Node: &nodeRecorder{},
  980. transport: &nopTransporter{},
  981. },
  982. Cluster: &Cluster{},
  983. w: &waitRecorder{},
  984. done: make(chan struct{}),
  985. stop: make(chan struct{}),
  986. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  987. }
  988. close(srv.done)
  989. srv.publish(time.Hour)
  990. }
  991. // TestPublishRetry tests that publish will keep retry until success.
  992. func TestPublishRetry(t *testing.T) {
  993. log.SetOutput(ioutil.Discard)
  994. defer log.SetOutput(os.Stderr)
  995. n := &nodeRecorder{}
  996. srv := &EtcdServer{
  997. r: raftNode{Node: n},
  998. w: &waitRecorder{},
  999. done: make(chan struct{}),
  1000. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1001. }
  1002. time.AfterFunc(500*time.Microsecond, func() { close(srv.done) })
  1003. srv.publish(10 * time.Nanosecond)
  1004. action := n.Action()
  1005. // multiple Proposes
  1006. if cnt := len(action); cnt < 2 {
  1007. t.Errorf("len(action) = %d, want >= 2", cnt)
  1008. }
  1009. }
  1010. func TestStopNotify(t *testing.T) {
  1011. s := &EtcdServer{
  1012. stop: make(chan struct{}),
  1013. done: make(chan struct{}),
  1014. }
  1015. go func() {
  1016. <-s.stop
  1017. close(s.done)
  1018. }()
  1019. notifier := s.StopNotify()
  1020. select {
  1021. case <-notifier:
  1022. t.Fatalf("received unexpected stop notification")
  1023. default:
  1024. }
  1025. s.Stop()
  1026. select {
  1027. case <-notifier:
  1028. default:
  1029. t.Fatalf("cannot receive stop notification")
  1030. }
  1031. }
  1032. func TestGetOtherPeerURLs(t *testing.T) {
  1033. tests := []struct {
  1034. membs []*Member
  1035. self string
  1036. wurls []string
  1037. }{
  1038. {
  1039. []*Member{
  1040. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1041. },
  1042. "a",
  1043. []string{},
  1044. },
  1045. {
  1046. []*Member{
  1047. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1048. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1049. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1050. },
  1051. "a",
  1052. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1053. },
  1054. {
  1055. []*Member{
  1056. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1057. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1058. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1059. },
  1060. "a",
  1061. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1062. },
  1063. }
  1064. for i, tt := range tests {
  1065. cl := NewClusterFromMembers("", types.ID(0), tt.membs)
  1066. urls := getRemotePeerURLs(cl, tt.self)
  1067. if !reflect.DeepEqual(urls, tt.wurls) {
  1068. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1069. }
  1070. }
  1071. }
  1072. // storeRecorder records all the methods it receives.
  1073. // storeRecorder DOES NOT work as a actual store.
  1074. // It always returns invaild empty response and no error.
  1075. type storeRecorder struct{ testutil.Recorder }
  1076. func (s *storeRecorder) Version() int { return 0 }
  1077. func (s *storeRecorder) Index() uint64 { return 0 }
  1078. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1079. s.Record(testutil.Action{
  1080. Name: "Get",
  1081. Params: []interface{}{path, recursive, sorted},
  1082. })
  1083. return &store.Event{}, nil
  1084. }
  1085. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1086. s.Record(testutil.Action{
  1087. Name: "Set",
  1088. Params: []interface{}{path, dir, val, expr},
  1089. })
  1090. return &store.Event{}, nil
  1091. }
  1092. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1093. s.Record(testutil.Action{
  1094. Name: "Update",
  1095. Params: []interface{}{path, val, expr},
  1096. })
  1097. return &store.Event{}, nil
  1098. }
  1099. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1100. s.Record(testutil.Action{
  1101. Name: "Create",
  1102. Params: []interface{}{path, dir, val, uniq, exp},
  1103. })
  1104. return &store.Event{}, nil
  1105. }
  1106. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1107. s.Record(testutil.Action{
  1108. Name: "CompareAndSwap",
  1109. Params: []interface{}{path, prevVal, prevIdx, val, expr},
  1110. })
  1111. return &store.Event{}, nil
  1112. }
  1113. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1114. s.Record(testutil.Action{
  1115. Name: "Delete",
  1116. Params: []interface{}{path, dir, recursive},
  1117. })
  1118. return &store.Event{}, nil
  1119. }
  1120. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1121. s.Record(testutil.Action{
  1122. Name: "CompareAndDelete",
  1123. Params: []interface{}{path, prevVal, prevIdx},
  1124. })
  1125. return &store.Event{}, nil
  1126. }
  1127. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1128. s.Record(testutil.Action{Name: "Watch"})
  1129. return &nopWatcher{}, nil
  1130. }
  1131. func (s *storeRecorder) Save() ([]byte, error) {
  1132. s.Record(testutil.Action{Name: "Save"})
  1133. return nil, nil
  1134. }
  1135. func (s *storeRecorder) Recovery(b []byte) error {
  1136. s.Record(testutil.Action{Name: "Recovery"})
  1137. return nil
  1138. }
  1139. func (s *storeRecorder) SaveNoCopy() ([]byte, error) {
  1140. s.Record(testutil.Action{Name: "SaveNoCopy"})
  1141. return nil, nil
  1142. }
  1143. func (s *storeRecorder) Clone() store.Store {
  1144. s.Record(testutil.Action{Name: "Clone"})
  1145. return s
  1146. }
  1147. func (s *storeRecorder) JsonStats() []byte { return nil }
  1148. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1149. s.Record(testutil.Action{
  1150. Name: "DeleteExpiredKeys",
  1151. Params: []interface{}{cutoff},
  1152. })
  1153. }
  1154. type nopWatcher struct{}
  1155. func (w *nopWatcher) EventChan() chan *store.Event { return nil }
  1156. func (w *nopWatcher) StartIndex() uint64 { return 0 }
  1157. func (w *nopWatcher) Remove() {}
  1158. // errStoreRecorder is a storeRecorder, but returns the given error on
  1159. // Get, Watch methods.
  1160. type errStoreRecorder struct {
  1161. storeRecorder
  1162. err error
  1163. }
  1164. func (s *errStoreRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1165. s.storeRecorder.Get(path, recursive, sorted)
  1166. return nil, s.err
  1167. }
  1168. func (s *errStoreRecorder) Watch(path string, recursive, sorted bool, index uint64) (store.Watcher, error) {
  1169. s.storeRecorder.Watch(path, recursive, sorted, index)
  1170. return nil, s.err
  1171. }
  1172. type waitRecorder struct {
  1173. action []testutil.Action
  1174. }
  1175. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1176. w.action = append(w.action, testutil.Action{Name: "Register"})
  1177. return nil
  1178. }
  1179. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1180. w.action = append(w.action, testutil.Action{Name: "Trigger"})
  1181. }
  1182. type waitWithResponse struct {
  1183. ch <-chan interface{}
  1184. }
  1185. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1186. return w.ch
  1187. }
  1188. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1189. type storageRecorder struct{ testutil.Recorder }
  1190. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  1191. p.Record(testutil.Action{Name: "Save"})
  1192. return nil
  1193. }
  1194. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) error {
  1195. if !raft.IsEmptySnap(st) {
  1196. p.Record(testutil.Action{Name: "SaveSnap"})
  1197. }
  1198. return nil
  1199. }
  1200. func (p *storageRecorder) Close() error { return nil }
  1201. type nodeRecorder struct{ testutil.Recorder }
  1202. func (n *nodeRecorder) Tick() { n.Record(testutil.Action{Name: "Tick"}) }
  1203. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1204. n.Record(testutil.Action{Name: "Campaign"})
  1205. return nil
  1206. }
  1207. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1208. n.Record(testutil.Action{Name: "Propose", Params: []interface{}{data}})
  1209. return nil
  1210. }
  1211. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1212. n.Record(testutil.Action{Name: "ProposeConfChange"})
  1213. return nil
  1214. }
  1215. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1216. n.Record(testutil.Action{Name: "Step"})
  1217. return nil
  1218. }
  1219. func (n *nodeRecorder) Status() raft.Status { return raft.Status{} }
  1220. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1221. func (n *nodeRecorder) Advance() {}
  1222. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1223. n.Record(testutil.Action{Name: "ApplyConfChange", Params: []interface{}{conf}})
  1224. return &raftpb.ConfState{}
  1225. }
  1226. func (n *nodeRecorder) Stop() {
  1227. n.Record(testutil.Action{Name: "Stop"})
  1228. }
  1229. func (n *nodeRecorder) ReportUnreachable(id uint64) {}
  1230. func (n *nodeRecorder) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  1231. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1232. n.Record(testutil.Action{Name: "Compact"})
  1233. }
  1234. type nodeProposalBlockerRecorder struct {
  1235. nodeRecorder
  1236. }
  1237. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1238. <-ctx.Done()
  1239. n.Record(testutil.Action{Name: "Propose blocked"})
  1240. return nil
  1241. }
  1242. type nodeConfChangeCommitterRecorder struct {
  1243. nodeRecorder
  1244. readyc chan raft.Ready
  1245. index uint64
  1246. }
  1247. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1248. readyc := make(chan raft.Ready, 1)
  1249. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1250. }
  1251. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1252. data, err := conf.Marshal()
  1253. if err != nil {
  1254. return err
  1255. }
  1256. n.index++
  1257. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: raftpb.EntryConfChange, Data: data}}}
  1258. n.Record(testutil.Action{Name: "ProposeConfChange:" + conf.Type.String()})
  1259. return nil
  1260. }
  1261. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1262. return n.readyc
  1263. }
  1264. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1265. n.Record(testutil.Action{Name: "ApplyConfChange:" + conf.Type.String()})
  1266. return &raftpb.ConfState{}
  1267. }
  1268. // nodeCommitter commits proposed data immediately.
  1269. type nodeCommitter struct {
  1270. nodeRecorder
  1271. readyc chan raft.Ready
  1272. index uint64
  1273. }
  1274. func newNodeCommitter() *nodeCommitter {
  1275. readyc := make(chan raft.Ready, 1)
  1276. return &nodeCommitter{readyc: readyc}
  1277. }
  1278. func (n *nodeCommitter) Propose(ctx context.Context, data []byte) error {
  1279. n.index++
  1280. ents := []raftpb.Entry{{Index: n.index, Data: data}}
  1281. n.readyc <- raft.Ready{
  1282. Entries: ents,
  1283. CommittedEntries: ents,
  1284. }
  1285. return nil
  1286. }
  1287. func (n *nodeCommitter) Ready() <-chan raft.Ready {
  1288. return n.readyc
  1289. }
  1290. type readyNode struct {
  1291. nodeRecorder
  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) Ready() <-chan raft.Ready { return n.readyc }
  1299. type nopTransporter struct{}
  1300. func (s *nopTransporter) Handler() http.Handler { return nil }
  1301. func (s *nopTransporter) Send(m []raftpb.Message) {}
  1302. func (s *nopTransporter) AddPeer(id types.ID, us []string) {}
  1303. func (s *nopTransporter) RemovePeer(id types.ID) {}
  1304. func (s *nopTransporter) RemoveAllPeers() {}
  1305. func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {}
  1306. func (s *nopTransporter) Stop() {}
  1307. func (s *nopTransporter) Pause() {}
  1308. func (s *nopTransporter) Resume() {}