server_test.go 39 KB

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