server_test.go 42 KB

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