server_test.go 37 KB

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