server_test.go 39 KB

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