server_test.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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. "testing"
  23. "time"
  24. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  25. "github.com/coreos/etcd/etcdserver/membership"
  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(&membership.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([]*membership.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: membership.MemberAttributesStorePath(1),
  450. Val: `{"Name":"abc","ClientURLs":["http://127.0.0.1:2379"]}`,
  451. }
  452. srv.applyRequest(req)
  453. w := membership.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 := membership.NewCluster("")
  460. cl.SetStore(store.New())
  461. for i := 1; i <= 4; i++ {
  462. cl.AddMember(&membership.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. membership.ErrIDRemoved,
  475. },
  476. {
  477. raftpb.ConfChange{
  478. Type: raftpb.ConfChangeUpdateNode,
  479. NodeID: 4,
  480. },
  481. membership.ErrIDRemoved,
  482. },
  483. {
  484. raftpb.ConfChange{
  485. Type: raftpb.ConfChangeAddNode,
  486. NodeID: 1,
  487. },
  488. membership.ErrIDExists,
  489. },
  490. {
  491. raftpb.ConfChange{
  492. Type: raftpb.ConfChangeRemoveNode,
  493. NodeID: 5,
  494. },
  495. membership.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 := membership.NewCluster("")
  523. cl.SetStore(store.New())
  524. for i := 1; i <= 3; i++ {
  525. cl.AddMember(&membership.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 {
  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 {
  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 := membership.NewCluster("")
  561. cl.SetStore(store.New())
  562. for i := 1; i <= 5; i++ {
  563. cl.AddMember(&membership.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 {
  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. st := store.New()
  872. cl := membership.NewCluster("abc")
  873. cl.SetStore(st)
  874. testdir, err := ioutil.TempDir(os.TempDir(), "testsnapdir")
  875. if err != nil {
  876. t.Fatalf("Couldn't open tempdir (%v)", err)
  877. }
  878. defer os.RemoveAll(testdir)
  879. if err := os.MkdirAll(testdir+"/member/snap", 0755); err != nil {
  880. t.Fatalf("Couldn't make snap dir (%v)", err)
  881. }
  882. rs := raft.NewMemoryStorage()
  883. tr, snapDoneC := rafthttp.NewSnapTransporter(testdir)
  884. s := &EtcdServer{
  885. cfg: &ServerConfig{
  886. DataDir: testdir,
  887. },
  888. r: raftNode{
  889. Node: n,
  890. transport: tr,
  891. storage: mockstorage.NewStorageRecorder(testdir),
  892. raftStorage: rs,
  893. },
  894. store: st,
  895. cluster: cl,
  896. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  897. }
  898. be, tmpPath := backend.NewDefaultTmpBackend()
  899. defer func() {
  900. os.RemoveAll(tmpPath)
  901. }()
  902. s.kv = dstorage.New(be, &lease.FakeLessor{}, &s.consistIndex)
  903. s.be = be
  904. s.start()
  905. defer s.Stop()
  906. // submit applied entries and snap entries
  907. idx := uint64(0)
  908. outdated := 0
  909. accepted := 0
  910. for k := 1; k <= 101; k++ {
  911. idx++
  912. ch := s.w.Register(uint64(idx))
  913. req := &pb.Request{Method: "QGET", ID: uint64(idx)}
  914. ent := raftpb.Entry{Index: uint64(idx), Data: pbutil.MustMarshal(req)}
  915. ready := raft.Ready{Entries: []raftpb.Entry{ent}}
  916. n.readyc <- ready
  917. ready = raft.Ready{CommittedEntries: []raftpb.Entry{ent}}
  918. n.readyc <- ready
  919. // "idx" applied
  920. <-ch
  921. // one snapshot for every two messages
  922. if k%2 != 0 {
  923. continue
  924. }
  925. n.readyc <- raft.Ready{Messages: []raftpb.Message{{Type: raftpb.MsgSnap}}}
  926. // get the snapshot sent by the transport
  927. snapMsg := <-snapDoneC
  928. // If the snapshot trails applied records, recovery will panic
  929. // since there's no allocated snapshot at the place of the
  930. // snapshot record. This only happens when the applier and the
  931. // snapshot sender get out of sync.
  932. if snapMsg.Snapshot.Metadata.Index == idx {
  933. idx++
  934. snapMsg.Snapshot.Metadata.Index = idx
  935. ready = raft.Ready{Snapshot: snapMsg.Snapshot}
  936. n.readyc <- ready
  937. accepted++
  938. } else {
  939. outdated++
  940. }
  941. // don't wait for the snapshot to complete, move to next message
  942. }
  943. if accepted != 50 {
  944. t.Errorf("accepted=%v, want 50", accepted)
  945. }
  946. if outdated != 0 {
  947. t.Errorf("outdated=%v, want 0", outdated)
  948. }
  949. }
  950. // TestAddMember tests AddMember can propose and perform node addition.
  951. func TestAddMember(t *testing.T) {
  952. n := newNodeConfChangeCommitterRecorder()
  953. n.readyc <- raft.Ready{
  954. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  955. }
  956. cl := newTestCluster(nil)
  957. st := store.New()
  958. cl.SetStore(st)
  959. s := &EtcdServer{
  960. r: raftNode{
  961. Node: n,
  962. raftStorage: raft.NewMemoryStorage(),
  963. storage: mockstorage.NewStorageRecorder(""),
  964. transport: rafthttp.NewNopTransporter(),
  965. },
  966. cfg: &ServerConfig{},
  967. store: st,
  968. cluster: cl,
  969. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  970. }
  971. s.start()
  972. m := membership.Member{ID: 1234, RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"foo"}}}
  973. err := s.AddMember(context.TODO(), m)
  974. gaction := n.Action()
  975. s.Stop()
  976. if err != nil {
  977. t.Fatalf("AddMember error: %v", err)
  978. }
  979. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeAddNode"}, {Name: "ApplyConfChange:ConfChangeAddNode"}}
  980. if !reflect.DeepEqual(gaction, wactions) {
  981. t.Errorf("action = %v, want %v", gaction, wactions)
  982. }
  983. if cl.Member(1234) == nil {
  984. t.Errorf("member with id 1234 is not added")
  985. }
  986. }
  987. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  988. func TestRemoveMember(t *testing.T) {
  989. n := newNodeConfChangeCommitterRecorder()
  990. n.readyc <- raft.Ready{
  991. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  992. }
  993. cl := newTestCluster(nil)
  994. st := store.New()
  995. cl.SetStore(store.New())
  996. cl.AddMember(&membership.Member{ID: 1234})
  997. s := &EtcdServer{
  998. r: raftNode{
  999. Node: n,
  1000. raftStorage: raft.NewMemoryStorage(),
  1001. storage: mockstorage.NewStorageRecorder(""),
  1002. transport: rafthttp.NewNopTransporter(),
  1003. },
  1004. cfg: &ServerConfig{},
  1005. store: st,
  1006. cluster: cl,
  1007. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1008. }
  1009. s.start()
  1010. err := s.RemoveMember(context.TODO(), 1234)
  1011. gaction := n.Action()
  1012. s.Stop()
  1013. if err != nil {
  1014. t.Fatalf("RemoveMember error: %v", err)
  1015. }
  1016. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeRemoveNode"}, {Name: "ApplyConfChange:ConfChangeRemoveNode"}}
  1017. if !reflect.DeepEqual(gaction, wactions) {
  1018. t.Errorf("action = %v, want %v", gaction, wactions)
  1019. }
  1020. if cl.Member(1234) != nil {
  1021. t.Errorf("member with id 1234 is not removed")
  1022. }
  1023. }
  1024. // TestUpdateMember tests RemoveMember can propose and perform node update.
  1025. func TestUpdateMember(t *testing.T) {
  1026. n := newNodeConfChangeCommitterRecorder()
  1027. n.readyc <- raft.Ready{
  1028. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  1029. }
  1030. cl := newTestCluster(nil)
  1031. st := store.New()
  1032. cl.SetStore(st)
  1033. cl.AddMember(&membership.Member{ID: 1234})
  1034. s := &EtcdServer{
  1035. r: raftNode{
  1036. Node: n,
  1037. raftStorage: raft.NewMemoryStorage(),
  1038. storage: mockstorage.NewStorageRecorder(""),
  1039. transport: rafthttp.NewNopTransporter(),
  1040. },
  1041. store: st,
  1042. cluster: cl,
  1043. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1044. }
  1045. s.start()
  1046. wm := membership.Member{ID: 1234, RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  1047. err := s.UpdateMember(context.TODO(), wm)
  1048. gaction := n.Action()
  1049. s.Stop()
  1050. if err != nil {
  1051. t.Fatalf("UpdateMember error: %v", err)
  1052. }
  1053. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeUpdateNode"}, {Name: "ApplyConfChange:ConfChangeUpdateNode"}}
  1054. if !reflect.DeepEqual(gaction, wactions) {
  1055. t.Errorf("action = %v, want %v", gaction, wactions)
  1056. }
  1057. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  1058. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  1059. }
  1060. }
  1061. // TODO: test server could stop itself when being removed
  1062. func TestPublish(t *testing.T) {
  1063. n := newNodeRecorder()
  1064. ch := make(chan interface{}, 1)
  1065. // simulate that request has gone through consensus
  1066. ch <- Response{}
  1067. w := wait.NewWithResponse(ch)
  1068. srv := &EtcdServer{
  1069. cfg: &ServerConfig{TickMs: 1},
  1070. id: 1,
  1071. r: raftNode{Node: n},
  1072. attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  1073. cluster: &membership.RaftCluster{},
  1074. w: w,
  1075. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1076. }
  1077. srv.publish(time.Hour)
  1078. action := n.Action()
  1079. if len(action) != 1 {
  1080. t.Fatalf("len(action) = %d, want 1", len(action))
  1081. }
  1082. if action[0].Name != "Propose" {
  1083. t.Fatalf("action = %s, want Propose", action[0].Name)
  1084. }
  1085. data := action[0].Params[0].([]byte)
  1086. var r pb.Request
  1087. if err := r.Unmarshal(data); err != nil {
  1088. t.Fatalf("unmarshal request error: %v", err)
  1089. }
  1090. if r.Method != "PUT" {
  1091. t.Errorf("method = %s, want PUT", r.Method)
  1092. }
  1093. wm := membership.Member{ID: 1, Attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1094. if wpath := membership.MemberAttributesStorePath(wm.ID); r.Path != wpath {
  1095. t.Errorf("path = %s, want %s", r.Path, wpath)
  1096. }
  1097. var gattr membership.Attributes
  1098. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1099. t.Fatalf("unmarshal val error: %v", err)
  1100. }
  1101. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1102. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1103. }
  1104. }
  1105. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1106. func TestPublishStopped(t *testing.T) {
  1107. srv := &EtcdServer{
  1108. cfg: &ServerConfig{TickMs: 1},
  1109. r: raftNode{
  1110. Node: newNodeNop(),
  1111. transport: rafthttp.NewNopTransporter(),
  1112. },
  1113. cluster: &membership.RaftCluster{},
  1114. w: mockwait.NewNop(),
  1115. done: make(chan struct{}),
  1116. stop: make(chan struct{}),
  1117. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1118. }
  1119. close(srv.done)
  1120. srv.publish(time.Hour)
  1121. }
  1122. // TestPublishRetry tests that publish will keep retry until success.
  1123. func TestPublishRetry(t *testing.T) {
  1124. n := newNodeRecorder()
  1125. srv := &EtcdServer{
  1126. cfg: &ServerConfig{TickMs: 1},
  1127. r: raftNode{Node: n},
  1128. w: mockwait.NewNop(),
  1129. done: make(chan struct{}),
  1130. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1131. }
  1132. // TODO: use fakeClockwork
  1133. time.AfterFunc(10*time.Millisecond, func() { close(srv.done) })
  1134. srv.publish(10 * time.Nanosecond)
  1135. action := n.Action()
  1136. // multiple Proposes
  1137. if cnt := len(action); cnt < 2 {
  1138. t.Errorf("len(action) = %d, want >= 2", cnt)
  1139. }
  1140. }
  1141. func TestUpdateVersion(t *testing.T) {
  1142. n := newNodeRecorder()
  1143. ch := make(chan interface{}, 1)
  1144. // simulate that request has gone through consensus
  1145. ch <- Response{}
  1146. w := wait.NewWithResponse(ch)
  1147. srv := &EtcdServer{
  1148. id: 1,
  1149. cfg: &ServerConfig{TickMs: 1},
  1150. r: raftNode{Node: n},
  1151. attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://node1.com"}},
  1152. cluster: &membership.RaftCluster{},
  1153. w: w,
  1154. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1155. }
  1156. srv.updateClusterVersion("2.0.0")
  1157. action := n.Action()
  1158. if len(action) != 1 {
  1159. t.Fatalf("len(action) = %d, want 1", len(action))
  1160. }
  1161. if action[0].Name != "Propose" {
  1162. t.Fatalf("action = %s, want Propose", action[0].Name)
  1163. }
  1164. data := action[0].Params[0].([]byte)
  1165. var r pb.Request
  1166. if err := r.Unmarshal(data); err != nil {
  1167. t.Fatalf("unmarshal request error: %v", err)
  1168. }
  1169. if r.Method != "PUT" {
  1170. t.Errorf("method = %s, want PUT", r.Method)
  1171. }
  1172. if wpath := path.Join(StoreClusterPrefix, "version"); r.Path != wpath {
  1173. t.Errorf("path = %s, want %s", r.Path, wpath)
  1174. }
  1175. if r.Val != "2.0.0" {
  1176. t.Errorf("val = %s, want %s", r.Val, "2.0.0")
  1177. }
  1178. }
  1179. func TestStopNotify(t *testing.T) {
  1180. s := &EtcdServer{
  1181. stop: make(chan struct{}),
  1182. done: make(chan struct{}),
  1183. }
  1184. go func() {
  1185. <-s.stop
  1186. close(s.done)
  1187. }()
  1188. notifier := s.StopNotify()
  1189. select {
  1190. case <-notifier:
  1191. t.Fatalf("received unexpected stop notification")
  1192. default:
  1193. }
  1194. s.Stop()
  1195. select {
  1196. case <-notifier:
  1197. default:
  1198. t.Fatalf("cannot receive stop notification")
  1199. }
  1200. }
  1201. func TestGetOtherPeerURLs(t *testing.T) {
  1202. tests := []struct {
  1203. membs []*membership.Member
  1204. wurls []string
  1205. }{
  1206. {
  1207. []*membership.Member{
  1208. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1209. },
  1210. []string{},
  1211. },
  1212. {
  1213. []*membership.Member{
  1214. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1215. membership.NewMember("2", types.MustNewURLs([]string{"http://10.0.0.2:2"}), "a", nil),
  1216. membership.NewMember("3", types.MustNewURLs([]string{"http://10.0.0.3:3"}), "a", nil),
  1217. },
  1218. []string{"http://10.0.0.2:2", "http://10.0.0.3:3"},
  1219. },
  1220. {
  1221. []*membership.Member{
  1222. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1223. membership.NewMember("3", types.MustNewURLs([]string{"http://10.0.0.3:3"}), "a", nil),
  1224. membership.NewMember("2", types.MustNewURLs([]string{"http://10.0.0.2:2"}), "a", nil),
  1225. },
  1226. []string{"http://10.0.0.2:2", "http://10.0.0.3:3"},
  1227. },
  1228. }
  1229. for i, tt := range tests {
  1230. cl := membership.NewClusterFromMembers("", types.ID(0), tt.membs)
  1231. self := "1"
  1232. urls := getRemotePeerURLs(cl, self)
  1233. if !reflect.DeepEqual(urls, tt.wurls) {
  1234. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1235. }
  1236. }
  1237. }
  1238. type nodeRecorder struct{ testutil.Recorder }
  1239. func newNodeRecorder() *nodeRecorder { return &nodeRecorder{&testutil.RecorderBuffered{}} }
  1240. func newNodeNop() raft.Node { return newNodeRecorder() }
  1241. func (n *nodeRecorder) Tick() { n.Record(testutil.Action{Name: "Tick"}) }
  1242. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1243. n.Record(testutil.Action{Name: "Campaign"})
  1244. return nil
  1245. }
  1246. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1247. n.Record(testutil.Action{Name: "Propose", Params: []interface{}{data}})
  1248. return nil
  1249. }
  1250. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1251. n.Record(testutil.Action{Name: "ProposeConfChange"})
  1252. return nil
  1253. }
  1254. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1255. n.Record(testutil.Action{Name: "Step"})
  1256. return nil
  1257. }
  1258. func (n *nodeRecorder) Status() raft.Status { return raft.Status{} }
  1259. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1260. func (n *nodeRecorder) Advance() {}
  1261. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1262. n.Record(testutil.Action{Name: "ApplyConfChange", Params: []interface{}{conf}})
  1263. return &raftpb.ConfState{}
  1264. }
  1265. func (n *nodeRecorder) Stop() {
  1266. n.Record(testutil.Action{Name: "Stop"})
  1267. }
  1268. func (n *nodeRecorder) ReportUnreachable(id uint64) {}
  1269. func (n *nodeRecorder) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  1270. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1271. n.Record(testutil.Action{Name: "Compact"})
  1272. }
  1273. type nodeProposalBlockerRecorder struct {
  1274. nodeRecorder
  1275. }
  1276. func newProposalBlockerRecorder() *nodeProposalBlockerRecorder {
  1277. return &nodeProposalBlockerRecorder{*newNodeRecorder()}
  1278. }
  1279. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1280. <-ctx.Done()
  1281. n.Record(testutil.Action{Name: "Propose blocked"})
  1282. return nil
  1283. }
  1284. // readyNode is a nodeRecorder with a user-writeable ready channel
  1285. type readyNode struct {
  1286. nodeRecorder
  1287. readyc chan raft.Ready
  1288. }
  1289. func newReadyNode() *readyNode {
  1290. return &readyNode{
  1291. nodeRecorder{testutil.NewRecorderStream()},
  1292. make(chan raft.Ready, 1)}
  1293. }
  1294. func newNopReadyNode() *readyNode {
  1295. return &readyNode{*newNodeRecorder(), make(chan raft.Ready, 1)}
  1296. }
  1297. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1298. type nodeConfChangeCommitterRecorder struct {
  1299. readyNode
  1300. index uint64
  1301. }
  1302. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1303. return &nodeConfChangeCommitterRecorder{*newNopReadyNode(), 0}
  1304. }
  1305. func newNodeConfChangeCommitterStream() *nodeConfChangeCommitterRecorder {
  1306. return &nodeConfChangeCommitterRecorder{*newReadyNode(), 0}
  1307. }
  1308. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1309. data, err := conf.Marshal()
  1310. if err != nil {
  1311. return err
  1312. }
  1313. n.index++
  1314. n.Record(testutil.Action{Name: "ProposeConfChange:" + conf.Type.String()})
  1315. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: raftpb.EntryConfChange, Data: data}}}
  1316. return nil
  1317. }
  1318. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1319. return n.readyc
  1320. }
  1321. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1322. n.Record(testutil.Action{Name: "ApplyConfChange:" + conf.Type.String()})
  1323. return &raftpb.ConfState{}
  1324. }
  1325. // nodeCommitter commits proposed data immediately.
  1326. type nodeCommitter struct {
  1327. readyNode
  1328. index uint64
  1329. }
  1330. func newNodeCommitter() raft.Node {
  1331. return &nodeCommitter{*newNopReadyNode(), 0}
  1332. }
  1333. func (n *nodeCommitter) Propose(ctx context.Context, data []byte) error {
  1334. n.index++
  1335. ents := []raftpb.Entry{{Index: n.index, Data: data}}
  1336. n.readyc <- raft.Ready{
  1337. Entries: ents,
  1338. CommittedEntries: ents,
  1339. }
  1340. return nil
  1341. }
  1342. func newTestCluster(membs []*membership.Member) *membership.RaftCluster {
  1343. c := membership.NewCluster("")
  1344. for _, m := range membs {
  1345. c.AddMember(m)
  1346. }
  1347. return c
  1348. }