server_test.go 40 KB

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