watch_command.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. 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. dialTimeout := dialTimeoutFromCmd(cmd)
  65. var (
  66. revision int64
  67. wg sync.WaitGroup
  68. gr *clientv3.GetResponse
  69. err error
  70. )
  71. client := newClient(eps, dialTimeout)
  72. defer client.Close()
  73. gr, err = getKey(ctx, client, "non-existent")
  74. if err != nil {
  75. log.Fatalf("failed to get the initial revision: %v", err)
  76. }
  77. revision = gr.Header.Revision
  78. ctxt, cancel := context.WithDeadline(ctx, time.Now().Add(runningTime*time.Second))
  79. defer cancel()
  80. // generate and put keys in cluster
  81. limiter := rate.NewLimiter(rate.Limit(reqRate), reqRate)
  82. go func() {
  83. for _, key := range keys {
  84. for _, prefix := range prefixes {
  85. if err = limiter.Wait(ctxt); err != nil {
  86. return
  87. }
  88. if err = putKeyAtMostOnce(ctxt, client, watchPrefix+"-"+roundPrefix+"-"+prefix+"-"+key); err != nil {
  89. log.Fatalf("failed to put key: %v", err)
  90. return
  91. }
  92. }
  93. }
  94. }()
  95. ctxc, cancelc := context.WithCancel(ctx)
  96. wcs := make([]clientv3.WatchChan, 0)
  97. rcs := make([]*clientv3.Client, 0)
  98. for _, prefix := range prefixes {
  99. for j := 0; j < watchPerPrefix; j++ {
  100. rc := newClient(eps, dialTimeout)
  101. rcs = append(rcs, rc)
  102. wprefix := watchPrefix + "-" + roundPrefix + "-" + prefix
  103. wc := rc.Watch(ctxc, wprefix, clientv3.WithPrefix(), clientv3.WithRev(revision))
  104. wcs = append(wcs, wc)
  105. wg.Add(1)
  106. go func() {
  107. defer wg.Done()
  108. checkWatchResponse(wc, wprefix, keys)
  109. }()
  110. }
  111. }
  112. wg.Wait()
  113. cancelc()
  114. // verify all watch channels are closed
  115. for e, wc := range wcs {
  116. if _, ok := <-wc; ok {
  117. log.Fatalf("expected wc to be closed, but received %v", e)
  118. }
  119. }
  120. for _, rc := range rcs {
  121. rc.Close()
  122. }
  123. if err = deletePrefix(ctx, client, watchPrefix); err != nil {
  124. log.Fatalf("failed to clean up keys after test: %v", err)
  125. }
  126. }
  127. func checkWatchResponse(wc clientv3.WatchChan, prefix string, keys []string) {
  128. for n := 0; n < len(keys); {
  129. wr, more := <-wc
  130. if !more {
  131. log.Fatalf("expect more keys (received %d/%d) for %s", n, len(keys), prefix)
  132. }
  133. for _, event := range wr.Events {
  134. expectedKey := prefix + "-" + keys[n]
  135. receivedKey := string(event.Kv.Key)
  136. if expectedKey != receivedKey {
  137. log.Fatalf("expected key %q, got %q for prefix : %q\n", expectedKey, receivedKey, prefix)
  138. }
  139. n++
  140. }
  141. }
  142. }
  143. func putKeyAtMostOnce(ctx context.Context, client *clientv3.Client, key string) error {
  144. gr, err := getKey(ctx, client, key)
  145. if err != nil {
  146. return err
  147. }
  148. var modrev int64
  149. if len(gr.Kvs) > 0 {
  150. modrev = gr.Kvs[0].ModRevision
  151. }
  152. for ctx.Err() == nil {
  153. _, err := client.Txn(ctx).If(clientv3.Compare(clientv3.ModRevision(key), "=", modrev)).Then(clientv3.OpPut(key, key)).Commit()
  154. if err == nil {
  155. return nil
  156. }
  157. }
  158. return ctx.Err()
  159. }
  160. func deletePrefix(ctx context.Context, client *clientv3.Client, key string) error {
  161. for ctx.Err() == nil {
  162. if _, err := client.Delete(ctx, key, clientv3.WithPrefix()); err == nil {
  163. return nil
  164. }
  165. }
  166. return ctx.Err()
  167. }
  168. func getKey(ctx context.Context, client *clientv3.Client, key string) (*clientv3.GetResponse, error) {
  169. for ctx.Err() == nil {
  170. if gr, err := client.Get(ctx, key); err == nil {
  171. return gr, nil
  172. }
  173. }
  174. return nil, ctx.Err()
  175. }