watch_command.go 5.2 KB

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