server_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  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.ConfChangeUpdateNode,
  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) Update(m *Member) {}
  482. func (s *fakeSender) Remove(id types.ID) {}
  483. func (s *fakeSender) Stop() {}
  484. func testServer(t *testing.T, ns uint64) {
  485. ctx, cancel := context.WithCancel(context.Background())
  486. defer cancel()
  487. ss := make([]*EtcdServer, ns)
  488. ids := make([]uint64, ns)
  489. for i := uint64(0); i < ns; i++ {
  490. ids[i] = i + 1
  491. }
  492. members := mustMakePeerSlice(t, ids...)
  493. for i := uint64(0); i < ns; i++ {
  494. id := i + 1
  495. s := raft.NewMemoryStorage()
  496. n := raft.StartNode(id, members, 10, 1, s)
  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. raftStorage: s,
  505. store: st,
  506. sender: &fakeSender{ss},
  507. storage: &storageRecorder{},
  508. Ticker: tk.C,
  509. Cluster: cl,
  510. }
  511. ss[i] = srv
  512. }
  513. // Start the servers after they're all created to avoid races in send().
  514. for i := uint64(0); i < ns; i++ {
  515. ss[i].start()
  516. }
  517. for i := 1; i <= 10; i++ {
  518. r := pb.Request{
  519. Method: "PUT",
  520. ID: uint64(i),
  521. Path: "/foo",
  522. Val: "bar",
  523. }
  524. j := rand.Intn(len(ss))
  525. t.Logf("ss = %d", j)
  526. resp, err := ss[j].Do(ctx, r)
  527. if err != nil {
  528. t.Fatal(err)
  529. }
  530. g, w := resp.Event.Node, &store.NodeExtern{
  531. Key: "/foo",
  532. ModifiedIndex: uint64(i) + ns,
  533. CreatedIndex: uint64(i) + ns,
  534. Value: stringp("bar"),
  535. }
  536. if !reflect.DeepEqual(g, w) {
  537. t.Error("value:", *g.Value)
  538. t.Errorf("g = %+v, w %+v", g, w)
  539. }
  540. }
  541. time.Sleep(10 * time.Millisecond)
  542. var last interface{}
  543. for i, sv := range ss {
  544. sv.Stop()
  545. g, _ := sv.store.Get("/", true, true)
  546. if last != nil && !reflect.DeepEqual(last, g) {
  547. t.Errorf("server %d: Root = %#v, want %#v", i, g, last)
  548. }
  549. last = g
  550. }
  551. }
  552. func TestDoProposal(t *testing.T) {
  553. tests := []pb.Request{
  554. pb.Request{Method: "POST", ID: 1},
  555. pb.Request{Method: "PUT", ID: 1},
  556. pb.Request{Method: "DELETE", ID: 1},
  557. pb.Request{Method: "GET", ID: 1, Quorum: true},
  558. }
  559. for i, tt := range tests {
  560. ctx, _ := context.WithCancel(context.Background())
  561. s := raft.NewMemoryStorage()
  562. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1, s)
  563. st := &storeRecorder{}
  564. tk := make(chan time.Time)
  565. // this makes <-tk always successful, which accelerates internal clock
  566. close(tk)
  567. cl := newCluster("abc")
  568. cl.SetStore(store.New())
  569. srv := &EtcdServer{
  570. node: n,
  571. raftStorage: s,
  572. store: st,
  573. sender: &nopSender{},
  574. storage: &storageRecorder{},
  575. Ticker: tk,
  576. Cluster: cl,
  577. }
  578. srv.start()
  579. resp, err := srv.Do(ctx, tt)
  580. srv.Stop()
  581. action := st.Action()
  582. if len(action) != 1 {
  583. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  584. }
  585. if err != nil {
  586. t.Fatalf("#%d: err = %v, want nil", i, err)
  587. }
  588. wresp := Response{Event: &store.Event{}}
  589. if !reflect.DeepEqual(resp, wresp) {
  590. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  591. }
  592. }
  593. }
  594. func TestDoProposalCancelled(t *testing.T) {
  595. ctx, cancel := context.WithCancel(context.Background())
  596. // node cannot make any progress because there are two nodes
  597. s := raft.NewMemoryStorage()
  598. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0, 0xBAD1), 10, 1, s)
  599. st := &storeRecorder{}
  600. wait := &waitRecorder{}
  601. srv := &EtcdServer{
  602. // TODO: use fake node for better testability
  603. node: n,
  604. raftStorage: s,
  605. store: st,
  606. w: wait,
  607. }
  608. done := make(chan struct{})
  609. var err error
  610. go func() {
  611. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  612. close(done)
  613. }()
  614. cancel()
  615. <-done
  616. gaction := st.Action()
  617. if len(gaction) != 0 {
  618. t.Errorf("len(action) = %v, want 0", len(gaction))
  619. }
  620. if err != ErrCanceled {
  621. t.Fatalf("err = %v, want %v", err, ErrCanceled)
  622. }
  623. w := []action{action{name: "Register1"}, action{name: "Trigger1"}}
  624. if !reflect.DeepEqual(wait.action, w) {
  625. t.Errorf("wait.action = %+v, want %+v", wait.action, w)
  626. }
  627. }
  628. func TestDoProposalTimeout(t *testing.T) {
  629. ctx, _ := context.WithTimeout(context.Background(), 0)
  630. srv := &EtcdServer{
  631. node: &nodeRecorder{},
  632. w: &waitRecorder{},
  633. }
  634. _, err := srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  635. if err != ErrTimeout {
  636. t.Fatalf("err = %v, want %v", err, ErrTimeout)
  637. }
  638. }
  639. func TestDoProposalStopped(t *testing.T) {
  640. ctx, cancel := context.WithCancel(context.Background())
  641. defer cancel()
  642. // node cannot make any progress because there are two nodes
  643. s := raft.NewMemoryStorage()
  644. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0, 0xBAD1), 10, 1, s)
  645. st := &storeRecorder{}
  646. tk := make(chan time.Time)
  647. // this makes <-tk always successful, which accelarates internal clock
  648. close(tk)
  649. srv := &EtcdServer{
  650. // TODO: use fake node for better testability
  651. node: n,
  652. raftStorage: s,
  653. store: st,
  654. sender: &nopSender{},
  655. storage: &storageRecorder{},
  656. Ticker: tk,
  657. }
  658. srv.start()
  659. done := make(chan struct{})
  660. var err error
  661. go func() {
  662. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  663. close(done)
  664. }()
  665. srv.Stop()
  666. <-done
  667. action := st.Action()
  668. if len(action) != 0 {
  669. t.Errorf("len(action) = %v, want 0", len(action))
  670. }
  671. if err != ErrStopped {
  672. t.Errorf("err = %v, want %v", err, ErrStopped)
  673. }
  674. }
  675. // TestSync tests sync 1. is nonblocking 2. sends out SYNC request.
  676. func TestSync(t *testing.T) {
  677. n := &nodeProposeDataRecorder{}
  678. srv := &EtcdServer{
  679. node: n,
  680. }
  681. done := make(chan struct{})
  682. go func() {
  683. srv.sync(10 * time.Second)
  684. close(done)
  685. }()
  686. // check that sync is non-blocking
  687. select {
  688. case <-done:
  689. case <-time.After(time.Second):
  690. t.Fatalf("sync should be non-blocking but did not return after 1s!")
  691. }
  692. testutil.ForceGosched()
  693. data := n.data()
  694. if len(data) != 1 {
  695. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  696. }
  697. var r pb.Request
  698. if err := r.Unmarshal(data[0]); err != nil {
  699. t.Fatalf("unmarshal request error: %v", err)
  700. }
  701. if r.Method != "SYNC" {
  702. t.Errorf("method = %s, want SYNC", r.Method)
  703. }
  704. }
  705. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  706. // after timeout
  707. func TestSyncTimeout(t *testing.T) {
  708. n := &nodeProposalBlockerRecorder{}
  709. srv := &EtcdServer{
  710. node: n,
  711. }
  712. done := make(chan struct{})
  713. go func() {
  714. srv.sync(0)
  715. close(done)
  716. }()
  717. // check that sync is non-blocking
  718. select {
  719. case <-done:
  720. case <-time.After(time.Second):
  721. t.Fatalf("sync should be non-blocking but did not return after 1s!")
  722. }
  723. // give time for goroutine in sync to cancel
  724. // TODO: use fake clock
  725. testutil.ForceGosched()
  726. w := []action{action{name: "Propose blocked"}}
  727. if g := n.Action(); !reflect.DeepEqual(g, w) {
  728. t.Errorf("action = %v, want %v", g, w)
  729. }
  730. }
  731. // TODO: TestNoSyncWhenNoLeader
  732. // blockingNodeProposer implements the node interface to allow users to
  733. // block until Propose has been called and then verify the Proposed data
  734. type blockingNodeProposer struct {
  735. ch chan []byte
  736. readyNode
  737. }
  738. func (n *blockingNodeProposer) Propose(_ context.Context, data []byte) error {
  739. n.ch <- data
  740. return nil
  741. }
  742. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  743. func TestSyncTrigger(t *testing.T) {
  744. n := &blockingNodeProposer{
  745. ch: make(chan []byte),
  746. readyNode: *newReadyNode(),
  747. }
  748. st := make(chan time.Time, 1)
  749. srv := &EtcdServer{
  750. node: n,
  751. raftStorage: raft.NewMemoryStorage(),
  752. store: &storeRecorder{},
  753. sender: &nopSender{},
  754. storage: &storageRecorder{},
  755. SyncTicker: st,
  756. }
  757. srv.start()
  758. // trigger the server to become a leader and accept sync requests
  759. n.readyc <- raft.Ready{
  760. SoftState: &raft.SoftState{
  761. RaftState: raft.StateLeader,
  762. },
  763. }
  764. // trigger a sync request
  765. st <- time.Time{}
  766. var data []byte
  767. select {
  768. case <-time.After(time.Second):
  769. t.Fatalf("did not receive proposed request as expected!")
  770. case data = <-n.ch:
  771. }
  772. srv.Stop()
  773. var req pb.Request
  774. if err := req.Unmarshal(data); err != nil {
  775. t.Fatalf("error unmarshalling data: %v", err)
  776. }
  777. if req.Method != "SYNC" {
  778. t.Fatalf("unexpected proposed request: %#v", req.Method)
  779. }
  780. }
  781. // snapshot should snapshot the store and cut the persistent
  782. // TODO: node.Compact is called... we need to make the node an interface
  783. func TestSnapshot(t *testing.T) {
  784. s := raft.NewMemoryStorage()
  785. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1, s)
  786. defer n.Stop()
  787. // Progress the node to the point where it has something to snapshot.
  788. // TODO(bdarnell): this could be improved with changes in the raft internals.
  789. // First, we must apply the initial conf changes so we can have an election.
  790. rd := <-n.Ready()
  791. s.Append(rd.Entries)
  792. for _, e := range rd.CommittedEntries {
  793. if e.Type == raftpb.EntryConfChange {
  794. var cc raftpb.ConfChange
  795. err := cc.Unmarshal(e.Data)
  796. if err != nil {
  797. t.Fatal(err)
  798. }
  799. n.ApplyConfChange(cc)
  800. }
  801. }
  802. n.Advance()
  803. // Now we can have an election and persist the rest of the log.
  804. // This causes HardState.Commit to advance. HardState.Commit must
  805. // be > 0 to snapshot.
  806. n.Campaign(context.Background())
  807. rd = <-n.Ready()
  808. s.Append(rd.Entries)
  809. n.Advance()
  810. st := &storeRecorder{}
  811. p := &storageRecorder{}
  812. srv := &EtcdServer{
  813. store: st,
  814. storage: p,
  815. node: n,
  816. raftStorage: s,
  817. }
  818. srv.snapshot(1, []uint64{1})
  819. gaction := st.Action()
  820. if len(gaction) != 1 {
  821. t.Fatalf("len(action) = %d, want 1", len(gaction))
  822. }
  823. if !reflect.DeepEqual(gaction[0], action{name: "Save"}) {
  824. t.Errorf("action = %s, want Save", gaction[0])
  825. }
  826. gaction = p.Action()
  827. if len(gaction) != 1 {
  828. t.Fatalf("len(action) = %d, want 1", len(gaction))
  829. }
  830. if !reflect.DeepEqual(gaction[0], action{name: "Cut"}) {
  831. t.Errorf("action = %s, want Cut", gaction[0])
  832. }
  833. }
  834. // Applied > SnapCount should trigger a SaveSnap event
  835. func TestTriggerSnap(t *testing.T) {
  836. ctx := context.Background()
  837. s := raft.NewMemoryStorage()
  838. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1, s)
  839. rd := <-n.Ready()
  840. s.Append(rd.Entries)
  841. n.Advance()
  842. n.ApplyConfChange(raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 0xBAD0})
  843. n.Campaign(ctx)
  844. st := &storeRecorder{}
  845. p := &storageRecorder{}
  846. cl := newCluster("abc")
  847. cl.SetStore(store.New())
  848. srv := &EtcdServer{
  849. store: st,
  850. sender: &nopSender{},
  851. storage: p,
  852. node: n,
  853. raftStorage: s,
  854. snapCount: 10,
  855. Cluster: cl,
  856. }
  857. srv.start()
  858. for i := 0; uint64(i) < srv.snapCount-1; i++ {
  859. srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  860. }
  861. time.Sleep(time.Millisecond)
  862. srv.Stop()
  863. gaction := p.Action()
  864. // each operation is recorded as a Save
  865. // BootstrapConfig/Nop + (SnapCount - 1) * Puts + Cut + SaveSnap = Save + (SnapCount - 1) * Save + Cut + SaveSnap
  866. wcnt := 2 + int(srv.snapCount)
  867. if len(gaction) != wcnt {
  868. t.Fatalf("len(action) = %d, want %d", len(gaction), wcnt)
  869. }
  870. if !reflect.DeepEqual(gaction[wcnt-1], action{name: "SaveSnap"}) {
  871. t.Errorf("action = %s, want SaveSnap", gaction[wcnt-1])
  872. }
  873. }
  874. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  875. // it should trigger storage.SaveSnap and also store.Recover.
  876. func TestRecvSnapshot(t *testing.T) {
  877. n := newReadyNode()
  878. st := &storeRecorder{}
  879. p := &storageRecorder{}
  880. s := &EtcdServer{
  881. store: st,
  882. sender: &nopSender{},
  883. storage: p,
  884. node: n,
  885. raftStorage: raft.NewMemoryStorage(),
  886. }
  887. s.start()
  888. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  889. // make goroutines move forward to receive snapshot
  890. testutil.ForceGosched()
  891. s.Stop()
  892. wactions := []action{action{name: "Recovery"}}
  893. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  894. t.Errorf("store action = %v, want %v", g, wactions)
  895. }
  896. wactions = []action{action{name: "Save"}, action{name: "SaveSnap"}}
  897. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  898. t.Errorf("storage action = %v, want %v", g, wactions)
  899. }
  900. }
  901. // TestRecvSlowSnapshot tests that slow snapshot will not be applied
  902. // to store.
  903. func TestRecvSlowSnapshot(t *testing.T) {
  904. n := newReadyNode()
  905. st := &storeRecorder{}
  906. s := &EtcdServer{
  907. store: st,
  908. sender: &nopSender{},
  909. storage: &storageRecorder{},
  910. node: n,
  911. raftStorage: raft.NewMemoryStorage(),
  912. }
  913. s.start()
  914. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  915. // make goroutines move forward to receive snapshot
  916. testutil.ForceGosched()
  917. action := st.Action()
  918. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  919. // make goroutines move forward to receive snapshot
  920. testutil.ForceGosched()
  921. s.Stop()
  922. if g := st.Action(); !reflect.DeepEqual(g, action) {
  923. t.Errorf("store action = %v, want %v", g, action)
  924. }
  925. }
  926. // TestAddMember tests AddMember can propose and perform node addition.
  927. func TestAddMember(t *testing.T) {
  928. n := newNodeConfChangeCommitterRecorder()
  929. n.readyc <- raft.Ready{
  930. SoftState: &raft.SoftState{
  931. RaftState: raft.StateLeader,
  932. Nodes: []uint64{2345, 3456},
  933. },
  934. }
  935. cl := newTestCluster(nil)
  936. cl.SetStore(store.New())
  937. s := &EtcdServer{
  938. node: n,
  939. raftStorage: raft.NewMemoryStorage(),
  940. store: &storeRecorder{},
  941. sender: &nopSender{},
  942. storage: &storageRecorder{},
  943. Cluster: cl,
  944. }
  945. s.start()
  946. m := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  947. err := s.AddMember(context.TODO(), m)
  948. gaction := n.Action()
  949. s.Stop()
  950. if err != nil {
  951. t.Fatalf("AddMember error: %v", err)
  952. }
  953. wactions := []action{action{name: "ProposeConfChange:ConfChangeAddNode"}, action{name: "ApplyConfChange:ConfChangeAddNode"}}
  954. if !reflect.DeepEqual(gaction, wactions) {
  955. t.Errorf("action = %v, want %v", gaction, wactions)
  956. }
  957. if cl.Member(1234) == nil {
  958. t.Errorf("member with id 1234 is not added")
  959. }
  960. }
  961. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  962. func TestRemoveMember(t *testing.T) {
  963. n := newNodeConfChangeCommitterRecorder()
  964. n.readyc <- raft.Ready{
  965. SoftState: &raft.SoftState{
  966. RaftState: raft.StateLeader,
  967. Nodes: []uint64{1234, 2345, 3456},
  968. },
  969. }
  970. cl := newTestCluster(nil)
  971. cl.SetStore(store.New())
  972. cl.AddMember(&Member{ID: 1234})
  973. s := &EtcdServer{
  974. node: n,
  975. raftStorage: raft.NewMemoryStorage(),
  976. store: &storeRecorder{},
  977. sender: &nopSender{},
  978. storage: &storageRecorder{},
  979. Cluster: cl,
  980. }
  981. s.start()
  982. err := s.RemoveMember(context.TODO(), 1234)
  983. gaction := n.Action()
  984. s.Stop()
  985. if err != nil {
  986. t.Fatalf("RemoveMember error: %v", err)
  987. }
  988. wactions := []action{action{name: "ProposeConfChange:ConfChangeRemoveNode"}, action{name: "ApplyConfChange:ConfChangeRemoveNode"}}
  989. if !reflect.DeepEqual(gaction, wactions) {
  990. t.Errorf("action = %v, want %v", gaction, wactions)
  991. }
  992. if cl.Member(1234) != nil {
  993. t.Errorf("member with id 1234 is not removed")
  994. }
  995. }
  996. // TestUpdateMember tests RemoveMember can propose and perform node update.
  997. func TestUpdateMember(t *testing.T) {
  998. n := newNodeConfChangeCommitterRecorder()
  999. n.readyc <- raft.Ready{
  1000. SoftState: &raft.SoftState{
  1001. RaftState: raft.StateLeader,
  1002. Nodes: []uint64{1234, 2345, 3456},
  1003. },
  1004. }
  1005. cl := newTestCluster(nil)
  1006. cl.SetStore(store.New())
  1007. cl.AddMember(&Member{ID: 1234})
  1008. s := &EtcdServer{
  1009. node: n,
  1010. raftStorage: raft.NewMemoryStorage(),
  1011. store: &storeRecorder{},
  1012. sender: &nopSender{},
  1013. storage: &storageRecorder{},
  1014. Cluster: cl,
  1015. }
  1016. s.start()
  1017. wm := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  1018. err := s.UpdateMember(context.TODO(), wm)
  1019. gaction := n.Action()
  1020. s.Stop()
  1021. if err != nil {
  1022. t.Fatalf("UpdateMember error: %v", err)
  1023. }
  1024. wactions := []action{action{name: "ProposeConfChange:ConfChangeUpdateNode"}, action{name: "ApplyConfChange:ConfChangeUpdateNode"}}
  1025. if !reflect.DeepEqual(gaction, wactions) {
  1026. t.Errorf("action = %v, want %v", gaction, wactions)
  1027. }
  1028. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  1029. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  1030. }
  1031. }
  1032. // TODO: test server could stop itself when being removed
  1033. // TODO: test wait trigger correctness in multi-server case
  1034. func TestPublish(t *testing.T) {
  1035. n := &nodeProposeDataRecorder{}
  1036. ch := make(chan interface{}, 1)
  1037. // simulate that request has gone through consensus
  1038. ch <- Response{}
  1039. w := &waitWithResponse{ch: ch}
  1040. srv := &EtcdServer{
  1041. id: 1,
  1042. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  1043. Cluster: &Cluster{},
  1044. node: n,
  1045. w: w,
  1046. }
  1047. srv.publish(time.Hour)
  1048. data := n.data()
  1049. if len(data) != 1 {
  1050. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  1051. }
  1052. var r pb.Request
  1053. if err := r.Unmarshal(data[0]); err != nil {
  1054. t.Fatalf("unmarshal request error: %v", err)
  1055. }
  1056. if r.Method != "PUT" {
  1057. t.Errorf("method = %s, want PUT", r.Method)
  1058. }
  1059. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1060. if w := path.Join(memberStoreKey(wm.ID), attributesSuffix); r.Path != w {
  1061. t.Errorf("path = %s, want %s", r.Path, w)
  1062. }
  1063. var gattr Attributes
  1064. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1065. t.Fatalf("unmarshal val error: %v", err)
  1066. }
  1067. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1068. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1069. }
  1070. }
  1071. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1072. func TestPublishStopped(t *testing.T) {
  1073. srv := &EtcdServer{
  1074. node: &nodeRecorder{},
  1075. sender: &nopSender{},
  1076. Cluster: &Cluster{},
  1077. w: &waitRecorder{},
  1078. done: make(chan struct{}),
  1079. stopped: make(chan struct{}),
  1080. }
  1081. close(srv.stopped)
  1082. srv.Stop()
  1083. srv.publish(time.Hour)
  1084. }
  1085. // TestPublishRetry tests that publish will keep retry until success.
  1086. func TestPublishRetry(t *testing.T) {
  1087. n := &nodeRecorder{}
  1088. srv := &EtcdServer{
  1089. node: n,
  1090. w: &waitRecorder{},
  1091. done: make(chan struct{}),
  1092. }
  1093. time.AfterFunc(500*time.Microsecond, srv.Stop)
  1094. srv.publish(10 * time.Nanosecond)
  1095. action := n.Action()
  1096. // multiple Proposes
  1097. if n := len(action); n < 2 {
  1098. t.Errorf("len(action) = %d, want >= 2", n)
  1099. }
  1100. }
  1101. func TestGetOtherPeerURLs(t *testing.T) {
  1102. tests := []struct {
  1103. membs []*Member
  1104. self string
  1105. wurls []string
  1106. }{
  1107. {
  1108. []*Member{
  1109. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1110. },
  1111. "a",
  1112. []string{},
  1113. },
  1114. {
  1115. []*Member{
  1116. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1117. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1118. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1119. },
  1120. "a",
  1121. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1122. },
  1123. {
  1124. []*Member{
  1125. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1126. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1127. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1128. },
  1129. "a",
  1130. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1131. },
  1132. }
  1133. for i, tt := range tests {
  1134. cl := NewClusterFromMembers("", types.ID(0), tt.membs)
  1135. urls := getOtherPeerURLs(cl, tt.self)
  1136. if !reflect.DeepEqual(urls, tt.wurls) {
  1137. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1138. }
  1139. }
  1140. }
  1141. func TestGetBool(t *testing.T) {
  1142. tests := []struct {
  1143. b *bool
  1144. wb bool
  1145. wset bool
  1146. }{
  1147. {nil, false, false},
  1148. {boolp(true), true, true},
  1149. {boolp(false), false, true},
  1150. }
  1151. for i, tt := range tests {
  1152. b, set := getBool(tt.b)
  1153. if b != tt.wb {
  1154. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  1155. }
  1156. if set != tt.wset {
  1157. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  1158. }
  1159. }
  1160. }
  1161. func TestGenID(t *testing.T) {
  1162. // Sanity check that the GenID function has been seeded appropriately
  1163. // (math/rand is seeded with 1 by default)
  1164. r := rand.NewSource(int64(1))
  1165. var n uint64
  1166. for n == 0 {
  1167. n = uint64(r.Int63())
  1168. }
  1169. if n == GenID() {
  1170. t.Fatalf("GenID's rand seeded with 1!")
  1171. }
  1172. }
  1173. type action struct {
  1174. name string
  1175. params []interface{}
  1176. }
  1177. type recorder struct {
  1178. sync.Mutex
  1179. actions []action
  1180. }
  1181. func (r *recorder) record(a action) {
  1182. r.Lock()
  1183. r.actions = append(r.actions, a)
  1184. r.Unlock()
  1185. }
  1186. func (r *recorder) Action() []action {
  1187. r.Lock()
  1188. cpy := make([]action, len(r.actions))
  1189. copy(cpy, r.actions)
  1190. r.Unlock()
  1191. return cpy
  1192. }
  1193. type storeRecorder struct {
  1194. recorder
  1195. }
  1196. func (s *storeRecorder) Version() int { return 0 }
  1197. func (s *storeRecorder) Index() uint64 { return 0 }
  1198. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1199. s.record(action{
  1200. name: "Get",
  1201. params: []interface{}{path, recursive, sorted},
  1202. })
  1203. return &store.Event{}, nil
  1204. }
  1205. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1206. s.record(action{
  1207. name: "Set",
  1208. params: []interface{}{path, dir, val, expr},
  1209. })
  1210. return &store.Event{}, nil
  1211. }
  1212. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1213. s.record(action{
  1214. name: "Update",
  1215. params: []interface{}{path, val, expr},
  1216. })
  1217. return &store.Event{}, nil
  1218. }
  1219. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1220. s.record(action{
  1221. name: "Create",
  1222. params: []interface{}{path, dir, val, uniq, exp},
  1223. })
  1224. return &store.Event{}, nil
  1225. }
  1226. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1227. s.record(action{
  1228. name: "CompareAndSwap",
  1229. params: []interface{}{path, prevVal, prevIdx, val, expr},
  1230. })
  1231. return &store.Event{}, nil
  1232. }
  1233. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1234. s.record(action{
  1235. name: "Delete",
  1236. params: []interface{}{path, dir, recursive},
  1237. })
  1238. return &store.Event{}, nil
  1239. }
  1240. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1241. s.record(action{
  1242. name: "CompareAndDelete",
  1243. params: []interface{}{path, prevVal, prevIdx},
  1244. })
  1245. return &store.Event{}, nil
  1246. }
  1247. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1248. s.record(action{name: "Watch"})
  1249. return &stubWatcher{}, nil
  1250. }
  1251. func (s *storeRecorder) Save() ([]byte, error) {
  1252. s.record(action{name: "Save"})
  1253. return nil, nil
  1254. }
  1255. func (s *storeRecorder) Recovery(b []byte) error {
  1256. s.record(action{name: "Recovery"})
  1257. return nil
  1258. }
  1259. func (s *storeRecorder) JsonStats() []byte { return nil }
  1260. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1261. s.record(action{
  1262. name: "DeleteExpiredKeys",
  1263. params: []interface{}{cutoff},
  1264. })
  1265. }
  1266. type stubWatcher struct{}
  1267. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  1268. func (w *stubWatcher) StartIndex() uint64 { return 0 }
  1269. func (w *stubWatcher) Remove() {}
  1270. // errStoreRecorder returns an store error on Get, Watch request
  1271. type errStoreRecorder struct {
  1272. storeRecorder
  1273. err error
  1274. }
  1275. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  1276. s.record(action{name: "Get"})
  1277. return nil, s.err
  1278. }
  1279. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1280. s.record(action{name: "Watch"})
  1281. return nil, s.err
  1282. }
  1283. type waitRecorder struct {
  1284. action []action
  1285. }
  1286. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1287. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  1288. return nil
  1289. }
  1290. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1291. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  1292. }
  1293. func boolp(b bool) *bool { return &b }
  1294. func stringp(s string) *string { return &s }
  1295. type storageRecorder struct {
  1296. recorder
  1297. }
  1298. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  1299. p.record(action{name: "Save"})
  1300. return nil
  1301. }
  1302. func (p *storageRecorder) Cut() error {
  1303. p.record(action{name: "Cut"})
  1304. return nil
  1305. }
  1306. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) error {
  1307. if !raft.IsEmptySnap(st) {
  1308. p.record(action{name: "SaveSnap"})
  1309. }
  1310. return nil
  1311. }
  1312. type readyNode struct {
  1313. readyc chan raft.Ready
  1314. }
  1315. func newReadyNode() *readyNode {
  1316. readyc := make(chan raft.Ready, 1)
  1317. return &readyNode{readyc: readyc}
  1318. }
  1319. func (n *readyNode) Tick() {}
  1320. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1321. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1322. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1323. return nil
  1324. }
  1325. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1326. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1327. func (n *readyNode) Advance() {}
  1328. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) {}
  1329. func (n *readyNode) Stop() {}
  1330. func (n *readyNode) Compact(index uint64, nodes []uint64, d []byte) {}
  1331. type nodeRecorder struct {
  1332. recorder
  1333. }
  1334. func (n *nodeRecorder) Tick() { n.record(action{name: "Tick"}) }
  1335. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1336. n.record(action{name: "Campaign"})
  1337. return nil
  1338. }
  1339. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1340. n.record(action{name: "Propose"})
  1341. return nil
  1342. }
  1343. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1344. n.record(action{name: "ProposeConfChange"})
  1345. return nil
  1346. }
  1347. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1348. n.record(action{name: "Step"})
  1349. return nil
  1350. }
  1351. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1352. func (n *nodeRecorder) Advance() {}
  1353. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1354. n.record(action{name: "ApplyConfChange", params: []interface{}{conf}})
  1355. }
  1356. func (n *nodeRecorder) Stop() {
  1357. n.record(action{name: "Stop"})
  1358. }
  1359. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1360. n.record(action{name: "Compact"})
  1361. }
  1362. type nodeProposeDataRecorder struct {
  1363. nodeRecorder
  1364. sync.Mutex
  1365. d [][]byte
  1366. }
  1367. func (n *nodeProposeDataRecorder) data() [][]byte {
  1368. n.Lock()
  1369. d := n.d
  1370. n.Unlock()
  1371. return d
  1372. }
  1373. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1374. n.nodeRecorder.Propose(ctx, data)
  1375. n.Lock()
  1376. n.d = append(n.d, data)
  1377. n.Unlock()
  1378. return nil
  1379. }
  1380. type nodeProposalBlockerRecorder struct {
  1381. nodeRecorder
  1382. }
  1383. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1384. <-ctx.Done()
  1385. n.record(action{name: "Propose blocked"})
  1386. return nil
  1387. }
  1388. type nodeConfChangeCommitterRecorder struct {
  1389. nodeRecorder
  1390. readyc chan raft.Ready
  1391. }
  1392. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1393. readyc := make(chan raft.Ready, 1)
  1394. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1395. }
  1396. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1397. data, err := conf.Marshal()
  1398. if err != nil {
  1399. return err
  1400. }
  1401. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1402. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1403. return nil
  1404. }
  1405. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1406. return n.readyc
  1407. }
  1408. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1409. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1410. }
  1411. type waitWithResponse struct {
  1412. ch <-chan interface{}
  1413. }
  1414. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1415. return w.ch
  1416. }
  1417. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1418. type nopSender struct{}
  1419. func (s *nopSender) Send(m []raftpb.Message) {}
  1420. func (s *nopSender) Add(m *Member) {}
  1421. func (s *nopSender) Remove(id types.ID) {}
  1422. func (s *nopSender) Update(m *Member) {}
  1423. func (s *nopSender) Stop() {}
  1424. func mustMakePeerSlice(t *testing.T, ids ...uint64) []raft.Peer {
  1425. peers := make([]raft.Peer, len(ids))
  1426. for i, id := range ids {
  1427. m := Member{ID: types.ID(id)}
  1428. b, err := json.Marshal(m)
  1429. if err != nil {
  1430. t.Fatal(err)
  1431. }
  1432. peers[i] = raft.Peer{ID: id, Context: b}
  1433. }
  1434. return peers
  1435. }