server_test.go 50 KB

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