server_test.go 39 KB

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