server_test.go 41 KB

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