stresser.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. "fmt"
  17. "math/rand"
  18. "net"
  19. "net/http"
  20. "sync"
  21. "time"
  22. clientV2 "github.com/coreos/etcd/client"
  23. "github.com/coreos/etcd/etcdserver"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "golang.org/x/net/context"
  27. "golang.org/x/time/rate"
  28. "google.golang.org/grpc"
  29. "google.golang.org/grpc/grpclog"
  30. "google.golang.org/grpc/transport"
  31. )
  32. func init() {
  33. grpclog.SetLogger(plog)
  34. }
  35. type stressFunc func(ctx context.Context) error
  36. type stressEntry struct {
  37. weight float32
  38. f stressFunc
  39. }
  40. type stressTable struct {
  41. entries []stressEntry
  42. sumWeights float32
  43. }
  44. func createStressTable(entries []stressEntry) *stressTable {
  45. st := stressTable{entries: entries}
  46. for _, entry := range st.entries {
  47. st.sumWeights += entry.weight
  48. }
  49. return &st
  50. }
  51. func (st *stressTable) choose() stressFunc {
  52. v := rand.Float32() * st.sumWeights
  53. var sum float32
  54. var idx int
  55. for i := range st.entries {
  56. sum += st.entries[i].weight
  57. if sum >= v {
  58. idx = i
  59. break
  60. }
  61. }
  62. return st.entries[idx].f
  63. }
  64. func newStressPut(kvc pb.KVClient, keySuffixRange, keySize int) stressFunc {
  65. return func(ctx context.Context) error {
  66. _, err := kvc.Put(ctx, &pb.PutRequest{
  67. Key: []byte(fmt.Sprintf("foo%016x", rand.Intn(keySuffixRange))),
  68. Value: randBytes(keySize),
  69. }, grpc.FailFast(false))
  70. return err
  71. }
  72. }
  73. func newStressRange(kvc pb.KVClient, keySuffixRange int) stressFunc {
  74. return func(ctx context.Context) error {
  75. _, err := kvc.Range(ctx, &pb.RangeRequest{
  76. Key: []byte(fmt.Sprintf("foo%016x", rand.Intn(keySuffixRange))),
  77. }, grpc.FailFast(false))
  78. return err
  79. }
  80. }
  81. func newStressRangeInterval(kvc pb.KVClient, keySuffixRange int) stressFunc {
  82. return func(ctx context.Context) error {
  83. start := rand.Intn(keySuffixRange)
  84. end := start + 500
  85. _, err := kvc.Range(ctx, &pb.RangeRequest{
  86. Key: []byte(fmt.Sprintf("foo%016x", start)),
  87. RangeEnd: []byte(fmt.Sprintf("foo%016x", end)),
  88. }, grpc.FailFast(false))
  89. return err
  90. }
  91. }
  92. func newStressDelete(kvc pb.KVClient, keySuffixRange int) stressFunc {
  93. return func(ctx context.Context) error {
  94. _, err := kvc.DeleteRange(ctx, &pb.DeleteRangeRequest{
  95. Key: []byte(fmt.Sprintf("foo%016x", rand.Intn(keySuffixRange))),
  96. }, grpc.FailFast(false))
  97. return err
  98. }
  99. }
  100. func newStressDeleteInterval(kvc pb.KVClient, keySuffixRange int) stressFunc {
  101. return func(ctx context.Context) error {
  102. start := rand.Intn(keySuffixRange)
  103. end := start + 500
  104. _, err := kvc.DeleteRange(ctx, &pb.DeleteRangeRequest{
  105. Key: []byte(fmt.Sprintf("foo%016x", start)),
  106. RangeEnd: []byte(fmt.Sprintf("foo%016x", end)),
  107. }, grpc.FailFast(false))
  108. return err
  109. }
  110. }
  111. type Stresser interface {
  112. // Stress starts to stress the etcd cluster
  113. Stress() error
  114. // Cancel cancels the stress test on the etcd cluster
  115. Cancel()
  116. // Report reports the success and failure of the stress test
  117. Report() (success int, failure int)
  118. }
  119. type stresser struct {
  120. Endpoint string
  121. keySize int
  122. keySuffixRange int
  123. N int
  124. mu sync.Mutex
  125. wg *sync.WaitGroup
  126. rateLimiter *rate.Limiter
  127. cancel func()
  128. conn *grpc.ClientConn
  129. success int
  130. failure int
  131. stressTable *stressTable
  132. }
  133. func (s *stresser) Stress() error {
  134. if s.rateLimiter == nil {
  135. panic("expect rateLimiter to be set")
  136. }
  137. // TODO: add backoff option
  138. conn, err := grpc.Dial(s.Endpoint, grpc.WithInsecure())
  139. if err != nil {
  140. return fmt.Errorf("%v (%s)", err, s.Endpoint)
  141. }
  142. ctx, cancel := context.WithCancel(context.Background())
  143. wg := &sync.WaitGroup{}
  144. wg.Add(s.N)
  145. s.mu.Lock()
  146. s.conn = conn
  147. s.cancel = cancel
  148. s.wg = wg
  149. s.mu.Unlock()
  150. kvc := pb.NewKVClient(conn)
  151. var stressEntries = []stressEntry{
  152. {weight: 0.7, f: newStressPut(kvc, s.keySuffixRange, s.keySize)},
  153. {weight: 0.07, f: newStressRange(kvc, s.keySuffixRange)},
  154. {weight: 0.07, f: newStressRangeInterval(kvc, s.keySuffixRange)},
  155. {weight: 0.07, f: newStressDelete(kvc, s.keySuffixRange)},
  156. {weight: 0.07, f: newStressDeleteInterval(kvc, s.keySuffixRange)},
  157. }
  158. s.stressTable = createStressTable(stressEntries)
  159. for i := 0; i < s.N; i++ {
  160. go s.run(ctx)
  161. }
  162. plog.Printf("stresser %q is started", s.Endpoint)
  163. return nil
  164. }
  165. func (s *stresser) run(ctx context.Context) {
  166. defer s.wg.Done()
  167. for {
  168. if err := s.rateLimiter.Wait(ctx); err == context.Canceled {
  169. return
  170. }
  171. // TODO: 10-second is enough timeout to cover leader failure
  172. // and immediate leader election. Find out what other cases this
  173. // could be timed out.
  174. sctx, scancel := context.WithTimeout(ctx, 10*time.Second)
  175. err := s.stressTable.choose()(sctx)
  176. scancel()
  177. if err != nil {
  178. s.mu.Lock()
  179. s.failure++
  180. s.mu.Unlock()
  181. switch grpc.ErrorDesc(err) {
  182. case context.DeadlineExceeded.Error():
  183. // This retries when request is triggered at the same time as
  184. // leader failure. When we terminate the leader, the request to
  185. // that leader cannot be processed, and times out. Also requests
  186. // to followers cannot be forwarded to the old leader, so timing out
  187. // as well. We want to keep stressing until the cluster elects a
  188. // new leader and start processing requests again.
  189. continue
  190. case etcdserver.ErrTimeoutDueToLeaderFail.Error(), etcdserver.ErrTimeout.Error():
  191. // This retries when request is triggered at the same time as
  192. // leader failure and follower nodes receive time out errors
  193. // from losing their leader. Followers should retry to connect
  194. // to the new leader.
  195. continue
  196. case etcdserver.ErrStopped.Error():
  197. // one of the etcd nodes stopped from failure injection
  198. continue
  199. case transport.ErrConnClosing.Desc:
  200. // server closed the transport (failure injected node)
  201. continue
  202. case rpctypes.ErrNotCapable.Error():
  203. // capability check has not been done (in the beginning)
  204. continue
  205. case rpctypes.ErrTooManyRequests.Error():
  206. // hitting the recovering member.
  207. continue
  208. case context.Canceled.Error():
  209. // from stresser.Cancel method:
  210. return
  211. case grpc.ErrClientConnClosing.Error():
  212. // from stresser.Cancel method:
  213. return
  214. }
  215. su, fa := s.Report()
  216. plog.Warningf("stresser %v (success %d, failure %d) exited with error (%v)", s.Endpoint, su, fa, err)
  217. return
  218. }
  219. s.mu.Lock()
  220. s.success++
  221. s.mu.Unlock()
  222. }
  223. }
  224. func (s *stresser) Cancel() {
  225. s.mu.Lock()
  226. s.cancel()
  227. s.conn.Close()
  228. wg := s.wg
  229. s.mu.Unlock()
  230. wg.Wait()
  231. plog.Printf("stresser %q is canceled", s.Endpoint)
  232. }
  233. func (s *stresser) Report() (int, int) {
  234. s.mu.Lock()
  235. defer s.mu.Unlock()
  236. return s.success, s.failure
  237. }
  238. type stresserV2 struct {
  239. Endpoint string
  240. keySize int
  241. keySuffixRange int
  242. N int
  243. mu sync.Mutex
  244. failure int
  245. success int
  246. cancel func()
  247. }
  248. func (s *stresserV2) Stress() error {
  249. cfg := clientV2.Config{
  250. Endpoints: []string{s.Endpoint},
  251. Transport: &http.Transport{
  252. Dial: (&net.Dialer{
  253. Timeout: time.Second,
  254. KeepAlive: 30 * time.Second,
  255. }).Dial,
  256. MaxIdleConnsPerHost: s.N,
  257. },
  258. }
  259. c, err := clientV2.New(cfg)
  260. if err != nil {
  261. return err
  262. }
  263. kv := clientV2.NewKeysAPI(c)
  264. ctx, cancel := context.WithCancel(context.Background())
  265. s.cancel = cancel
  266. for i := 0; i < s.N; i++ {
  267. go func() {
  268. for {
  269. setctx, setcancel := context.WithTimeout(ctx, clientV2.DefaultRequestTimeout)
  270. key := fmt.Sprintf("foo%016x", rand.Intn(s.keySuffixRange))
  271. _, err := kv.Set(setctx, key, string(randBytes(s.keySize)), nil)
  272. setcancel()
  273. if err == context.Canceled {
  274. return
  275. }
  276. s.mu.Lock()
  277. if err != nil {
  278. s.failure++
  279. } else {
  280. s.success++
  281. }
  282. s.mu.Unlock()
  283. }
  284. }()
  285. }
  286. <-ctx.Done()
  287. return nil
  288. }
  289. func (s *stresserV2) Cancel() {
  290. s.cancel()
  291. }
  292. func (s *stresserV2) Report() (success int, failure int) {
  293. s.mu.Lock()
  294. defer s.mu.Unlock()
  295. return s.success, s.failure
  296. }
  297. func randBytes(size int) []byte {
  298. data := make([]byte, size)
  299. for i := 0; i < size; i++ {
  300. data[i] = byte(int('a') + rand.Intn(26))
  301. }
  302. return data
  303. }