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