sender_test.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. if tr.Request() == nil {
  92. t.Errorf("sender fails to post the data")
  93. }
  94. fs.Lock()
  95. defer fs.Unlock()
  96. if fs.Counts.Success != 1 {
  97. t.Errorf("success = %d, want 1", fs.Counts.Success)
  98. }
  99. }
  100. func TestSenderExceedMaximalServing(t *testing.T) {
  101. tr := newRoundTripperBlocker()
  102. fs := &stats.FollowerStats{}
  103. s := newSender(tr, "http://10.0.0.1", types.ID(1), fs)
  104. // wait for handle goroutines start
  105. // TODO: wait for goroutines ready before return newSender
  106. time.Sleep(10 * time.Millisecond)
  107. // It could handle that many requests at the same time.
  108. for i := 0; i < connPerSender; i++ {
  109. if err := s.send([]byte("some data")); err != nil {
  110. t.Errorf("send err = %v, want nil", err)
  111. }
  112. }
  113. // This one exceeds its maximal serving ability
  114. if err := s.send([]byte("some data")); err == nil {
  115. t.Errorf("unexpect send success")
  116. }
  117. tr.unblock()
  118. // Make handles finish their post
  119. testutil.ForceGosched()
  120. // It could send new data after previous ones succeed
  121. if err := s.send([]byte("some data")); err != nil {
  122. t.Errorf("send err = %v, want nil", err)
  123. }
  124. s.stop()
  125. }
  126. // TestSenderSendFailed tests that when send func meets the post error,
  127. // it increases fail count in stats.
  128. func TestSenderSendFailed(t *testing.T) {
  129. fs := &stats.FollowerStats{}
  130. s := newSender(newRespRoundTripper(0, errors.New("blah")), "http://10.0.0.1", types.ID(1), fs)
  131. // wait for handle goroutines start
  132. // TODO: wait for goroutines ready before return newSender
  133. time.Sleep(10 * time.Millisecond)
  134. if err := s.send([]byte("some data")); err != nil {
  135. t.Fatalf("unexpect send error: %v", err)
  136. }
  137. s.stop()
  138. fs.Lock()
  139. defer fs.Unlock()
  140. if fs.Counts.Fail != 1 {
  141. t.Errorf("fail = %d, want 1", fs.Counts.Fail)
  142. }
  143. }
  144. func TestSenderPost(t *testing.T) {
  145. tr := &roundTripperRecorder{}
  146. s := newSender(tr, "http://10.0.0.1", types.ID(1), nil)
  147. if err := s.post([]byte("some data")); err != nil {
  148. t.Fatalf("unexpect post error: %v", err)
  149. }
  150. s.stop()
  151. if g := tr.Request().Method; g != "POST" {
  152. t.Errorf("method = %s, want %s", g, "POST")
  153. }
  154. if g := tr.Request().URL.String(); g != "http://10.0.0.1" {
  155. t.Errorf("url = %s, want %s", g, "http://10.0.0.1")
  156. }
  157. if g := tr.Request().Header.Get("Content-Type"); g != "application/protobuf" {
  158. t.Errorf("content type = %s, want %s", g, "application/protobuf")
  159. }
  160. if g := tr.Request().Header.Get("X-Etcd-Cluster-ID"); g != "1" {
  161. t.Errorf("cluster id = %s, want %s", g, "1")
  162. }
  163. b, err := ioutil.ReadAll(tr.Request().Body)
  164. if err != nil {
  165. t.Fatalf("unexpected ReadAll error: %v", err)
  166. }
  167. if string(b) != "some data" {
  168. t.Errorf("body = %s, want %s", b, "some data")
  169. }
  170. }
  171. func TestSenderPostBad(t *testing.T) {
  172. tests := []struct {
  173. u string
  174. code int
  175. err error
  176. }{
  177. // bad url
  178. {":bad url", http.StatusNoContent, nil},
  179. // RoundTrip returns error
  180. {"http://10.0.0.1", 0, errors.New("blah")},
  181. // unexpected response status code
  182. {"http://10.0.0.1", http.StatusOK, nil},
  183. {"http://10.0.0.1", http.StatusCreated, nil},
  184. }
  185. for i, tt := range tests {
  186. s := newSender(newRespRoundTripper(tt.code, tt.err), tt.u, types.ID(1), nil)
  187. err := s.post([]byte("some data"))
  188. s.stop()
  189. if err == nil {
  190. t.Errorf("#%d: err = nil, want not nil", i)
  191. }
  192. }
  193. }
  194. type roundTripperBlocker struct {
  195. c chan struct{}
  196. }
  197. func newRoundTripperBlocker() *roundTripperBlocker {
  198. return &roundTripperBlocker{c: make(chan struct{})}
  199. }
  200. func (t *roundTripperBlocker) RoundTrip(req *http.Request) (*http.Response, error) {
  201. <-t.c
  202. return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil
  203. }
  204. func (t *roundTripperBlocker) unblock() {
  205. close(t.c)
  206. }
  207. type respRoundTripper struct {
  208. code int
  209. err error
  210. }
  211. func newRespRoundTripper(code int, err error) *respRoundTripper {
  212. return &respRoundTripper{code: code, err: err}
  213. }
  214. func (t *respRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  215. return &http.Response{StatusCode: t.code, Body: &nopReadCloser{}}, t.err
  216. }
  217. type roundTripperRecorder struct {
  218. req *http.Request
  219. sync.Mutex
  220. }
  221. func (t *roundTripperRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
  222. t.Lock()
  223. defer t.Unlock()
  224. t.req = req
  225. return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil
  226. }
  227. func (t *roundTripperRecorder) Request() *http.Request {
  228. t.Lock()
  229. defer t.Unlock()
  230. return t.req
  231. }
  232. type nopReadCloser struct{}
  233. func (n *nopReadCloser) Read(p []byte) (int, error) { return 0, nil }
  234. func (n *nopReadCloser) Close() error { return nil }