raftexample_test.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright 2015 The etcd Authors
  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 main
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/http/httptest"
  21. "os"
  22. "testing"
  23. "time"
  24. "go.etcd.io/etcd/raft/raftpb"
  25. )
  26. type cluster struct {
  27. peers []string
  28. commitC []<-chan *string
  29. errorC []<-chan error
  30. proposeC []chan string
  31. confChangeC []chan raftpb.ConfChange
  32. }
  33. // newCluster creates a cluster of n nodes
  34. func newCluster(n int) *cluster {
  35. peers := make([]string, n)
  36. for i := range peers {
  37. peers[i] = fmt.Sprintf("http://127.0.0.1:%d", 10000+i)
  38. }
  39. clus := &cluster{
  40. peers: peers,
  41. commitC: make([]<-chan *string, len(peers)),
  42. errorC: make([]<-chan error, len(peers)),
  43. proposeC: make([]chan string, len(peers)),
  44. confChangeC: make([]chan raftpb.ConfChange, len(peers)),
  45. }
  46. for i := range clus.peers {
  47. os.RemoveAll(fmt.Sprintf("raftexample-%d", i+1))
  48. os.RemoveAll(fmt.Sprintf("raftexample-%d-snap", i+1))
  49. clus.proposeC[i] = make(chan string, 1)
  50. clus.confChangeC[i] = make(chan raftpb.ConfChange, 1)
  51. clus.commitC[i], clus.errorC[i], _ = newRaftNode(i+1, clus.peers, false, nil, clus.proposeC[i], clus.confChangeC[i])
  52. }
  53. return clus
  54. }
  55. // sinkReplay reads all commits in each node's local log.
  56. func (clus *cluster) sinkReplay() {
  57. for i := range clus.peers {
  58. for s := range clus.commitC[i] {
  59. if s == nil {
  60. break
  61. }
  62. }
  63. }
  64. }
  65. // Close closes all cluster nodes and returns an error if any failed.
  66. func (clus *cluster) Close() (err error) {
  67. for i := range clus.peers {
  68. close(clus.proposeC[i])
  69. for range clus.commitC[i] {
  70. // drain pending commits
  71. }
  72. // wait for channel to close
  73. if erri := <-clus.errorC[i]; erri != nil {
  74. err = erri
  75. }
  76. // clean intermediates
  77. os.RemoveAll(fmt.Sprintf("raftexample-%d", i+1))
  78. os.RemoveAll(fmt.Sprintf("raftexample-%d-snap", i+1))
  79. }
  80. return err
  81. }
  82. func (clus *cluster) closeNoErrors(t *testing.T) {
  83. if err := clus.Close(); err != nil {
  84. t.Fatal(err)
  85. }
  86. }
  87. // TestProposeOnCommit starts three nodes and feeds commits back into the proposal
  88. // channel. The intent is to ensure blocking on a proposal won't block raft progress.
  89. func TestProposeOnCommit(t *testing.T) {
  90. clus := newCluster(3)
  91. defer clus.closeNoErrors(t)
  92. clus.sinkReplay()
  93. donec := make(chan struct{})
  94. for i := range clus.peers {
  95. // feedback for "n" committed entries, then update donec
  96. go func(pC chan<- string, cC <-chan *string, eC <-chan error) {
  97. for n := 0; n < 100; n++ {
  98. s, ok := <-cC
  99. if !ok {
  100. pC = nil
  101. }
  102. select {
  103. case pC <- *s:
  104. continue
  105. case err := <-eC:
  106. t.Errorf("eC message (%v)", err)
  107. }
  108. }
  109. donec <- struct{}{}
  110. for range cC {
  111. // acknowledge the commits from other nodes so
  112. // raft continues to make progress
  113. }
  114. }(clus.proposeC[i], clus.commitC[i], clus.errorC[i])
  115. // one message feedback per node
  116. go func(i int) { clus.proposeC[i] <- "foo" }(i)
  117. }
  118. for range clus.peers {
  119. <-donec
  120. }
  121. }
  122. // TestCloseProposerBeforeReplay tests closing the producer before raft starts.
  123. func TestCloseProposerBeforeReplay(t *testing.T) {
  124. clus := newCluster(1)
  125. // close before replay so raft never starts
  126. defer clus.closeNoErrors(t)
  127. }
  128. // TestCloseProposerInflight tests closing the producer while
  129. // committed messages are being published to the client.
  130. func TestCloseProposerInflight(t *testing.T) {
  131. clus := newCluster(1)
  132. defer clus.closeNoErrors(t)
  133. clus.sinkReplay()
  134. // some inflight ops
  135. go func() {
  136. clus.proposeC[0] <- "foo"
  137. clus.proposeC[0] <- "bar"
  138. }()
  139. // wait for one message
  140. if c, ok := <-clus.commitC[0]; *c != "foo" || !ok {
  141. t.Fatalf("Commit failed")
  142. }
  143. }
  144. func TestPutAndGetKeyValue(t *testing.T) {
  145. clusters := []string{"http://127.0.0.1:9021"}
  146. proposeC := make(chan string)
  147. defer close(proposeC)
  148. confChangeC := make(chan raftpb.ConfChange)
  149. defer close(confChangeC)
  150. var kvs *kvstore
  151. getSnapshot := func() ([]byte, error) { return kvs.getSnapshot() }
  152. commitC, errorC, snapshotterReady := newRaftNode(1, clusters, false, getSnapshot, proposeC, confChangeC)
  153. kvs = newKVStore(<-snapshotterReady, proposeC, commitC, errorC)
  154. srv := httptest.NewServer(&httpKVAPI{
  155. store: kvs,
  156. confChangeC: confChangeC,
  157. })
  158. defer srv.Close()
  159. // wait server started
  160. <-time.After(time.Second * 3)
  161. wantKey, wantValue := "test-key", "test-value"
  162. url := fmt.Sprintf("%s/%s", srv.URL, wantKey)
  163. body := bytes.NewBufferString(wantValue)
  164. cli := srv.Client()
  165. req, err := http.NewRequest("PUT", url, body)
  166. if err != nil {
  167. t.Fatal(err)
  168. }
  169. req.Header.Set("Content-Type", "text/html; charset=utf-8")
  170. _, err = cli.Do(req)
  171. if err != nil {
  172. t.Fatal(err)
  173. }
  174. // wait for a moment for processing message, otherwise get would be failed.
  175. <-time.After(time.Second)
  176. resp, err := cli.Get(url)
  177. if err != nil {
  178. t.Fatal(err)
  179. }
  180. data, err := ioutil.ReadAll(resp.Body)
  181. if err != nil {
  182. t.Fatal(err)
  183. }
  184. defer resp.Body.Close()
  185. if gotValue := string(data); wantValue != gotValue {
  186. t.Fatalf("expect %s, got %s", wantValue, gotValue)
  187. }
  188. }