server_test.go 37 KB

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