server_test.go 39 KB

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