watch_command.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 runner
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "log"
  20. "sync"
  21. "time"
  22. "go.etcd.io/etcd/clientv3"
  23. "go.etcd.io/etcd/pkg/stringutil"
  24. "github.com/spf13/cobra"
  25. "golang.org/x/time/rate"
  26. )
  27. var (
  28. runningTime time.Duration // time for which operation should be performed
  29. noOfPrefixes int // total number of prefixes which will be watched upon
  30. watchPerPrefix int // number of watchers per prefix
  31. watchPrefix string // prefix append to keys in watcher
  32. totalKeys int // total number of keys for operation
  33. )
  34. // NewWatchCommand returns the cobra command for "watcher runner".
  35. func NewWatchCommand() *cobra.Command {
  36. cmd := &cobra.Command{
  37. Use: "watcher",
  38. Short: "Performs watch operation",
  39. Run: runWatcherFunc,
  40. }
  41. cmd.Flags().DurationVar(&runningTime, "running-time", 60, "number of seconds to run")
  42. cmd.Flags().StringVar(&watchPrefix, "prefix", "", "the prefix to append on all keys")
  43. cmd.Flags().IntVar(&noOfPrefixes, "total-prefixes", 10, "total no of prefixes to use")
  44. cmd.Flags().IntVar(&watchPerPrefix, "watch-per-prefix", 10, "number of watchers per prefix")
  45. cmd.Flags().IntVar(&totalKeys, "total-keys", 1000, "total number of keys to watch")
  46. return cmd
  47. }
  48. func runWatcherFunc(cmd *cobra.Command, args []string) {
  49. if len(args) > 0 {
  50. ExitWithError(ExitBadArgs, errors.New("watcher does not take any argument"))
  51. }
  52. ctx := context.Background()
  53. for round := 0; round < rounds || rounds <= 0; round++ {
  54. fmt.Println("round", round)
  55. performWatchOnPrefixes(ctx, cmd, round)
  56. }
  57. }
  58. func performWatchOnPrefixes(ctx context.Context, cmd *cobra.Command, round int) {
  59. keyPerPrefix := totalKeys / noOfPrefixes
  60. prefixes := stringutil.UniqueStrings(5, noOfPrefixes)
  61. keys := stringutil.RandomStrings(10, keyPerPrefix)
  62. roundPrefix := fmt.Sprintf("%16x", round)
  63. eps := endpointsFromFlag(cmd)
  64. var (
  65. revision int64
  66. wg sync.WaitGroup
  67. gr *clientv3.GetResponse
  68. err error
  69. )
  70. client := newClient(eps, dialTimeout)
  71. defer client.Close()
  72. gr, err = getKey(ctx, client, "non-existent")
  73. if err != nil {
  74. log.Fatalf("failed to get the initial revision: %v", err)
  75. }
  76. revision = gr.Header.Revision
  77. ctxt, cancel := context.WithDeadline(ctx, time.Now().Add(runningTime*time.Second))
  78. defer cancel()
  79. // generate and put keys in cluster
  80. limiter := rate.NewLimiter(rate.Limit(reqRate), reqRate)
  81. go func() {
  82. for _, key := range keys {
  83. for _, prefix := range prefixes {
  84. if err = limiter.Wait(ctxt); err != nil {
  85. return
  86. }
  87. if err = putKeyAtMostOnce(ctxt, client, watchPrefix+"-"+roundPrefix+"-"+prefix+"-"+key); err != nil {
  88. log.Fatalf("failed to put key: %v", err)
  89. return
  90. }
  91. }
  92. }
  93. }()
  94. ctxc, cancelc := context.WithCancel(ctx)
  95. wcs := make([]clientv3.WatchChan, 0)
  96. rcs := make([]*clientv3.Client, 0)
  97. for _, prefix := range prefixes {
  98. for j := 0; j < watchPerPrefix; j++ {
  99. rc := newClient(eps, dialTimeout)
  100. rcs = append(rcs, rc)
  101. wprefix := watchPrefix + "-" + roundPrefix + "-" + prefix
  102. wc := rc.Watch(ctxc, wprefix, clientv3.WithPrefix(), clientv3.WithRev(revision))
  103. wcs = append(wcs, wc)
  104. wg.Add(1)
  105. go func() {
  106. defer wg.Done()
  107. checkWatchResponse(wc, wprefix, keys)
  108. }()
  109. }
  110. }
  111. wg.Wait()
  112. cancelc()
  113. // verify all watch channels are closed
  114. for e, wc := range wcs {
  115. if _, ok := <-wc; ok {
  116. log.Fatalf("expected wc to be closed, but received %v", e)
  117. }
  118. }
  119. for _, rc := range rcs {
  120. rc.Close()
  121. }
  122. if err = deletePrefix(ctx, client, watchPrefix); err != nil {
  123. log.Fatalf("failed to clean up keys after test: %v", err)
  124. }
  125. }
  126. func checkWatchResponse(wc clientv3.WatchChan, prefix string, keys []string) {
  127. for n := 0; n < len(keys); {
  128. wr, more := <-wc
  129. if !more {
  130. log.Fatalf("expect more keys (received %d/%d) for %s", n, len(keys), prefix)
  131. }
  132. for _, event := range wr.Events {
  133. expectedKey := prefix + "-" + keys[n]
  134. receivedKey := string(event.Kv.Key)
  135. if expectedKey != receivedKey {
  136. log.Fatalf("expected key %q, got %q for prefix : %q\n", expectedKey, receivedKey, prefix)
  137. }
  138. n++
  139. }
  140. }
  141. }
  142. func putKeyAtMostOnce(ctx context.Context, client *clientv3.Client, key string) error {
  143. gr, err := getKey(ctx, client, key)
  144. if err != nil {
  145. return err
  146. }
  147. var modrev int64
  148. if len(gr.Kvs) > 0 {
  149. modrev = gr.Kvs[0].ModRevision
  150. }
  151. for ctx.Err() == nil {
  152. _, err := client.Txn(ctx).If(clientv3.Compare(clientv3.ModRevision(key), "=", modrev)).Then(clientv3.OpPut(key, key)).Commit()
  153. if err == nil {
  154. return nil
  155. }
  156. }
  157. return ctx.Err()
  158. }
  159. func deletePrefix(ctx context.Context, client *clientv3.Client, key string) error {
  160. for ctx.Err() == nil {
  161. if _, err := client.Delete(ctx, key, clientv3.WithPrefix()); err == nil {
  162. return nil
  163. }
  164. }
  165. return ctx.Err()
  166. }
  167. func getKey(ctx context.Context, client *clientv3.Client, key string) (*clientv3.GetResponse, error) {
  168. for ctx.Err() == nil {
  169. if gr, err := client.Get(ctx, key); err == nil {
  170. return gr, nil
  171. }
  172. }
  173. return nil, ctx.Err()
  174. }