put.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 cmd
  15. import (
  16. "context"
  17. "encoding/binary"
  18. "fmt"
  19. "math"
  20. "math/rand"
  21. "os"
  22. "strings"
  23. "time"
  24. v3 "go.etcd.io/etcd/clientv3"
  25. "go.etcd.io/etcd/pkg/report"
  26. "github.com/dustin/go-humanize"
  27. "github.com/spf13/cobra"
  28. "golang.org/x/time/rate"
  29. "gopkg.in/cheggaaa/pb.v1"
  30. )
  31. // putCmd represents the put command
  32. var putCmd = &cobra.Command{
  33. Use: "put",
  34. Short: "Benchmark put",
  35. Run: putFunc,
  36. }
  37. var (
  38. keySize int
  39. valSize int
  40. putTotal int
  41. putRate int
  42. keySpaceSize int
  43. seqKeys bool
  44. compactInterval time.Duration
  45. compactIndexDelta int64
  46. checkHashkv bool
  47. )
  48. func init() {
  49. RootCmd.AddCommand(putCmd)
  50. putCmd.Flags().IntVar(&keySize, "key-size", 8, "Key size of put request")
  51. putCmd.Flags().IntVar(&valSize, "val-size", 8, "Value size of put request")
  52. putCmd.Flags().IntVar(&putRate, "rate", 0, "Maximum puts per second (0 is no limit)")
  53. putCmd.Flags().IntVar(&putTotal, "total", 10000, "Total number of put requests")
  54. putCmd.Flags().IntVar(&keySpaceSize, "key-space-size", 1, "Maximum possible keys")
  55. putCmd.Flags().BoolVar(&seqKeys, "sequential-keys", false, "Use sequential keys")
  56. putCmd.Flags().DurationVar(&compactInterval, "compact-interval", 0, `Interval to compact database (do not duplicate this with etcd's 'auto-compaction-retention' flag) (e.g. --compact-interval=5m compacts every 5-minute)`)
  57. putCmd.Flags().Int64Var(&compactIndexDelta, "compact-index-delta", 1000, "Delta between current revision and compact revision (e.g. current revision 10000, compact at 9000)")
  58. putCmd.Flags().BoolVar(&checkHashkv, "check-hashkv", false, "'true' to check hashkv")
  59. }
  60. func putFunc(cmd *cobra.Command, args []string) {
  61. if keySpaceSize <= 0 {
  62. fmt.Fprintf(os.Stderr, "expected positive --key-space-size, got (%v)", keySpaceSize)
  63. os.Exit(1)
  64. }
  65. requests := make(chan v3.Op, totalClients)
  66. if putRate == 0 {
  67. putRate = math.MaxInt32
  68. }
  69. limit := rate.NewLimiter(rate.Limit(putRate), 1)
  70. clients := mustCreateClients(totalClients, totalConns)
  71. k, v := make([]byte, keySize), string(mustRandBytes(valSize))
  72. bar = pb.New(putTotal)
  73. bar.Format("Bom !")
  74. bar.Start()
  75. r := newReport()
  76. for i := range clients {
  77. wg.Add(1)
  78. go func(c *v3.Client) {
  79. defer wg.Done()
  80. for op := range requests {
  81. limit.Wait(context.Background())
  82. st := time.Now()
  83. _, err := c.Do(context.Background(), op)
  84. r.Results() <- report.Result{Err: err, Start: st, End: time.Now()}
  85. bar.Increment()
  86. }
  87. }(clients[i])
  88. }
  89. go func() {
  90. for i := 0; i < putTotal; i++ {
  91. if seqKeys {
  92. binary.PutVarint(k, int64(i%keySpaceSize))
  93. } else {
  94. binary.PutVarint(k, int64(rand.Intn(keySpaceSize)))
  95. }
  96. requests <- v3.OpPut(string(k), v)
  97. }
  98. close(requests)
  99. }()
  100. if compactInterval > 0 {
  101. go func() {
  102. for {
  103. time.Sleep(compactInterval)
  104. compactKV(clients)
  105. }
  106. }()
  107. }
  108. rc := r.Run()
  109. wg.Wait()
  110. close(r.Results())
  111. bar.Finish()
  112. fmt.Println(<-rc)
  113. if checkHashkv {
  114. hashKV(cmd, clients)
  115. }
  116. }
  117. func compactKV(clients []*v3.Client) {
  118. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  119. resp, err := clients[0].KV.Get(ctx, "foo")
  120. cancel()
  121. if err != nil {
  122. panic(err)
  123. }
  124. revToCompact := max(0, resp.Header.Revision-compactIndexDelta)
  125. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
  126. _, err = clients[0].KV.Compact(ctx, revToCompact)
  127. cancel()
  128. if err != nil {
  129. panic(err)
  130. }
  131. }
  132. func max(n1, n2 int64) int64 {
  133. if n1 > n2 {
  134. return n1
  135. }
  136. return n2
  137. }
  138. func hashKV(cmd *cobra.Command, clients []*v3.Client) {
  139. eps, err := cmd.Flags().GetStringSlice("endpoints")
  140. if err != nil {
  141. panic(err)
  142. }
  143. for i, ip := range eps {
  144. eps[i] = strings.TrimSpace(ip)
  145. }
  146. host := eps[0]
  147. st := time.Now()
  148. clients[0].HashKV(context.Background(), eps[0], 0)
  149. rh, eh := clients[0].HashKV(context.Background(), host, 0)
  150. if eh != nil {
  151. fmt.Fprintf(os.Stderr, "Failed to get the hashkv of endpoint %s (%v)\n", host, eh)
  152. panic(err)
  153. }
  154. rt, es := clients[0].Status(context.Background(), host)
  155. if es != nil {
  156. fmt.Fprintf(os.Stderr, "Failed to get the status of endpoint %s (%v)\n", host, es)
  157. panic(err)
  158. }
  159. rs := "HashKV Summary:\n"
  160. rs += fmt.Sprintf("\tHashKV: %d\n", rh.Hash)
  161. rs += fmt.Sprintf("\tEndpoint: %s\n", host)
  162. rs += fmt.Sprintf("\tTime taken to get hashkv: %v\n", time.Since(st))
  163. rs += fmt.Sprintf("\tDB size: %s", humanize.Bytes(uint64(rt.DbSize)))
  164. fmt.Println(rs)
  165. }