server_test.go 39 KB

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