server_test.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. r: raftNode{
  726. Node: &nodeRecorder{},
  727. raftStorage: s,
  728. storage: p,
  729. },
  730. store: st,
  731. }
  732. srv.snapshot(1, raftpb.ConfState{Nodes: []uint64{1}})
  733. testutil.WaitSchedule()
  734. gaction := st.Action()
  735. if len(gaction) != 2 {
  736. t.Fatalf("len(action) = %d, want 1", len(gaction))
  737. }
  738. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "Clone"}) {
  739. t.Errorf("action = %s, want Clone", gaction[0])
  740. }
  741. if !reflect.DeepEqual(gaction[1], testutil.Action{Name: "SaveNoCopy"}) {
  742. t.Errorf("action = %s, want SaveNoCopy", gaction[1])
  743. }
  744. gaction = p.Action()
  745. if len(gaction) != 1 {
  746. t.Fatalf("len(action) = %d, want 1", len(gaction))
  747. }
  748. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "SaveSnap"}) {
  749. t.Errorf("action = %s, want SaveSnap", gaction[0])
  750. }
  751. }
  752. // Applied > SnapCount should trigger a SaveSnap event
  753. func TestTriggerSnap(t *testing.T) {
  754. snapc := 10
  755. st := &storeRecorder{}
  756. p := &storageRecorder{}
  757. srv := &EtcdServer{
  758. cfg: &ServerConfig{TickMs: 1},
  759. snapCount: uint64(snapc),
  760. r: raftNode{
  761. Node: newNodeCommitter(),
  762. raftStorage: newRaftStorage(),
  763. storage: p,
  764. transport: &nopTransporter{},
  765. },
  766. store: st,
  767. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  768. }
  769. srv.start()
  770. for i := 0; i < snapc+1; i++ {
  771. srv.Do(context.Background(), pb.Request{Method: "PUT"})
  772. }
  773. srv.Stop()
  774. // wait for snapshot goroutine to finish
  775. testutil.WaitSchedule()
  776. gaction := p.Action()
  777. // each operation is recorded as a Save
  778. // (SnapCount+1) * Puts + SaveSnap = (SnapCount+1) * Save + SaveSnap
  779. wcnt := 2 + snapc
  780. if len(gaction) != wcnt {
  781. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  782. }
  783. if !reflect.DeepEqual(gaction[wcnt-1], testutil.Action{Name: "SaveSnap"}) {
  784. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  785. }
  786. }
  787. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  788. // it should trigger storage.SaveSnap and also store.Recover.
  789. func TestRecvSnapshot(t *testing.T) {
  790. n := newReadyNode()
  791. st := &storeRecorder{}
  792. p := &storageRecorder{}
  793. cl := newCluster("abc")
  794. cl.SetStore(store.New())
  795. s := &EtcdServer{
  796. r: raftNode{
  797. Node: n,
  798. transport: &nopTransporter{},
  799. storage: p,
  800. raftStorage: newRaftStorage(),
  801. },
  802. store: st,
  803. cluster: cl,
  804. }
  805. s.start()
  806. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
  807. // make goroutines move forward to receive snapshot
  808. testutil.WaitSchedule()
  809. s.Stop()
  810. wactions := []testutil.Action{{Name: "Recovery"}}
  811. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  812. t.Errorf("store action = %v, want %v", g, wactions)
  813. }
  814. wactions = []testutil.Action{{Name: "SaveSnap"}, {Name: "Save"}}
  815. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  816. t.Errorf("storage action = %v, want %v", g, wactions)
  817. }
  818. }
  819. // TestApplySnapshotAndCommittedEntries tests that server applies snapshot
  820. // first and then committed entries.
  821. func TestApplySnapshotAndCommittedEntries(t *testing.T) {
  822. n := newReadyNode()
  823. st := &storeRecorder{}
  824. cl := newCluster("abc")
  825. cl.SetStore(store.New())
  826. storage := newRaftStorage()
  827. s := &EtcdServer{
  828. r: raftNode{
  829. Node: n,
  830. storage: &storageRecorder{},
  831. raftStorage: storage,
  832. transport: &nopTransporter{},
  833. },
  834. store: st,
  835. cluster: cl,
  836. }
  837. s.start()
  838. req := &pb.Request{Method: "QGET"}
  839. n.readyc <- raft.Ready{
  840. Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}},
  841. CommittedEntries: []raftpb.Entry{
  842. {Index: 2, Data: pbutil.MustMarshal(req)},
  843. },
  844. }
  845. // make goroutines move forward to receive snapshot
  846. testutil.WaitSchedule()
  847. s.Stop()
  848. actions := st.Action()
  849. if len(actions) != 2 {
  850. t.Fatalf("len(action) = %d, want 2", len(actions))
  851. }
  852. if actions[0].Name != "Recovery" {
  853. t.Errorf("actions[0] = %s, want %s", actions[0].Name, "Recovery")
  854. }
  855. if actions[1].Name != "Get" {
  856. t.Errorf("actions[1] = %s, want %s", actions[1].Name, "Get")
  857. }
  858. }
  859. // TestAddMember tests AddMember can propose and perform node addition.
  860. func TestAddMember(t *testing.T) {
  861. n := newNodeConfChangeCommitterRecorder()
  862. n.readyc <- raft.Ready{
  863. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  864. }
  865. cl := newTestCluster(nil)
  866. st := store.New()
  867. cl.SetStore(st)
  868. s := &EtcdServer{
  869. r: raftNode{
  870. Node: n,
  871. raftStorage: newRaftStorage(),
  872. storage: &storageRecorder{},
  873. transport: &nopTransporter{},
  874. },
  875. cfg: &ServerConfig{},
  876. store: st,
  877. cluster: cl,
  878. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  879. }
  880. s.start()
  881. m := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  882. err := s.AddMember(context.TODO(), m)
  883. gaction := n.Action()
  884. s.Stop()
  885. if err != nil {
  886. t.Fatalf("AddMember error: %v", err)
  887. }
  888. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeAddNode"}, {Name: "ApplyConfChange:ConfChangeAddNode"}}
  889. if !reflect.DeepEqual(gaction, wactions) {
  890. t.Errorf("action = %v, want %v", gaction, wactions)
  891. }
  892. if cl.Member(1234) == nil {
  893. t.Errorf("member with id 1234 is not added")
  894. }
  895. }
  896. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  897. func TestRemoveMember(t *testing.T) {
  898. n := newNodeConfChangeCommitterRecorder()
  899. n.readyc <- raft.Ready{
  900. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  901. }
  902. cl := newTestCluster(nil)
  903. st := store.New()
  904. cl.SetStore(store.New())
  905. cl.AddMember(&Member{ID: 1234})
  906. s := &EtcdServer{
  907. r: raftNode{
  908. Node: n,
  909. raftStorage: newRaftStorage(),
  910. storage: &storageRecorder{},
  911. transport: &nopTransporter{},
  912. },
  913. cfg: &ServerConfig{},
  914. store: st,
  915. cluster: cl,
  916. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  917. }
  918. s.start()
  919. err := s.RemoveMember(context.TODO(), 1234)
  920. gaction := n.Action()
  921. s.Stop()
  922. if err != nil {
  923. t.Fatalf("RemoveMember error: %v", err)
  924. }
  925. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeRemoveNode"}, {Name: "ApplyConfChange:ConfChangeRemoveNode"}}
  926. if !reflect.DeepEqual(gaction, wactions) {
  927. t.Errorf("action = %v, want %v", gaction, wactions)
  928. }
  929. if cl.Member(1234) != nil {
  930. t.Errorf("member with id 1234 is not removed")
  931. }
  932. }
  933. // TestUpdateMember tests RemoveMember can propose and perform node update.
  934. func TestUpdateMember(t *testing.T) {
  935. n := newNodeConfChangeCommitterRecorder()
  936. n.readyc <- raft.Ready{
  937. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  938. }
  939. cl := newTestCluster(nil)
  940. st := store.New()
  941. cl.SetStore(st)
  942. cl.AddMember(&Member{ID: 1234})
  943. s := &EtcdServer{
  944. r: raftNode{
  945. Node: n,
  946. raftStorage: newRaftStorage(),
  947. storage: &storageRecorder{},
  948. transport: &nopTransporter{},
  949. },
  950. store: st,
  951. cluster: cl,
  952. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  953. }
  954. s.start()
  955. wm := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  956. err := s.UpdateMember(context.TODO(), wm)
  957. gaction := n.Action()
  958. s.Stop()
  959. if err != nil {
  960. t.Fatalf("UpdateMember error: %v", err)
  961. }
  962. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeUpdateNode"}, {Name: "ApplyConfChange:ConfChangeUpdateNode"}}
  963. if !reflect.DeepEqual(gaction, wactions) {
  964. t.Errorf("action = %v, want %v", gaction, wactions)
  965. }
  966. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  967. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  968. }
  969. }
  970. // TODO: test server could stop itself when being removed
  971. func TestPublish(t *testing.T) {
  972. n := &nodeRecorder{}
  973. ch := make(chan interface{}, 1)
  974. // simulate that request has gone through consensus
  975. ch <- Response{}
  976. w := &waitWithResponse{ch: ch}
  977. srv := &EtcdServer{
  978. cfg: &ServerConfig{TickMs: 1},
  979. id: 1,
  980. r: raftNode{Node: n},
  981. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  982. cluster: &cluster{},
  983. w: w,
  984. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  985. }
  986. srv.publish(time.Hour)
  987. action := n.Action()
  988. if len(action) != 1 {
  989. t.Fatalf("len(action) = %d, want 1", len(action))
  990. }
  991. if action[0].Name != "Propose" {
  992. t.Fatalf("action = %s, want Propose", action[0].Name)
  993. }
  994. data := action[0].Params[0].([]byte)
  995. var r pb.Request
  996. if err := r.Unmarshal(data); err != nil {
  997. t.Fatalf("unmarshal request error: %v", err)
  998. }
  999. if r.Method != "PUT" {
  1000. t.Errorf("method = %s, want PUT", r.Method)
  1001. }
  1002. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1003. if wpath := path.Join(memberStoreKey(wm.ID), attributesSuffix); r.Path != wpath {
  1004. t.Errorf("path = %s, want %s", r.Path, wpath)
  1005. }
  1006. var gattr Attributes
  1007. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1008. t.Fatalf("unmarshal val error: %v", err)
  1009. }
  1010. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1011. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1012. }
  1013. }
  1014. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1015. func TestPublishStopped(t *testing.T) {
  1016. srv := &EtcdServer{
  1017. cfg: &ServerConfig{TickMs: 1},
  1018. r: raftNode{
  1019. Node: &nodeRecorder{},
  1020. transport: &nopTransporter{},
  1021. },
  1022. cluster: &cluster{},
  1023. w: &waitRecorder{},
  1024. done: make(chan struct{}),
  1025. stop: make(chan struct{}),
  1026. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1027. }
  1028. close(srv.done)
  1029. srv.publish(time.Hour)
  1030. }
  1031. // TestPublishRetry tests that publish will keep retry until success.
  1032. func TestPublishRetry(t *testing.T) {
  1033. n := &nodeRecorder{}
  1034. srv := &EtcdServer{
  1035. cfg: &ServerConfig{TickMs: 1},
  1036. r: raftNode{Node: n},
  1037. w: &waitRecorder{},
  1038. done: make(chan struct{}),
  1039. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1040. }
  1041. time.AfterFunc(500*time.Microsecond, func() { close(srv.done) })
  1042. srv.publish(10 * time.Nanosecond)
  1043. action := n.Action()
  1044. // multiple Proposes
  1045. if cnt := len(action); cnt < 2 {
  1046. t.Errorf("len(action) = %d, want >= 2", cnt)
  1047. }
  1048. }
  1049. func TestUpdateVersion(t *testing.T) {
  1050. n := &nodeRecorder{}
  1051. ch := make(chan interface{}, 1)
  1052. // simulate that request has gone through consensus
  1053. ch <- Response{}
  1054. w := &waitWithResponse{ch: ch}
  1055. srv := &EtcdServer{
  1056. id: 1,
  1057. cfg: &ServerConfig{TickMs: 1},
  1058. r: raftNode{Node: n},
  1059. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://node1.com"}},
  1060. cluster: &cluster{},
  1061. w: w,
  1062. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1063. }
  1064. srv.updateClusterVersion("2.0.0")
  1065. action := n.Action()
  1066. if len(action) != 1 {
  1067. t.Fatalf("len(action) = %d, want 1", len(action))
  1068. }
  1069. if action[0].Name != "Propose" {
  1070. t.Fatalf("action = %s, want Propose", action[0].Name)
  1071. }
  1072. data := action[0].Params[0].([]byte)
  1073. var r pb.Request
  1074. if err := r.Unmarshal(data); err != nil {
  1075. t.Fatalf("unmarshal request error: %v", err)
  1076. }
  1077. if r.Method != "PUT" {
  1078. t.Errorf("method = %s, want PUT", r.Method)
  1079. }
  1080. if wpath := path.Join(StoreClusterPrefix, "version"); r.Path != wpath {
  1081. t.Errorf("path = %s, want %s", r.Path, wpath)
  1082. }
  1083. if r.Val != "2.0.0" {
  1084. t.Errorf("val = %s, want %s", r.Val, "2.0.0")
  1085. }
  1086. }
  1087. func TestStopNotify(t *testing.T) {
  1088. s := &EtcdServer{
  1089. stop: make(chan struct{}),
  1090. done: make(chan struct{}),
  1091. }
  1092. go func() {
  1093. <-s.stop
  1094. close(s.done)
  1095. }()
  1096. notifier := s.StopNotify()
  1097. select {
  1098. case <-notifier:
  1099. t.Fatalf("received unexpected stop notification")
  1100. default:
  1101. }
  1102. s.Stop()
  1103. select {
  1104. case <-notifier:
  1105. default:
  1106. t.Fatalf("cannot receive stop notification")
  1107. }
  1108. }
  1109. func TestGetOtherPeerURLs(t *testing.T) {
  1110. tests := []struct {
  1111. membs []*Member
  1112. self string
  1113. wurls []string
  1114. }{
  1115. {
  1116. []*Member{
  1117. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1118. },
  1119. "a",
  1120. []string{},
  1121. },
  1122. {
  1123. []*Member{
  1124. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1125. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1126. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1127. },
  1128. "a",
  1129. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1130. },
  1131. {
  1132. []*Member{
  1133. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1134. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1135. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1136. },
  1137. "a",
  1138. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1139. },
  1140. }
  1141. for i, tt := range tests {
  1142. cl := newClusterFromMembers("", types.ID(0), tt.membs)
  1143. urls := getRemotePeerURLs(cl, tt.self)
  1144. if !reflect.DeepEqual(urls, tt.wurls) {
  1145. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1146. }
  1147. }
  1148. }
  1149. // storeRecorder records all the methods it receives.
  1150. // storeRecorder DOES NOT work as a actual store.
  1151. // It always returns invalid empty response and no error.
  1152. type storeRecorder struct{ testutil.Recorder }
  1153. func (s *storeRecorder) Version() int { return 0 }
  1154. func (s *storeRecorder) Index() uint64 { return 0 }
  1155. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1156. s.Record(testutil.Action{
  1157. Name: "Get",
  1158. Params: []interface{}{path, recursive, sorted},
  1159. })
  1160. return &store.Event{}, nil
  1161. }
  1162. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1163. s.Record(testutil.Action{
  1164. Name: "Set",
  1165. Params: []interface{}{path, dir, val, expr},
  1166. })
  1167. return &store.Event{}, nil
  1168. }
  1169. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1170. s.Record(testutil.Action{
  1171. Name: "Update",
  1172. Params: []interface{}{path, val, expr},
  1173. })
  1174. return &store.Event{}, nil
  1175. }
  1176. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1177. s.Record(testutil.Action{
  1178. Name: "Create",
  1179. Params: []interface{}{path, dir, val, uniq, exp},
  1180. })
  1181. return &store.Event{}, nil
  1182. }
  1183. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1184. s.Record(testutil.Action{
  1185. Name: "CompareAndSwap",
  1186. Params: []interface{}{path, prevVal, prevIdx, val, expr},
  1187. })
  1188. return &store.Event{}, nil
  1189. }
  1190. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1191. s.Record(testutil.Action{
  1192. Name: "Delete",
  1193. Params: []interface{}{path, dir, recursive},
  1194. })
  1195. return &store.Event{}, nil
  1196. }
  1197. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1198. s.Record(testutil.Action{
  1199. Name: "CompareAndDelete",
  1200. Params: []interface{}{path, prevVal, prevIdx},
  1201. })
  1202. return &store.Event{}, nil
  1203. }
  1204. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1205. s.Record(testutil.Action{Name: "Watch"})
  1206. return &nopWatcher{}, nil
  1207. }
  1208. func (s *storeRecorder) Save() ([]byte, error) {
  1209. s.Record(testutil.Action{Name: "Save"})
  1210. return nil, nil
  1211. }
  1212. func (s *storeRecorder) Recovery(b []byte) error {
  1213. s.Record(testutil.Action{Name: "Recovery"})
  1214. return nil
  1215. }
  1216. func (s *storeRecorder) SaveNoCopy() ([]byte, error) {
  1217. s.Record(testutil.Action{Name: "SaveNoCopy"})
  1218. return nil, nil
  1219. }
  1220. func (s *storeRecorder) Clone() store.Store {
  1221. s.Record(testutil.Action{Name: "Clone"})
  1222. return s
  1223. }
  1224. func (s *storeRecorder) JsonStats() []byte { return nil }
  1225. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1226. s.Record(testutil.Action{
  1227. Name: "DeleteExpiredKeys",
  1228. Params: []interface{}{cutoff},
  1229. })
  1230. }
  1231. type nopWatcher struct{}
  1232. func (w *nopWatcher) EventChan() chan *store.Event { return nil }
  1233. func (w *nopWatcher) StartIndex() uint64 { return 0 }
  1234. func (w *nopWatcher) Remove() {}
  1235. // errStoreRecorder is a storeRecorder, but returns the given error on
  1236. // Get, Watch methods.
  1237. type errStoreRecorder struct {
  1238. storeRecorder
  1239. err error
  1240. }
  1241. func (s *errStoreRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1242. s.storeRecorder.Get(path, recursive, sorted)
  1243. return nil, s.err
  1244. }
  1245. func (s *errStoreRecorder) Watch(path string, recursive, sorted bool, index uint64) (store.Watcher, error) {
  1246. s.storeRecorder.Watch(path, recursive, sorted, index)
  1247. return nil, s.err
  1248. }
  1249. type waitRecorder struct {
  1250. action []testutil.Action
  1251. }
  1252. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1253. w.action = append(w.action, testutil.Action{Name: "Register"})
  1254. return nil
  1255. }
  1256. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1257. w.action = append(w.action, testutil.Action{Name: "Trigger"})
  1258. }
  1259. type waitWithResponse struct {
  1260. ch <-chan interface{}
  1261. }
  1262. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1263. return w.ch
  1264. }
  1265. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1266. type storageRecorder struct{ testutil.Recorder }
  1267. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  1268. p.Record(testutil.Action{Name: "Save"})
  1269. return nil
  1270. }
  1271. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) error {
  1272. if !raft.IsEmptySnap(st) {
  1273. p.Record(testutil.Action{Name: "SaveSnap"})
  1274. }
  1275. return nil
  1276. }
  1277. func (p *storageRecorder) Close() error { return nil }
  1278. type nodeRecorder struct{ testutil.Recorder }
  1279. func (n *nodeRecorder) Tick() { n.Record(testutil.Action{Name: "Tick"}) }
  1280. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1281. n.Record(testutil.Action{Name: "Campaign"})
  1282. return nil
  1283. }
  1284. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1285. n.Record(testutil.Action{Name: "Propose", Params: []interface{}{data}})
  1286. return nil
  1287. }
  1288. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1289. n.Record(testutil.Action{Name: "ProposeConfChange"})
  1290. return nil
  1291. }
  1292. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1293. n.Record(testutil.Action{Name: "Step"})
  1294. return nil
  1295. }
  1296. func (n *nodeRecorder) Status() raft.Status { return raft.Status{} }
  1297. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1298. func (n *nodeRecorder) Advance() {}
  1299. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1300. n.Record(testutil.Action{Name: "ApplyConfChange", Params: []interface{}{conf}})
  1301. return &raftpb.ConfState{}
  1302. }
  1303. func (n *nodeRecorder) Stop() {
  1304. n.Record(testutil.Action{Name: "Stop"})
  1305. }
  1306. func (n *nodeRecorder) ReportUnreachable(id uint64) {}
  1307. func (n *nodeRecorder) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  1308. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1309. n.Record(testutil.Action{Name: "Compact"})
  1310. }
  1311. type nodeProposalBlockerRecorder struct {
  1312. nodeRecorder
  1313. }
  1314. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1315. <-ctx.Done()
  1316. n.Record(testutil.Action{Name: "Propose blocked"})
  1317. return nil
  1318. }
  1319. type nodeConfChangeCommitterRecorder struct {
  1320. nodeRecorder
  1321. readyc chan raft.Ready
  1322. index uint64
  1323. }
  1324. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1325. readyc := make(chan raft.Ready, 1)
  1326. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1327. }
  1328. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1329. data, err := conf.Marshal()
  1330. if err != nil {
  1331. return err
  1332. }
  1333. n.index++
  1334. n.Record(testutil.Action{Name: "ProposeConfChange:" + conf.Type.String()})
  1335. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: raftpb.EntryConfChange, Data: data}}}
  1336. return nil
  1337. }
  1338. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1339. return n.readyc
  1340. }
  1341. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1342. n.Record(testutil.Action{Name: "ApplyConfChange:" + conf.Type.String()})
  1343. return &raftpb.ConfState{}
  1344. }
  1345. // nodeCommitter commits proposed data immediately.
  1346. type nodeCommitter struct {
  1347. nodeRecorder
  1348. readyc chan raft.Ready
  1349. index uint64
  1350. }
  1351. func newNodeCommitter() *nodeCommitter {
  1352. readyc := make(chan raft.Ready, 1)
  1353. return &nodeCommitter{readyc: readyc}
  1354. }
  1355. func (n *nodeCommitter) Propose(ctx context.Context, data []byte) error {
  1356. n.index++
  1357. ents := []raftpb.Entry{{Index: n.index, Data: data}}
  1358. n.readyc <- raft.Ready{
  1359. Entries: ents,
  1360. CommittedEntries: ents,
  1361. }
  1362. return nil
  1363. }
  1364. func (n *nodeCommitter) Ready() <-chan raft.Ready {
  1365. return n.readyc
  1366. }
  1367. type readyNode struct {
  1368. nodeRecorder
  1369. readyc chan raft.Ready
  1370. }
  1371. func newReadyNode() *readyNode {
  1372. readyc := make(chan raft.Ready, 1)
  1373. return &readyNode{readyc: readyc}
  1374. }
  1375. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1376. type nopTransporter struct{}
  1377. func (s *nopTransporter) Start() error { return nil }
  1378. func (s *nopTransporter) Handler() http.Handler { return nil }
  1379. func (s *nopTransporter) Send(m []raftpb.Message) {}
  1380. func (s *nopTransporter) AddRemote(id types.ID, us []string) {}
  1381. func (s *nopTransporter) AddPeer(id types.ID, us []string) {}
  1382. func (s *nopTransporter) RemovePeer(id types.ID) {}
  1383. func (s *nopTransporter) RemoveAllPeers() {}
  1384. func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {}
  1385. func (s *nopTransporter) ActiveSince(id types.ID) time.Time { return time.Time{} }
  1386. func (s *nopTransporter) SnapshotReady(rc io.ReadCloser, index uint64) {}
  1387. func (s *nopTransporter) Stop() {}
  1388. func (s *nopTransporter) Pause() {}
  1389. func (s *nopTransporter) Resume() {}