server_test.go 38 KB

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