server_test.go 39 KB

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