watch.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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/rand"
  20. "os"
  21. "sync/atomic"
  22. "time"
  23. "go.etcd.io/etcd/clientv3"
  24. "go.etcd.io/etcd/pkg/report"
  25. "github.com/spf13/cobra"
  26. "golang.org/x/time/rate"
  27. "gopkg.in/cheggaaa/pb.v1"
  28. )
  29. // watchCmd represents the watch command
  30. var watchCmd = &cobra.Command{
  31. Use: "watch",
  32. Short: "Benchmark watch",
  33. Long: `Benchmark watch tests the performance of processing watch requests and
  34. sending events to watchers. It tests the sending performance by
  35. changing the value of the watched keys with concurrent put
  36. requests.
  37. During the test, each watcher watches (--total/--watchers) keys
  38. (a watcher might watch on the same key multiple times if
  39. --watched-key-total is small).
  40. Each key is watched by (--total/--watched-key-total) watchers.
  41. `,
  42. Run: watchFunc,
  43. }
  44. var (
  45. watchStreams int
  46. watchWatchesPerStream int
  47. watchedKeyTotal int
  48. watchPutRate int
  49. watchPutTotal int
  50. watchKeySize int
  51. watchKeySpaceSize int
  52. watchSeqKeys bool
  53. )
  54. type watchedKeys struct {
  55. watched []string
  56. numWatchers map[string]int
  57. watches []clientv3.WatchChan
  58. // ctx to control all watches
  59. ctx context.Context
  60. cancel context.CancelFunc
  61. }
  62. func init() {
  63. RootCmd.AddCommand(watchCmd)
  64. watchCmd.Flags().IntVar(&watchStreams, "streams", 10, "Total watch streams")
  65. watchCmd.Flags().IntVar(&watchWatchesPerStream, "watch-per-stream", 100, "Total watchers per stream")
  66. watchCmd.Flags().IntVar(&watchedKeyTotal, "watched-key-total", 1, "Total number of keys to be watched")
  67. watchCmd.Flags().IntVar(&watchPutRate, "put-rate", 0, "Number of keys to put per second")
  68. watchCmd.Flags().IntVar(&watchPutTotal, "put-total", 1000, "Number of put requests")
  69. watchCmd.Flags().IntVar(&watchKeySize, "key-size", 32, "Key size of watch request")
  70. watchCmd.Flags().IntVar(&watchKeySpaceSize, "key-space-size", 1, "Maximum possible keys")
  71. watchCmd.Flags().BoolVar(&watchSeqKeys, "sequential-keys", false, "Use sequential keys")
  72. }
  73. func watchFunc(cmd *cobra.Command, args []string) {
  74. if watchKeySpaceSize <= 0 {
  75. fmt.Fprintf(os.Stderr, "expected positive --key-space-size, got (%v)", watchKeySpaceSize)
  76. os.Exit(1)
  77. }
  78. grpcConns := int(totalClients)
  79. if totalClients > totalConns {
  80. grpcConns = int(totalConns)
  81. }
  82. wantedConns := 1 + (watchStreams / 100)
  83. if grpcConns < wantedConns {
  84. fmt.Fprintf(os.Stderr, "warning: grpc limits 100 streams per client connection, have %d but need %d\n", grpcConns, wantedConns)
  85. }
  86. clients := mustCreateClients(totalClients, totalConns)
  87. wk := newWatchedKeys()
  88. benchMakeWatches(clients, wk)
  89. benchPutWatches(clients, wk)
  90. }
  91. func benchMakeWatches(clients []*clientv3.Client, wk *watchedKeys) {
  92. streams := make([]clientv3.Watcher, watchStreams)
  93. for i := range streams {
  94. streams[i] = clientv3.NewWatcher(clients[i%len(clients)])
  95. }
  96. keyc := make(chan string, watchStreams)
  97. bar = pb.New(watchStreams * watchWatchesPerStream)
  98. bar.Format("Bom !")
  99. bar.Start()
  100. r := newReport()
  101. rch := r.Results()
  102. wg.Add(len(streams) + 1)
  103. wc := make(chan []clientv3.WatchChan, len(streams))
  104. for _, s := range streams {
  105. go func(s clientv3.Watcher) {
  106. defer wg.Done()
  107. var ws []clientv3.WatchChan
  108. for i := 0; i < watchWatchesPerStream; i++ {
  109. k := <-keyc
  110. st := time.Now()
  111. wch := s.Watch(wk.ctx, k)
  112. rch <- report.Result{Start: st, End: time.Now()}
  113. ws = append(ws, wch)
  114. bar.Increment()
  115. }
  116. wc <- ws
  117. }(s)
  118. }
  119. go func() {
  120. defer func() {
  121. close(keyc)
  122. wg.Done()
  123. }()
  124. for i := 0; i < watchStreams*watchWatchesPerStream; i++ {
  125. key := wk.watched[i%len(wk.watched)]
  126. keyc <- key
  127. wk.numWatchers[key]++
  128. }
  129. }()
  130. rc := r.Run()
  131. wg.Wait()
  132. bar.Finish()
  133. close(r.Results())
  134. fmt.Printf("Watch creation summary:\n%s", <-rc)
  135. for i := 0; i < len(streams); i++ {
  136. wk.watches = append(wk.watches, (<-wc)...)
  137. }
  138. }
  139. func newWatchedKeys() *watchedKeys {
  140. watched := make([]string, watchedKeyTotal)
  141. for i := range watched {
  142. k := make([]byte, watchKeySize)
  143. if watchSeqKeys {
  144. binary.PutVarint(k, int64(i%watchKeySpaceSize))
  145. } else {
  146. binary.PutVarint(k, int64(rand.Intn(watchKeySpaceSize)))
  147. }
  148. watched[i] = string(k)
  149. }
  150. ctx, cancel := context.WithCancel(context.TODO())
  151. return &watchedKeys{
  152. watched: watched,
  153. numWatchers: make(map[string]int),
  154. ctx: ctx,
  155. cancel: cancel,
  156. }
  157. }
  158. func benchPutWatches(clients []*clientv3.Client, wk *watchedKeys) {
  159. eventsTotal := 0
  160. for i := 0; i < watchPutTotal; i++ {
  161. eventsTotal += wk.numWatchers[wk.watched[i%len(wk.watched)]]
  162. }
  163. bar = pb.New(eventsTotal)
  164. bar.Format("Bom !")
  165. bar.Start()
  166. r := newReport()
  167. wg.Add(len(wk.watches))
  168. nrRxed := int32(eventsTotal)
  169. for _, w := range wk.watches {
  170. go func(wc clientv3.WatchChan) {
  171. defer wg.Done()
  172. recvWatchChan(wc, r.Results(), &nrRxed)
  173. wk.cancel()
  174. }(w)
  175. }
  176. putreqc := make(chan clientv3.Op, len(clients))
  177. go func() {
  178. defer close(putreqc)
  179. for i := 0; i < watchPutTotal; i++ {
  180. putreqc <- clientv3.OpPut(wk.watched[i%(len(wk.watched))], "data")
  181. }
  182. }()
  183. limit := rate.NewLimiter(rate.Limit(watchPutRate), 1)
  184. for _, cc := range clients {
  185. go func(c *clientv3.Client) {
  186. for op := range putreqc {
  187. if err := limit.Wait(context.TODO()); err != nil {
  188. panic(err)
  189. }
  190. if _, err := c.Do(context.TODO(), op); err != nil {
  191. panic(err)
  192. }
  193. }
  194. }(cc)
  195. }
  196. rc := r.Run()
  197. wg.Wait()
  198. bar.Finish()
  199. close(r.Results())
  200. fmt.Printf("Watch events received summary:\n%s", <-rc)
  201. }
  202. func recvWatchChan(wch clientv3.WatchChan, results chan<- report.Result, nrRxed *int32) {
  203. for r := range wch {
  204. st := time.Now()
  205. for range r.Events {
  206. results <- report.Result{Start: st, End: time.Now()}
  207. bar.Increment()
  208. if atomic.AddInt32(nrRxed, -1) <= 0 {
  209. return
  210. }
  211. }
  212. }
  213. }