server_test.go 36 KB

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