watcher.go 4.5 KB

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