server_test.go 42 KB

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