main.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. "flag"
  17. "fmt"
  18. "log"
  19. "math/rand"
  20. "os"
  21. "strings"
  22. "sync"
  23. "time"
  24. "golang.org/x/net/context"
  25. "google.golang.org/grpc"
  26. "google.golang.org/grpc/codes"
  27. "github.com/coreos/etcd/clientv3"
  28. "github.com/coreos/etcd/clientv3/concurrency"
  29. )
  30. func main() {
  31. log.SetFlags(log.Lmicroseconds)
  32. endpointStr := flag.String("endpoints", "localhost:2379", "endpoints of etcd cluster")
  33. mode := flag.String("mode", "lock-racer", "test mode (election, lock-racer, lease-renewer)")
  34. round := flag.Int("rounds", 100, "number of rounds to run")
  35. flag.Parse()
  36. eps := strings.Split(*endpointStr, ",")
  37. switch *mode {
  38. case "election":
  39. runElection(eps, *round)
  40. case "lock-racer":
  41. runRacer(eps, *round)
  42. case "lease-renewer":
  43. runLeaseRenewer(eps)
  44. default:
  45. fmt.Fprintf(os.Stderr, "unsupported mode %v\n", *mode)
  46. }
  47. }
  48. func runElection(eps []string, rounds int) {
  49. rcs := make([]roundClient, 15)
  50. validatec, releasec := make(chan struct{}, len(rcs)), make(chan struct{}, len(rcs))
  51. for range rcs {
  52. releasec <- struct{}{}
  53. }
  54. for i := range rcs {
  55. v := fmt.Sprintf("%d", i)
  56. observedLeader := ""
  57. validateWaiters := 0
  58. rcs[i].c = randClient(eps)
  59. e := concurrency.NewElection(rcs[i].c, "electors")
  60. rcs[i].acquire = func() error {
  61. <-releasec
  62. ctx, cancel := context.WithCancel(context.Background())
  63. go func() {
  64. if ol, ok := <-e.Observe(ctx); ok {
  65. observedLeader = string(ol.Kvs[0].Value)
  66. if observedLeader != v {
  67. cancel()
  68. }
  69. }
  70. }()
  71. err := e.Campaign(ctx, v)
  72. if err == nil {
  73. observedLeader = v
  74. }
  75. if observedLeader == v {
  76. validateWaiters = len(rcs)
  77. }
  78. select {
  79. case <-ctx.Done():
  80. return nil
  81. default:
  82. cancel()
  83. return err
  84. }
  85. }
  86. rcs[i].validate = func() error {
  87. if l, err := e.Leader(context.TODO()); err == nil && l != observedLeader {
  88. return fmt.Errorf("expected leader %q, got %q", observedLeader, l)
  89. }
  90. validatec <- struct{}{}
  91. return nil
  92. }
  93. rcs[i].release = func() error {
  94. for validateWaiters > 0 {
  95. select {
  96. case <-validatec:
  97. validateWaiters--
  98. default:
  99. return fmt.Errorf("waiting on followers")
  100. }
  101. }
  102. if err := e.Resign(context.TODO()); err != nil {
  103. return err
  104. }
  105. if observedLeader == v {
  106. for range rcs {
  107. releasec <- struct{}{}
  108. }
  109. }
  110. observedLeader = ""
  111. return nil
  112. }
  113. }
  114. doRounds(rcs, rounds)
  115. }
  116. func runLeaseRenewer(eps []string) {
  117. c := randClient(eps)
  118. ctx := context.Background()
  119. for {
  120. var (
  121. l *clientv3.LeaseGrantResponse
  122. lk *clientv3.LeaseKeepAliveResponse
  123. err error
  124. )
  125. for {
  126. l, err = c.Lease.Grant(ctx, 5)
  127. if err == nil {
  128. break
  129. }
  130. }
  131. expire := time.Now().Add(time.Duration(l.TTL-1) * time.Second)
  132. for {
  133. lk, err = c.Lease.KeepAliveOnce(ctx, l.ID)
  134. if grpc.Code(err) == codes.NotFound {
  135. if time.Since(expire) < 0 {
  136. log.Printf("bad renew! exceeded: %v", time.Since(expire))
  137. for {
  138. lk, err = c.Lease.KeepAliveOnce(ctx, l.ID)
  139. fmt.Println(lk, err)
  140. time.Sleep(time.Second)
  141. }
  142. }
  143. log.Printf("lost lease %d, expire: %v\n", l.ID, expire)
  144. break
  145. }
  146. if err != nil {
  147. continue
  148. }
  149. expire = time.Now().Add(time.Duration(lk.TTL-1) * time.Second)
  150. log.Printf("renewed lease %d, expire: %v\n", lk.ID, expire)
  151. time.Sleep(time.Duration(lk.TTL-2) * time.Second)
  152. }
  153. }
  154. }
  155. func runRacer(eps []string, round int) {
  156. rcs := make([]roundClient, 15)
  157. ctx := context.Background()
  158. cnt := 0
  159. for i := range rcs {
  160. rcs[i].c = randClient(eps)
  161. m := concurrency.NewMutex(rcs[i].c, "racers")
  162. rcs[i].acquire = func() error { return m.Lock(ctx) }
  163. rcs[i].validate = func() error {
  164. if cnt++; cnt != 1 {
  165. return fmt.Errorf("bad lock; count: %d", cnt)
  166. }
  167. return nil
  168. }
  169. rcs[i].release = func() error {
  170. if err := m.Unlock(ctx); err != nil {
  171. return err
  172. }
  173. cnt = 0
  174. return nil
  175. }
  176. }
  177. doRounds(rcs, round)
  178. }
  179. func randClient(eps []string) *clientv3.Client {
  180. neps := make([]string, len(eps))
  181. copy(neps, eps)
  182. for i := range neps {
  183. j := rand.Intn(i + 1)
  184. neps[i], neps[j] = neps[j], neps[i]
  185. }
  186. c, err := clientv3.New(clientv3.Config{
  187. Endpoints: eps,
  188. DialTimeout: 5 * time.Second,
  189. })
  190. if err != nil {
  191. log.Fatal(err)
  192. }
  193. return c
  194. }
  195. type roundClient struct {
  196. c *clientv3.Client
  197. progress int
  198. acquire func() error
  199. validate func() error
  200. release func() error
  201. }
  202. func doRounds(rcs []roundClient, rounds int) {
  203. var mu sync.Mutex
  204. var wg sync.WaitGroup
  205. wg.Add(len(rcs))
  206. finished := make(chan struct{}, 0)
  207. for i := range rcs {
  208. go func(rc *roundClient) {
  209. defer wg.Done()
  210. for rc.progress < rounds {
  211. for rc.acquire() != nil { /* spin */
  212. }
  213. mu.Lock()
  214. if err := rc.validate(); err != nil {
  215. log.Fatal(err)
  216. }
  217. mu.Unlock()
  218. time.Sleep(10 * time.Millisecond)
  219. rc.progress++
  220. finished <- struct{}{}
  221. mu.Lock()
  222. for rc.release() != nil {
  223. mu.Unlock()
  224. mu.Lock()
  225. }
  226. mu.Unlock()
  227. }
  228. }(&rcs[i])
  229. }
  230. start := time.Now()
  231. for i := 1; i < len(rcs)*rounds+1; i++ {
  232. select {
  233. case <-finished:
  234. if i%100 == 0 {
  235. fmt.Printf("finished %d, took %v\n", i, time.Since(start))
  236. start = time.Now()
  237. }
  238. case <-time.After(time.Minute):
  239. log.Panic("no progress after 1 minute!")
  240. }
  241. }
  242. wg.Wait()
  243. for _, rc := range rcs {
  244. rc.c.Close()
  245. }
  246. }