key_stresser.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright 2016 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. "context"
  17. "fmt"
  18. "math/rand"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. "github.com/coreos/etcd/etcdserver"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  24. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  25. "golang.org/x/time/rate"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/transport"
  28. )
  29. type keyStresser struct {
  30. Endpoint string
  31. keyLargeSize int
  32. keySize int
  33. keySuffixRange int
  34. keyTxnSuffixRange int
  35. keyTxnOps int
  36. N int
  37. rateLimiter *rate.Limiter
  38. wg sync.WaitGroup
  39. cancel func()
  40. conn *grpc.ClientConn
  41. // atomicModifiedKeys records the number of keys created and deleted by the stresser.
  42. atomicModifiedKeys int64
  43. stressTable *stressTable
  44. }
  45. func (s *keyStresser) Stress() error {
  46. // TODO: add backoff option
  47. conn, err := grpc.Dial(s.Endpoint, grpc.WithInsecure())
  48. if err != nil {
  49. return fmt.Errorf("%v (%s)", err, s.Endpoint)
  50. }
  51. ctx, cancel := context.WithCancel(context.Background())
  52. s.wg.Add(s.N)
  53. s.conn = conn
  54. s.cancel = cancel
  55. kvc := pb.NewKVClient(conn)
  56. var stressEntries = []stressEntry{
  57. {weight: 0.7, f: newStressPut(kvc, s.keySuffixRange, s.keySize)},
  58. {
  59. weight: 0.7 * float32(s.keySize) / float32(s.keyLargeSize),
  60. f: newStressPut(kvc, s.keySuffixRange, s.keyLargeSize),
  61. },
  62. {weight: 0.07, f: newStressRange(kvc, s.keySuffixRange)},
  63. {weight: 0.07, f: newStressRangeInterval(kvc, s.keySuffixRange)},
  64. {weight: 0.07, f: newStressDelete(kvc, s.keySuffixRange)},
  65. {weight: 0.07, f: newStressDeleteInterval(kvc, s.keySuffixRange)},
  66. }
  67. if s.keyTxnSuffixRange > 0 {
  68. // adjust to make up ±70% of workloads with writes
  69. stressEntries[0].weight = 0.35
  70. stressEntries = append(stressEntries, stressEntry{
  71. weight: 0.35,
  72. f: newStressTxn(kvc, s.keyTxnSuffixRange, s.keyTxnOps),
  73. })
  74. }
  75. s.stressTable = createStressTable(stressEntries)
  76. for i := 0; i < s.N; i++ {
  77. go s.run(ctx)
  78. }
  79. plog.Infof("keyStresser %q is started", s.Endpoint)
  80. return nil
  81. }
  82. func (s *keyStresser) run(ctx context.Context) {
  83. defer s.wg.Done()
  84. for {
  85. if err := s.rateLimiter.Wait(ctx); err == context.Canceled {
  86. return
  87. }
  88. // TODO: 10-second is enough timeout to cover leader failure
  89. // and immediate leader election. Find out what other cases this
  90. // could be timed out.
  91. sctx, scancel := context.WithTimeout(ctx, 10*time.Second)
  92. err, modifiedKeys := s.stressTable.choose()(sctx)
  93. scancel()
  94. if err == nil {
  95. atomic.AddInt64(&s.atomicModifiedKeys, modifiedKeys)
  96. continue
  97. }
  98. switch rpctypes.ErrorDesc(err) {
  99. case context.DeadlineExceeded.Error():
  100. // This retries when request is triggered at the same time as
  101. // leader failure. When we terminate the leader, the request to
  102. // that leader cannot be processed, and times out. Also requests
  103. // to followers cannot be forwarded to the old leader, so timing out
  104. // as well. We want to keep stressing until the cluster elects a
  105. // new leader and start processing requests again.
  106. case etcdserver.ErrTimeoutDueToLeaderFail.Error(), etcdserver.ErrTimeout.Error():
  107. // This retries when request is triggered at the same time as
  108. // leader failure and follower nodes receive time out errors
  109. // from losing their leader. Followers should retry to connect
  110. // to the new leader.
  111. case etcdserver.ErrStopped.Error():
  112. // one of the etcd nodes stopped from failure injection
  113. case transport.ErrConnClosing.Desc:
  114. // server closed the transport (failure injected node)
  115. case rpctypes.ErrNotCapable.Error():
  116. // capability check has not been done (in the beginning)
  117. case rpctypes.ErrTooManyRequests.Error():
  118. // hitting the recovering member.
  119. case context.Canceled.Error():
  120. // from stresser.Cancel method:
  121. return
  122. case grpc.ErrClientConnClosing.Error():
  123. // from stresser.Cancel method:
  124. return
  125. default:
  126. plog.Errorf("keyStresser %v exited with error (%v)", s.Endpoint, err)
  127. return
  128. }
  129. }
  130. }
  131. func (s *keyStresser) Pause() {
  132. s.Close()
  133. }
  134. func (s *keyStresser) Close() {
  135. s.cancel()
  136. s.conn.Close()
  137. s.wg.Wait()
  138. plog.Infof("keyStresser %q is closed", s.Endpoint)
  139. }
  140. func (s *keyStresser) ModifiedKeys() int64 {
  141. return atomic.LoadInt64(&s.atomicModifiedKeys)
  142. }
  143. func (s *keyStresser) Checker() Checker { return nil }
  144. type stressFunc func(ctx context.Context) (err error, modifiedKeys int64)
  145. type stressEntry struct {
  146. weight float32
  147. f stressFunc
  148. }
  149. type stressTable struct {
  150. entries []stressEntry
  151. sumWeights float32
  152. }
  153. func createStressTable(entries []stressEntry) *stressTable {
  154. st := stressTable{entries: entries}
  155. for _, entry := range st.entries {
  156. st.sumWeights += entry.weight
  157. }
  158. return &st
  159. }
  160. func (st *stressTable) choose() stressFunc {
  161. v := rand.Float32() * st.sumWeights
  162. var sum float32
  163. var idx int
  164. for i := range st.entries {
  165. sum += st.entries[i].weight
  166. if sum >= v {
  167. idx = i
  168. break
  169. }
  170. }
  171. return st.entries[idx].f
  172. }
  173. func newStressPut(kvc pb.KVClient, keySuffixRange, keySize int) stressFunc {
  174. return func(ctx context.Context) (error, int64) {
  175. _, err := kvc.Put(ctx, &pb.PutRequest{
  176. Key: []byte(fmt.Sprintf("foo%016x", rand.Intn(keySuffixRange))),
  177. Value: randBytes(keySize),
  178. }, grpc.FailFast(false))
  179. return err, 1
  180. }
  181. }
  182. func newStressTxn(kvc pb.KVClient, keyTxnSuffixRange, txnOps int) stressFunc {
  183. keys := make([]string, keyTxnSuffixRange)
  184. for i := range keys {
  185. keys[i] = fmt.Sprintf("/k%03d", i)
  186. }
  187. return writeTxn(kvc, keys, txnOps)
  188. }
  189. func writeTxn(kvc pb.KVClient, keys []string, txnOps int) stressFunc {
  190. return func(ctx context.Context) (error, int64) {
  191. ks := make(map[string]struct{}, txnOps)
  192. for len(ks) != txnOps {
  193. ks[keys[rand.Intn(len(keys))]] = struct{}{}
  194. }
  195. selected := make([]string, 0, txnOps)
  196. for k := range ks {
  197. selected = append(selected, k)
  198. }
  199. com, delOp, putOp := getTxnReqs(selected[0], "bar00")
  200. txnReq := &pb.TxnRequest{
  201. Compare: []*pb.Compare{com},
  202. Success: []*pb.RequestOp{delOp},
  203. Failure: []*pb.RequestOp{putOp},
  204. }
  205. // add nested txns if any
  206. for i := 1; i < txnOps; i++ {
  207. k, v := selected[i], fmt.Sprintf("bar%02d", i)
  208. com, delOp, putOp = getTxnReqs(k, v)
  209. nested := &pb.RequestOp{
  210. Request: &pb.RequestOp_RequestTxn{
  211. RequestTxn: &pb.TxnRequest{
  212. Compare: []*pb.Compare{com},
  213. Success: []*pb.RequestOp{delOp},
  214. Failure: []*pb.RequestOp{putOp},
  215. },
  216. },
  217. }
  218. txnReq.Success = append(txnReq.Success, nested)
  219. txnReq.Failure = append(txnReq.Failure, nested)
  220. }
  221. _, err := kvc.Txn(ctx, txnReq, grpc.FailFast(false))
  222. return err, int64(txnOps)
  223. }
  224. }
  225. func getTxnReqs(key, val string) (com *pb.Compare, delOp *pb.RequestOp, putOp *pb.RequestOp) {
  226. // if key exists (version > 0)
  227. com = &pb.Compare{
  228. Key: []byte(key),
  229. Target: pb.Compare_VERSION,
  230. Result: pb.Compare_GREATER,
  231. TargetUnion: &pb.Compare_Version{Version: 0},
  232. }
  233. delOp = &pb.RequestOp{
  234. Request: &pb.RequestOp_RequestDeleteRange{
  235. RequestDeleteRange: &pb.DeleteRangeRequest{
  236. Key: []byte(key),
  237. },
  238. },
  239. }
  240. putOp = &pb.RequestOp{
  241. Request: &pb.RequestOp_RequestPut{
  242. RequestPut: &pb.PutRequest{
  243. Key: []byte(key),
  244. Value: []byte(val),
  245. },
  246. },
  247. }
  248. return com, delOp, putOp
  249. }
  250. func newStressRange(kvc pb.KVClient, keySuffixRange int) stressFunc {
  251. return func(ctx context.Context) (error, int64) {
  252. _, err := kvc.Range(ctx, &pb.RangeRequest{
  253. Key: []byte(fmt.Sprintf("foo%016x", rand.Intn(keySuffixRange))),
  254. }, grpc.FailFast(false))
  255. return err, 0
  256. }
  257. }
  258. func newStressRangeInterval(kvc pb.KVClient, keySuffixRange int) stressFunc {
  259. return func(ctx context.Context) (error, int64) {
  260. start := rand.Intn(keySuffixRange)
  261. end := start + 500
  262. _, err := kvc.Range(ctx, &pb.RangeRequest{
  263. Key: []byte(fmt.Sprintf("foo%016x", start)),
  264. RangeEnd: []byte(fmt.Sprintf("foo%016x", end)),
  265. }, grpc.FailFast(false))
  266. return err, 0
  267. }
  268. }
  269. func newStressDelete(kvc pb.KVClient, keySuffixRange int) stressFunc {
  270. return func(ctx context.Context) (error, int64) {
  271. _, err := kvc.DeleteRange(ctx, &pb.DeleteRangeRequest{
  272. Key: []byte(fmt.Sprintf("foo%016x", rand.Intn(keySuffixRange))),
  273. }, grpc.FailFast(false))
  274. return err, 1
  275. }
  276. }
  277. func newStressDeleteInterval(kvc pb.KVClient, keySuffixRange int) stressFunc {
  278. return func(ctx context.Context) (error, int64) {
  279. start := rand.Intn(keySuffixRange)
  280. end := start + 500
  281. resp, err := kvc.DeleteRange(ctx, &pb.DeleteRangeRequest{
  282. Key: []byte(fmt.Sprintf("foo%016x", start)),
  283. RangeEnd: []byte(fmt.Sprintf("foo%016x", end)),
  284. }, grpc.FailFast(false))
  285. if err == nil {
  286. return nil, resp.Deleted
  287. }
  288. return err, 0
  289. }
  290. }