watcher.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. "math/rand"
  20. "sync"
  21. "time"
  22. "github.com/coreos/etcd/clientv3"
  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. performWatchOnPrefixes(ctx, getClient, round)
  29. }
  30. }
  31. func performWatchOnPrefixes(ctx context.Context, getClient getClientFunc, round int) {
  32. runningTime := 60 * time.Second // time for which operation should be performed
  33. noOfPrefixes := 36 // total number of prefixes which will be watched upon
  34. watchPerPrefix := 10 // number of watchers per prefix
  35. reqRate := 30 // put request per second
  36. keyPrePrefix := 30 // max number of keyPrePrefixs for put operation
  37. prefixes := generateUniqueKeys(5, noOfPrefixes)
  38. keys := generateRandomKeys(10, keyPrePrefix)
  39. roundPrefix := fmt.Sprintf("%16x", round)
  40. var (
  41. revision int64
  42. wg sync.WaitGroup
  43. gr *clientv3.GetResponse
  44. err error
  45. )
  46. client := getClient()
  47. defer client.Close()
  48. // get revision using get request
  49. gr = getWithRetry(client, ctx, "non-existent")
  50. revision = gr.Header.Revision
  51. ctxt, cancel := context.WithDeadline(ctx, time.Now().Add(runningTime))
  52. defer cancel()
  53. // generate and put keys in cluster
  54. limiter := rate.NewLimiter(rate.Limit(reqRate), reqRate)
  55. go func() {
  56. var modrevision int64
  57. for _, key := range keys {
  58. for _, prefix := range prefixes {
  59. key := roundPrefix + "-" + prefix + "-" + key
  60. // limit key put as per reqRate
  61. if err = limiter.Wait(ctxt); err != nil {
  62. break
  63. }
  64. modrevision = 0
  65. gr = getWithRetry(client, ctxt, key)
  66. kvs := gr.Kvs
  67. if len(kvs) > 0 {
  68. modrevision = gr.Kvs[0].ModRevision
  69. }
  70. for {
  71. txn := client.Txn(ctxt)
  72. _, err = txn.If(clientv3.Compare(clientv3.ModRevision(key), "=", modrevision)).Then(clientv3.OpPut(key, key)).Commit()
  73. if err == nil {
  74. break
  75. }
  76. if err == context.DeadlineExceeded {
  77. return
  78. }
  79. }
  80. }
  81. }
  82. }()
  83. ctxc, cancelc := context.WithCancel(ctx)
  84. wcs := make([]clientv3.WatchChan, 0)
  85. rcs := make([]*clientv3.Client, 0)
  86. wg.Add(noOfPrefixes * watchPerPrefix)
  87. for _, prefix := range prefixes {
  88. for j := 0; j < watchPerPrefix; j++ {
  89. go func(prefix string) {
  90. defer wg.Done()
  91. rc := getClient()
  92. rcs = append(rcs, rc)
  93. wc := rc.Watch(ctxc, prefix, clientv3.WithPrefix(), clientv3.WithRev(revision))
  94. wcs = append(wcs, wc)
  95. for n := 0; n < len(keys); {
  96. select {
  97. case watchChan := <-wc:
  98. for _, event := range watchChan.Events {
  99. expectedKey := prefix + "-" + keys[n]
  100. receivedKey := string(event.Kv.Key)
  101. if expectedKey != receivedKey {
  102. log.Fatalf("expected key %q, got %q for prefix : %q\n", expectedKey, receivedKey, prefix)
  103. }
  104. n++
  105. }
  106. case <-ctxt.Done():
  107. return
  108. }
  109. }
  110. }(roundPrefix + "-" + prefix)
  111. }
  112. }
  113. wg.Wait()
  114. // cancel all watch channels
  115. cancelc()
  116. // verify all watch channels are closed
  117. for e, wc := range wcs {
  118. if _, ok := <-wc; ok {
  119. log.Fatalf("expected wc to be closed, but received %v", e)
  120. }
  121. }
  122. for _, rc := range rcs {
  123. rc.Close()
  124. }
  125. deletePrefixWithRety(client, ctx, roundPrefix)
  126. }
  127. func deletePrefixWithRety(client *clientv3.Client, ctx context.Context, key string) {
  128. for {
  129. if _, err := client.Delete(ctx, key, clientv3.WithRange(key+"z")); err == nil {
  130. return
  131. }
  132. }
  133. }
  134. func getWithRetry(client *clientv3.Client, ctx context.Context, key string) *clientv3.GetResponse {
  135. for {
  136. if gr, err := client.Get(ctx, key); err == nil {
  137. return gr
  138. }
  139. }
  140. }
  141. func generateUniqueKeys(maxstrlen uint, keynos int) []string {
  142. keyMap := make(map[string]bool)
  143. keys := make([]string, 0)
  144. count := 0
  145. key := ""
  146. for {
  147. key = generateRandomKey(maxstrlen)
  148. _, ok := keyMap[key]
  149. if !ok {
  150. keyMap[key] = true
  151. keys = append(keys, key)
  152. count++
  153. if len(keys) == keynos {
  154. break
  155. }
  156. }
  157. }
  158. return keys
  159. }
  160. func generateRandomKeys(maxstrlen uint, keynos int) []string {
  161. keys := make([]string, 0)
  162. key := ""
  163. for i := 0; i < keynos; i++ {
  164. key = generateRandomKey(maxstrlen)
  165. keys = append(keys, key)
  166. }
  167. return keys
  168. }
  169. func generateRandomKey(strlen uint) string {
  170. chars := "abcdefghijklmnopqrstuvwxyz0123456789"
  171. result := make([]byte, strlen)
  172. for i := 0; i < int(strlen); i++ {
  173. result[i] = chars[rand.Intn(len(chars))]
  174. }
  175. key := string(result)
  176. return key
  177. }