server_test.go 40 KB

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