server_test.go 36 KB

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