server_test.go 42 KB

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