server_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  1. // Copyright 2015 CoreOS, Inc.
  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. "strconv"
  23. "testing"
  24. "time"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/coreos/etcd/etcdserver/membership"
  27. "github.com/coreos/etcd/lease"
  28. "github.com/coreos/etcd/pkg/idutil"
  29. "github.com/coreos/etcd/pkg/mock/mockstorage"
  30. "github.com/coreos/etcd/pkg/mock/mockstore"
  31. "github.com/coreos/etcd/pkg/mock/mockwait"
  32. "github.com/coreos/etcd/pkg/pbutil"
  33. "github.com/coreos/etcd/pkg/testutil"
  34. "github.com/coreos/etcd/pkg/types"
  35. "github.com/coreos/etcd/pkg/wait"
  36. "github.com/coreos/etcd/raft"
  37. "github.com/coreos/etcd/raft/raftpb"
  38. "github.com/coreos/etcd/rafthttp"
  39. dstorage "github.com/coreos/etcd/storage"
  40. "github.com/coreos/etcd/storage/backend"
  41. "github.com/coreos/etcd/store"
  42. "golang.org/x/net/context"
  43. )
  44. // TestDoLocalAction tests requests which do not need to go through raft to be applied,
  45. // and are served through local data.
  46. func TestDoLocalAction(t *testing.T) {
  47. tests := []struct {
  48. req pb.Request
  49. wresp Response
  50. werr error
  51. wactions []testutil.Action
  52. }{
  53. {
  54. pb.Request{Method: "GET", ID: 1, Wait: true},
  55. Response{Watcher: store.NewNopWatcher()}, nil, []testutil.Action{{Name: "Watch"}},
  56. },
  57. {
  58. pb.Request{Method: "GET", ID: 1},
  59. Response{Event: &store.Event{}}, nil,
  60. []testutil.Action{
  61. {
  62. Name: "Get",
  63. Params: []interface{}{"", false, false},
  64. },
  65. },
  66. },
  67. {
  68. pb.Request{Method: "HEAD", ID: 1},
  69. Response{Event: &store.Event{}}, nil,
  70. []testutil.Action{
  71. {
  72. Name: "Get",
  73. Params: []interface{}{"", false, false},
  74. },
  75. },
  76. },
  77. {
  78. pb.Request{Method: "BADMETHOD", ID: 1},
  79. Response{}, ErrUnknownMethod, []testutil.Action{},
  80. },
  81. }
  82. for i, tt := range tests {
  83. st := mockstore.NewRecorder()
  84. srv := &EtcdServer{
  85. store: st,
  86. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  87. }
  88. resp, err := srv.Do(context.TODO(), tt.req)
  89. if err != tt.werr {
  90. t.Fatalf("#%d: err = %+v, want %+v", i, err, tt.werr)
  91. }
  92. if !reflect.DeepEqual(resp, tt.wresp) {
  93. t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp)
  94. }
  95. gaction := st.Action()
  96. if !reflect.DeepEqual(gaction, tt.wactions) {
  97. t.Errorf("#%d: action = %+v, want %+v", i, gaction, tt.wactions)
  98. }
  99. }
  100. }
  101. // TestDoBadLocalAction tests server requests which do not need to go through consensus,
  102. // and return errors when they fetch from local data.
  103. func TestDoBadLocalAction(t *testing.T) {
  104. storeErr := fmt.Errorf("bah")
  105. tests := []struct {
  106. req pb.Request
  107. wactions []testutil.Action
  108. }{
  109. {
  110. pb.Request{Method: "GET", ID: 1, Wait: true},
  111. []testutil.Action{{Name: "Watch"}},
  112. },
  113. {
  114. pb.Request{Method: "GET", ID: 1},
  115. []testutil.Action{
  116. {
  117. Name: "Get",
  118. Params: []interface{}{"", false, false},
  119. },
  120. },
  121. },
  122. {
  123. pb.Request{Method: "HEAD", ID: 1},
  124. []testutil.Action{
  125. {
  126. Name: "Get",
  127. Params: []interface{}{"", false, false},
  128. },
  129. },
  130. },
  131. }
  132. for i, tt := range tests {
  133. st := mockstore.NewErrRecorder(storeErr)
  134. srv := &EtcdServer{
  135. store: st,
  136. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  137. }
  138. resp, err := srv.Do(context.Background(), tt.req)
  139. if err != storeErr {
  140. t.Fatalf("#%d: err = %+v, want %+v", i, err, storeErr)
  141. }
  142. if !reflect.DeepEqual(resp, Response{}) {
  143. t.Errorf("#%d: resp = %+v, want %+v", i, resp, Response{})
  144. }
  145. gaction := st.Action()
  146. if !reflect.DeepEqual(gaction, tt.wactions) {
  147. t.Errorf("#%d: action = %+v, want %+v", i, gaction, tt.wactions)
  148. }
  149. }
  150. }
  151. // TestApplyRepeat tests that server handles repeat raft messages gracefully
  152. func TestApplyRepeat(t *testing.T) {
  153. n := newNodeConfChangeCommitterStream()
  154. n.readyc <- raft.Ready{
  155. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  156. }
  157. cl := newTestCluster(nil)
  158. st := store.New()
  159. cl.SetStore(store.New())
  160. cl.AddMember(&membership.Member{ID: 1234})
  161. s := &EtcdServer{
  162. r: raftNode{
  163. Node: n,
  164. raftStorage: raft.NewMemoryStorage(),
  165. storage: mockstorage.NewStorageRecorder(""),
  166. transport: rafthttp.NewNopTransporter(),
  167. },
  168. cfg: &ServerConfig{},
  169. store: st,
  170. cluster: cl,
  171. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  172. }
  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. resp := srv.applyRequest(tt.req)
  432. if !reflect.DeepEqual(resp, tt.wresp) {
  433. t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp)
  434. }
  435. gaction := st.Action()
  436. if !reflect.DeepEqual(gaction, tt.wactions) {
  437. t.Errorf("#%d: action = %#v, want %#v", i, gaction, tt.wactions)
  438. }
  439. }
  440. }
  441. func TestApplyRequestOnAdminMemberAttributes(t *testing.T) {
  442. cl := newTestCluster([]*membership.Member{{ID: 1}})
  443. srv := &EtcdServer{
  444. store: mockstore.NewRecorder(),
  445. cluster: cl,
  446. }
  447. req := pb.Request{
  448. Method: "PUT",
  449. ID: 1,
  450. Path: path.Join(membership.StoreMembersPrefix, strconv.FormatUint(1, 16), membership.AttributesSuffix),
  451. Val: `{"Name":"abc","ClientURLs":["http://127.0.0.1:2379"]}`,
  452. }
  453. srv.applyRequest(req)
  454. w := membership.Attributes{Name: "abc", ClientURLs: []string{"http://127.0.0.1:2379"}}
  455. if g := cl.Member(1).Attributes; !reflect.DeepEqual(g, w) {
  456. t.Errorf("attributes = %v, want %v", g, w)
  457. }
  458. }
  459. func TestApplyConfChangeError(t *testing.T) {
  460. cl := membership.NewCluster("")
  461. cl.SetStore(store.New())
  462. for i := 1; i <= 4; i++ {
  463. cl.AddMember(&membership.Member{ID: types.ID(i)})
  464. }
  465. cl.RemoveMember(4)
  466. tests := []struct {
  467. cc raftpb.ConfChange
  468. werr error
  469. }{
  470. {
  471. raftpb.ConfChange{
  472. Type: raftpb.ConfChangeAddNode,
  473. NodeID: 4,
  474. },
  475. membership.ErrIDRemoved,
  476. },
  477. {
  478. raftpb.ConfChange{
  479. Type: raftpb.ConfChangeUpdateNode,
  480. NodeID: 4,
  481. },
  482. membership.ErrIDRemoved,
  483. },
  484. {
  485. raftpb.ConfChange{
  486. Type: raftpb.ConfChangeAddNode,
  487. NodeID: 1,
  488. },
  489. membership.ErrIDExists,
  490. },
  491. {
  492. raftpb.ConfChange{
  493. Type: raftpb.ConfChangeRemoveNode,
  494. NodeID: 5,
  495. },
  496. membership.ErrIDNotFound,
  497. },
  498. }
  499. for i, tt := range tests {
  500. n := newNodeRecorder()
  501. srv := &EtcdServer{
  502. r: raftNode{Node: n},
  503. cluster: cl,
  504. cfg: &ServerConfig{},
  505. }
  506. _, err := srv.applyConfChange(tt.cc, nil)
  507. if err != tt.werr {
  508. t.Errorf("#%d: applyConfChange error = %v, want %v", i, err, tt.werr)
  509. }
  510. cc := raftpb.ConfChange{Type: tt.cc.Type, NodeID: raft.None}
  511. w := []testutil.Action{
  512. {
  513. Name: "ApplyConfChange",
  514. Params: []interface{}{cc},
  515. },
  516. }
  517. if g, _ := n.Wait(1); !reflect.DeepEqual(g, w) {
  518. t.Errorf("#%d: action = %+v, want %+v", i, g, w)
  519. }
  520. }
  521. }
  522. func TestApplyConfChangeShouldStop(t *testing.T) {
  523. cl := membership.NewCluster("")
  524. cl.SetStore(store.New())
  525. for i := 1; i <= 3; i++ {
  526. cl.AddMember(&membership.Member{ID: types.ID(i)})
  527. }
  528. srv := &EtcdServer{
  529. id: 1,
  530. r: raftNode{
  531. Node: newNodeNop(),
  532. transport: rafthttp.NewNopTransporter(),
  533. },
  534. cluster: cl,
  535. }
  536. cc := raftpb.ConfChange{
  537. Type: raftpb.ConfChangeRemoveNode,
  538. NodeID: 2,
  539. }
  540. // remove non-local member
  541. shouldStop, err := srv.applyConfChange(cc, &raftpb.ConfState{})
  542. if err != nil {
  543. t.Fatalf("unexpected error %v", err)
  544. }
  545. if shouldStop {
  546. t.Errorf("shouldStop = %t, want %t", shouldStop, false)
  547. }
  548. // remove local member
  549. cc.NodeID = 1
  550. shouldStop, err = srv.applyConfChange(cc, &raftpb.ConfState{})
  551. if err != nil {
  552. t.Fatalf("unexpected error %v", err)
  553. }
  554. if !shouldStop {
  555. t.Errorf("shouldStop = %t, want %t", shouldStop, true)
  556. }
  557. }
  558. // TestApplyMultiConfChangeShouldStop ensures that apply will return shouldStop
  559. // if the local member is removed along with other conf updates.
  560. func TestApplyMultiConfChangeShouldStop(t *testing.T) {
  561. cl := membership.NewCluster("")
  562. cl.SetStore(store.New())
  563. for i := 1; i <= 5; i++ {
  564. cl.AddMember(&membership.Member{ID: types.ID(i)})
  565. }
  566. srv := &EtcdServer{
  567. id: 2,
  568. r: raftNode{
  569. Node: newNodeNop(),
  570. transport: rafthttp.NewNopTransporter(),
  571. },
  572. cluster: cl,
  573. w: wait.New(),
  574. }
  575. ents := []raftpb.Entry{}
  576. for i := 1; i <= 4; i++ {
  577. ent := raftpb.Entry{
  578. Term: 1,
  579. Index: uint64(i),
  580. Type: raftpb.EntryConfChange,
  581. Data: pbutil.MustMarshal(
  582. &raftpb.ConfChange{
  583. Type: raftpb.ConfChangeRemoveNode,
  584. NodeID: uint64(i)}),
  585. }
  586. ents = append(ents, ent)
  587. }
  588. _, shouldStop := srv.apply(ents, &raftpb.ConfState{})
  589. if !shouldStop {
  590. t.Errorf("shouldStop = %t, want %t", shouldStop, true)
  591. }
  592. }
  593. func TestDoProposal(t *testing.T) {
  594. tests := []pb.Request{
  595. {Method: "POST", ID: 1},
  596. {Method: "PUT", ID: 1},
  597. {Method: "DELETE", ID: 1},
  598. {Method: "GET", ID: 1, Quorum: true},
  599. }
  600. for i, tt := range tests {
  601. st := mockstore.NewRecorder()
  602. srv := &EtcdServer{
  603. cfg: &ServerConfig{TickMs: 1},
  604. r: raftNode{
  605. Node: newNodeCommitter(),
  606. storage: mockstorage.NewStorageRecorder(""),
  607. raftStorage: raft.NewMemoryStorage(),
  608. transport: rafthttp.NewNopTransporter(),
  609. },
  610. store: st,
  611. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  612. }
  613. srv.start()
  614. resp, err := srv.Do(context.Background(), tt)
  615. srv.Stop()
  616. action := st.Action()
  617. if len(action) != 1 {
  618. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  619. }
  620. if err != nil {
  621. t.Fatalf("#%d: err = %v, want nil", i, err)
  622. }
  623. wresp := Response{Event: &store.Event{}}
  624. if !reflect.DeepEqual(resp, wresp) {
  625. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  626. }
  627. }
  628. }
  629. func TestDoProposalCancelled(t *testing.T) {
  630. wait := mockwait.NewRecorder()
  631. srv := &EtcdServer{
  632. cfg: &ServerConfig{TickMs: 1},
  633. r: raftNode{Node: newNodeNop()},
  634. w: wait,
  635. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  636. }
  637. ctx, cancel := context.WithCancel(context.Background())
  638. cancel()
  639. _, err := srv.Do(ctx, pb.Request{Method: "PUT"})
  640. if err != ErrCanceled {
  641. t.Fatalf("err = %v, want %v", err, ErrCanceled)
  642. }
  643. w := []testutil.Action{{Name: "Register"}, {Name: "Trigger"}}
  644. if !reflect.DeepEqual(wait.Action(), w) {
  645. t.Errorf("wait.action = %+v, want %+v", wait.Action(), w)
  646. }
  647. }
  648. func TestDoProposalTimeout(t *testing.T) {
  649. srv := &EtcdServer{
  650. cfg: &ServerConfig{TickMs: 1},
  651. r: raftNode{Node: newNodeNop()},
  652. w: mockwait.NewNop(),
  653. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  654. }
  655. ctx, _ := context.WithTimeout(context.Background(), 0)
  656. _, err := srv.Do(ctx, pb.Request{Method: "PUT"})
  657. if err != ErrTimeout {
  658. t.Fatalf("err = %v, want %v", err, ErrTimeout)
  659. }
  660. }
  661. func TestDoProposalStopped(t *testing.T) {
  662. srv := &EtcdServer{
  663. cfg: &ServerConfig{TickMs: 1},
  664. r: raftNode{Node: newNodeNop()},
  665. w: mockwait.NewNop(),
  666. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  667. }
  668. srv.done = make(chan struct{})
  669. close(srv.done)
  670. _, err := srv.Do(context.Background(), pb.Request{Method: "PUT", ID: 1})
  671. if err != ErrStopped {
  672. t.Errorf("err = %v, want %v", err, ErrStopped)
  673. }
  674. }
  675. // TestSync tests sync 1. is nonblocking 2. proposes SYNC request.
  676. func TestSync(t *testing.T) {
  677. n := newNodeRecorder()
  678. srv := &EtcdServer{
  679. r: raftNode{Node: n},
  680. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  681. }
  682. // check that sync is non-blocking
  683. done := make(chan struct{})
  684. go func() {
  685. srv.sync(10 * time.Second)
  686. done <- struct{}{}
  687. }()
  688. select {
  689. case <-done:
  690. case <-time.After(time.Second):
  691. t.Fatal("sync should be non-blocking but did not return after 1s!")
  692. }
  693. action, _ := n.Wait(1)
  694. if len(action) != 1 {
  695. t.Fatalf("len(action) = %d, want 1", len(action))
  696. }
  697. if action[0].Name != "Propose" {
  698. t.Fatalf("action = %s, want Propose", action[0].Name)
  699. }
  700. data := action[0].Params[0].([]byte)
  701. var r pb.Request
  702. if err := r.Unmarshal(data); err != nil {
  703. t.Fatalf("unmarshal request error: %v", err)
  704. }
  705. if r.Method != "SYNC" {
  706. t.Errorf("method = %s, want SYNC", r.Method)
  707. }
  708. }
  709. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  710. // after timeout
  711. func TestSyncTimeout(t *testing.T) {
  712. n := newProposalBlockerRecorder()
  713. srv := &EtcdServer{
  714. r: raftNode{Node: n},
  715. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  716. }
  717. // check that sync is non-blocking
  718. done := make(chan struct{})
  719. go func() {
  720. srv.sync(0)
  721. done <- struct{}{}
  722. }()
  723. select {
  724. case <-done:
  725. case <-time.After(time.Second):
  726. t.Fatal("sync should be non-blocking but did not return after 1s!")
  727. }
  728. w := []testutil.Action{{Name: "Propose blocked"}}
  729. if g, _ := n.Wait(1); !reflect.DeepEqual(g, w) {
  730. t.Errorf("action = %v, want %v", g, w)
  731. }
  732. }
  733. // TODO: TestNoSyncWhenNoLeader
  734. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  735. func TestSyncTrigger(t *testing.T) {
  736. n := newReadyNode()
  737. st := make(chan time.Time, 1)
  738. srv := &EtcdServer{
  739. cfg: &ServerConfig{TickMs: 1},
  740. r: raftNode{
  741. Node: n,
  742. raftStorage: raft.NewMemoryStorage(),
  743. transport: rafthttp.NewNopTransporter(),
  744. storage: mockstorage.NewStorageRecorder(""),
  745. },
  746. store: mockstore.NewNop(),
  747. SyncTicker: st,
  748. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  749. }
  750. // trigger the server to become a leader and accept sync requests
  751. go func() {
  752. srv.start()
  753. n.readyc <- raft.Ready{
  754. SoftState: &raft.SoftState{
  755. RaftState: raft.StateLeader,
  756. },
  757. }
  758. // trigger a sync request
  759. st <- time.Time{}
  760. }()
  761. action, _ := n.Wait(1)
  762. go srv.Stop()
  763. if len(action) != 1 {
  764. t.Fatalf("len(action) = %d, want 1", len(action))
  765. }
  766. if action[0].Name != "Propose" {
  767. t.Fatalf("action = %s, want Propose", action[0].Name)
  768. }
  769. data := action[0].Params[0].([]byte)
  770. var req pb.Request
  771. if err := req.Unmarshal(data); err != nil {
  772. t.Fatalf("error unmarshalling data: %v", err)
  773. }
  774. if req.Method != "SYNC" {
  775. t.Fatalf("unexpected proposed request: %#v", req.Method)
  776. }
  777. // wait on stop message
  778. <-n.Chan()
  779. }
  780. // snapshot should snapshot the store and cut the persistent
  781. func TestSnapshot(t *testing.T) {
  782. be, tmpPath := backend.NewDefaultTmpBackend()
  783. defer func() {
  784. os.RemoveAll(tmpPath)
  785. }()
  786. s := raft.NewMemoryStorage()
  787. s.Append([]raftpb.Entry{{Index: 1}})
  788. st := mockstore.NewRecorder()
  789. p := mockstorage.NewStorageRecorder("")
  790. srv := &EtcdServer{
  791. cfg: &ServerConfig{},
  792. r: raftNode{
  793. Node: newNodeNop(),
  794. raftStorage: s,
  795. storage: p,
  796. },
  797. store: st,
  798. }
  799. srv.kv = dstorage.New(be, &lease.FakeLessor{}, &srv.consistIndex)
  800. srv.be = be
  801. srv.snapshot(1, raftpb.ConfState{Nodes: []uint64{1}})
  802. gaction, _ := st.Wait(2)
  803. if len(gaction) != 2 {
  804. t.Fatalf("len(action) = %d, want 1", len(gaction))
  805. }
  806. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "Clone"}) {
  807. t.Errorf("action = %s, want Clone", gaction[0])
  808. }
  809. if !reflect.DeepEqual(gaction[1], testutil.Action{Name: "SaveNoCopy"}) {
  810. t.Errorf("action = %s, want SaveNoCopy", gaction[1])
  811. }
  812. gaction = p.Action()
  813. if len(gaction) != 1 {
  814. t.Fatalf("len(action) = %d, want 1", len(gaction))
  815. }
  816. if !reflect.DeepEqual(gaction[0], testutil.Action{Name: "SaveSnap"}) {
  817. t.Errorf("action = %s, want SaveSnap", gaction[0])
  818. }
  819. }
  820. // Applied > SnapCount should trigger a SaveSnap event
  821. func TestTriggerSnap(t *testing.T) {
  822. be, tmpPath := backend.NewDefaultTmpBackend()
  823. defer func() {
  824. os.RemoveAll(tmpPath)
  825. }()
  826. snapc := 10
  827. st := mockstore.NewRecorder()
  828. p := mockstorage.NewStorageRecorderStream("")
  829. srv := &EtcdServer{
  830. cfg: &ServerConfig{TickMs: 1},
  831. snapCount: uint64(snapc),
  832. r: raftNode{
  833. Node: newNodeCommitter(),
  834. raftStorage: raft.NewMemoryStorage(),
  835. storage: p,
  836. transport: rafthttp.NewNopTransporter(),
  837. },
  838. store: st,
  839. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  840. }
  841. srv.kv = dstorage.New(be, &lease.FakeLessor{}, &srv.consistIndex)
  842. srv.be = be
  843. srv.start()
  844. donec := make(chan struct{})
  845. go func() {
  846. wcnt := 2 + snapc
  847. gaction, _ := p.Wait(wcnt)
  848. // each operation is recorded as a Save
  849. // (SnapCount+1) * Puts + SaveSnap = (SnapCount+1) * Save + SaveSnap
  850. if len(gaction) != wcnt {
  851. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  852. }
  853. if !reflect.DeepEqual(gaction[wcnt-1], testutil.Action{Name: "SaveSnap"}) {
  854. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  855. }
  856. close(donec)
  857. }()
  858. for i := 0; i < snapc+1; i++ {
  859. srv.Do(context.Background(), pb.Request{Method: "PUT"})
  860. }
  861. srv.Stop()
  862. <-donec
  863. }
  864. // TestConcurrentApplyAndSnapshotV3 will send out snapshots concurrently with
  865. // proposals.
  866. func TestConcurrentApplyAndSnapshotV3(t *testing.T) {
  867. const (
  868. // snapshots that may queue up at once without dropping
  869. maxInFlightMsgSnap = 16
  870. )
  871. n := newNopReadyNode()
  872. st := store.New()
  873. cl := membership.NewCluster("abc")
  874. cl.SetStore(st)
  875. testdir, err := ioutil.TempDir(os.TempDir(), "testsnapdir")
  876. if err != nil {
  877. t.Fatalf("Couldn't open tempdir (%v)", err)
  878. }
  879. defer os.RemoveAll(testdir)
  880. if err := os.MkdirAll(testdir+"/member/snap", 0755); err != nil {
  881. t.Fatalf("Couldn't make snap dir (%v)", err)
  882. }
  883. rs := raft.NewMemoryStorage()
  884. tr, snapDoneC := rafthttp.NewSnapTransporter(testdir)
  885. s := &EtcdServer{
  886. cfg: &ServerConfig{
  887. DataDir: testdir,
  888. },
  889. r: raftNode{
  890. Node: n,
  891. transport: tr,
  892. storage: mockstorage.NewStorageRecorder(testdir),
  893. raftStorage: rs,
  894. },
  895. store: st,
  896. cluster: cl,
  897. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  898. }
  899. be, tmpPath := backend.NewDefaultTmpBackend()
  900. defer func() {
  901. os.RemoveAll(tmpPath)
  902. }()
  903. s.kv = dstorage.New(be, &lease.FakeLessor{}, &s.consistIndex)
  904. s.be = be
  905. s.start()
  906. defer s.Stop()
  907. // submit applied entries and snap entries
  908. idx := uint64(0)
  909. outdated := 0
  910. accepted := 0
  911. for k := 1; k <= 101; k++ {
  912. idx++
  913. ch := s.w.Register(uint64(idx))
  914. req := &pb.Request{Method: "QGET", ID: uint64(idx)}
  915. ent := raftpb.Entry{Index: uint64(idx), Data: pbutil.MustMarshal(req)}
  916. ready := raft.Ready{Entries: []raftpb.Entry{ent}}
  917. n.readyc <- ready
  918. ready = raft.Ready{CommittedEntries: []raftpb.Entry{ent}}
  919. n.readyc <- ready
  920. // "idx" applied
  921. <-ch
  922. // one snapshot for every two messages
  923. if k%2 != 0 {
  924. continue
  925. }
  926. n.readyc <- raft.Ready{Messages: []raftpb.Message{{Type: raftpb.MsgSnap}}}
  927. // get the snapshot sent by the transport
  928. snapMsg := <-snapDoneC
  929. // If the snapshot trails applied records, recovery will panic
  930. // since there's no allocated snapshot at the place of the
  931. // snapshot record. This only happens when the applier and the
  932. // snapshot sender get out of sync.
  933. if snapMsg.Snapshot.Metadata.Index == idx {
  934. idx++
  935. snapMsg.Snapshot.Metadata.Index = idx
  936. ready = raft.Ready{Snapshot: snapMsg.Snapshot}
  937. n.readyc <- ready
  938. accepted++
  939. } else {
  940. outdated++
  941. }
  942. // don't wait for the snapshot to complete, move to next message
  943. }
  944. if accepted != 50 {
  945. t.Errorf("accepted=%v, want 50", accepted)
  946. }
  947. if outdated != 0 {
  948. t.Errorf("outdated=%v, want 0", outdated)
  949. }
  950. }
  951. // TestAddMember tests AddMember can propose and perform node addition.
  952. func TestAddMember(t *testing.T) {
  953. n := newNodeConfChangeCommitterRecorder()
  954. n.readyc <- raft.Ready{
  955. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  956. }
  957. cl := newTestCluster(nil)
  958. st := store.New()
  959. cl.SetStore(st)
  960. s := &EtcdServer{
  961. r: raftNode{
  962. Node: n,
  963. raftStorage: raft.NewMemoryStorage(),
  964. storage: mockstorage.NewStorageRecorder(""),
  965. transport: rafthttp.NewNopTransporter(),
  966. },
  967. cfg: &ServerConfig{},
  968. store: st,
  969. cluster: cl,
  970. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  971. }
  972. s.start()
  973. m := membership.Member{ID: 1234, RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"foo"}}}
  974. err := s.AddMember(context.TODO(), m)
  975. gaction := n.Action()
  976. s.Stop()
  977. if err != nil {
  978. t.Fatalf("AddMember error: %v", err)
  979. }
  980. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeAddNode"}, {Name: "ApplyConfChange:ConfChangeAddNode"}}
  981. if !reflect.DeepEqual(gaction, wactions) {
  982. t.Errorf("action = %v, want %v", gaction, wactions)
  983. }
  984. if cl.Member(1234) == nil {
  985. t.Errorf("member with id 1234 is not added")
  986. }
  987. }
  988. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  989. func TestRemoveMember(t *testing.T) {
  990. n := newNodeConfChangeCommitterRecorder()
  991. n.readyc <- raft.Ready{
  992. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  993. }
  994. cl := newTestCluster(nil)
  995. st := store.New()
  996. cl.SetStore(store.New())
  997. cl.AddMember(&membership.Member{ID: 1234})
  998. s := &EtcdServer{
  999. r: raftNode{
  1000. Node: n,
  1001. raftStorage: raft.NewMemoryStorage(),
  1002. storage: mockstorage.NewStorageRecorder(""),
  1003. transport: rafthttp.NewNopTransporter(),
  1004. },
  1005. cfg: &ServerConfig{},
  1006. store: st,
  1007. cluster: cl,
  1008. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1009. }
  1010. s.start()
  1011. err := s.RemoveMember(context.TODO(), 1234)
  1012. gaction := n.Action()
  1013. s.Stop()
  1014. if err != nil {
  1015. t.Fatalf("RemoveMember error: %v", err)
  1016. }
  1017. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeRemoveNode"}, {Name: "ApplyConfChange:ConfChangeRemoveNode"}}
  1018. if !reflect.DeepEqual(gaction, wactions) {
  1019. t.Errorf("action = %v, want %v", gaction, wactions)
  1020. }
  1021. if cl.Member(1234) != nil {
  1022. t.Errorf("member with id 1234 is not removed")
  1023. }
  1024. }
  1025. // TestUpdateMember tests RemoveMember can propose and perform node update.
  1026. func TestUpdateMember(t *testing.T) {
  1027. n := newNodeConfChangeCommitterRecorder()
  1028. n.readyc <- raft.Ready{
  1029. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  1030. }
  1031. cl := newTestCluster(nil)
  1032. st := store.New()
  1033. cl.SetStore(st)
  1034. cl.AddMember(&membership.Member{ID: 1234})
  1035. s := &EtcdServer{
  1036. r: raftNode{
  1037. Node: n,
  1038. raftStorage: raft.NewMemoryStorage(),
  1039. storage: mockstorage.NewStorageRecorder(""),
  1040. transport: rafthttp.NewNopTransporter(),
  1041. },
  1042. store: st,
  1043. cluster: cl,
  1044. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1045. }
  1046. s.start()
  1047. wm := membership.Member{ID: 1234, RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  1048. err := s.UpdateMember(context.TODO(), wm)
  1049. gaction := n.Action()
  1050. s.Stop()
  1051. if err != nil {
  1052. t.Fatalf("UpdateMember error: %v", err)
  1053. }
  1054. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeUpdateNode"}, {Name: "ApplyConfChange:ConfChangeUpdateNode"}}
  1055. if !reflect.DeepEqual(gaction, wactions) {
  1056. t.Errorf("action = %v, want %v", gaction, wactions)
  1057. }
  1058. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  1059. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  1060. }
  1061. }
  1062. // TODO: test server could stop itself when being removed
  1063. func TestPublish(t *testing.T) {
  1064. n := newNodeRecorder()
  1065. ch := make(chan interface{}, 1)
  1066. // simulate that request has gone through consensus
  1067. ch <- Response{}
  1068. w := wait.NewWithResponse(ch)
  1069. srv := &EtcdServer{
  1070. cfg: &ServerConfig{TickMs: 1},
  1071. id: 1,
  1072. r: raftNode{Node: n},
  1073. attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  1074. cluster: &membership.RaftCluster{},
  1075. w: w,
  1076. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1077. }
  1078. srv.publish(time.Hour)
  1079. action := n.Action()
  1080. if len(action) != 1 {
  1081. t.Fatalf("len(action) = %d, want 1", len(action))
  1082. }
  1083. if action[0].Name != "Propose" {
  1084. t.Fatalf("action = %s, want Propose", action[0].Name)
  1085. }
  1086. data := action[0].Params[0].([]byte)
  1087. var r pb.Request
  1088. if err := r.Unmarshal(data); err != nil {
  1089. t.Fatalf("unmarshal request error: %v", err)
  1090. }
  1091. if r.Method != "PUT" {
  1092. t.Errorf("method = %s, want PUT", r.Method)
  1093. }
  1094. wm := membership.Member{ID: 1, Attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1095. if wpath := membership.MemberAttributesStorePath(wm.ID); r.Path != wpath {
  1096. t.Errorf("path = %s, want %s", r.Path, wpath)
  1097. }
  1098. var gattr membership.Attributes
  1099. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1100. t.Fatalf("unmarshal val error: %v", err)
  1101. }
  1102. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1103. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1104. }
  1105. }
  1106. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1107. func TestPublishStopped(t *testing.T) {
  1108. srv := &EtcdServer{
  1109. cfg: &ServerConfig{TickMs: 1},
  1110. r: raftNode{
  1111. Node: newNodeNop(),
  1112. transport: rafthttp.NewNopTransporter(),
  1113. },
  1114. cluster: &membership.RaftCluster{},
  1115. w: mockwait.NewNop(),
  1116. done: make(chan struct{}),
  1117. stop: make(chan struct{}),
  1118. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1119. }
  1120. close(srv.done)
  1121. srv.publish(time.Hour)
  1122. }
  1123. // TestPublishRetry tests that publish will keep retry until success.
  1124. func TestPublishRetry(t *testing.T) {
  1125. n := newNodeRecorder()
  1126. srv := &EtcdServer{
  1127. cfg: &ServerConfig{TickMs: 1},
  1128. r: raftNode{Node: n},
  1129. w: mockwait.NewNop(),
  1130. done: make(chan struct{}),
  1131. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1132. }
  1133. // TODO: use fakeClockwork
  1134. time.AfterFunc(10*time.Millisecond, func() { close(srv.done) })
  1135. srv.publish(10 * time.Nanosecond)
  1136. action := n.Action()
  1137. // multiple Proposes
  1138. if cnt := len(action); cnt < 2 {
  1139. t.Errorf("len(action) = %d, want >= 2", cnt)
  1140. }
  1141. }
  1142. func TestUpdateVersion(t *testing.T) {
  1143. n := newNodeRecorder()
  1144. ch := make(chan interface{}, 1)
  1145. // simulate that request has gone through consensus
  1146. ch <- Response{}
  1147. w := wait.NewWithResponse(ch)
  1148. srv := &EtcdServer{
  1149. id: 1,
  1150. cfg: &ServerConfig{TickMs: 1},
  1151. r: raftNode{Node: n},
  1152. attributes: membership.Attributes{Name: "node1", ClientURLs: []string{"http://node1.com"}},
  1153. cluster: &membership.RaftCluster{},
  1154. w: w,
  1155. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1156. }
  1157. srv.updateClusterVersion("2.0.0")
  1158. action := n.Action()
  1159. if len(action) != 1 {
  1160. t.Fatalf("len(action) = %d, want 1", len(action))
  1161. }
  1162. if action[0].Name != "Propose" {
  1163. t.Fatalf("action = %s, want Propose", action[0].Name)
  1164. }
  1165. data := action[0].Params[0].([]byte)
  1166. var r pb.Request
  1167. if err := r.Unmarshal(data); err != nil {
  1168. t.Fatalf("unmarshal request error: %v", err)
  1169. }
  1170. if r.Method != "PUT" {
  1171. t.Errorf("method = %s, want PUT", r.Method)
  1172. }
  1173. if wpath := path.Join(StoreClusterPrefix, "version"); r.Path != wpath {
  1174. t.Errorf("path = %s, want %s", r.Path, wpath)
  1175. }
  1176. if r.Val != "2.0.0" {
  1177. t.Errorf("val = %s, want %s", r.Val, "2.0.0")
  1178. }
  1179. }
  1180. func TestStopNotify(t *testing.T) {
  1181. s := &EtcdServer{
  1182. stop: make(chan struct{}),
  1183. done: make(chan struct{}),
  1184. }
  1185. go func() {
  1186. <-s.stop
  1187. close(s.done)
  1188. }()
  1189. notifier := s.StopNotify()
  1190. select {
  1191. case <-notifier:
  1192. t.Fatalf("received unexpected stop notification")
  1193. default:
  1194. }
  1195. s.Stop()
  1196. select {
  1197. case <-notifier:
  1198. default:
  1199. t.Fatalf("cannot receive stop notification")
  1200. }
  1201. }
  1202. func TestGetOtherPeerURLs(t *testing.T) {
  1203. tests := []struct {
  1204. membs []*membership.Member
  1205. wurls []string
  1206. }{
  1207. {
  1208. []*membership.Member{
  1209. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1210. },
  1211. []string{},
  1212. },
  1213. {
  1214. []*membership.Member{
  1215. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1216. membership.NewMember("2", types.MustNewURLs([]string{"http://10.0.0.2:2"}), "a", nil),
  1217. membership.NewMember("3", types.MustNewURLs([]string{"http://10.0.0.3:3"}), "a", nil),
  1218. },
  1219. []string{"http://10.0.0.2:2", "http://10.0.0.3:3"},
  1220. },
  1221. {
  1222. []*membership.Member{
  1223. membership.NewMember("1", types.MustNewURLs([]string{"http://10.0.0.1:1"}), "a", nil),
  1224. membership.NewMember("3", types.MustNewURLs([]string{"http://10.0.0.3:3"}), "a", nil),
  1225. membership.NewMember("2", types.MustNewURLs([]string{"http://10.0.0.2:2"}), "a", nil),
  1226. },
  1227. []string{"http://10.0.0.2:2", "http://10.0.0.3:3"},
  1228. },
  1229. }
  1230. for i, tt := range tests {
  1231. cl := membership.NewClusterFromMembers("", types.ID(0), tt.membs)
  1232. self := "1"
  1233. urls := getRemotePeerURLs(cl, self)
  1234. if !reflect.DeepEqual(urls, tt.wurls) {
  1235. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1236. }
  1237. }
  1238. }
  1239. type nodeRecorder struct{ testutil.Recorder }
  1240. func newNodeRecorder() *nodeRecorder { return &nodeRecorder{&testutil.RecorderBuffered{}} }
  1241. func newNodeNop() raft.Node { return newNodeRecorder() }
  1242. func (n *nodeRecorder) Tick() { n.Record(testutil.Action{Name: "Tick"}) }
  1243. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1244. n.Record(testutil.Action{Name: "Campaign"})
  1245. return nil
  1246. }
  1247. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1248. n.Record(testutil.Action{Name: "Propose", Params: []interface{}{data}})
  1249. return nil
  1250. }
  1251. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1252. n.Record(testutil.Action{Name: "ProposeConfChange"})
  1253. return nil
  1254. }
  1255. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1256. n.Record(testutil.Action{Name: "Step"})
  1257. return nil
  1258. }
  1259. func (n *nodeRecorder) Status() raft.Status { return raft.Status{} }
  1260. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1261. func (n *nodeRecorder) Advance() {}
  1262. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1263. n.Record(testutil.Action{Name: "ApplyConfChange", Params: []interface{}{conf}})
  1264. return &raftpb.ConfState{}
  1265. }
  1266. func (n *nodeRecorder) Stop() {
  1267. n.Record(testutil.Action{Name: "Stop"})
  1268. }
  1269. func (n *nodeRecorder) ReportUnreachable(id uint64) {}
  1270. func (n *nodeRecorder) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  1271. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1272. n.Record(testutil.Action{Name: "Compact"})
  1273. }
  1274. type nodeProposalBlockerRecorder struct {
  1275. nodeRecorder
  1276. }
  1277. func newProposalBlockerRecorder() *nodeProposalBlockerRecorder {
  1278. return &nodeProposalBlockerRecorder{*newNodeRecorder()}
  1279. }
  1280. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1281. <-ctx.Done()
  1282. n.Record(testutil.Action{Name: "Propose blocked"})
  1283. return nil
  1284. }
  1285. // readyNode is a nodeRecorder with a user-writeable ready channel
  1286. type readyNode struct {
  1287. nodeRecorder
  1288. readyc chan raft.Ready
  1289. }
  1290. func newReadyNode() *readyNode {
  1291. return &readyNode{
  1292. nodeRecorder{testutil.NewRecorderStream()},
  1293. make(chan raft.Ready, 1)}
  1294. }
  1295. func newNopReadyNode() *readyNode {
  1296. return &readyNode{*newNodeRecorder(), make(chan raft.Ready, 1)}
  1297. }
  1298. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1299. type nodeConfChangeCommitterRecorder struct {
  1300. readyNode
  1301. index uint64
  1302. }
  1303. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1304. return &nodeConfChangeCommitterRecorder{*newNopReadyNode(), 0}
  1305. }
  1306. func newNodeConfChangeCommitterStream() *nodeConfChangeCommitterRecorder {
  1307. return &nodeConfChangeCommitterRecorder{*newReadyNode(), 0}
  1308. }
  1309. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1310. data, err := conf.Marshal()
  1311. if err != nil {
  1312. return err
  1313. }
  1314. n.index++
  1315. n.Record(testutil.Action{Name: "ProposeConfChange:" + conf.Type.String()})
  1316. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: raftpb.EntryConfChange, Data: data}}}
  1317. return nil
  1318. }
  1319. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1320. return n.readyc
  1321. }
  1322. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1323. n.Record(testutil.Action{Name: "ApplyConfChange:" + conf.Type.String()})
  1324. return &raftpb.ConfState{}
  1325. }
  1326. // nodeCommitter commits proposed data immediately.
  1327. type nodeCommitter struct {
  1328. readyNode
  1329. index uint64
  1330. }
  1331. func newNodeCommitter() raft.Node {
  1332. return &nodeCommitter{*newNopReadyNode(), 0}
  1333. }
  1334. func (n *nodeCommitter) Propose(ctx context.Context, data []byte) error {
  1335. n.index++
  1336. ents := []raftpb.Entry{{Index: n.index, Data: data}}
  1337. n.readyc <- raft.Ready{
  1338. Entries: ents,
  1339. CommittedEntries: ents,
  1340. }
  1341. return nil
  1342. }
  1343. func newTestCluster(membs []*membership.Member) *membership.RaftCluster {
  1344. c := membership.NewCluster("")
  1345. for _, m := range membs {
  1346. c.AddMember(m)
  1347. }
  1348. return c
  1349. }