server_test.go 39 KB

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