server_test.go 41 KB

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