stm.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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 cmd
  15. import (
  16. "context"
  17. "encoding/binary"
  18. "fmt"
  19. "math"
  20. "math/rand"
  21. "os"
  22. "time"
  23. v3 "go.etcd.io/etcd/clientv3"
  24. v3sync "go.etcd.io/etcd/clientv3/concurrency"
  25. "go.etcd.io/etcd/etcdserver/api/v3lock/v3lockpb"
  26. "go.etcd.io/etcd/pkg/report"
  27. "github.com/spf13/cobra"
  28. "golang.org/x/time/rate"
  29. "gopkg.in/cheggaaa/pb.v1"
  30. )
  31. // stmCmd represents the STM benchmark command
  32. var stmCmd = &cobra.Command{
  33. Use: "stm",
  34. Short: "Benchmark STM",
  35. Run: stmFunc,
  36. }
  37. type stmApply func(v3sync.STM) error
  38. var (
  39. stmIsolation string
  40. stmIso v3sync.Isolation
  41. stmTotal int
  42. stmKeysPerTxn int
  43. stmKeyCount int
  44. stmValSize int
  45. stmWritePercent int
  46. stmLocker string
  47. stmRate int
  48. )
  49. func init() {
  50. RootCmd.AddCommand(stmCmd)
  51. stmCmd.Flags().StringVar(&stmIsolation, "isolation", "r", "Read Committed (c), Repeatable Reads (r), Serializable (s), or Snapshot (ss)")
  52. stmCmd.Flags().IntVar(&stmKeyCount, "keys", 1, "Total unique keys accessible by the benchmark")
  53. stmCmd.Flags().IntVar(&stmTotal, "total", 10000, "Total number of completed STM transactions")
  54. stmCmd.Flags().IntVar(&stmKeysPerTxn, "keys-per-txn", 1, "Number of keys to access per transaction")
  55. stmCmd.Flags().IntVar(&stmWritePercent, "txn-wr-percent", 50, "Percentage of keys to overwrite per transaction")
  56. stmCmd.Flags().StringVar(&stmLocker, "stm-locker", "stm", "Wrap STM transaction with a custom locking mechanism (stm, lock-client, lock-rpc)")
  57. stmCmd.Flags().IntVar(&stmValSize, "val-size", 8, "Value size of each STM put request")
  58. stmCmd.Flags().IntVar(&stmRate, "rate", 0, "Maximum STM transactions per second (0 is no limit)")
  59. }
  60. func stmFunc(cmd *cobra.Command, args []string) {
  61. if stmKeyCount <= 0 {
  62. fmt.Fprintf(os.Stderr, "expected positive --keys, got (%v)", stmKeyCount)
  63. os.Exit(1)
  64. }
  65. if stmWritePercent < 0 || stmWritePercent > 100 {
  66. fmt.Fprintf(os.Stderr, "expected [0, 100] --txn-wr-percent, got (%v)", stmWritePercent)
  67. os.Exit(1)
  68. }
  69. if stmKeysPerTxn < 0 || stmKeysPerTxn > stmKeyCount {
  70. fmt.Fprintf(os.Stderr, "expected --keys-per-txn between 0 and %v, got (%v)", stmKeyCount, stmKeysPerTxn)
  71. os.Exit(1)
  72. }
  73. switch stmIsolation {
  74. case "c":
  75. stmIso = v3sync.ReadCommitted
  76. case "r":
  77. stmIso = v3sync.RepeatableReads
  78. case "s":
  79. stmIso = v3sync.Serializable
  80. case "ss":
  81. stmIso = v3sync.SerializableSnapshot
  82. default:
  83. fmt.Fprintln(os.Stderr, cmd.Usage())
  84. os.Exit(1)
  85. }
  86. if stmRate == 0 {
  87. stmRate = math.MaxInt32
  88. }
  89. limit := rate.NewLimiter(rate.Limit(stmRate), 1)
  90. requests := make(chan stmApply, totalClients)
  91. clients := mustCreateClients(totalClients, totalConns)
  92. bar = pb.New(stmTotal)
  93. bar.Format("Bom !")
  94. bar.Start()
  95. r := newReport()
  96. for i := range clients {
  97. wg.Add(1)
  98. go doSTM(clients[i], requests, r.Results())
  99. }
  100. go func() {
  101. for i := 0; i < stmTotal; i++ {
  102. kset := make(map[string]struct{})
  103. for len(kset) != stmKeysPerTxn {
  104. k := make([]byte, 16)
  105. binary.PutVarint(k, int64(rand.Intn(stmKeyCount)))
  106. s := string(k)
  107. kset[s] = struct{}{}
  108. }
  109. applyf := func(s v3sync.STM) error {
  110. limit.Wait(context.Background())
  111. wrs := int(float32(len(kset)*stmWritePercent) / 100.0)
  112. for k := range kset {
  113. s.Get(k)
  114. if wrs > 0 {
  115. s.Put(k, string(mustRandBytes(stmValSize)))
  116. wrs--
  117. }
  118. }
  119. return nil
  120. }
  121. requests <- applyf
  122. }
  123. close(requests)
  124. }()
  125. rc := r.Run()
  126. wg.Wait()
  127. close(r.Results())
  128. bar.Finish()
  129. fmt.Printf("%s", <-rc)
  130. }
  131. func doSTM(client *v3.Client, requests <-chan stmApply, results chan<- report.Result) {
  132. defer wg.Done()
  133. lock, unlock := func() error { return nil }, func() error { return nil }
  134. switch stmLocker {
  135. case "lock-client":
  136. s, err := v3sync.NewSession(client)
  137. if err != nil {
  138. panic(err)
  139. }
  140. defer s.Close()
  141. m := v3sync.NewMutex(s, "stmlock")
  142. lock = func() error { return m.Lock(context.TODO()) }
  143. unlock = func() error { return m.Unlock(context.TODO()) }
  144. case "lock-rpc":
  145. var lockKey []byte
  146. s, err := v3sync.NewSession(client)
  147. if err != nil {
  148. panic(err)
  149. }
  150. defer s.Close()
  151. lc := v3lockpb.NewLockClient(client.ActiveConnection())
  152. lock = func() error {
  153. req := &v3lockpb.LockRequest{Name: []byte("stmlock"), Lease: int64(s.Lease())}
  154. resp, err := lc.Lock(context.TODO(), req)
  155. if resp != nil {
  156. lockKey = resp.Key
  157. }
  158. return err
  159. }
  160. unlock = func() error {
  161. req := &v3lockpb.UnlockRequest{Key: lockKey}
  162. _, err := lc.Unlock(context.TODO(), req)
  163. return err
  164. }
  165. case "stm":
  166. default:
  167. fmt.Fprintf(os.Stderr, "unexpected stm locker %q\n", stmLocker)
  168. os.Exit(1)
  169. }
  170. for applyf := range requests {
  171. st := time.Now()
  172. if lerr := lock(); lerr != nil {
  173. panic(lerr)
  174. }
  175. _, err := v3sync.NewSTM(client, applyf, v3sync.WithIsolation(stmIso))
  176. if lerr := unlock(); lerr != nil {
  177. panic(lerr)
  178. }
  179. results <- report.Result{Err: err, Start: st, End: time.Now()}
  180. bar.Increment()
  181. }
  182. }