server_test.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. package etcdserver
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/rand"
  6. "reflect"
  7. "sync"
  8. "testing"
  9. "time"
  10. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  11. "github.com/coreos/etcd/pkg"
  12. "github.com/coreos/etcd/raft"
  13. "github.com/coreos/etcd/raft/raftpb"
  14. "github.com/coreos/etcd/store"
  15. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  16. )
  17. func TestGetExpirationTime(t *testing.T) {
  18. tests := []struct {
  19. r pb.Request
  20. want time.Time
  21. }{
  22. {
  23. pb.Request{Expiration: 0},
  24. time.Time{},
  25. },
  26. {
  27. pb.Request{Expiration: 60000},
  28. time.Unix(0, 60000),
  29. },
  30. {
  31. pb.Request{Expiration: -60000},
  32. time.Unix(0, -60000),
  33. },
  34. }
  35. for i, tt := range tests {
  36. got := getExpirationTime(&tt.r)
  37. if !reflect.DeepEqual(tt.want, got) {
  38. t.Errorf("#%d: incorrect expiration time: want=%v got=%v", i, tt.want, got)
  39. }
  40. }
  41. }
  42. // TestDoLocalAction tests requests which do not need to go through raft to be applied,
  43. // and are served through local data.
  44. func TestDoLocalAction(t *testing.T) {
  45. tests := []struct {
  46. req pb.Request
  47. wresp Response
  48. werr error
  49. wactions []action
  50. }{
  51. {
  52. pb.Request{Method: "GET", ID: 1, Wait: true},
  53. Response{Watcher: &stubWatcher{}}, nil, []action{action{name: "Watch"}},
  54. },
  55. {
  56. pb.Request{Method: "GET", ID: 1},
  57. Response{Event: &store.Event{}}, nil,
  58. []action{
  59. action{
  60. name: "Get",
  61. params: []interface{}{"", false, false},
  62. },
  63. },
  64. },
  65. {
  66. pb.Request{Method: "BADMETHOD", ID: 1},
  67. Response{}, ErrUnknownMethod, []action{},
  68. },
  69. }
  70. for i, tt := range tests {
  71. st := &storeRecorder{}
  72. srv := &EtcdServer{store: st}
  73. resp, err := srv.Do(context.TODO(), tt.req)
  74. if err != tt.werr {
  75. t.Fatalf("#%d: err = %+v, want %+v", i, err, tt.werr)
  76. }
  77. if !reflect.DeepEqual(resp, tt.wresp) {
  78. t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp)
  79. }
  80. gaction := st.Action()
  81. if !reflect.DeepEqual(gaction, tt.wactions) {
  82. t.Errorf("#%d: action = %+v, want %+v", i, gaction, tt.wactions)
  83. }
  84. }
  85. }
  86. // TestDoBadLocalAction tests server requests which do not need to go through consensus,
  87. // and return errors when they fetch from local data.
  88. func TestDoBadLocalAction(t *testing.T) {
  89. storeErr := fmt.Errorf("bah")
  90. tests := []struct {
  91. req pb.Request
  92. wactions []action
  93. }{
  94. {
  95. pb.Request{Method: "GET", ID: 1, Wait: true},
  96. []action{action{name: "Watch"}},
  97. },
  98. {
  99. pb.Request{Method: "GET", ID: 1},
  100. []action{action{name: "Get"}},
  101. },
  102. }
  103. for i, tt := range tests {
  104. st := &errStoreRecorder{err: storeErr}
  105. srv := &EtcdServer{store: st}
  106. resp, err := srv.Do(context.Background(), tt.req)
  107. if err != storeErr {
  108. t.Fatalf("#%d: err = %+v, want %+v", i, err, storeErr)
  109. }
  110. if !reflect.DeepEqual(resp, Response{}) {
  111. t.Errorf("#%d: resp = %+v, want %+v", i, resp, Response{})
  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. func TestApplyRequest(t *testing.T) {
  120. tests := []struct {
  121. req pb.Request
  122. wresp Response
  123. wactions []action
  124. }{
  125. // POST ==> Create
  126. {
  127. pb.Request{Method: "POST", ID: 1},
  128. Response{Event: &store.Event{}},
  129. []action{
  130. action{
  131. name: "Create",
  132. params: []interface{}{"", false, "", true, time.Time{}},
  133. },
  134. },
  135. },
  136. // POST ==> Create, with expiration
  137. {
  138. pb.Request{Method: "POST", ID: 1, Expiration: 1337},
  139. Response{Event: &store.Event{}},
  140. []action{
  141. action{
  142. name: "Create",
  143. params: []interface{}{"", false, "", true, time.Unix(0, 1337)},
  144. },
  145. },
  146. },
  147. // POST ==> Create, with dir
  148. {
  149. pb.Request{Method: "POST", ID: 1, Dir: true},
  150. Response{Event: &store.Event{}},
  151. []action{
  152. action{
  153. name: "Create",
  154. params: []interface{}{"", true, "", true, time.Time{}},
  155. },
  156. },
  157. },
  158. // PUT ==> Set
  159. {
  160. pb.Request{Method: "PUT", ID: 1},
  161. Response{Event: &store.Event{}},
  162. []action{
  163. action{
  164. name: "Set",
  165. params: []interface{}{"", false, "", time.Time{}},
  166. },
  167. },
  168. },
  169. // PUT ==> Set, with dir
  170. {
  171. pb.Request{Method: "PUT", ID: 1, Dir: true},
  172. Response{Event: &store.Event{}},
  173. []action{
  174. action{
  175. name: "Set",
  176. params: []interface{}{"", true, "", time.Time{}},
  177. },
  178. },
  179. },
  180. // PUT with PrevExist=true ==> Update
  181. {
  182. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(true)},
  183. Response{Event: &store.Event{}},
  184. []action{
  185. action{
  186. name: "Update",
  187. params: []interface{}{"", "", time.Time{}},
  188. },
  189. },
  190. },
  191. // PUT with PrevExist=false ==> Create
  192. {
  193. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(false)},
  194. Response{Event: &store.Event{}},
  195. []action{
  196. action{
  197. name: "Create",
  198. params: []interface{}{"", false, "", false, time.Time{}},
  199. },
  200. },
  201. },
  202. // PUT with PrevExist=true *and* PrevIndex set ==> Update
  203. // TODO(jonboulle): is this expected?!
  204. {
  205. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(true), PrevIndex: 1},
  206. Response{Event: &store.Event{}},
  207. []action{
  208. action{
  209. name: "Update",
  210. params: []interface{}{"", "", time.Time{}},
  211. },
  212. },
  213. },
  214. // PUT with PrevExist=false *and* PrevIndex set ==> Create
  215. // TODO(jonboulle): is this expected?!
  216. {
  217. pb.Request{Method: "PUT", ID: 1, PrevExist: boolp(false), PrevIndex: 1},
  218. Response{Event: &store.Event{}},
  219. []action{
  220. action{
  221. name: "Create",
  222. params: []interface{}{"", false, "", false, time.Time{}},
  223. },
  224. },
  225. },
  226. // PUT with PrevIndex set ==> CompareAndSwap
  227. {
  228. pb.Request{Method: "PUT", ID: 1, PrevIndex: 1},
  229. Response{Event: &store.Event{}},
  230. []action{
  231. action{
  232. name: "CompareAndSwap",
  233. params: []interface{}{"", "", uint64(1), "", time.Time{}},
  234. },
  235. },
  236. },
  237. // PUT with PrevValue set ==> CompareAndSwap
  238. {
  239. pb.Request{Method: "PUT", ID: 1, PrevValue: "bar"},
  240. Response{Event: &store.Event{}},
  241. []action{
  242. action{
  243. name: "CompareAndSwap",
  244. params: []interface{}{"", "bar", uint64(0), "", time.Time{}},
  245. },
  246. },
  247. },
  248. // PUT with PrevIndex and PrevValue set ==> CompareAndSwap
  249. {
  250. pb.Request{Method: "PUT", ID: 1, PrevIndex: 1, PrevValue: "bar"},
  251. Response{Event: &store.Event{}},
  252. []action{
  253. action{
  254. name: "CompareAndSwap",
  255. params: []interface{}{"", "bar", uint64(1), "", time.Time{}},
  256. },
  257. },
  258. },
  259. // DELETE ==> Delete
  260. {
  261. pb.Request{Method: "DELETE", ID: 1},
  262. Response{Event: &store.Event{}},
  263. []action{
  264. action{
  265. name: "Delete",
  266. params: []interface{}{"", false, false},
  267. },
  268. },
  269. },
  270. // DELETE with PrevIndex set ==> CompareAndDelete
  271. {
  272. pb.Request{Method: "DELETE", ID: 1, PrevIndex: 1},
  273. Response{Event: &store.Event{}},
  274. []action{
  275. action{
  276. name: "CompareAndDelete",
  277. params: []interface{}{"", "", uint64(1)},
  278. },
  279. },
  280. },
  281. // DELETE with PrevValue set ==> CompareAndDelete
  282. {
  283. pb.Request{Method: "DELETE", ID: 1, PrevValue: "bar"},
  284. Response{Event: &store.Event{}},
  285. []action{
  286. action{
  287. name: "CompareAndDelete",
  288. params: []interface{}{"", "bar", uint64(0)},
  289. },
  290. },
  291. },
  292. // DELETE with PrevIndex *and* PrevValue set ==> CompareAndDelete
  293. {
  294. pb.Request{Method: "DELETE", ID: 1, PrevIndex: 5, PrevValue: "bar"},
  295. Response{Event: &store.Event{}},
  296. []action{
  297. action{
  298. name: "CompareAndDelete",
  299. params: []interface{}{"", "bar", uint64(5)},
  300. },
  301. },
  302. },
  303. // QGET ==> Get
  304. {
  305. pb.Request{Method: "QGET", ID: 1},
  306. Response{Event: &store.Event{}},
  307. []action{
  308. action{
  309. name: "Get",
  310. params: []interface{}{"", false, false},
  311. },
  312. },
  313. },
  314. // SYNC ==> DeleteExpiredKeys
  315. {
  316. pb.Request{Method: "SYNC", ID: 1},
  317. Response{},
  318. []action{
  319. action{
  320. name: "DeleteExpiredKeys",
  321. params: []interface{}{time.Unix(0, 0)},
  322. },
  323. },
  324. },
  325. {
  326. pb.Request{Method: "SYNC", ID: 1, Time: 12345},
  327. Response{},
  328. []action{
  329. action{
  330. name: "DeleteExpiredKeys",
  331. params: []interface{}{time.Unix(0, 12345)},
  332. },
  333. },
  334. },
  335. // Unknown method - error
  336. {
  337. pb.Request{Method: "BADMETHOD", ID: 1},
  338. Response{err: ErrUnknownMethod},
  339. []action{},
  340. },
  341. }
  342. for i, tt := range tests {
  343. st := &storeRecorder{}
  344. srv := &EtcdServer{store: st}
  345. resp := srv.applyRequest(tt.req)
  346. if !reflect.DeepEqual(resp, tt.wresp) {
  347. t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp)
  348. }
  349. gaction := st.Action()
  350. if !reflect.DeepEqual(gaction, tt.wactions) {
  351. t.Errorf("#%d: action = %#v, want %#v", i, gaction, tt.wactions)
  352. }
  353. }
  354. }
  355. func TestClusterOf1(t *testing.T) { testServer(t, 1) }
  356. func TestClusterOf3(t *testing.T) { testServer(t, 3) }
  357. func testServer(t *testing.T, ns uint64) {
  358. ctx, cancel := context.WithCancel(context.Background())
  359. defer cancel()
  360. ss := make([]*EtcdServer, ns)
  361. send := func(msgs []raftpb.Message) {
  362. for _, m := range msgs {
  363. t.Logf("m = %+v\n", m)
  364. ss[m.To-1].node.Step(ctx, m)
  365. }
  366. }
  367. ids := make([]uint64, ns)
  368. for i := uint64(0); i < ns; i++ {
  369. ids[i] = i + 1
  370. }
  371. members := mustMakePeerSlice(t, ids...)
  372. for i := uint64(0); i < ns; i++ {
  373. id := i + 1
  374. n := raft.StartNode(id, members, 10, 1)
  375. tk := time.NewTicker(10 * time.Millisecond)
  376. defer tk.Stop()
  377. srv := &EtcdServer{
  378. node: n,
  379. store: store.New(),
  380. send: send,
  381. storage: &storageRecorder{},
  382. ticker: tk.C,
  383. ClusterStore: &clusterStoreRecorder{},
  384. }
  385. srv.start()
  386. ss[i] = srv
  387. }
  388. for i := 1; i <= 10; i++ {
  389. r := pb.Request{
  390. Method: "PUT",
  391. ID: uint64(i),
  392. Path: "/foo",
  393. Val: "bar",
  394. }
  395. j := rand.Intn(len(ss))
  396. t.Logf("ss = %d", j)
  397. resp, err := ss[j].Do(ctx, r)
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. g, w := resp.Event.Node, &store.NodeExtern{
  402. Key: "/foo",
  403. ModifiedIndex: uint64(i),
  404. CreatedIndex: uint64(i),
  405. Value: stringp("bar"),
  406. }
  407. if !reflect.DeepEqual(g, w) {
  408. t.Error("value:", *g.Value)
  409. t.Errorf("g = %+v, w %+v", g, w)
  410. }
  411. }
  412. time.Sleep(10 * time.Millisecond)
  413. var last interface{}
  414. for i, sv := range ss {
  415. sv.Stop()
  416. g, _ := sv.store.Get("/", true, true)
  417. if last != nil && !reflect.DeepEqual(last, g) {
  418. t.Errorf("server %d: Root = %#v, want %#v", i, g, last)
  419. }
  420. last = g
  421. }
  422. }
  423. func TestDoProposal(t *testing.T) {
  424. tests := []pb.Request{
  425. pb.Request{Method: "POST", ID: 1},
  426. pb.Request{Method: "PUT", ID: 1},
  427. pb.Request{Method: "DELETE", ID: 1},
  428. pb.Request{Method: "GET", ID: 1, Quorum: true},
  429. }
  430. for i, tt := range tests {
  431. ctx, _ := context.WithCancel(context.Background())
  432. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1)
  433. st := &storeRecorder{}
  434. tk := make(chan time.Time)
  435. // this makes <-tk always successful, which accelerates internal clock
  436. close(tk)
  437. srv := &EtcdServer{
  438. node: n,
  439. store: st,
  440. send: func(_ []raftpb.Message) {},
  441. storage: &storageRecorder{},
  442. ticker: tk,
  443. ClusterStore: &clusterStoreRecorder{},
  444. }
  445. srv.start()
  446. resp, err := srv.Do(ctx, tt)
  447. srv.Stop()
  448. action := st.Action()
  449. if len(action) != 1 {
  450. t.Errorf("#%d: len(action) = %d, want 1", i, len(action))
  451. }
  452. if err != nil {
  453. t.Fatalf("#%d: err = %v, want nil", i, err)
  454. }
  455. wresp := Response{Event: &store.Event{}}
  456. if !reflect.DeepEqual(resp, wresp) {
  457. t.Errorf("#%d: resp = %v, want %v", i, resp, wresp)
  458. }
  459. }
  460. }
  461. func TestDoProposalCancelled(t *testing.T) {
  462. ctx, cancel := context.WithCancel(context.Background())
  463. // node cannot make any progress because there are two nodes
  464. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0, 0xBAD1), 10, 1)
  465. st := &storeRecorder{}
  466. wait := &waitRecorder{}
  467. srv := &EtcdServer{
  468. // TODO: use fake node for better testability
  469. node: n,
  470. store: st,
  471. w: wait,
  472. }
  473. done := make(chan struct{})
  474. var err error
  475. go func() {
  476. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  477. close(done)
  478. }()
  479. cancel()
  480. <-done
  481. gaction := st.Action()
  482. if len(gaction) != 0 {
  483. t.Errorf("len(action) = %v, want 0", len(gaction))
  484. }
  485. if err != context.Canceled {
  486. t.Fatalf("err = %v, want %v", err, context.Canceled)
  487. }
  488. w := []action{action{name: "Register1"}, action{name: "Trigger1"}}
  489. if !reflect.DeepEqual(wait.action, w) {
  490. t.Errorf("wait.action = %+v, want %+v", wait.action, w)
  491. }
  492. }
  493. func TestDoProposalStopped(t *testing.T) {
  494. ctx, cancel := context.WithCancel(context.Background())
  495. defer cancel()
  496. // node cannot make any progress because there are two nodes
  497. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0, 0xBAD1), 10, 1)
  498. st := &storeRecorder{}
  499. tk := make(chan time.Time)
  500. // this makes <-tk always successful, which accelarates internal clock
  501. close(tk)
  502. srv := &EtcdServer{
  503. // TODO: use fake node for better testability
  504. node: n,
  505. store: st,
  506. send: func(_ []raftpb.Message) {},
  507. storage: &storageRecorder{},
  508. ticker: tk,
  509. }
  510. srv.start()
  511. done := make(chan struct{})
  512. var err error
  513. go func() {
  514. _, err = srv.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  515. close(done)
  516. }()
  517. srv.Stop()
  518. <-done
  519. action := st.Action()
  520. if len(action) != 0 {
  521. t.Errorf("len(action) = %v, want 0", len(action))
  522. }
  523. if err != ErrStopped {
  524. t.Errorf("err = %v, want %v", err, ErrStopped)
  525. }
  526. }
  527. // TestSync tests sync 1. is nonblocking 2. sends out SYNC request.
  528. func TestSync(t *testing.T) {
  529. n := &nodeProposeDataRecorder{}
  530. srv := &EtcdServer{
  531. node: n,
  532. }
  533. start := time.Now()
  534. srv.sync(defaultSyncTimeout)
  535. // check that sync is non-blocking
  536. if d := time.Since(start); d > time.Millisecond {
  537. t.Errorf("CallSyncTime = %v, want < %v", d, time.Millisecond)
  538. }
  539. pkg.ForceGosched()
  540. data := n.data()
  541. if len(data) != 1 {
  542. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  543. }
  544. var r pb.Request
  545. if err := r.Unmarshal(data[0]); err != nil {
  546. t.Fatalf("unmarshal request error: %v", err)
  547. }
  548. if r.Method != "SYNC" {
  549. t.Errorf("method = %s, want SYNC", r.Method)
  550. }
  551. }
  552. // TestSyncTimeout tests the case that sync 1. is non-blocking 2. cancel request
  553. // after timeout
  554. func TestSyncTimeout(t *testing.T) {
  555. n := &nodeProposalBlockerRecorder{}
  556. srv := &EtcdServer{
  557. node: n,
  558. }
  559. start := time.Now()
  560. srv.sync(0)
  561. // check that sync is non-blocking
  562. if d := time.Since(start); d > time.Millisecond {
  563. t.Errorf("CallSyncTime = %v, want < %v", d, time.Millisecond)
  564. }
  565. // give time for goroutine in sync to cancel
  566. // TODO: use fake clock
  567. pkg.ForceGosched()
  568. w := []action{action{name: "Propose blocked"}}
  569. if g := n.Action(); !reflect.DeepEqual(g, w) {
  570. t.Errorf("action = %v, want %v", g, w)
  571. }
  572. }
  573. // TODO: TestNoSyncWhenNoLeader
  574. // blockingNodeProposer implements the node interface to allow users to
  575. // block until Propose has been called and then verify the Proposed data
  576. type blockingNodeProposer struct {
  577. ch chan []byte
  578. readyNode
  579. }
  580. func (n *blockingNodeProposer) Propose(_ context.Context, data []byte) error {
  581. n.ch <- data
  582. return nil
  583. }
  584. // TestSyncTrigger tests that the server proposes a SYNC request when its sync timer ticks
  585. func TestSyncTrigger(t *testing.T) {
  586. n := &blockingNodeProposer{
  587. ch: make(chan []byte),
  588. readyNode: *newReadyNode(),
  589. }
  590. st := make(chan time.Time, 1)
  591. srv := &EtcdServer{
  592. node: n,
  593. store: &storeRecorder{},
  594. send: func(_ []raftpb.Message) {},
  595. storage: &storageRecorder{},
  596. syncTicker: st,
  597. }
  598. srv.start()
  599. // trigger the server to become a leader and accept sync requests
  600. n.readyc <- raft.Ready{
  601. SoftState: &raft.SoftState{
  602. RaftState: raft.StateLeader,
  603. },
  604. }
  605. // trigger a sync request
  606. st <- time.Time{}
  607. var data []byte
  608. select {
  609. case <-time.After(time.Second):
  610. t.Fatalf("did not receive proposed request as expected!")
  611. case data = <-n.ch:
  612. }
  613. srv.Stop()
  614. var req pb.Request
  615. if err := req.Unmarshal(data); err != nil {
  616. t.Fatalf("error unmarshalling data: %v", err)
  617. }
  618. if req.Method != "SYNC" {
  619. t.Fatalf("unexpected proposed request: %#v", req.Method)
  620. }
  621. }
  622. // snapshot should snapshot the store and cut the persistent
  623. // TODO: node.Compact is called... we need to make the node an interface
  624. func TestSnapshot(t *testing.T) {
  625. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1)
  626. defer n.Stop()
  627. st := &storeRecorder{}
  628. p := &storageRecorder{}
  629. s := &EtcdServer{
  630. store: st,
  631. storage: p,
  632. node: n,
  633. }
  634. s.snapshot(0, []uint64{1})
  635. gaction := st.Action()
  636. if len(gaction) != 1 {
  637. t.Fatalf("len(action) = %d, want 1", len(gaction))
  638. }
  639. if !reflect.DeepEqual(gaction[0], action{name: "Save"}) {
  640. t.Errorf("action = %s, want Save", gaction[0])
  641. }
  642. gaction = p.Action()
  643. if len(gaction) != 1 {
  644. t.Fatalf("len(action) = %d, want 1", len(gaction))
  645. }
  646. if !reflect.DeepEqual(gaction[0], action{name: "Cut"}) {
  647. t.Errorf("action = %s, want Cut", gaction[0])
  648. }
  649. }
  650. // Applied > SnapCount should trigger a SaveSnap event
  651. func TestTriggerSnap(t *testing.T) {
  652. ctx := context.Background()
  653. n := raft.StartNode(0xBAD0, mustMakePeerSlice(t, 0xBAD0), 10, 1)
  654. <-n.Ready()
  655. n.ApplyConfChange(raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 0xBAD0})
  656. n.Campaign(ctx)
  657. st := &storeRecorder{}
  658. p := &storageRecorder{}
  659. s := &EtcdServer{
  660. store: st,
  661. send: func(_ []raftpb.Message) {},
  662. storage: p,
  663. node: n,
  664. snapCount: 10,
  665. ClusterStore: &clusterStoreRecorder{},
  666. }
  667. s.start()
  668. for i := 0; uint64(i) < s.snapCount-1; i++ {
  669. s.Do(ctx, pb.Request{Method: "PUT", ID: 1})
  670. }
  671. time.Sleep(time.Millisecond)
  672. s.Stop()
  673. gaction := p.Action()
  674. // each operation is recorded as a Save
  675. // BootstrapConfig/Nop + (SnapCount - 1) * Puts + Cut + SaveSnap = Save + (SnapCount - 1) * Save + Cut + SaveSnap
  676. if len(gaction) != 2+int(s.snapCount) {
  677. t.Fatalf("len(action) = %d, want %d", len(gaction), 2+int(s.snapCount))
  678. }
  679. if !reflect.DeepEqual(gaction[11], action{name: "SaveSnap"}) {
  680. t.Errorf("action = %s, want SaveSnap", gaction[11])
  681. }
  682. }
  683. // TestRecvSnapshot tests when it receives a snapshot from raft leader,
  684. // it should trigger storage.SaveSnap and also store.Recover.
  685. func TestRecvSnapshot(t *testing.T) {
  686. n := newReadyNode()
  687. st := &storeRecorder{}
  688. p := &storageRecorder{}
  689. s := &EtcdServer{
  690. store: st,
  691. send: func(_ []raftpb.Message) {},
  692. storage: p,
  693. node: n,
  694. }
  695. s.start()
  696. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  697. // make goroutines move forward to receive snapshot
  698. pkg.ForceGosched()
  699. s.Stop()
  700. wactions := []action{action{name: "Recovery"}}
  701. if g := st.Action(); !reflect.DeepEqual(g, wactions) {
  702. t.Errorf("store action = %v, want %v", g, wactions)
  703. }
  704. wactions = []action{action{name: "Save"}, action{name: "SaveSnap"}}
  705. if g := p.Action(); !reflect.DeepEqual(g, wactions) {
  706. t.Errorf("storage action = %v, want %v", g, wactions)
  707. }
  708. }
  709. // TestRecvSlowSnapshot tests that slow snapshot will not be applied
  710. // to store.
  711. func TestRecvSlowSnapshot(t *testing.T) {
  712. n := newReadyNode()
  713. st := &storeRecorder{}
  714. s := &EtcdServer{
  715. store: st,
  716. send: func(_ []raftpb.Message) {},
  717. storage: &storageRecorder{},
  718. node: n,
  719. }
  720. s.start()
  721. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  722. // make goroutines move forward to receive snapshot
  723. pkg.ForceGosched()
  724. action := st.Action()
  725. n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Index: 1}}
  726. // make goroutines move forward to receive snapshot
  727. pkg.ForceGosched()
  728. s.Stop()
  729. if g := st.Action(); !reflect.DeepEqual(g, action) {
  730. t.Errorf("store action = %v, want %v", g, action)
  731. }
  732. }
  733. // TestAddMember tests AddMember can propose and perform node addition.
  734. func TestAddMember(t *testing.T) {
  735. n := newNodeConfChangeCommitterRecorder()
  736. cs := &clusterStoreRecorder{}
  737. s := &EtcdServer{
  738. node: n,
  739. store: &storeRecorder{},
  740. send: func(_ []raftpb.Message) {},
  741. storage: &storageRecorder{},
  742. ClusterStore: cs,
  743. }
  744. s.start()
  745. m := Member{ID: 1, RaftAttributes: RaftAttributes{PeerURLs: []string{"foo"}}}
  746. s.AddMember(context.TODO(), m)
  747. gaction := n.Action()
  748. s.Stop()
  749. wactions := []action{action{name: "ProposeConfChange:ConfChangeAddNode"}, action{name: "ApplyConfChange:ConfChangeAddNode"}}
  750. if !reflect.DeepEqual(gaction, wactions) {
  751. t.Errorf("action = %v, want %v", gaction, wactions)
  752. }
  753. wcsactions := []action{{name: "Add", params: []interface{}{m}}}
  754. if g := cs.Action(); !reflect.DeepEqual(g, wcsactions) {
  755. t.Errorf("csaction = %v, want %v", g, wcsactions)
  756. }
  757. }
  758. // TestRemoveMember tests RemoveMember can propose and perform node removal.
  759. func TestRemoveMember(t *testing.T) {
  760. n := newNodeConfChangeCommitterRecorder()
  761. cs := &clusterStoreRecorder{}
  762. s := &EtcdServer{
  763. node: n,
  764. store: &storeRecorder{},
  765. send: func(_ []raftpb.Message) {},
  766. storage: &storageRecorder{},
  767. ClusterStore: cs,
  768. }
  769. s.start()
  770. id := uint64(1)
  771. s.RemoveMember(context.TODO(), id)
  772. gaction := n.Action()
  773. s.Stop()
  774. wactions := []action{action{name: "ProposeConfChange:ConfChangeRemoveNode"}, action{name: "ApplyConfChange:ConfChangeRemoveNode"}}
  775. if !reflect.DeepEqual(gaction, wactions) {
  776. t.Errorf("action = %v, want %v", gaction, wactions)
  777. }
  778. wcsactions := []action{{name: "Remove", params: []interface{}{id}}}
  779. if g := cs.Action(); !reflect.DeepEqual(g, wcsactions) {
  780. t.Errorf("csaction = %v, want %v", g, wcsactions)
  781. }
  782. }
  783. // TestServerStopItself tests that if node sends out Ready with ShouldStop,
  784. // server will stop.
  785. func TestServerStopItself(t *testing.T) {
  786. n := newReadyNode()
  787. s := &EtcdServer{
  788. node: n,
  789. store: &storeRecorder{},
  790. send: func(_ []raftpb.Message) {},
  791. storage: &storageRecorder{},
  792. }
  793. s.start()
  794. n.readyc <- raft.Ready{SoftState: &raft.SoftState{ShouldStop: true}}
  795. select {
  796. case <-s.done:
  797. case <-time.After(time.Millisecond):
  798. t.Errorf("did not receive from closed done channel as expected")
  799. }
  800. }
  801. // TODO: test wait trigger correctness in multi-server case
  802. func TestPublish(t *testing.T) {
  803. n := &nodeProposeDataRecorder{}
  804. ch := make(chan interface{}, 1)
  805. // simulate that request has gone through consensus
  806. ch <- Response{}
  807. w := &waitWithResponse{ch: ch}
  808. srv := &EtcdServer{
  809. id: 1,
  810. attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}},
  811. node: n,
  812. w: w,
  813. }
  814. srv.publish(time.Hour)
  815. data := n.data()
  816. if len(data) != 1 {
  817. t.Fatalf("len(proposeData) = %d, want 1", len(data))
  818. }
  819. var r pb.Request
  820. if err := r.Unmarshal(data[0]); err != nil {
  821. t.Fatalf("unmarshal request error: %v", err)
  822. }
  823. if r.Method != "PUT" {
  824. t.Errorf("method = %s, want PUT", r.Method)
  825. }
  826. wm := Member{ID: 1, Attributes: Attributes{Name: "node1", ClientURLs: []string{"http://a", "http://b"}}}
  827. if r.Path != wm.storeKey()+attributesSuffix {
  828. t.Errorf("path = %s, want %s", r.Path, wm.storeKey()+attributesSuffix)
  829. }
  830. var gattr Attributes
  831. if err := json.Unmarshal([]byte(r.Val), &gattr); err != nil {
  832. t.Fatalf("unmarshal val error: %v", err)
  833. }
  834. if !reflect.DeepEqual(gattr, wm.Attributes) {
  835. t.Errorf("member = %v, want %v", gattr, wm.Attributes)
  836. }
  837. }
  838. // TestPublishStopped tests that publish will be stopped if server is stopped.
  839. func TestPublishStopped(t *testing.T) {
  840. srv := &EtcdServer{
  841. node: &nodeRecorder{},
  842. w: &waitRecorder{},
  843. done: make(chan struct{}),
  844. }
  845. srv.Stop()
  846. srv.publish(time.Hour)
  847. }
  848. // TestPublishRetry tests that publish will keep retry until success.
  849. func TestPublishRetry(t *testing.T) {
  850. n := &nodeRecorder{}
  851. srv := &EtcdServer{
  852. node: n,
  853. w: &waitRecorder{},
  854. done: make(chan struct{}),
  855. }
  856. time.AfterFunc(500*time.Microsecond, srv.Stop)
  857. srv.publish(10 * time.Nanosecond)
  858. action := n.Action()
  859. // multiple Proposes
  860. if len(action) < 2 {
  861. t.Errorf("len(action) = %d, want >= 2", action)
  862. }
  863. }
  864. func TestGetBool(t *testing.T) {
  865. tests := []struct {
  866. b *bool
  867. wb bool
  868. wset bool
  869. }{
  870. {nil, false, false},
  871. {boolp(true), true, true},
  872. {boolp(false), false, true},
  873. }
  874. for i, tt := range tests {
  875. b, set := getBool(tt.b)
  876. if b != tt.wb {
  877. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  878. }
  879. if set != tt.wset {
  880. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  881. }
  882. }
  883. }
  884. func TestGenID(t *testing.T) {
  885. // Sanity check that the GenID function has been seeded appropriately
  886. // (math/rand is seeded with 1 by default)
  887. r := rand.NewSource(int64(1))
  888. var n uint64
  889. for n == 0 {
  890. n = uint64(r.Int63())
  891. }
  892. if n == GenID() {
  893. t.Fatalf("GenID's rand seeded with 1!")
  894. }
  895. }
  896. type action struct {
  897. name string
  898. params []interface{}
  899. }
  900. type recorder struct {
  901. sync.Mutex
  902. actions []action
  903. }
  904. func (r *recorder) record(a action) {
  905. r.Lock()
  906. r.actions = append(r.actions, a)
  907. r.Unlock()
  908. }
  909. func (r *recorder) Action() []action {
  910. r.Lock()
  911. cpy := make([]action, len(r.actions))
  912. copy(cpy, r.actions)
  913. r.Unlock()
  914. return cpy
  915. }
  916. type storeRecorder struct {
  917. recorder
  918. }
  919. func (s *storeRecorder) Version() int { return 0 }
  920. func (s *storeRecorder) Index() uint64 { return 0 }
  921. func (s *storeRecorder) Get(path string, recursive, sorted bool) (*store.Event, error) {
  922. s.record(action{
  923. name: "Get",
  924. params: []interface{}{path, recursive, sorted},
  925. })
  926. return &store.Event{}, nil
  927. }
  928. func (s *storeRecorder) Set(path string, dir bool, val string, expr time.Time) (*store.Event, error) {
  929. s.record(action{
  930. name: "Set",
  931. params: []interface{}{path, dir, val, expr},
  932. })
  933. return &store.Event{}, nil
  934. }
  935. func (s *storeRecorder) Update(path, val string, expr time.Time) (*store.Event, error) {
  936. s.record(action{
  937. name: "Update",
  938. params: []interface{}{path, val, expr},
  939. })
  940. return &store.Event{}, nil
  941. }
  942. func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp time.Time) (*store.Event, error) {
  943. s.record(action{
  944. name: "Create",
  945. params: []interface{}{path, dir, val, uniq, exp},
  946. })
  947. return &store.Event{}, nil
  948. }
  949. func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expr time.Time) (*store.Event, error) {
  950. s.record(action{
  951. name: "CompareAndSwap",
  952. params: []interface{}{path, prevVal, prevIdx, val, expr},
  953. })
  954. return &store.Event{}, nil
  955. }
  956. func (s *storeRecorder) Delete(path string, dir, recursive bool) (*store.Event, error) {
  957. s.record(action{
  958. name: "Delete",
  959. params: []interface{}{path, dir, recursive},
  960. })
  961. return &store.Event{}, nil
  962. }
  963. func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*store.Event, error) {
  964. s.record(action{
  965. name: "CompareAndDelete",
  966. params: []interface{}{path, prevVal, prevIdx},
  967. })
  968. return &store.Event{}, nil
  969. }
  970. func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  971. s.record(action{name: "Watch"})
  972. return &stubWatcher{}, nil
  973. }
  974. func (s *storeRecorder) Save() ([]byte, error) {
  975. s.record(action{name: "Save"})
  976. return nil, nil
  977. }
  978. func (s *storeRecorder) Recovery(b []byte) error {
  979. s.record(action{name: "Recovery"})
  980. return nil
  981. }
  982. func (s *storeRecorder) TotalTransactions() uint64 { return 0 }
  983. func (s *storeRecorder) JsonStats() []byte { return nil }
  984. func (s *storeRecorder) DeleteExpiredKeys(cutoff time.Time) {
  985. s.record(action{
  986. name: "DeleteExpiredKeys",
  987. params: []interface{}{cutoff},
  988. })
  989. }
  990. type stubWatcher struct{}
  991. func (w *stubWatcher) EventChan() chan *store.Event { return nil }
  992. func (w *stubWatcher) StartIndex() uint64 { return 0 }
  993. func (w *stubWatcher) Remove() {}
  994. // errStoreRecorder returns an store error on Get, Watch request
  995. type errStoreRecorder struct {
  996. storeRecorder
  997. err error
  998. }
  999. func (s *errStoreRecorder) Get(_ string, _, _ bool) (*store.Event, error) {
  1000. s.record(action{name: "Get"})
  1001. return nil, s.err
  1002. }
  1003. func (s *errStoreRecorder) Watch(_ string, _, _ bool, _ uint64) (store.Watcher, error) {
  1004. s.record(action{name: "Watch"})
  1005. return nil, s.err
  1006. }
  1007. type waitRecorder struct {
  1008. action []action
  1009. }
  1010. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  1011. w.action = append(w.action, action{name: fmt.Sprint("Register", id)})
  1012. return nil
  1013. }
  1014. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  1015. w.action = append(w.action, action{name: fmt.Sprint("Trigger", id)})
  1016. }
  1017. func boolp(b bool) *bool { return &b }
  1018. func stringp(s string) *string { return &s }
  1019. type storageRecorder struct {
  1020. recorder
  1021. }
  1022. func (p *storageRecorder) Save(st raftpb.HardState, ents []raftpb.Entry) {
  1023. p.record(action{name: "Save"})
  1024. }
  1025. func (p *storageRecorder) Cut() error {
  1026. p.record(action{name: "Cut"})
  1027. return nil
  1028. }
  1029. func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
  1030. if raft.IsEmptySnap(st) {
  1031. return
  1032. }
  1033. p.record(action{name: "SaveSnap"})
  1034. }
  1035. type readyNode struct {
  1036. readyc chan raft.Ready
  1037. }
  1038. func newReadyNode() *readyNode {
  1039. readyc := make(chan raft.Ready, 1)
  1040. return &readyNode{readyc: readyc}
  1041. }
  1042. func (n *readyNode) Tick() {}
  1043. func (n *readyNode) Campaign(ctx context.Context) error { return nil }
  1044. func (n *readyNode) Propose(ctx context.Context, data []byte) error { return nil }
  1045. func (n *readyNode) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1046. return nil
  1047. }
  1048. func (n *readyNode) Step(ctx context.Context, msg raftpb.Message) error { return nil }
  1049. func (n *readyNode) Ready() <-chan raft.Ready { return n.readyc }
  1050. func (n *readyNode) ApplyConfChange(conf raftpb.ConfChange) {}
  1051. func (n *readyNode) Stop() {}
  1052. func (n *readyNode) Compact(index uint64, nodes []uint64, d []byte) {}
  1053. type nodeRecorder struct {
  1054. recorder
  1055. }
  1056. func (n *nodeRecorder) Tick() {
  1057. n.record(action{name: "Tick"})
  1058. }
  1059. func (n *nodeRecorder) Campaign(ctx context.Context) error {
  1060. n.record(action{name: "Campaign"})
  1061. return nil
  1062. }
  1063. func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error {
  1064. n.record(action{name: "Propose"})
  1065. return nil
  1066. }
  1067. func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1068. n.record(action{name: "ProposeConfChange"})
  1069. return nil
  1070. }
  1071. func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error {
  1072. n.record(action{name: "Step"})
  1073. return nil
  1074. }
  1075. func (n *nodeRecorder) Ready() <-chan raft.Ready { return nil }
  1076. func (n *nodeRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1077. n.record(action{name: "ApplyConfChange"})
  1078. }
  1079. func (n *nodeRecorder) Stop() {
  1080. n.record(action{name: "Stop"})
  1081. }
  1082. func (n *nodeRecorder) Compact(index uint64, nodes []uint64, d []byte) {
  1083. n.record(action{name: "Compact"})
  1084. }
  1085. type nodeProposeDataRecorder struct {
  1086. nodeRecorder
  1087. sync.Mutex
  1088. d [][]byte
  1089. }
  1090. func (n *nodeProposeDataRecorder) data() [][]byte {
  1091. n.Lock()
  1092. d := n.d
  1093. n.Unlock()
  1094. return d
  1095. }
  1096. func (n *nodeProposeDataRecorder) Propose(ctx context.Context, data []byte) error {
  1097. n.nodeRecorder.Propose(ctx, data)
  1098. n.Lock()
  1099. n.d = append(n.d, data)
  1100. n.Unlock()
  1101. return nil
  1102. }
  1103. type nodeProposalBlockerRecorder struct {
  1104. nodeRecorder
  1105. }
  1106. func (n *nodeProposalBlockerRecorder) Propose(ctx context.Context, data []byte) error {
  1107. <-ctx.Done()
  1108. n.record(action{name: "Propose blocked"})
  1109. return nil
  1110. }
  1111. type nodeConfChangeCommitterRecorder struct {
  1112. nodeRecorder
  1113. readyc chan raft.Ready
  1114. }
  1115. func newNodeConfChangeCommitterRecorder() *nodeConfChangeCommitterRecorder {
  1116. readyc := make(chan raft.Ready, 1)
  1117. readyc <- raft.Ready{SoftState: &raft.SoftState{RaftState: raft.StateLeader}}
  1118. return &nodeConfChangeCommitterRecorder{readyc: readyc}
  1119. }
  1120. func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChange) error {
  1121. data, err := conf.Marshal()
  1122. if err != nil {
  1123. return err
  1124. }
  1125. n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Type: raftpb.EntryConfChange, Data: data}}}
  1126. n.record(action{name: "ProposeConfChange:" + conf.Type.String()})
  1127. return nil
  1128. }
  1129. func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready {
  1130. return n.readyc
  1131. }
  1132. func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange) {
  1133. n.record(action{name: "ApplyConfChange:" + conf.Type.String()})
  1134. }
  1135. type waitWithResponse struct {
  1136. ch <-chan interface{}
  1137. }
  1138. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  1139. return w.ch
  1140. }
  1141. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  1142. type clusterStoreRecorder struct {
  1143. recorder
  1144. }
  1145. func (cs *clusterStoreRecorder) Add(m Member) {
  1146. cs.record(action{name: "Add", params: []interface{}{m}})
  1147. }
  1148. func (cs *clusterStoreRecorder) Get() Cluster {
  1149. cs.record(action{name: "Get"})
  1150. return nil
  1151. }
  1152. func (cs *clusterStoreRecorder) Remove(id uint64) {
  1153. cs.record(action{name: "Remove", params: []interface{}{id}})
  1154. }
  1155. func mustMakePeerSlice(t *testing.T, ids ...uint64) []raft.Peer {
  1156. peers := make([]raft.Peer, len(ids))
  1157. for i, id := range ids {
  1158. m := Member{ID: id}
  1159. b, err := json.Marshal(m)
  1160. if err != nil {
  1161. t.Fatal(err)
  1162. }
  1163. peers[i] = raft.Peer{ID: id, Context: b}
  1164. }
  1165. return peers
  1166. }