stresser.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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%d", 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%d", rand.Intn(keySuffixRange))),
  77. }, grpc.FailFast(false))
  78. return err
  79. }
  80. }
  81. func newStressRangePrefix(kvc pb.KVClient, keySuffixRange int) stressFunc {
  82. return func(ctx context.Context) error {
  83. _, err := kvc.Range(ctx, &pb.RangeRequest{
  84. Key: []byte("foo"),
  85. RangeEnd: []byte(fmt.Sprintf("foo%d", rand.Intn(keySuffixRange))),
  86. }, grpc.FailFast(false))
  87. return err
  88. }
  89. }
  90. func newStressDelete(kvc pb.KVClient, keySuffixRange int) stressFunc {
  91. return func(ctx context.Context) error {
  92. _, err := kvc.DeleteRange(ctx, &pb.DeleteRangeRequest{
  93. Key: []byte(fmt.Sprintf("foo%d", rand.Intn(keySuffixRange))),
  94. }, grpc.FailFast(false))
  95. return err
  96. }
  97. }
  98. func newStressDeletePrefix(kvc pb.KVClient, keySuffixRange int) stressFunc {
  99. return func(ctx context.Context) error {
  100. _, err := kvc.DeleteRange(ctx, &pb.DeleteRangeRequest{
  101. Key: []byte("foo"),
  102. RangeEnd: []byte(fmt.Sprintf("foo%d", rand.Intn(keySuffixRange))),
  103. }, grpc.FailFast(false))
  104. return err
  105. }
  106. }
  107. type Stresser interface {
  108. // Stress starts to stress the etcd cluster
  109. Stress() error
  110. // Cancel cancels the stress test on the etcd cluster
  111. Cancel()
  112. // Report reports the success and failure of the stress test
  113. Report() (success int, failure int)
  114. }
  115. type stresser struct {
  116. Endpoint string
  117. KeySize int
  118. KeySuffixRange int
  119. qps int
  120. N int
  121. mu sync.Mutex
  122. wg *sync.WaitGroup
  123. rateLimiter *rate.Limiter
  124. cancel func()
  125. conn *grpc.ClientConn
  126. success int
  127. stressTable *stressTable
  128. }
  129. func (s *stresser) Stress() error {
  130. // TODO: add backoff option
  131. conn, err := grpc.Dial(s.Endpoint, grpc.WithInsecure())
  132. if err != nil {
  133. return fmt.Errorf("%v (%s)", err, s.Endpoint)
  134. }
  135. ctx, cancel := context.WithCancel(context.Background())
  136. wg := &sync.WaitGroup{}
  137. wg.Add(s.N)
  138. s.mu.Lock()
  139. s.conn = conn
  140. s.cancel = cancel
  141. s.wg = wg
  142. s.rateLimiter = rate.NewLimiter(rate.Every(time.Second), s.qps)
  143. s.mu.Unlock()
  144. kvc := pb.NewKVClient(conn)
  145. var stressEntries = []stressEntry{
  146. {weight: 0.7, f: newStressPut(kvc, s.KeySuffixRange, s.KeySize)},
  147. {weight: 0.07, f: newStressRange(kvc, s.KeySuffixRange)},
  148. {weight: 0.07, f: newStressRangePrefix(kvc, s.KeySuffixRange)},
  149. {weight: 0.07, f: newStressDelete(kvc, s.KeySuffixRange)},
  150. {weight: 0.07, f: newStressDeletePrefix(kvc, s.KeySuffixRange)},
  151. }
  152. s.stressTable = createStressTable(stressEntries)
  153. for i := 0; i < s.N; i++ {
  154. go s.run(ctx, kvc)
  155. }
  156. plog.Printf("stresser %q is started", s.Endpoint)
  157. return nil
  158. }
  159. func (s *stresser) run(ctx context.Context, kvc pb.KVClient) {
  160. defer s.wg.Done()
  161. for {
  162. if err := s.rateLimiter.Wait(ctx); err == context.Canceled {
  163. return
  164. }
  165. // TODO: 10-second is enough timeout to cover leader failure
  166. // and immediate leader election. Find out what other cases this
  167. // could be timed out.
  168. sctx, scancel := context.WithTimeout(ctx, 10*time.Second)
  169. err := s.stressTable.choose()(sctx)
  170. scancel()
  171. if err != nil {
  172. shouldContinue := false
  173. switch grpc.ErrorDesc(err) {
  174. case context.DeadlineExceeded.Error():
  175. // This retries when request is triggered at the same time as
  176. // leader failure. When we terminate the leader, the request to
  177. // that leader cannot be processed, and times out. Also requests
  178. // to followers cannot be forwarded to the old leader, so timing out
  179. // as well. We want to keep stressing until the cluster elects a
  180. // new leader and start processing requests again.
  181. shouldContinue = true
  182. case etcdserver.ErrTimeoutDueToLeaderFail.Error(), etcdserver.ErrTimeout.Error():
  183. // This retries when request is triggered at the same time as
  184. // leader failure and follower nodes receive time out errors
  185. // from losing their leader. Followers should retry to connect
  186. // to the new leader.
  187. shouldContinue = true
  188. case etcdserver.ErrStopped.Error():
  189. // one of the etcd nodes stopped from failure injection
  190. shouldContinue = true
  191. case transport.ErrConnClosing.Desc:
  192. // server closed the transport (failure injected node)
  193. shouldContinue = true
  194. case rpctypes.ErrNotCapable.Error():
  195. // capability check has not been done (in the beginning)
  196. shouldContinue = true
  197. // default:
  198. // errors from stresser.Cancel method:
  199. // rpc error: code = 1 desc = context canceled (type grpc.rpcError)
  200. // rpc error: code = 2 desc = grpc: the client connection is closing (type grpc.rpcError)
  201. }
  202. if shouldContinue {
  203. continue
  204. }
  205. return
  206. }
  207. s.mu.Lock()
  208. s.success++
  209. s.mu.Unlock()
  210. }
  211. }
  212. func (s *stresser) Cancel() {
  213. s.mu.Lock()
  214. s.cancel()
  215. s.conn.Close()
  216. wg := s.wg
  217. s.mu.Unlock()
  218. wg.Wait()
  219. plog.Printf("stresser %q is canceled", s.Endpoint)
  220. }
  221. func (s *stresser) Report() (int, int) {
  222. s.mu.Lock()
  223. defer s.mu.Unlock()
  224. // TODO: find a better way to report v3 tests
  225. return s.success, -1
  226. }
  227. type stresserV2 struct {
  228. Endpoint string
  229. KeySize int
  230. KeySuffixRange int
  231. N int
  232. mu sync.Mutex
  233. failure int
  234. success int
  235. cancel func()
  236. }
  237. func (s *stresserV2) Stress() error {
  238. cfg := clientV2.Config{
  239. Endpoints: []string{s.Endpoint},
  240. Transport: &http.Transport{
  241. Dial: (&net.Dialer{
  242. Timeout: time.Second,
  243. KeepAlive: 30 * time.Second,
  244. }).Dial,
  245. MaxIdleConnsPerHost: s.N,
  246. },
  247. }
  248. c, err := clientV2.New(cfg)
  249. if err != nil {
  250. return err
  251. }
  252. kv := clientV2.NewKeysAPI(c)
  253. ctx, cancel := context.WithCancel(context.Background())
  254. s.cancel = cancel
  255. for i := 0; i < s.N; i++ {
  256. go func() {
  257. for {
  258. setctx, setcancel := context.WithTimeout(ctx, clientV2.DefaultRequestTimeout)
  259. key := fmt.Sprintf("foo%d", rand.Intn(s.KeySuffixRange))
  260. _, err := kv.Set(setctx, key, string(randBytes(s.KeySize)), nil)
  261. setcancel()
  262. if err == context.Canceled {
  263. return
  264. }
  265. s.mu.Lock()
  266. if err != nil {
  267. s.failure++
  268. } else {
  269. s.success++
  270. }
  271. s.mu.Unlock()
  272. }
  273. }()
  274. }
  275. <-ctx.Done()
  276. return nil
  277. }
  278. func (s *stresserV2) Cancel() {
  279. s.cancel()
  280. }
  281. func (s *stresserV2) Report() (success int, failure int) {
  282. s.mu.Lock()
  283. defer s.mu.Unlock()
  284. return s.success, s.failure
  285. }
  286. func randBytes(size int) []byte {
  287. data := make([]byte, size)
  288. for i := 0; i < size; i++ {
  289. data[i] = byte(int('a') + rand.Intn(26))
  290. }
  291. return data
  292. }