lock_racer_command.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "github.com/coreos/etcd/clientv3/concurrency"
  20. "github.com/spf13/cobra"
  21. )
  22. // NewLockRacerCommand returns the cobra command for "lock-racer runner".
  23. func NewLockRacerCommand() *cobra.Command {
  24. cmd := &cobra.Command{
  25. Use: "lock-racer",
  26. Short: "Performs lock race operation",
  27. Run: runRacerFunc,
  28. }
  29. cmd.Flags().IntVar(&rounds, "rounds", 100, "number of rounds to run")
  30. cmd.Flags().IntVar(&totalClientConnections, "total-client-connections", 10, "total number of client connections")
  31. return cmd
  32. }
  33. func runRacerFunc(cmd *cobra.Command, args []string) {
  34. if len(args) > 0 {
  35. ExitWithError(ExitBadArgs, errors.New("lock-racer does not take any argument"))
  36. }
  37. rcs := make([]roundClient, totalClientConnections)
  38. ctx := context.Background()
  39. cnt := 0
  40. eps := endpointsFromFlag(cmd)
  41. dialTimeout := dialTimeoutFromCmd(cmd)
  42. for i := range rcs {
  43. var (
  44. s *concurrency.Session
  45. err error
  46. )
  47. rcs[i].c = newClient(eps, dialTimeout)
  48. for {
  49. s, err = concurrency.NewSession(rcs[i].c)
  50. if err == nil {
  51. break
  52. }
  53. }
  54. m := concurrency.NewMutex(s, "racers")
  55. rcs[i].acquire = func() error { return m.Lock(ctx) }
  56. rcs[i].validate = func() error {
  57. if cnt++; cnt != 1 {
  58. return fmt.Errorf("bad lock; count: %d", cnt)
  59. }
  60. return nil
  61. }
  62. rcs[i].release = func() error {
  63. if err := m.Unlock(ctx); err != nil {
  64. return err
  65. }
  66. cnt = 0
  67. return nil
  68. }
  69. }
  70. doRounds(rcs, rounds)
  71. }