sender_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcdserver
  14. import (
  15. "errors"
  16. "io/ioutil"
  17. "net/http"
  18. "sync"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/etcdserver/stats"
  22. "github.com/coreos/etcd/pkg/testutil"
  23. "github.com/coreos/etcd/pkg/types"
  24. )
  25. func TestSendHubInitSenders(t *testing.T) {
  26. membs := []*Member{
  27. newTestMember(1, []string{"http://a"}, "", nil),
  28. newTestMember(2, []string{"http://b"}, "", nil),
  29. newTestMember(3, []string{"http://c"}, "", nil),
  30. }
  31. cl := newTestCluster(membs)
  32. ls := stats.NewLeaderStats("")
  33. h := newSendHub(nil, cl, nil, ls)
  34. ids := cl.MemberIDs()
  35. if len(h.senders) != len(ids) {
  36. t.Errorf("len(ids) = %d, want %d", len(h.senders), len(ids))
  37. }
  38. for _, id := range ids {
  39. if _, ok := h.senders[id]; !ok {
  40. t.Errorf("senders[%s] is nil, want exists", id)
  41. }
  42. }
  43. }
  44. func TestSendHubAdd(t *testing.T) {
  45. cl := newTestCluster(nil)
  46. ls := stats.NewLeaderStats("")
  47. h := newSendHub(nil, cl, nil, ls)
  48. m := newTestMember(1, []string{"http://a"}, "", nil)
  49. h.Add(m)
  50. if _, ok := ls.Followers["1"]; !ok {
  51. t.Errorf("FollowerStats[1] is nil, want exists")
  52. }
  53. s, ok := h.senders[types.ID(1)]
  54. if !ok {
  55. t.Fatalf("senders[1] is nil, want exists")
  56. }
  57. if s.u != "http://a/raft" {
  58. t.Errorf("url = %s, want %s", s.u, "http://a/raft")
  59. }
  60. h.Add(m)
  61. ns := h.senders[types.ID(1)]
  62. if s != ns {
  63. t.Errorf("sender = %p, want %p", ns, s)
  64. }
  65. }
  66. func TestSendHubRemove(t *testing.T) {
  67. membs := []*Member{
  68. newTestMember(1, []string{"http://a"}, "", nil),
  69. }
  70. cl := newTestCluster(membs)
  71. ls := stats.NewLeaderStats("")
  72. h := newSendHub(nil, cl, nil, ls)
  73. h.Remove(types.ID(1))
  74. if _, ok := h.senders[types.ID(1)]; ok {
  75. t.Fatalf("senders[1] exists, want removed")
  76. }
  77. }
  78. // TestSenderSend tests that send func could post data using roundtripper
  79. // and increase success count in stats.
  80. func TestSenderSend(t *testing.T) {
  81. tr := &roundTripperRecorder{}
  82. fs := &stats.FollowerStats{}
  83. s := newSender(tr, "http://10.0.0.1", types.ID(1), fs)
  84. // wait for handle goroutines start
  85. // TODO: wait for goroutines ready before return newSender
  86. time.Sleep(10 * time.Millisecond)
  87. if err := s.send([]byte("some data")); err != nil {
  88. t.Fatalf("unexpect send error: %v", err)
  89. }
  90. s.stop()
  91. // wait for goroutines end
  92. // TODO: elegant stop
  93. time.Sleep(10 * time.Millisecond)
  94. if tr.Request() == nil {
  95. t.Errorf("sender fails to post the data")
  96. }
  97. fs.Lock()
  98. defer fs.Unlock()
  99. if fs.Counts.Success != 1 {
  100. t.Errorf("success = %d, want 1", fs.Counts.Success)
  101. }
  102. }
  103. func TestSenderExceedMaximalServing(t *testing.T) {
  104. tr := newRoundTripperBlocker()
  105. fs := &stats.FollowerStats{}
  106. s := newSender(tr, "http://10.0.0.1", types.ID(1), fs)
  107. // wait for handle goroutines start
  108. // TODO: wait for goroutines ready before return newSender
  109. time.Sleep(10 * time.Millisecond)
  110. // It could handle that many requests at the same time.
  111. for i := 0; i < connPerSender; i++ {
  112. if err := s.send([]byte("some data")); err != nil {
  113. t.Errorf("send err = %v, want nil", err)
  114. }
  115. }
  116. // This one exceeds its maximal serving ability
  117. if err := s.send([]byte("some data")); err == nil {
  118. t.Errorf("unexpect send success")
  119. }
  120. tr.unblock()
  121. // Make handles finish their post
  122. testutil.ForceGosched()
  123. // It could send new data after previous ones succeed
  124. if err := s.send([]byte("some data")); err != nil {
  125. t.Errorf("send err = %v, want nil", err)
  126. }
  127. s.stop()
  128. }
  129. // TestSenderSendFailed tests that when send func meets the post error,
  130. // it increases fail count in stats.
  131. func TestSenderSendFailed(t *testing.T) {
  132. fs := &stats.FollowerStats{}
  133. s := newSender(newRespRoundTripper(0, errors.New("blah")), "http://10.0.0.1", types.ID(1), fs)
  134. // wait for handle goroutines start
  135. // TODO: wait for goroutines ready before return newSender
  136. time.Sleep(10 * time.Millisecond)
  137. if err := s.send([]byte("some data")); err != nil {
  138. t.Fatalf("unexpect send error: %v", err)
  139. }
  140. s.stop()
  141. // wait for goroutines end
  142. // TODO: elegant stop
  143. time.Sleep(10 * time.Millisecond)
  144. fs.Lock()
  145. defer fs.Unlock()
  146. if fs.Counts.Fail != 1 {
  147. t.Errorf("fail = %d, want 1", fs.Counts.Fail)
  148. }
  149. }
  150. func TestSenderPost(t *testing.T) {
  151. tr := &roundTripperRecorder{}
  152. s := newSender(tr, "http://10.0.0.1", types.ID(1), nil)
  153. if err := s.post([]byte("some data")); err != nil {
  154. t.Fatalf("unexpect post error: %v", err)
  155. }
  156. s.stop()
  157. if g := tr.Request().Method; g != "POST" {
  158. t.Errorf("method = %s, want %s", g, "POST")
  159. }
  160. if g := tr.Request().URL.String(); g != "http://10.0.0.1" {
  161. t.Errorf("url = %s, want %s", g, "http://10.0.0.1")
  162. }
  163. if g := tr.Request().Header.Get("Content-Type"); g != "application/protobuf" {
  164. t.Errorf("content type = %s, want %s", g, "application/protobuf")
  165. }
  166. if g := tr.Request().Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  167. t.Errorf("cluster id = %s, want %s", g, "1")
  168. }
  169. b, err := ioutil.ReadAll(tr.Request().Body)
  170. if err != nil {
  171. t.Fatalf("unexpected ReadAll error: %v", err)
  172. }
  173. if string(b) != "some data" {
  174. t.Errorf("body = %s, want %s", b, "some data")
  175. }
  176. }
  177. func TestSenderPostBad(t *testing.T) {
  178. tests := []struct {
  179. u string
  180. code int
  181. err error
  182. }{
  183. // bad url
  184. {":bad url", http.StatusNoContent, nil},
  185. // RoundTrip returns error
  186. {"http://10.0.0.1", 0, errors.New("blah")},
  187. // unexpected response status code
  188. {"http://10.0.0.1", http.StatusOK, nil},
  189. {"http://10.0.0.1", http.StatusCreated, nil},
  190. }
  191. for i, tt := range tests {
  192. s := newSender(newRespRoundTripper(tt.code, tt.err), tt.u, types.ID(1), nil)
  193. err := s.post([]byte("some data"))
  194. s.stop()
  195. if err == nil {
  196. t.Errorf("#%d: err = nil, want not nil", i)
  197. }
  198. }
  199. }
  200. type roundTripperBlocker struct {
  201. c chan struct{}
  202. }
  203. func newRoundTripperBlocker() *roundTripperBlocker {
  204. return &roundTripperBlocker{c: make(chan struct{})}
  205. }
  206. func (t *roundTripperBlocker) RoundTrip(req *http.Request) (*http.Response, error) {
  207. <-t.c
  208. return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil
  209. }
  210. func (t *roundTripperBlocker) unblock() {
  211. close(t.c)
  212. }
  213. type respRoundTripper struct {
  214. code int
  215. err error
  216. }
  217. func newRespRoundTripper(code int, err error) *respRoundTripper {
  218. return &respRoundTripper{code: code, err: err}
  219. }
  220. func (t *respRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  221. return &http.Response{StatusCode: t.code, Body: &nopReadCloser{}}, t.err
  222. }
  223. type roundTripperRecorder struct {
  224. req *http.Request
  225. sync.Mutex
  226. }
  227. func (t *roundTripperRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
  228. t.Lock()
  229. defer t.Unlock()
  230. t.req = req
  231. return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil
  232. }
  233. func (t *roundTripperRecorder) Request() *http.Request {
  234. t.Lock()
  235. defer t.Unlock()
  236. return t.req
  237. }
  238. type nopReadCloser struct{}
  239. func (n *nopReadCloser) Read(p []byte) (int, error) { return 0, nil }
  240. func (n *nopReadCloser) Close() error { return nil }