server_test.go 36 KB

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