server_test.go 42 KB

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