server_test.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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. cfg: &ServerConfig{},
  798. r: raftNode{
  799. Node: n,
  800. transport: &nopTransporter{},
  801. storage: p,
  802. raftStorage: newRaftStorage(),
  803. },
  804. store: st,
  805. cluster: cl,
  806. }
  807. s.start()
  808. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
  809. // make goroutines move forward to receive snapshot
  810. testutil.WaitSchedule()
  811. s.Stop()
  812. wactions := []testutil.Action{{Name: "Recovery"}}
  813. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  814. t.Errorf("store action = %v, want %v", g, wactions)
  815. }
  816. wactions = []testutil.Action{{Name: "SaveSnap"}, {Name: "Save"}}
  817. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  818. t.Errorf("storage action = %v, want %v", g, wactions)
  819. }
  820. }
  821. // TestApplySnapshotAndCommittedEntries tests that server applies snapshot
  822. // first and then committed entries.
  823. func TestApplySnapshotAndCommittedEntries(t *testing.T) {
  824. n := newReadyNode()
  825. st := &storeRecorder{}
  826. cl := newCluster("abc")
  827. cl.SetStore(store.New())
  828. storage := newRaftStorage()
  829. s := &EtcdServer{
  830. cfg: &ServerConfig{},
  831. r: raftNode{
  832. Node: n,
  833. storage: &storageRecorder{},
  834. raftStorage: storage,
  835. transport: &nopTransporter{},
  836. },
  837. store: st,
  838. cluster: cl,
  839. }
  840. s.start()
  841. req := &pb.Request{Method: "QGET"}
  842. n.readyc <- raft.Ready{
  843. Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}},
  844. CommittedEntries: []raftpb.Entry{
  845. {Index: 2, Data: pbutil.MustMarshal(req)},
  846. },
  847. }
  848. // make goroutines move forward to receive snapshot
  849. testutil.WaitSchedule()
  850. s.Stop()
  851. actions := st.Action()
  852. if len(actions) != 2 {
  853. t.Fatalf("len(action) = %d, want 2", len(actions))
  854. }
  855. if actions[0].Name != "Recovery" {
  856. t.Errorf("actions[0] = %s, want %s", actions[0].Name, "Recovery")
  857. }
  858. if actions[1].Name != "Get" {
  859. t.Errorf("actions[1] = %s, want %s", actions[1].Name, "Get")
  860. }
  861. }
  862. // TestAddMember tests AddMember can propose and perform node addition.
  863. func TestAddMember(t *testing.T) {
  864. n := newNodeConfChangeCommitterRecorder()
  865. n.readyc <- raft.Ready{
  866. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  867. }
  868. cl := newTestCluster(nil)
  869. st := store.New()
  870. cl.SetStore(st)
  871. s := &EtcdServer{
  872. r: raftNode{
  873. Node: n,
  874. raftStorage: newRaftStorage(),
  875. storage: &storageRecorder{},
  876. transport: &nopTransporter{},
  877. },
  878. cfg: &ServerConfig{},
  879. store: st,
  880. cluster: cl,
  881. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  882. }
  883. s.start()
  884. m := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  885. err := s.AddMember(context.TODO(), m)
  886. gaction := n.Action()
  887. s.Stop()
  888. if err != nil {
  889. t.Fatalf("AddMember error: %v", err)
  890. }
  891. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeAddNode"}, {Name: "ApplyConfChange:ConfChangeAddNode"}}
  892. if !reflect.DeepEqual(gaction, wactions) {
  893. t.Errorf("action = %v, want %v", gaction, wactions)
  894. }
  895. if cl.Member(1234) == nil {
  896. t.Errorf("member with id 1234 is not added")
  897. }
  898. }
  899. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  900. func TestRemoveMember(t *testing.T) {
  901. n := newNodeConfChangeCommitterRecorder()
  902. n.readyc <- raft.Ready{
  903. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  904. }
  905. cl := newTestCluster(nil)
  906. st := store.New()
  907. cl.SetStore(store.New())
  908. cl.AddMember(&Member{ID: 1234})
  909. s := &EtcdServer{
  910. r: raftNode{
  911. Node: n,
  912. raftStorage: newRaftStorage(),
  913. storage: &storageRecorder{},
  914. transport: &nopTransporter{},
  915. },
  916. cfg: &ServerConfig{},
  917. store: st,
  918. cluster: cl,
  919. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  920. }
  921. s.start()
  922. err := s.RemoveMember(context.TODO(), 1234)
  923. gaction := n.Action()
  924. s.Stop()
  925. if err != nil {
  926. t.Fatalf("RemoveMember error: %v", err)
  927. }
  928. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeRemoveNode"}, {Name: "ApplyConfChange:ConfChangeRemoveNode"}}
  929. if !reflect.DeepEqual(gaction, wactions) {
  930. t.Errorf("action = %v, want %v", gaction, wactions)
  931. }
  932. if cl.Member(1234) != nil {
  933. t.Errorf("member with id 1234 is not removed")
  934. }
  935. }
  936. // TestUpdateMember tests RemoveMember can propose and perform node update.
  937. func TestUpdateMember(t *testing.T) {
  938. n := newNodeConfChangeCommitterRecorder()
  939. n.readyc <- raft.Ready{
  940. SoftState: &raft.SoftState{RaftState: raft.StateLeader},
  941. }
  942. cl := newTestCluster(nil)
  943. st := store.New()
  944. cl.SetStore(st)
  945. cl.AddMember(&Member{ID: 1234})
  946. s := &EtcdServer{
  947. r: raftNode{
  948. Node: n,
  949. raftStorage: newRaftStorage(),
  950. storage: &storageRecorder{},
  951. transport: &nopTransporter{},
  952. },
  953. store: st,
  954. cluster: cl,
  955. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  956. }
  957. s.start()
  958. wm := Member{ID: 1234, RaftAttributes: RaftAttributes{PeerURLs: []string{"http://127.0.0.1:1"}}}
  959. err := s.UpdateMember(context.TODO(), wm)
  960. gaction := n.Action()
  961. s.Stop()
  962. if err != nil {
  963. t.Fatalf("UpdateMember error: %v", err)
  964. }
  965. wactions := []testutil.Action{{Name: "ProposeConfChange:ConfChangeUpdateNode"}, {Name: "ApplyConfChange:ConfChangeUpdateNode"}}
  966. if !reflect.DeepEqual(gaction, wactions) {
  967. t.Errorf("action = %v, want %v", gaction, wactions)
  968. }
  969. if !reflect.DeepEqual(cl.Member(1234), &wm) {
  970. t.Errorf("member = %v, want %v", cl.Member(1234), &wm)
  971. }
  972. }
  973. // TODO: test server could stop itself when being removed
  974. func TestPublish(t *testing.T) {
  975. n := &nodeRecorder{}
  976. ch := make(chan interface{}, 1)
  977. // simulate that request has gone through consensus
  978. ch <- Response{}
  979. w := &waitWithResponse{ch: ch}
  980. srv := &EtcdServer{
  981. cfg: &ServerConfig{TickMs: 1},
  982. id: 1,
  983. r: raftNode{Node: n},
  984. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  985. cluster: &cluster{},
  986. w: w,
  987. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  988. }
  989. srv.publish(time.Hour)
  990. action := n.Action()
  991. if len(action) != 1 {
  992. t.Fatalf("len(action) = %d, want 1", len(action))
  993. }
  994. if action[0].Name != "Propose" {
  995. t.Fatalf("action = %s, want Propose", action[0].Name)
  996. }
  997. data := action[0].Params[0].([]byte)
  998. var r pb.Request
  999. if err := r.Unmarshal(data); err != nil {
  1000. t.Fatalf("unmarshal request error: %v", err)
  1001. }
  1002. if r.Method != "PUT" {
  1003. t.Errorf("method = %s, want PUT", r.Method)
  1004. }
  1005. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  1006. if wpath := path.Join(memberStoreKey(wm.ID), attributesSuffix); r.Path != wpath {
  1007. t.Errorf("path = %s, want %s", r.Path, wpath)
  1008. }
  1009. var gattr Attributes
  1010. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  1011. t.Fatalf("unmarshal val error: %v", err)
  1012. }
  1013. if !reflect.DeepEqual(gattr, wm.Attributes) {
  1014. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  1015. }
  1016. }
  1017. // TestPublishStopped tests that publish will be stopped if server is stopped.
  1018. func TestPublishStopped(t *testing.T) {
  1019. srv := &EtcdServer{
  1020. cfg: &ServerConfig{TickMs: 1},
  1021. r: raftNode{
  1022. Node: &nodeRecorder{},
  1023. transport: &nopTransporter{},
  1024. },
  1025. cluster: &cluster{},
  1026. w: &waitRecorder{},
  1027. done: make(chan struct{}),
  1028. stop: make(chan struct{}),
  1029. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1030. }
  1031. close(srv.done)
  1032. srv.publish(time.Hour)
  1033. }
  1034. // TestPublishRetry tests that publish will keep retry until success.
  1035. func TestPublishRetry(t *testing.T) {
  1036. n := &nodeRecorder{}
  1037. srv := &EtcdServer{
  1038. cfg: &ServerConfig{TickMs: 1},
  1039. r: raftNode{Node: n},
  1040. w: &waitRecorder{},
  1041. done: make(chan struct{}),
  1042. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1043. }
  1044. // TODO: use fakeClockwork
  1045. time.AfterFunc(10*time.Millisecond, func() { close(srv.done) })
  1046. srv.publish(10 * time.Nanosecond)
  1047. action := n.Action()
  1048. // multiple Proposes
  1049. if cnt := len(action); cnt < 2 {
  1050. t.Errorf("len(action) = %d, want >= 2", cnt)
  1051. }
  1052. }
  1053. func TestUpdateVersion(t *testing.T) {
  1054. n := &nodeRecorder{}
  1055. ch := make(chan interface{}, 1)
  1056. // simulate that request has gone through consensus
  1057. ch <- Response{}
  1058. w := &waitWithResponse{ch: ch}
  1059. srv := &EtcdServer{
  1060. id: 1,
  1061. cfg: &ServerConfig{TickMs: 1},
  1062. r: raftNode{Node: n},
  1063. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://node1.com"}},
  1064. cluster: &cluster{},
  1065. w: w,
  1066. reqIDGen: idutil.NewGenerator(0, time.Time{}),
  1067. }
  1068. srv.updateClusterVersion("2.0.0")
  1069. action := n.Action()
  1070. if len(action) != 1 {
  1071. t.Fatalf("len(action) = %d, want 1", len(action))
  1072. }
  1073. if action[0].Name != "Propose" {
  1074. t.Fatalf("action = %s, want Propose", action[0].Name)
  1075. }
  1076. data := action[0].Params[0].([]byte)
  1077. var r pb.Request
  1078. if err := r.Unmarshal(data); err != nil {
  1079. t.Fatalf("unmarshal request error: %v", err)
  1080. }
  1081. if r.Method != "PUT" {
  1082. t.Errorf("method = %s, want PUT", r.Method)
  1083. }
  1084. if wpath := path.Join(StoreClusterPrefix, "version"); r.Path != wpath {
  1085. t.Errorf("path = %s, want %s", r.Path, wpath)
  1086. }
  1087. if r.Val != "2.0.0" {
  1088. t.Errorf("val = %s, want %s", r.Val, "2.0.0")
  1089. }
  1090. }
  1091. func TestStopNotify(t *testing.T) {
  1092. s := &EtcdServer{
  1093. stop: make(chan struct{}),
  1094. done: make(chan struct{}),
  1095. }
  1096. go func() {
  1097. <-s.stop
  1098. close(s.done)
  1099. }()
  1100. notifier := s.StopNotify()
  1101. select {
  1102. case <-notifier:
  1103. t.Fatalf("received unexpected stop notification")
  1104. default:
  1105. }
  1106. s.Stop()
  1107. select {
  1108. case <-notifier:
  1109. default:
  1110. t.Fatalf("cannot receive stop notification")
  1111. }
  1112. }
  1113. func TestGetOtherPeerURLs(t *testing.T) {
  1114. tests := []struct {
  1115. membs []*Member
  1116. self string
  1117. wurls []string
  1118. }{
  1119. {
  1120. []*Member{
  1121. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1122. },
  1123. "a",
  1124. []string{},
  1125. },
  1126. {
  1127. []*Member{
  1128. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1129. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1130. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1131. },
  1132. "a",
  1133. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1134. },
  1135. {
  1136. []*Member{
  1137. newTestMember(1, []string{"http://10.0.0.1"}, "a", nil),
  1138. newTestMember(3, []string{"http://10.0.0.3"}, "c", nil),
  1139. newTestMember(2, []string{"http://10.0.0.2"}, "b", nil),
  1140. },
  1141. "a",
  1142. []string{"http://10.0.0.2", "http://10.0.0.3"},
  1143. },
  1144. }
  1145. for i, tt := range tests {
  1146. cl := newClusterFromMembers("", types.ID(0), tt.membs)
  1147. urls := getRemotePeerURLs(cl, tt.self)
  1148. if !reflect.DeepEqual(urls, tt.wurls) {
  1149. t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
  1150. }
  1151. }
  1152. }
  1153. // storeRecorder records all the methods it receives.
  1154. // storeRecorder DOES NOT work as a actual store.
  1155. // It always returns invalid empty response and no error.
  1156. type storeRecorder struct{ testutil.Recorder }
  1157. func (s *storeRecorder) Version() int { return 0 }
  1158. func (s *storeRecorder) Index() uint64 { return 0 }
  1159. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1160. s.Record(testutil.Action{
  1161. Name: "Get",
  1162. Params: []interface{}{path, recursive, sorted},
  1163. })
  1164. return &store.Event{}, nil
  1165. }
  1166. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  1167. s.Record(testutil.Action{
  1168. Name: "Set",
  1169. Params: []interface{}{path, dir, val, expr},
  1170. })
  1171. return &store.Event{}, nil
  1172. }
  1173. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  1174. s.Record(testutil.Action{
  1175. Name: "Update",
  1176. Params: []interface{}{path, val, expr},
  1177. })
  1178. return &store.Event{}, nil
  1179. }
  1180. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  1181. s.Record(testutil.Action{
  1182. Name: "Create",
  1183. Params: []interface{}{path, dir, val, uniq, exp},
  1184. })
  1185. return &store.Event{}, nil
  1186. }
  1187. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  1188. s.Record(testutil.Action{
  1189. Name: "CompareAndSwap",
  1190. Params: []interface{}{path, prevVal, prevIdx, val, expr},
  1191. })
  1192. return &store.Event{}, nil
  1193. }
  1194. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  1195. s.Record(testutil.Action{
  1196. Name: "Delete",
  1197. Params: []interface{}{path, dir, recursive},
  1198. })
  1199. return &store.Event{}, nil
  1200. }
  1201. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  1202. s.Record(testutil.Action{
  1203. Name: "CompareAndDelete",
  1204. Params: []interface{}{path, prevVal, prevIdx},
  1205. })
  1206. return &store.Event{}, nil
  1207. }
  1208. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1209. s.Record(testutil.Action{Name: "Watch"})
  1210. return &nopWatcher{}, nil
  1211. }
  1212. func (s *storeRecorder) Save() ([]byte, error) {
  1213. s.Record(testutil.Action{Name: "Save"})
  1214. return nil, nil
  1215. }
  1216. func (s *storeRecorder) Recovery(b []byte) error {
  1217. s.Record(testutil.Action{Name: "Recovery"})
  1218. return nil
  1219. }
  1220. func (s *storeRecorder) SaveNoCopy() ([]byte, error) {
  1221. s.Record(testutil.Action{Name: "SaveNoCopy"})
  1222. return nil, nil
  1223. }
  1224. func (s *storeRecorder) Clone() store.Store {
  1225. s.Record(testutil.Action{Name: "Clone"})
  1226. return s
  1227. }
  1228. func (s *storeRecorder) JsonStats() []byte { return nil }
  1229. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  1230. s.Record(testutil.Action{
  1231. Name: "DeleteExpiredKeys",
  1232. Params: []interface{}{cutoff},
  1233. })
  1234. }
  1235. type nopWatcher struct{}
  1236. func (w *nopWatcher) EventChan() chan *store.Event { return nil }
  1237. func (w *nopWatcher) StartIndex() uint64 { return 0 }
  1238. func (w *nopWatcher) Remove() {}
  1239. // errStoreRecorder is a storeRecorder, but returns the given error on
  1240. // Get, Watch methods.
  1241. type errStoreRecorder struct {
  1242. storeRecorder
  1243. err error
  1244. }
  1245. func (s *errStoreRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  1246. s.storeRecorder.Get(path, recursive, sorted)
  1247. return nil, s.err
  1248. }
  1249. func (s *errStoreRecorder) Watch(path string, recursive, sorted bool, index uint64) (store.Watcher, error) {
  1250. s.storeRecorder.Watch(path, recursive, sorted, index)
  1251. return nil, s.err
  1252. }
  1253. type waitRecorder struct {
  1254. action []testutil.Action
  1255. }
  1256. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1257. w.action = append(w.action, testutil.Action{Name: "Register"})
  1258. return nil
  1259. }
  1260. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1261. w.action = append(w.action, testutil.Action{Name: "Trigger"})
  1262. }
  1263. type waitWithResponse struct {
  1264. ch <-chan interface{}
  1265. }
  1266. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1267. return w.ch
  1268. }
  1269. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1270. type storageRecorder struct{ testutil.Recorder }
  1271. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  1272. p.Record(testutil.Action{Name: "Save"})
  1273. return nil
  1274. }
  1275. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) error {
  1276. if !raft.IsEmptySnap(st) {
  1277. p.Record(testutil.Action{Name: "SaveSnap"})
  1278. }
  1279. return nil
  1280. }
  1281. func (p *storageRecorder) Close() error { return nil }
  1282. type nodeRecorder struct{ testutil.Recorder }
  1283. func (n *nodeRecorder) Tick() { n.Record(testutil.Action{Name: "Tick"}) }
  1284. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1285. n.Record(testutil.Action{Name: "Campaign"})
  1286. return nil
  1287. }
  1288. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1289. n.Record(testutil.Action{Name: "Propose", Params: []interface{}{data}})
  1290. return nil
  1291. }
  1292. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1293. n.Record(testutil.Action{Name: "ProposeConfChange"})
  1294. return nil
  1295. }
  1296. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1297. n.Record(testutil.Action{Name: "Step"})
  1298. return nil
  1299. }
  1300. func (n *nodeRecorder) Status() raft.Status { return raft.Status{} }
  1301. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1302. func (n *nodeRecorder) Advance() {}
  1303. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1304. n.Record(testutil.Action{Name: "ApplyConfChange", Params: []interface{}{conf}})
  1305. return &raftpb.ConfState{}
  1306. }
  1307. func (n *nodeRecorder) Stop() {
  1308. n.Record(testutil.Action{Name: "Stop"})
  1309. }
  1310. func (n *nodeRecorder) ReportUnreachable(id uint64) {}
  1311. func (n *nodeRecorder) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}
  1312. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1313. n.Record(testutil.Action{Name: "Compact"})
  1314. }
  1315. type nodeProposalBlockerRecorder struct {
  1316. nodeRecorder
  1317. }
  1318. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1319. <-ctx.Done()
  1320. n.Record(testutil.Action{Name: "Propose blocked"})
  1321. return nil
  1322. }
  1323. type nodeConfChangeCommitterRecorder struct {
  1324. nodeRecorder
  1325. readyc chan raft.Ready
  1326. index uint64
  1327. }
  1328. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1329. readyc := make(chan raft.Ready, 1)
  1330. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1331. }
  1332. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1333. data, err := conf.Marshal()
  1334. if err != nil {
  1335. return err
  1336. }
  1337. n.index++
  1338. n.Record(testutil.Action{Name: "ProposeConfChange:" + conf.Type.String()})
  1339. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: raftpb.EntryConfChange, Data: data}}}
  1340. return nil
  1341. }
  1342. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1343. return n.readyc
  1344. }
  1345. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) *raftpb.ConfState {
  1346. n.Record(testutil.Action{Name: "ApplyConfChange:" + conf.Type.String()})
  1347. return &raftpb.ConfState{}
  1348. }
  1349. // nodeCommitter commits proposed data immediately.
  1350. type nodeCommitter struct {
  1351. nodeRecorder
  1352. readyc chan raft.Ready
  1353. index uint64
  1354. }
  1355. func newNodeCommitter() *nodeCommitter {
  1356. readyc := make(chan raft.Ready, 1)
  1357. return &nodeCommitter{readyc: readyc}
  1358. }
  1359. func (n *nodeCommitter) Propose(ctx context.Context, data []byte) error {
  1360. n.index++
  1361. ents := []raftpb.Entry{{Index: n.index, Data: data}}
  1362. n.readyc <- raft.Ready{
  1363. Entries: ents,
  1364. CommittedEntries: ents,
  1365. }
  1366. return nil
  1367. }
  1368. func (n *nodeCommitter) Ready() <-chan raft.Ready {
  1369. return n.readyc
  1370. }
  1371. type readyNode struct {
  1372. nodeRecorder
  1373. readyc chan raft.Ready
  1374. }
  1375. func newReadyNode() *readyNode {
  1376. readyc := make(chan raft.Ready, 1)
  1377. return &readyNode{readyc: readyc}
  1378. }
  1379. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1380. type nopTransporter struct{}
  1381. func (s *nopTransporter) Start() error { return nil }
  1382. func (s *nopTransporter) Handler() http.Handler { return nil }
  1383. func (s *nopTransporter) Send(m []raftpb.Message) {}
  1384. func (s *nopTransporter) AddRemote(id types.ID, us []string) {}
  1385. func (s *nopTransporter) AddPeer(id types.ID, us []string) {}
  1386. func (s *nopTransporter) RemovePeer(id types.ID) {}
  1387. func (s *nopTransporter) RemoveAllPeers() {}
  1388. func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {}
  1389. func (s *nopTransporter) ActiveSince(id types.ID) time.Time { return time.Time{} }
  1390. func (s *nopTransporter) SnapshotReady(rc io.ReadCloser, index uint64) {}
  1391. func (s *nopTransporter) Stop() {}
  1392. func (s *nopTransporter) Pause() {}
  1393. func (s *nopTransporter) Resume() {}