server_test.go 38 KB

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