main.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. var (
  60. s *concurrency.Session
  61. err error
  62. )
  63. for {
  64. s, err = concurrency.NewSession(rcs[i].c)
  65. if err == nil {
  66. break
  67. }
  68. }
  69. e := concurrency.NewElection(s, "electors")
  70. rcs[i].acquire = func() error {
  71. <-releasec
  72. ctx, cancel := context.WithCancel(context.Background())
  73. go func() {
  74. if ol, ok := <-e.Observe(ctx); ok {
  75. observedLeader = string(ol.Kvs[0].Value)
  76. if observedLeader != v {
  77. cancel()
  78. }
  79. }
  80. }()
  81. err = e.Campaign(ctx, v)
  82. if err == nil {
  83. observedLeader = v
  84. }
  85. if observedLeader == v {
  86. validateWaiters = len(rcs)
  87. }
  88. select {
  89. case <-ctx.Done():
  90. return nil
  91. default:
  92. cancel()
  93. return err
  94. }
  95. }
  96. rcs[i].validate = func() error {
  97. if l, err := e.Leader(context.TODO()); err == nil && l != observedLeader {
  98. return fmt.Errorf("expected leader %q, got %q", observedLeader, l)
  99. }
  100. validatec <- struct{}{}
  101. return nil
  102. }
  103. rcs[i].release = func() error {
  104. for validateWaiters > 0 {
  105. select {
  106. case <-validatec:
  107. validateWaiters--
  108. default:
  109. return fmt.Errorf("waiting on followers")
  110. }
  111. }
  112. if err := e.Resign(context.TODO()); err != nil {
  113. return err
  114. }
  115. if observedLeader == v {
  116. for range rcs {
  117. releasec <- struct{}{}
  118. }
  119. }
  120. observedLeader = ""
  121. return nil
  122. }
  123. }
  124. doRounds(rcs, rounds)
  125. }
  126. func runLeaseRenewer(eps []string) {
  127. c := randClient(eps)
  128. ctx := context.Background()
  129. for {
  130. var (
  131. l *clientv3.LeaseGrantResponse
  132. lk *clientv3.LeaseKeepAliveResponse
  133. err error
  134. )
  135. for {
  136. l, err = c.Lease.Grant(ctx, 5)
  137. if err == nil {
  138. break
  139. }
  140. }
  141. expire := time.Now().Add(time.Duration(l.TTL-1) * time.Second)
  142. for {
  143. lk, err = c.Lease.KeepAliveOnce(ctx, l.ID)
  144. if grpc.Code(err) == codes.NotFound {
  145. if time.Since(expire) < 0 {
  146. log.Printf("bad renew! exceeded: %v", time.Since(expire))
  147. for {
  148. lk, err = c.Lease.KeepAliveOnce(ctx, l.ID)
  149. fmt.Println(lk, err)
  150. time.Sleep(time.Second)
  151. }
  152. }
  153. log.Printf("lost lease %d, expire: %v\n", l.ID, expire)
  154. break
  155. }
  156. if err != nil {
  157. continue
  158. }
  159. expire = time.Now().Add(time.Duration(lk.TTL-1) * time.Second)
  160. log.Printf("renewed lease %d, expire: %v\n", lk.ID, expire)
  161. time.Sleep(time.Duration(lk.TTL-2) * time.Second)
  162. }
  163. }
  164. }
  165. func runRacer(eps []string, round int) {
  166. rcs := make([]roundClient, 15)
  167. ctx := context.Background()
  168. cnt := 0
  169. for i := range rcs {
  170. rcs[i].c = randClient(eps)
  171. var (
  172. s *concurrency.Session
  173. err error
  174. )
  175. for {
  176. s, err = concurrency.NewSession(rcs[i].c)
  177. if err == nil {
  178. break
  179. }
  180. }
  181. m := concurrency.NewMutex(s, "racers")
  182. rcs[i].acquire = func() error { return m.Lock(ctx) }
  183. rcs[i].validate = func() error {
  184. if cnt++; cnt != 1 {
  185. return fmt.Errorf("bad lock; count: %d", cnt)
  186. }
  187. return nil
  188. }
  189. rcs[i].release = func() error {
  190. if err := m.Unlock(ctx); err != nil {
  191. return err
  192. }
  193. cnt = 0
  194. return nil
  195. }
  196. }
  197. doRounds(rcs, round)
  198. }
  199. func randClient(eps []string) *clientv3.Client {
  200. neps := make([]string, len(eps))
  201. copy(neps, eps)
  202. for i := range neps {
  203. j := rand.Intn(i + 1)
  204. neps[i], neps[j] = neps[j], neps[i]
  205. }
  206. c, err := clientv3.New(clientv3.Config{
  207. Endpoints: eps,
  208. DialTimeout: 5 * time.Second,
  209. })
  210. if err != nil {
  211. log.Fatal(err)
  212. }
  213. return c
  214. }
  215. type roundClient struct {
  216. c *clientv3.Client
  217. progress int
  218. acquire func() error
  219. validate func() error
  220. release func() error
  221. }
  222. func doRounds(rcs []roundClient, rounds int) {
  223. var mu sync.Mutex
  224. var wg sync.WaitGroup
  225. wg.Add(len(rcs))
  226. finished := make(chan struct{}, 0)
  227. for i := range rcs {
  228. go func(rc *roundClient) {
  229. defer wg.Done()
  230. for rc.progress < rounds {
  231. for rc.acquire() != nil { /* spin */
  232. }
  233. mu.Lock()
  234. if err := rc.validate(); err != nil {
  235. log.Fatal(err)
  236. }
  237. mu.Unlock()
  238. time.Sleep(10 * time.Millisecond)
  239. rc.progress++
  240. finished <- struct{}{}
  241. mu.Lock()
  242. for rc.release() != nil {
  243. mu.Unlock()
  244. mu.Lock()
  245. }
  246. mu.Unlock()
  247. }
  248. }(&rcs[i])
  249. }
  250. start := time.Now()
  251. for i := 1; i < len(rcs)*rounds+1; i++ {
  252. select {
  253. case <-finished:
  254. if i%100 == 0 {
  255. fmt.Printf("finished %d, took %v\n", i, time.Since(start))
  256. start = time.Now()
  257. }
  258. case <-time.After(time.Minute):
  259. log.Panic("no progress after 1 minute!")
  260. }
  261. }
  262. wg.Wait()
  263. for _, rc := range rcs {
  264. rc.c.Close()
  265. }
  266. }