server_test.go 44 KB

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