server_test.go 42 KB

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