server_test.go 45 KB

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