server_test.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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. s := &EtcdServer{
  161. r: raftNode{
  162. Node: n,
  163. raftStorage: raft.NewMemoryStorage(),
  164. storage: mockstorage.NewStorageRecorder(""),
  165. transport: rafthttp.NewNopTransporter(),
  166. ticker: &time.Ticker{},
  167. },
  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: raftNode{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. srv := &EtcdServer{
  533. id: 1,
  534. r: raftNode{
  535. Node: newNodeNop(),
  536. transport: rafthttp.NewNopTransporter(),
  537. },
  538. cluster: cl,
  539. }
  540. cc := raftpb.ConfChange{
  541. Type: raftpb.ConfChangeRemoveNode,
  542. NodeID: 2,
  543. }
  544. // remove non-local member
  545. shouldStop, err := srv.applyConfChange(cc, &raftpb.ConfState{})
  546. if err != nil {
  547. t.Fatalf("unexpected error %v", err)
  548. }
  549. if shouldStop {
  550. t.Errorf("shouldStop = %t, want %t", shouldStop, false)
  551. }
  552. // remove local member
  553. cc.NodeID = 1
  554. shouldStop, err = srv.applyConfChange(cc, &raftpb.ConfState{})
  555. if err != nil {
  556. t.Fatalf("unexpected error %v", err)
  557. }
  558. if !shouldStop {
  559. t.Errorf("shouldStop = %t, want %t", shouldStop, true)
  560. }
  561. }
  562. // TestApplyMultiConfChangeShouldStop ensures that apply will return shouldStop
  563. // if the local member is removed along with other conf updates.
  564. func TestApplyMultiConfChangeShouldStop(t *testing.T) {
  565. cl := membership.NewCluster("")
  566. cl.SetStore(store.New())
  567. for i := 1; i <= 5; i++ {
  568. cl.AddMember(&membership.Member{ID: types.ID(i)})
  569. }
  570. srv := &EtcdServer{
  571. id: 2,
  572. r: raftNode{
  573. Node: newNodeNop(),
  574. transport: rafthttp.NewNopTransporter(),
  575. },
  576. cluster: cl,
  577. w: wait.New(),
  578. }
  579. ents := []raftpb.Entry{}
  580. for i := 1; i <= 4; i++ {
  581. ent := raftpb.Entry{
  582. Term: 1,
  583. Index: uint64(i),
  584. Type: raftpb.EntryConfChange,
  585. Data: pbutil.MustMarshal(
  586. &raftpb.ConfChange{
  587. Type: raftpb.ConfChangeRemoveNode,
  588. NodeID: uint64(i)}),
  589. }
  590. ents = append(ents, ent)
  591. }
  592. _, _, shouldStop := srv.apply(ents, &raftpb.ConfState{})
  593. if !shouldStop {
  594. t.Errorf("shouldStop = %t, want %t", shouldStop, true)
  595. }
  596. }
  597. func TestDoProposal(t *testing.T) {
  598. tests := []pb.Request{
  599. {Method: "POST", ID: 1},
  600. {Method: "PUT", ID: 1},
  601. {Method: "DELETE", ID: 1},
  602. {Method: "GET", ID: 1, Quorum: true},
  603. }
  604. for i, tt := range tests {
  605. st := mockstore.NewRecorder()
  606. srv := &EtcdServer{
  607. Cfg: &ServerConfig{TickMs: 1},
  608. r: raftNode{
  609. Node: newNodeCommitter(),
  610. storage: mockstorage.NewStorageRecorder(""),
  611. raftStorage: raft.NewMemoryStorage(),
  612. transport: rafthttp.NewNopTransporter(),
  613. ticker: &time.Ticker{},
  614. },
  615. store: st,
  616. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  617. SyncTicker: &time.Ticker{},
  618. }
  619. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  620. srv.start()
  621. resp, err := srv.Do(context.Background(), tt)
  622. srv.Stop()
  623. action := st.Action()
  624. if len(action) != 1 {
  625. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  626. }
  627. if err != nil {
  628. t.Fatalf("#%d: err = %v, want nil", i, err)
  629. }
  630. wresp := Response{Event: &store.Event{}}
  631. if !reflect.DeepEqual(resp, wresp) {
  632. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  633. }
  634. }
  635. }
  636. func TestDoProposalCancelled(t *testing.T) {
  637. wt := mockwait.NewRecorder()
  638. srv := &EtcdServer{
  639. Cfg: &ServerConfig{TickMs: 1},
  640. r: raftNode{Node: newNodeNop()},
  641. w: wt,
  642. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  643. }
  644. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  645. ctx, cancel := context.WithCancel(context.Background())
  646. cancel()
  647. _, err := srv.Do(ctx, pb.Request{Method: "PUT"})
  648. if err != ErrCanceled {
  649. t.Fatalf("err = %v, want %v", err, ErrCanceled)
  650. }
  651. w := []testutil.Action{{Name: "Register"}, {Name: "Trigger"}}
  652. if !reflect.DeepEqual(wt.Action(), w) {
  653. t.Errorf("wt.action = %+v, want %+v", wt.Action(), w)
  654. }
  655. }
  656. func TestDoProposalTimeout(t *testing.T) {
  657. srv := &EtcdServer{
  658. Cfg: &ServerConfig{TickMs: 1},
  659. r: raftNode{Node: newNodeNop()},
  660. w: mockwait.NewNop(),
  661. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  662. }
  663. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  664. ctx, _ := context.WithTimeout(context.Background(), 0)
  665. _, err := srv.Do(ctx, pb.Request{Method: "PUT"})
  666. if err != ErrTimeout {
  667. t.Fatalf("err = %v, want %v", err, ErrTimeout)
  668. }
  669. }
  670. func TestDoProposalStopped(t *testing.T) {
  671. srv := &EtcdServer{
  672. Cfg: &ServerConfig{TickMs: 1},
  673. r: raftNode{Node: newNodeNop()},
  674. w: mockwait.NewNop(),
  675. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  676. }
  677. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  678. srv.stopping = make(chan struct{})
  679. close(srv.stopping)
  680. _, err := srv.Do(context.Background(), pb.Request{Method: "PUT", ID: 1})
  681. if err != ErrStopped {
  682. t.Errorf("err = %v, want %v", err, ErrStopped)
  683. }
  684. }
  685. // TestSync tests sync 1. is nonblocking 2. proposes SYNC request.
  686. func TestSync(t *testing.T) {
  687. n := newNodeRecorder()
  688. ctx, cancel := context.WithCancel(context.TODO())
  689. srv := &EtcdServer{
  690. r: raftNode{Node: n},
  691. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  692. ctx: ctx,
  693. cancel: cancel,
  694. }
  695. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  696. // check that sync is non-blocking
  697. done := make(chan struct{})
  698. go func() {
  699. srv.sync(10 * time.Second)
  700. done <- struct{}{}
  701. }()
  702. select {
  703. case <-done:
  704. case <-time.After(time.Second):
  705. t.Fatal("sync should be non-blocking but did not return after 1s!")
  706. }
  707. action, _ := n.Wait(1)
  708. if len(action) != 1 {
  709. t.Fatalf("len(action) = %d, want 1", len(action))
  710. }
  711. if action[0].Name != "Propose" {
  712. t.Fatalf("action = %s, want Propose", action[0].Name)
  713. }
  714. data := action[0].Params[0].([]byte)
  715. var r pb.Request
  716. if err := r.Unmarshal(data); err != nil {
  717. t.Fatalf("unmarshal request error: %v", err)
  718. }
  719. if r.Method != "SYNC" {
  720. t.Errorf("method = %s, want SYNC", r.Method)
  721. }
  722. }
  723. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  724. // after timeout
  725. func TestSyncTimeout(t *testing.T) {
  726. n := newProposalBlockerRecorder()
  727. ctx, cancel := context.WithCancel(context.TODO())
  728. srv := &EtcdServer{
  729. r: raftNode{Node: n},
  730. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  731. ctx: ctx,
  732. cancel: cancel,
  733. }
  734. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  735. // check that sync is non-blocking
  736. done := make(chan struct{})
  737. go func() {
  738. srv.sync(0)
  739. done <- struct{}{}
  740. }()
  741. select {
  742. case <-done:
  743. case <-time.After(time.Second):
  744. t.Fatal("sync should be non-blocking but did not return after 1s!")
  745. }
  746. w := []testutil.Action{{Name: "Propose blocked"}}
  747. if g, _ := n.Wait(1); !reflect.DeepEqual(g, w) {
  748. t.Errorf("action = %v, want %v", g, w)
  749. }
  750. }
  751. // TODO: TestNoSyncWhenNoLeader
  752. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  753. func TestSyncTrigger(t *testing.T) {
  754. n := newReadyNode()
  755. st := make(chan time.Time, 1)
  756. tk := &time.Ticker{C: st}
  757. srv := &EtcdServer{
  758. Cfg: &ServerConfig{TickMs: 1},
  759. r: raftNode{
  760. Node: n,
  761. raftStorage: raft.NewMemoryStorage(),
  762. transport: rafthttp.NewNopTransporter(),
  763. storage: mockstorage.NewStorageRecorder(""),
  764. ticker: &time.Ticker{},
  765. },
  766. store: mockstore.NewNop(),
  767. SyncTicker: tk,
  768. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  769. }
  770. // trigger the server to become a leader and accept sync requests
  771. go func() {
  772. srv.start()
  773. n.readyc <- raft.Ready{
  774. SoftState: &raft.SoftState{
  775. RaftState: raft.StateLeader,
  776. },
  777. }
  778. // trigger a sync request
  779. st <- time.Time{}
  780. }()
  781. action, _ := n.Wait(1)
  782. go srv.Stop()
  783. if len(action) != 1 {
  784. t.Fatalf("len(action) = %d, want 1", len(action))
  785. }
  786. if action[0].Name != "Propose" {
  787. t.Fatalf("action = %s, want Propose", action[0].Name)
  788. }
  789. data := action[0].Params[0].([]byte)
  790. var req pb.Request
  791. if err := req.Unmarshal(data); err != nil {
  792. t.Fatalf("error unmarshalling data: %v", err)
  793. }
  794. if req.Method != "SYNC" {
  795. t.Fatalf("unexpected proposed request: %#v", req.Method)
  796. }
  797. // wait on stop message
  798. <-n.Chan()
  799. }
  800. // snapshot should snapshot the store and cut the persistent
  801. func TestSnapshot(t *testing.T) {
  802. be, tmpPath := backend.NewDefaultTmpBackend()
  803. defer func() {
  804. os.RemoveAll(tmpPath)
  805. }()
  806. s := raft.NewMemoryStorage()
  807. s.Append([]raftpb.Entry{{Index: 1}})
  808. st := mockstore.NewRecorderStream()
  809. p := mockstorage.NewStorageRecorderStream("")
  810. srv := &EtcdServer{
  811. Cfg: &ServerConfig{},
  812. r: raftNode{
  813. Node: newNodeNop(),
  814. raftStorage: s,
  815. storage: p,
  816. },
  817. store: st,
  818. }
  819. srv.kv = mvcc.New(be, &lease.FakeLessor{}, &srv.consistIndex)
  820. srv.be = be
  821. ch := make(chan struct{}, 2)
  822. go func() {
  823. gaction, _ := p.Wait(1)
  824. defer func() { ch <- struct{}{} }()
  825. if len(gaction) != 1 {
  826. t.Fatalf("len(action) = %d, want 1", len(gaction))
  827. }
  828. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "SaveSnap"}) {
  829. t.Errorf("action = %s, want SaveSnap", gaction[0])
  830. }
  831. }()
  832. go func() {
  833. gaction, _ := st.Wait(2)
  834. defer func() { ch <- struct{}{} }()
  835. if len(gaction) != 2 {
  836. t.Fatalf("len(action) = %d, want 2", len(gaction))
  837. }
  838. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "Clone"}) {
  839. t.Errorf("action = %s, want Clone", gaction[0])
  840. }
  841. if !reflect.DeepEqual(gaction[1], testutil.Action{Name: "SaveNoCopy"}) {
  842. t.Errorf("action = %s, want SaveNoCopy", gaction[1])
  843. }
  844. }()
  845. srv.snapshot(1, raftpb.ConfState{Nodes: []uint64{1}})
  846. <-ch
  847. <-ch
  848. }
  849. // Applied > SnapCount should trigger a SaveSnap event
  850. func TestTriggerSnap(t *testing.T) {
  851. be, tmpPath := backend.NewDefaultTmpBackend()
  852. defer func() {
  853. os.RemoveAll(tmpPath)
  854. }()
  855. snapc := 10
  856. st := mockstore.NewRecorder()
  857. p := mockstorage.NewStorageRecorderStream("")
  858. srv := &EtcdServer{
  859. Cfg: &ServerConfig{TickMs: 1},
  860. snapCount: uint64(snapc),
  861. r: raftNode{
  862. Node: newNodeCommitter(),
  863. raftStorage: raft.NewMemoryStorage(),
  864. storage: p,
  865. transport: rafthttp.NewNopTransporter(),
  866. ticker: &time.Ticker{},
  867. },
  868. store: st,
  869. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  870. SyncTicker: &time.Ticker{},
  871. }
  872. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  873. srv.kv = mvcc.New(be, &lease.FakeLessor{}, &srv.consistIndex)
  874. srv.be = be
  875. srv.start()
  876. donec := make(chan struct{})
  877. go func() {
  878. wcnt := 2 + snapc
  879. gaction, _ := p.Wait(wcnt)
  880. // each operation is recorded as a Save
  881. // (SnapCount+1) * Puts + SaveSnap = (SnapCount+1) * Save + SaveSnap
  882. if len(gaction) != wcnt {
  883. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  884. }
  885. if !reflect.DeepEqual(gaction[wcnt-1], testutil.Action{Name: "SaveSnap"}) {
  886. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  887. }
  888. close(donec)
  889. }()
  890. for i := 0; i < snapc+1; i++ {
  891. srv.Do(context.Background(), pb.Request{Method: "PUT"})
  892. }
  893. <-donec
  894. srv.Stop()
  895. }
  896. // TestConcurrentApplyAndSnapshotV3 will send out snapshots concurrently with
  897. // proposals.
  898. func TestConcurrentApplyAndSnapshotV3(t *testing.T) {
  899. const (
  900. // snapshots that may queue up at once without dropping
  901. maxInFlightMsgSnap = 16
  902. )
  903. n := newNopReadyNode()
  904. st := store.New()
  905. cl := membership.NewCluster("abc")
  906. cl.SetStore(st)
  907. testdir, err := ioutil.TempDir(os.TempDir(), "testsnapdir")
  908. if err != nil {
  909. t.Fatalf("Couldn't open tempdir (%v)", err)
  910. }
  911. defer os.RemoveAll(testdir)
  912. if err := os.MkdirAll(testdir+"/member/snap", 0755); err != nil {
  913. t.Fatalf("Couldn't make snap dir (%v)", err)
  914. }
  915. rs := raft.NewMemoryStorage()
  916. tr, snapDoneC := rafthttp.NewSnapTransporter(testdir)
  917. s := &EtcdServer{
  918. Cfg: &ServerConfig{
  919. DataDir: testdir,
  920. },
  921. r: raftNode{
  922. isIDRemoved: func(id uint64) bool { return cl.IsIDRemoved(types.ID(id)) },
  923. Node: n,
  924. transport: tr,
  925. storage: mockstorage.NewStorageRecorder(testdir),
  926. raftStorage: rs,
  927. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  928. ticker: &time.Ticker{},
  929. },
  930. store: st,
  931. cluster: cl,
  932. SyncTicker: &time.Ticker{},
  933. }
  934. s.applyV2 = &applierV2store{store: s.store, cluster: s.cluster}
  935. be, tmpPath := backend.NewDefaultTmpBackend()
  936. defer func() {
  937. os.RemoveAll(tmpPath)
  938. }()
  939. s.kv = mvcc.New(be, &lease.FakeLessor{}, &s.consistIndex)
  940. s.be = be
  941. s.start()
  942. defer s.Stop()
  943. // submit applied entries and snap entries
  944. idx := uint64(0)
  945. outdated := 0
  946. accepted := 0
  947. for k := 1; k <= 101; k++ {
  948. idx++
  949. ch := s.w.Register(uint64(idx))
  950. req := &pb.Request{Method: "QGET", ID: uint64(idx)}
  951. ent := raftpb.Entry{Index: uint64(idx), Data: pbutil.MustMarshal(req)}
  952. ready := raft.Ready{Entries: []raftpb.Entry{ent}}
  953. n.readyc <- ready
  954. ready = raft.Ready{CommittedEntries: []raftpb.Entry{ent}}
  955. n.readyc <- ready
  956. // "idx" applied
  957. <-ch
  958. // one snapshot for every two messages
  959. if k%2 != 0 {
  960. continue
  961. }
  962. n.readyc <- raft.Ready{Messages: []raftpb.Message{{Type: raftpb.MsgSnap}}}
  963. // get the snapshot sent by the transport
  964. snapMsg := <-snapDoneC
  965. // If the snapshot trails applied records, recovery will panic
  966. // since there's no allocated snapshot at the place of the
  967. // snapshot record. This only happens when the applier and the
  968. // snapshot sender get out of sync.
  969. if snapMsg.Snapshot.Metadata.Index == idx {
  970. idx++
  971. snapMsg.Snapshot.Metadata.Index = idx
  972. ready = raft.Ready{Snapshot: snapMsg.Snapshot}
  973. n.readyc <- ready
  974. accepted++
  975. } else {
  976. outdated++
  977. }
  978. // don't wait for the snapshot to complete, move to next message
  979. }
  980. if accepted != 50 {
  981. t.Errorf("accepted=%v, want 50", accepted)
  982. }
  983. if outdated != 0 {
  984. t.Errorf("outdated=%v, want 0", outdated)
  985. }
  986. }
  987. // TestAddMember tests AddMember can propose and perform node addition.
  988. func TestAddMember(t *testing.T) {
  989. n := newNodeConfChangeCommitterRecorder()
  990. n.readyc <- raft.Ready{
  991. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  992. }
  993. cl := newTestCluster(nil)
  994. st := store.New()
  995. cl.SetStore(st)
  996. s := &EtcdServer{
  997. r: raftNode{
  998. Node: n,
  999. raftStorage: raft.NewMemoryStorage(),
  1000. storage: mockstorage.NewStorageRecorder(""),
  1001. transport: rafthttp.NewNopTransporter(),
  1002. ticker: &time.Ticker{},
  1003. },
  1004. Cfg: &ServerConfig{},
  1005. store: st,
  1006. cluster: cl,
  1007. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1008. SyncTicker: &time.Ticker{},
  1009. }
  1010. s.start()
  1011. m := membership.Member{ID: 1234, RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"foo"}}}
  1012. err := s.AddMember(context.TODO(), m)
  1013. gaction := n.Action()
  1014. s.Stop()
  1015. if err != nil {
  1016. t.Fatalf("AddMember error: %v", err)
  1017. }
  1018. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeAddNode"}, {Name: "ApplyConfChange:ConfChangeAddNode"}}
  1019. if !reflect.DeepEqual(gaction, wactions) {
  1020. t.Errorf("action = %v, want %v", gaction, wactions)
  1021. }
  1022. if cl.Member(1234) == nil {
  1023. t.Errorf("member with id 1234 is not added")
  1024. }
  1025. }
  1026. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  1027. func TestRemoveMember(t *testing.T) {
  1028. n := newNodeConfChangeCommitterRecorder()
  1029. n.readyc <- raft.Ready{
  1030. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  1031. }
  1032. cl := newTestCluster(nil)
  1033. st := store.New()
  1034. cl.SetStore(store.New())
  1035. cl.AddMember(&membership.Member{ID: 1234})
  1036. s := &EtcdServer{
  1037. r: raftNode{
  1038. Node: n,
  1039. raftStorage: raft.NewMemoryStorage(),
  1040. storage: mockstorage.NewStorageRecorder(""),
  1041. transport: rafthttp.NewNopTransporter(),
  1042. ticker: &time.Ticker{},
  1043. },
  1044. Cfg: &ServerConfig{},
  1045. store: st,
  1046. cluster: cl,
  1047. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1048. SyncTicker: &time.Ticker{},
  1049. }
  1050. s.start()
  1051. err := s.RemoveMember(context.TODO(), 1234)
  1052. gaction := n.Action()
  1053. s.Stop()
  1054. if err != nil {
  1055. t.Fatalf("RemoveMember error: %v", err)
  1056. }
  1057. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeRemoveNode"}, {Name: "ApplyConfChange:ConfChangeRemoveNode"}}
  1058. if !reflect.DeepEqual(gaction, wactions) {
  1059. t.Errorf("action = %v, want %v", gaction, wactions)
  1060. }
  1061. if cl.Member(1234) != nil {
  1062. t.Errorf("member with id 1234 is not removed")
  1063. }
  1064. }
  1065. // TestUpdateMember tests RemoveMember can propose and perform node update.
  1066. func TestUpdateMember(t *testing.T) {
  1067. n := newNodeConfChangeCommitterRecorder()
  1068. n.readyc <- raft.Ready{
  1069. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  1070. }
  1071. cl := newTestCluster(nil)
  1072. st := store.New()
  1073. cl.SetStore(st)
  1074. cl.AddMember(&membership.Member{ID: 1234})
  1075. s := &EtcdServer{
  1076. r: raftNode{
  1077. Node: n,
  1078. raftStorage: raft.NewMemoryStorage(),
  1079. storage: mockstorage.NewStorageRecorder(""),
  1080. transport: rafthttp.NewNopTransporter(),
  1081. ticker: &time.Ticker{},
  1082. },
  1083. store: st,
  1084. cluster: cl,
  1085. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1086. SyncTicker: &time.Ticker{},
  1087. }
  1088. s.start()
  1089. wm := membership.Member{ID: 1234, RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  1090. err := s.UpdateMember(context.TODO(), wm)
  1091. gaction := n.Action()
  1092. s.Stop()
  1093. if err != nil {
  1094. t.Fatalf("UpdateMember error: %v", err)
  1095. }
  1096. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeUpdateNode"}, {Name: "ApplyConfChange:ConfChangeUpdateNode"}}
  1097. if !reflect.DeepEqual(gaction, wactions) {
  1098. t.Errorf("action = %v, want %v", gaction, wactions)
  1099. }
  1100. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  1101. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  1102. }
  1103. }
  1104. // TODO: test server could stop itself when being removed
  1105. func TestPublish(t *testing.T) {
  1106. n := newNodeRecorder()
  1107. ch := make(chan interface{}, 1)
  1108. // simulate that request has gone through consensus
  1109. ch <- Response{}
  1110. w := wait.NewWithResponse(ch)
  1111. ctx, cancel := context.WithCancel(context.TODO())
  1112. srv := &EtcdServer{
  1113. readych: make(chan struct{}),
  1114. Cfg: &ServerConfig{TickMs: 1},
  1115. id: 1,
  1116. r: raftNode{Node: n, ticker: &time.Ticker{}},
  1117. attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  1118. cluster: &membership.RaftCluster{},
  1119. w: w,
  1120. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1121. SyncTicker: &time.Ticker{},
  1122. ctx: ctx,
  1123. cancel: cancel,
  1124. }
  1125. srv.publish(time.Hour)
  1126. action := n.Action()
  1127. if len(action) != 1 {
  1128. t.Fatalf("len(action) = %d, want 1", len(action))
  1129. }
  1130. if action[0].Name != "Propose" {
  1131. t.Fatalf("action = %s, want Propose", action[0].Name)
  1132. }
  1133. data := action[0].Params[0].([]byte)
  1134. var r pb.Request
  1135. if err := r.Unmarshal(data); err != nil {
  1136. t.Fatalf("unmarshal request error: %v", err)
  1137. }
  1138. if r.Method != "PUT" {
  1139. t.Errorf("method = %s, want PUT", r.Method)
  1140. }
  1141. wm := membership.Member{ID: 1, Attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1142. if wpath := membership.MemberAttributesStorePath(wm.ID); r.Path != wpath {
  1143. t.Errorf("path = %s, want %s", r.Path, wpath)
  1144. }
  1145. var gattr membership.Attributes
  1146. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1147. t.Fatalf("unmarshal val error: %v", err)
  1148. }
  1149. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1150. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1151. }
  1152. }
  1153. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1154. func TestPublishStopped(t *testing.T) {
  1155. ctx, cancel := context.WithCancel(context.TODO())
  1156. srv := &EtcdServer{
  1157. Cfg: &ServerConfig{TickMs: 1},
  1158. r: raftNode{
  1159. Node: newNodeNop(),
  1160. transport: rafthttp.NewNopTransporter(),
  1161. ticker: &time.Ticker{},
  1162. },
  1163. cluster: &membership.RaftCluster{},
  1164. w: mockwait.NewNop(),
  1165. done: make(chan struct{}),
  1166. stopping: make(chan struct{}),
  1167. stop: make(chan struct{}),
  1168. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1169. SyncTicker: &time.Ticker{},
  1170. ctx: ctx,
  1171. cancel: cancel,
  1172. }
  1173. close(srv.stopping)
  1174. srv.publish(time.Hour)
  1175. }
  1176. // TestPublishRetry tests that publish will keep retry until success.
  1177. func TestPublishRetry(t *testing.T) {
  1178. ctx, cancel := context.WithCancel(context.TODO())
  1179. n := newNodeRecorderStream()
  1180. srv := &EtcdServer{
  1181. Cfg: &ServerConfig{TickMs: 1},
  1182. r: raftNode{Node: n, ticker: &time.Ticker{}},
  1183. w: mockwait.NewNop(),
  1184. stopping: make(chan struct{}),
  1185. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1186. SyncTicker: &time.Ticker{},
  1187. ctx: ctx,
  1188. cancel: cancel,
  1189. }
  1190. // expect multiple proposals from retrying
  1191. ch := make(chan struct{})
  1192. go func() {
  1193. defer close(ch)
  1194. if action, err := n.Wait(2); err != nil {
  1195. t.Errorf("len(action) = %d, want >= 2 (%v)", len(action), err)
  1196. }
  1197. close(srv.stopping)
  1198. // drain remaining actions, if any, so publish can terminate
  1199. for {
  1200. select {
  1201. case <-ch:
  1202. return
  1203. default:
  1204. n.Action()
  1205. }
  1206. }
  1207. }()
  1208. srv.publish(10 * time.Nanosecond)
  1209. ch <- struct{}{}
  1210. <-ch
  1211. }
  1212. func TestUpdateVersion(t *testing.T) {
  1213. n := newNodeRecorder()
  1214. ch := make(chan interface{}, 1)
  1215. // simulate that request has gone through consensus
  1216. ch <- Response{}
  1217. w := wait.NewWithResponse(ch)
  1218. ctx, cancel := context.WithCancel(context.TODO())
  1219. srv := &EtcdServer{
  1220. id: 1,
  1221. Cfg: &ServerConfig{TickMs: 1},
  1222. r: raftNode{Node: n, ticker: &time.Ticker{}},
  1223. attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://node1.com"}},
  1224. cluster: &membership.RaftCluster{},
  1225. w: w,
  1226. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1227. SyncTicker: &time.Ticker{},
  1228. ctx: ctx,
  1229. cancel: cancel,
  1230. }
  1231. srv.updateClusterVersion("2.0.0")
  1232. action := n.Action()
  1233. if len(action) != 1 {
  1234. t.Fatalf("len(action) = %d, want 1", len(action))
  1235. }
  1236. if action[0].Name != "Propose" {
  1237. t.Fatalf("action = %s, want Propose", action[0].Name)
  1238. }
  1239. data := action[0].Params[0].([]byte)
  1240. var r pb.Request
  1241. if err := r.Unmarshal(data); err != nil {
  1242. t.Fatalf("unmarshal request error: %v", err)
  1243. }
  1244. if r.Method != "PUT" {
  1245. t.Errorf("method = %s, want PUT", r.Method)
  1246. }
  1247. if wpath := path.Join(StoreClusterPrefix, "version"); r.Path != wpath {
  1248. t.Errorf("path = %s, want %s", r.Path, wpath)
  1249. }
  1250. if r.Val != "2.0.0" {
  1251. t.Errorf("val = %s, want %s", r.Val, "2.0.0")
  1252. }
  1253. }
  1254. func TestStopNotify(t *testing.T) {
  1255. s := &EtcdServer{
  1256. stop: make(chan struct{}),
  1257. done: make(chan struct{}),
  1258. }
  1259. go func() {
  1260. <-s.stop
  1261. close(s.done)
  1262. }()
  1263. notifier := s.StopNotify()
  1264. select {
  1265. case <-notifier:
  1266. t.Fatalf("received unexpected stop notification")
  1267. default:
  1268. }
  1269. s.Stop()
  1270. select {
  1271. case <-notifier:
  1272. default:
  1273. t.Fatalf("cannot receive stop notification")
  1274. }
  1275. }
  1276. func TestGetOtherPeerURLs(t *testing.T) {
  1277. tests := []struct {
  1278. membs []*membership.Member
  1279. wurls []string
  1280. }{
  1281. {
  1282. []*membership.Member{
  1283. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1284. },
  1285. []string{},
  1286. },
  1287. {
  1288. []*membership.Member{
  1289. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1290. membership.NewMember("2", types.MustNewURLs([]string{"http://10.0.0.2:2"}), "a", nil),
  1291. membership.NewMember("3", types.MustNewURLs([]string{"http://10.0.0.3:3"}), "a", nil),
  1292. },
  1293. []string{"http://10.0.0.2:2", "http://10.0.0.3:3"},
  1294. },
  1295. {
  1296. []*membership.Member{
  1297. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1298. membership.NewMember("3", types.MustNewURLs([]string{"http://10.0.0.3:3"}), "a", nil),
  1299. membership.NewMember("2", types.MustNewURLs([]string{"http://10.0.0.2:2"}), "a", nil),
  1300. },
  1301. []string{"http://10.0.0.2:2", "http://10.0.0.3:3"},
  1302. },
  1303. }
  1304. for i, tt := range tests {
  1305. cl := membership.NewClusterFromMembers("", types.ID(0), tt.membs)
  1306. self := "1"
  1307. urls := getRemotePeerURLs(cl, self)
  1308. if !reflect.DeepEqual(urls, tt.wurls) {
  1309. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1310. }
  1311. }
  1312. }
  1313. type nodeRecorder struct{ testutil.Recorder }
  1314. func newNodeRecorder() *nodeRecorder { return &nodeRecorder{&testutil.RecorderBuffered{}} }
  1315. func newNodeRecorderStream() *nodeRecorder { return &nodeRecorder{testutil.NewRecorderStream()} }
  1316. func newNodeNop() raft.Node { return newNodeRecorder() }
  1317. func (n *nodeRecorder) Tick() { n.Record(testutil.Action{Name: "Tick"}) }
  1318. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1319. n.Record(testutil.Action{Name: "Campaign"})
  1320. return nil
  1321. }
  1322. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1323. n.Record(testutil.Action{Name: "Propose", Params: []interface{}{data}})
  1324. return nil
  1325. }
  1326. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1327. n.Record(testutil.Action{Name: "ProposeConfChange"})
  1328. return nil
  1329. }
  1330. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1331. n.Record(testutil.Action{Name: "Step"})
  1332. return nil
  1333. }
  1334. func (n *nodeRecorder) Status() raft.Status { return raft.Status{} }
  1335. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1336. func (n *nodeRecorder) TransferLeadership(ctx context.Context, lead, transferee uint64) {}
  1337. func (n *nodeRecorder) ReadIndex(ctx context.Context, rctx []byte) error { return nil }
  1338. func (n *nodeRecorder) Advance() {}
  1339. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1340. n.Record(testutil.Action{Name: "ApplyConfChange", Params: []interface{}{conf}})
  1341. return &raftpb.ConfState{}
  1342. }
  1343. func (n *nodeRecorder) Stop() {
  1344. n.Record(testutil.Action{Name: "Stop"})
  1345. }
  1346. func (n *nodeRecorder) ReportUnreachable(id uint64) {}
  1347. func (n *nodeRecorder) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  1348. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1349. n.Record(testutil.Action{Name: "Compact"})
  1350. }
  1351. type nodeProposalBlockerRecorder struct {
  1352. nodeRecorder
  1353. }
  1354. func newProposalBlockerRecorder() *nodeProposalBlockerRecorder {
  1355. return &nodeProposalBlockerRecorder{*newNodeRecorder()}
  1356. }
  1357. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1358. <-ctx.Done()
  1359. n.Record(testutil.Action{Name: "Propose blocked"})
  1360. return nil
  1361. }
  1362. // readyNode is a nodeRecorder with a user-writeable ready channel
  1363. type readyNode struct {
  1364. nodeRecorder
  1365. readyc chan raft.Ready
  1366. }
  1367. func newReadyNode() *readyNode {
  1368. return &readyNode{
  1369. nodeRecorder{testutil.NewRecorderStream()},
  1370. make(chan raft.Ready, 1)}
  1371. }
  1372. func newNopReadyNode() *readyNode {
  1373. return &readyNode{*newNodeRecorder(), make(chan raft.Ready, 1)}
  1374. }
  1375. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1376. type nodeConfChangeCommitterRecorder struct {
  1377. readyNode
  1378. index uint64
  1379. }
  1380. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1381. return &nodeConfChangeCommitterRecorder{*newNopReadyNode(), 0}
  1382. }
  1383. func newNodeConfChangeCommitterStream() *nodeConfChangeCommitterRecorder {
  1384. return &nodeConfChangeCommitterRecorder{*newReadyNode(), 0}
  1385. }
  1386. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1387. data, err := conf.Marshal()
  1388. if err != nil {
  1389. return err
  1390. }
  1391. n.index++
  1392. n.Record(testutil.Action{Name: "ProposeConfChange:" + conf.Type.String()})
  1393. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: raftpb.EntryConfChange, Data: data}}}
  1394. return nil
  1395. }
  1396. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1397. return n.readyc
  1398. }
  1399. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1400. n.Record(testutil.Action{Name: "ApplyConfChange:" + conf.Type.String()})
  1401. return &raftpb.ConfState{}
  1402. }
  1403. // nodeCommitter commits proposed data immediately.
  1404. type nodeCommitter struct {
  1405. readyNode
  1406. index uint64
  1407. }
  1408. func newNodeCommitter() raft.Node {
  1409. return &nodeCommitter{*newNopReadyNode(), 0}
  1410. }
  1411. func (n *nodeCommitter) Propose(ctx context.Context, data []byte) error {
  1412. n.index++
  1413. ents := []raftpb.Entry{{Index: n.index, Data: data}}
  1414. n.readyc <- raft.Ready{
  1415. Entries: ents,
  1416. CommittedEntries: ents,
  1417. }
  1418. return nil
  1419. }
  1420. func newTestCluster(membs []*membership.Member) *membership.RaftCluster {
  1421. c := membership.NewCluster("")
  1422. for _, m := range membs {
  1423. c.AddMember(m)
  1424. }
  1425. return c
  1426. }