server_test.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  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. for i := 0; uint64(i) < srv.snapCount-1; i++ {
  903. srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  904. }
  905. time.Sleep(time.Millisecond)
  906. srv.Stop()
  907. gaction := p.Action()
  908. // each operation is recorded as a Save
  909. // BootstrapConfig/Nop + (SnapCount - 1) * Puts + Cut + SaveSnap = Save + (SnapCount - 1) * Save + Cut + SaveSnap
  910. wcnt := 1 + int(srv.snapCount)
  911. if len(gaction) != wcnt {
  912. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  913. }
  914. if !reflect.DeepEqual(gaction[wcnt-1], action{name: "SaveSnap"}) {
  915. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  916. }
  917. }
  918. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  919. // it should trigger storage.SaveSnap and also store.Recover.
  920. func TestRecvSnapshot(t *testing.T) {
  921. n := newReadyNode()
  922. st := &storeRecorder{}
  923. p := &storageRecorder{}
  924. cl := newCluster("abc")
  925. cl.SetStore(store.New())
  926. s := &EtcdServer{
  927. store: st,
  928. sendhub: &nopSender{},
  929. storage: p,
  930. node: n,
  931. raftStorage: raft.NewMemoryStorage(),
  932. Cluster: cl,
  933. }
  934. s.start()
  935. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
  936. // make goroutines move forward to receive snapshot
  937. testutil.ForceGosched()
  938. s.Stop()
  939. wactions := []action{action{name: "Recovery"}}
  940. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  941. t.Errorf("store action = %v, want %v", g, wactions)
  942. }
  943. wactions = []action{action{name: "Save"}, action{name: "SaveSnap"}}
  944. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  945. t.Errorf("storage action = %v, want %v", g, wactions)
  946. }
  947. }
  948. // TestRecvSlowSnapshot tests that slow snapshot will not be applied
  949. // to store. The case could happen when server compacts the log and
  950. // raft returns the compacted snapshot.
  951. func TestRecvSlowSnapshot(t *testing.T) {
  952. n := newReadyNode()
  953. st := &storeRecorder{}
  954. cl := newCluster("abc")
  955. cl.SetStore(store.New())
  956. s := &EtcdServer{
  957. store: st,
  958. sendhub: &nopSender{},
  959. storage: &storageRecorder{},
  960. node: n,
  961. raftStorage: raft.NewMemoryStorage(),
  962. Cluster: cl,
  963. }
  964. s.start()
  965. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
  966. // make goroutines move forward to receive snapshot
  967. testutil.ForceGosched()
  968. action := st.Action()
  969. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
  970. // make goroutines move forward to receive snapshot
  971. testutil.ForceGosched()
  972. s.Stop()
  973. if g := st.Action(); !reflect.DeepEqual(g, action) {
  974. t.Errorf("store action = %v, want %v", g, action)
  975. }
  976. }
  977. // TestApplySnapshotAndCommittedEntries tests that server applies snapshot
  978. // first and then committed entries.
  979. func TestApplySnapshotAndCommittedEntries(t *testing.T) {
  980. n := newReadyNode()
  981. st := &storeRecorder{}
  982. cl := newCluster("abc")
  983. cl.SetStore(store.New())
  984. storage := raft.NewMemoryStorage()
  985. s := &EtcdServer{
  986. store: st,
  987. sendhub: &nopSender{},
  988. storage: &storageRecorder{},
  989. node: n,
  990. raftStorage: storage,
  991. Cluster: cl,
  992. }
  993. s.start()
  994. req := &pb.Request{Method: "QGET"}
  995. n.readyc <- raft.Ready{
  996. Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}},
  997. CommittedEntries: []raftpb.Entry{
  998. {Index: 2, Data: pbutil.MustMarshal(req)},
  999. },
  1000. }
  1001. // make goroutines move forward to receive snapshot
  1002. testutil.ForceGosched()
  1003. s.Stop()
  1004. actions := st.Action()
  1005. if len(actions) != 2 {
  1006. t.Fatalf("len(action) = %d, want 2", len(actions))
  1007. }
  1008. if actions[0].name != "Recovery" {
  1009. t.Errorf("actions[0] = %s, want %s", actions[0].name, "Recovery")
  1010. }
  1011. if actions[1].name != "Get" {
  1012. t.Errorf("actions[1] = %s, want %s", actions[1].name, "Get")
  1013. }
  1014. }
  1015. // TestAddMember tests AddMember can propose and perform node addition.
  1016. func TestAddMember(t *testing.T) {
  1017. n := newNodeConfChangeCommitterRecorder()
  1018. n.readyc <- raft.Ready{
  1019. SoftState: &raft.SoftState{
  1020. RaftState: raft.StateLeader,
  1021. Nodes: []uint64{2345, 3456},
  1022. },
  1023. }
  1024. cl := newTestCluster(nil)
  1025. cl.SetStore(store.New())
  1026. s := &EtcdServer{
  1027. node: n,
  1028. raftStorage: raft.NewMemoryStorage(),
  1029. store: &storeRecorder{},
  1030. sendhub: &nopSender{},
  1031. storage: &storageRecorder{},
  1032. Cluster: cl,
  1033. }
  1034. s.start()
  1035. m := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  1036. err := s.AddMember(context.TODO(), m)
  1037. gaction := n.Action()
  1038. s.Stop()
  1039. if err != nil {
  1040. t.Fatalf("AddMember error: %v", err)
  1041. }
  1042. wactions := []action{action{name: "ProposeConfChange:ConfChangeAddNode"}, action{name: "ApplyConfChange:ConfChangeAddNode"}}
  1043. if !reflect.DeepEqual(gaction, wactions) {
  1044. t.Errorf("action = %v, want %v", gaction, wactions)
  1045. }
  1046. if cl.Member(1234) == nil {
  1047. t.Errorf("member with id 1234 is not added")
  1048. }
  1049. }
  1050. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  1051. func TestRemoveMember(t *testing.T) {
  1052. n := newNodeConfChangeCommitterRecorder()
  1053. n.readyc <- raft.Ready{
  1054. SoftState: &raft.SoftState{
  1055. RaftState: raft.StateLeader,
  1056. Nodes: []uint64{1234, 2345, 3456},
  1057. },
  1058. }
  1059. cl := newTestCluster(nil)
  1060. cl.SetStore(store.New())
  1061. cl.AddMember(&Member{ID: 1234})
  1062. s := &EtcdServer{
  1063. node: n,
  1064. raftStorage: raft.NewMemoryStorage(),
  1065. store: &storeRecorder{},
  1066. sendhub: &nopSender{},
  1067. storage: &storageRecorder{},
  1068. Cluster: cl,
  1069. }
  1070. s.start()
  1071. err := s.RemoveMember(context.TODO(), 1234)
  1072. gaction := n.Action()
  1073. s.Stop()
  1074. if err != nil {
  1075. t.Fatalf("RemoveMember error: %v", err)
  1076. }
  1077. wactions := []action{action{name: "ProposeConfChange:ConfChangeRemoveNode"}, action{name: "ApplyConfChange:ConfChangeRemoveNode"}}
  1078. if !reflect.DeepEqual(gaction, wactions) {
  1079. t.Errorf("action = %v, want %v", gaction, wactions)
  1080. }
  1081. if cl.Member(1234) != nil {
  1082. t.Errorf("member with id 1234 is not removed")
  1083. }
  1084. }
  1085. // TestUpdateMember tests RemoveMember can propose and perform node update.
  1086. func TestUpdateMember(t *testing.T) {
  1087. n := newNodeConfChangeCommitterRecorder()
  1088. n.readyc <- raft.Ready{
  1089. SoftState: &raft.SoftState{
  1090. RaftState: raft.StateLeader,
  1091. Nodes: []uint64{1234, 2345, 3456},
  1092. },
  1093. }
  1094. cl := newTestCluster(nil)
  1095. cl.SetStore(store.New())
  1096. cl.AddMember(&Member{ID: 1234})
  1097. s := &EtcdServer{
  1098. node: n,
  1099. raftStorage: raft.NewMemoryStorage(),
  1100. store: &storeRecorder{},
  1101. sendhub: &nopSender{},
  1102. storage: &storageRecorder{},
  1103. Cluster: cl,
  1104. }
  1105. s.start()
  1106. wm := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  1107. err := s.UpdateMember(context.TODO(), wm)
  1108. gaction := n.Action()
  1109. s.Stop()
  1110. if err != nil {
  1111. t.Fatalf("UpdateMember error: %v", err)
  1112. }
  1113. wactions := []action{action{name: "ProposeConfChange:ConfChangeUpdateNode"}, action{name: "ApplyConfChange:ConfChangeUpdateNode"}}
  1114. if !reflect.DeepEqual(gaction, wactions) {
  1115. t.Errorf("action = %v, want %v", gaction, wactions)
  1116. }
  1117. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  1118. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  1119. }
  1120. }
  1121. // TODO: test server could stop itself when being removed
  1122. // TODO: test wait trigger correctness in multi-server case
  1123. func TestPublish(t *testing.T) {
  1124. n := &nodeProposeDataRecorder{}
  1125. ch := make(chan interface{}, 1)
  1126. // simulate that request has gone through consensus
  1127. ch <- Response{}
  1128. w := &waitWithResponse{ch: ch}
  1129. srv := &EtcdServer{
  1130. id: 1,
  1131. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  1132. Cluster: &Cluster{},
  1133. node: n,
  1134. w: w,
  1135. }
  1136. srv.publish(time.Hour)
  1137. data := n.data()
  1138. if len(data) != 1 {
  1139. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  1140. }
  1141. var r pb.Request
  1142. if err := r.Unmarshal(data[0]); err != nil {
  1143. t.Fatalf("unmarshal request error: %v", err)
  1144. }
  1145. if r.Method != "PUT" {
  1146. t.Errorf("method = %s, want PUT", r.Method)
  1147. }
  1148. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1149. if w := path.Join(memberStoreKey(wm.ID), attributesSuffix); r.Path != w {
  1150. t.Errorf("path = %s, want %s", r.Path, w)
  1151. }
  1152. var gattr Attributes
  1153. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1154. t.Fatalf("unmarshal val error: %v", err)
  1155. }
  1156. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1157. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1158. }
  1159. }
  1160. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1161. func TestPublishStopped(t *testing.T) {
  1162. srv := &EtcdServer{
  1163. node: &nodeRecorder{},
  1164. sendhub: &nopSender{},
  1165. Cluster: &Cluster{},
  1166. w: &waitRecorder{},
  1167. done: make(chan struct{}),
  1168. stop: make(chan struct{}),
  1169. }
  1170. close(srv.done)
  1171. srv.publish(time.Hour)
  1172. }
  1173. // TestPublishRetry tests that publish will keep retry until success.
  1174. func TestPublishRetry(t *testing.T) {
  1175. n := &nodeRecorder{}
  1176. srv := &EtcdServer{
  1177. node: n,
  1178. w: &waitRecorder{},
  1179. done: make(chan struct{}),
  1180. }
  1181. time.AfterFunc(500*time.Microsecond, func() { close(srv.done) })
  1182. srv.publish(10 * time.Nanosecond)
  1183. action := n.Action()
  1184. // multiple Proposes
  1185. if n := len(action); n < 2 {
  1186. t.Errorf("len(action) = %d, want >= 2", n)
  1187. }
  1188. }
  1189. func TestStopNotify(t *testing.T) {
  1190. s := &EtcdServer{
  1191. stop: make(chan struct{}),
  1192. done: make(chan struct{}),
  1193. }
  1194. go func() {
  1195. <-s.stop
  1196. close(s.done)
  1197. }()
  1198. notifier := s.StopNotify()
  1199. select {
  1200. case <-notifier:
  1201. t.Fatalf("received unexpected stop notification")
  1202. default:
  1203. }
  1204. s.Stop()
  1205. select {
  1206. case <-notifier:
  1207. default:
  1208. t.Fatalf("cannot receive stop notification")
  1209. }
  1210. }
  1211. func TestGetOtherPeerURLs(t *testing.T) {
  1212. tests := []struct {
  1213. membs []*Member
  1214. self string
  1215. wurls []string
  1216. }{
  1217. {
  1218. []*Member{
  1219. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1220. },
  1221. "a",
  1222. []string{},
  1223. },
  1224. {
  1225. []*Member{
  1226. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1227. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1228. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1229. },
  1230. "a",
  1231. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1232. },
  1233. {
  1234. []*Member{
  1235. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1236. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1237. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1238. },
  1239. "a",
  1240. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1241. },
  1242. }
  1243. for i, tt := range tests {
  1244. cl := NewClusterFromMembers("", types.ID(0), tt.membs)
  1245. urls := getOtherPeerURLs(cl, tt.self)
  1246. if !reflect.DeepEqual(urls, tt.wurls) {
  1247. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1248. }
  1249. }
  1250. }
  1251. func TestGetBool(t *testing.T) {
  1252. tests := []struct {
  1253. b *bool
  1254. wb bool
  1255. wset bool
  1256. }{
  1257. {nil, false, false},
  1258. {boolp(true), true, true},
  1259. {boolp(false), false, true},
  1260. }
  1261. for i, tt := range tests {
  1262. b, set := getBool(tt.b)
  1263. if b != tt.wb {
  1264. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  1265. }
  1266. if set != tt.wset {
  1267. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  1268. }
  1269. }
  1270. }
  1271. func TestGenID(t *testing.T) {
  1272. // Sanity check that the GenID function has been seeded appropriately
  1273. // (math/rand is seeded with 1 by default)
  1274. r := rand.NewSource(int64(1))
  1275. var n uint64
  1276. for n == 0 {
  1277. n = uint64(r.Int63())
  1278. }
  1279. if n == GenID() {
  1280. t.Fatalf("GenID's rand seeded with 1!")
  1281. }
  1282. }
  1283. type action struct {
  1284. name string
  1285. params []interface{}
  1286. }
  1287. type recorder struct {
  1288. sync.Mutex
  1289. actions []action
  1290. }
  1291. func (r *recorder) record(a action) {
  1292. r.Lock()
  1293. r.actions = append(r.actions, a)
  1294. r.Unlock()
  1295. }
  1296. func (r *recorder) Action() []action {
  1297. r.Lock()
  1298. cpy := make([]action, len(r.actions))
  1299. copy(cpy, r.actions)
  1300. r.Unlock()
  1301. return cpy
  1302. }
  1303. type storeRecorder struct {
  1304. recorder
  1305. }
  1306. func (s *storeRecorder) Version() int { return 0 }
  1307. func (s *storeRecorder) Index() uint64 { return 0 }
  1308. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1309. s.record(action{
  1310. name: "Get",
  1311. params: []interface{}{path, recursive, sorted},
  1312. })
  1313. return &store.Event{}, nil
  1314. }
  1315. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1316. s.record(action{
  1317. name: "Set",
  1318. params: []interface{}{path, dir, val, expr},
  1319. })
  1320. return &store.Event{}, nil
  1321. }
  1322. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1323. s.record(action{
  1324. name: "Update",
  1325. params: []interface{}{path, val, expr},
  1326. })
  1327. return &store.Event{}, nil
  1328. }
  1329. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1330. s.record(action{
  1331. name: "Create",
  1332. params: []interface{}{path, dir, val, uniq, exp},
  1333. })
  1334. return &store.Event{}, nil
  1335. }
  1336. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1337. s.record(action{
  1338. name: "CompareAndSwap",
  1339. params: []interface{}{path, prevVal, prevIdx, val, expr},
  1340. })
  1341. return &store.Event{}, nil
  1342. }
  1343. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1344. s.record(action{
  1345. name: "Delete",
  1346. params: []interface{}{path, dir, recursive},
  1347. })
  1348. return &store.Event{}, nil
  1349. }
  1350. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1351. s.record(action{
  1352. name: "CompareAndDelete",
  1353. params: []interface{}{path, prevVal, prevIdx},
  1354. })
  1355. return &store.Event{}, nil
  1356. }
  1357. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1358. s.record(action{name: "Watch"})
  1359. return &stubWatcher{}, nil
  1360. }
  1361. func (s *storeRecorder) Save() ([]byte, error) {
  1362. s.record(action{name: "Save"})
  1363. return nil, nil
  1364. }
  1365. func (s *storeRecorder) Recovery(b []byte) error {
  1366. s.record(action{name: "Recovery"})
  1367. return nil
  1368. }
  1369. func (s *storeRecorder) JsonStats() []byte { return nil }
  1370. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1371. s.record(action{
  1372. name: "DeleteExpiredKeys",
  1373. params: []interface{}{cutoff},
  1374. })
  1375. }
  1376. type stubWatcher struct{}
  1377. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  1378. func (w *stubWatcher) StartIndex() uint64 { return 0 }
  1379. func (w *stubWatcher) Remove() {}
  1380. // errStoreRecorder returns an store error on Get, Watch request
  1381. type errStoreRecorder struct {
  1382. storeRecorder
  1383. err error
  1384. }
  1385. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  1386. s.record(action{name: "Get"})
  1387. return nil, s.err
  1388. }
  1389. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1390. s.record(action{name: "Watch"})
  1391. return nil, s.err
  1392. }
  1393. type waitRecorder struct {
  1394. action []action
  1395. }
  1396. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1397. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  1398. return nil
  1399. }
  1400. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1401. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  1402. }
  1403. func boolp(b bool) *bool { return &b }
  1404. func stringp(s string) *string { return &s }
  1405. type storageRecorder struct {
  1406. recorder
  1407. }
  1408. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  1409. p.record(action{name: "Save"})
  1410. return nil
  1411. }
  1412. func (p *storageRecorder) Cut() error {
  1413. p.record(action{name: "Cut"})
  1414. return nil
  1415. }
  1416. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) error {
  1417. if !raft.IsEmptySnap(st) {
  1418. p.record(action{name: "SaveSnap"})
  1419. }
  1420. return nil
  1421. }
  1422. type readyNode struct {
  1423. readyc chan raft.Ready
  1424. }
  1425. func newReadyNode() *readyNode {
  1426. readyc := make(chan raft.Ready, 1)
  1427. return &readyNode{readyc: readyc}
  1428. }
  1429. func (n *readyNode) Tick() {}
  1430. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1431. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1432. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1433. return nil
  1434. }
  1435. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1436. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1437. func (n *readyNode) Advance() {}
  1438. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState { return nil }
  1439. func (n *readyNode) Stop() {}
  1440. func (n *readyNode) Compact(index uint64, nodes []uint64, d []byte) {}
  1441. type nodeRecorder struct {
  1442. recorder
  1443. }
  1444. func (n *nodeRecorder) Tick() { n.record(action{name: "Tick"}) }
  1445. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1446. n.record(action{name: "Campaign"})
  1447. return nil
  1448. }
  1449. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1450. n.record(action{name: "Propose"})
  1451. return nil
  1452. }
  1453. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1454. n.record(action{name: "ProposeConfChange"})
  1455. return nil
  1456. }
  1457. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1458. n.record(action{name: "Step"})
  1459. return nil
  1460. }
  1461. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1462. func (n *nodeRecorder) Advance() {}
  1463. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1464. n.record(action{name: "ApplyConfChange", params: []interface{}{conf}})
  1465. return nil
  1466. }
  1467. func (n *nodeRecorder) Stop() {
  1468. n.record(action{name: "Stop"})
  1469. }
  1470. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1471. n.record(action{name: "Compact"})
  1472. }
  1473. type nodeProposeDataRecorder struct {
  1474. nodeRecorder
  1475. sync.Mutex
  1476. d [][]byte
  1477. }
  1478. func (n *nodeProposeDataRecorder) data() [][]byte {
  1479. n.Lock()
  1480. d := n.d
  1481. n.Unlock()
  1482. return d
  1483. }
  1484. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1485. n.nodeRecorder.Propose(ctx, data)
  1486. n.Lock()
  1487. n.d = append(n.d, data)
  1488. n.Unlock()
  1489. return nil
  1490. }
  1491. type nodeProposalBlockerRecorder struct {
  1492. nodeRecorder
  1493. }
  1494. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1495. <-ctx.Done()
  1496. n.record(action{name: "Propose blocked"})
  1497. return nil
  1498. }
  1499. type nodeConfChangeCommitterRecorder struct {
  1500. nodeRecorder
  1501. readyc chan raft.Ready
  1502. }
  1503. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1504. readyc := make(chan raft.Ready, 1)
  1505. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1506. }
  1507. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1508. data, err := conf.Marshal()
  1509. if err != nil {
  1510. return err
  1511. }
  1512. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1513. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1514. return nil
  1515. }
  1516. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1517. return n.readyc
  1518. }
  1519. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1520. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1521. return nil
  1522. }
  1523. type waitWithResponse struct {
  1524. ch <-chan interface{}
  1525. }
  1526. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1527. return w.ch
  1528. }
  1529. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1530. type nopSender struct{}
  1531. func (s *nopSender) Sender(id types.ID) rafthttp.Sender { return nil }
  1532. func (s *nopSender) Send(m []raftpb.Message) {}
  1533. func (s *nopSender) Add(m *Member) {}
  1534. func (s *nopSender) Remove(id types.ID) {}
  1535. func (s *nopSender) Update(m *Member) {}
  1536. func (s *nopSender) Stop() {}
  1537. func (s *nopSender) ShouldStopNotify() <-chan struct{} { return nil }
  1538. func mustMakePeerSlice(t *testing.T, ids ...uint64) []raft.Peer {
  1539. peers := make([]raft.Peer, len(ids))
  1540. for i, id := range ids {
  1541. m := Member{ID: types.ID(id)}
  1542. b, err := json.Marshal(m)
  1543. if err != nil {
  1544. t.Fatal(err)
  1545. }
  1546. peers[i] = raft.Peer{ID: id, Context: b}
  1547. }
  1548. return peers
  1549. }