server_test.go 37 KB

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