server_test.go 38 KB

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