server_test.go 36 KB

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