go.etcd.io/etcd@v3.3.27+incompatible/functional/runner/lock_racer_command.go (about) 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 15 package runner 16 17 import ( 18 "context" 19 "errors" 20 "fmt" 21 "sync" 22 23 "github.com/coreos/etcd/clientv3/concurrency" 24 25 "github.com/spf13/cobra" 26 ) 27 28 // NewLockRacerCommand returns the cobra command for "lock-racer runner". 29 func NewLockRacerCommand() *cobra.Command { 30 cmd := &cobra.Command{ 31 Use: "lock-racer [name of lock (defaults to 'racers')]", 32 Short: "Performs lock race operation", 33 Run: runRacerFunc, 34 } 35 cmd.Flags().IntVar(&totalClientConnections, "total-client-connections", 10, "total number of client connections") 36 return cmd 37 } 38 39 func runRacerFunc(cmd *cobra.Command, args []string) { 40 racers := "racers" 41 if len(args) == 1 { 42 racers = args[0] 43 } 44 45 if len(args) > 1 { 46 ExitWithError(ExitBadArgs, errors.New("lock-racer takes at most one argument")) 47 } 48 49 rcs := make([]roundClient, totalClientConnections) 50 ctx := context.Background() 51 // mu ensures validate and release funcs are atomic. 52 var mu sync.Mutex 53 cnt := 0 54 55 eps := endpointsFromFlag(cmd) 56 57 for i := range rcs { 58 var ( 59 s *concurrency.Session 60 err error 61 ) 62 63 rcs[i].c = newClient(eps, dialTimeout) 64 65 for { 66 s, err = concurrency.NewSession(rcs[i].c) 67 if err == nil { 68 break 69 } 70 } 71 m := concurrency.NewMutex(s, racers) 72 rcs[i].acquire = func() error { return m.Lock(ctx) } 73 rcs[i].validate = func() error { 74 mu.Lock() 75 defer mu.Unlock() 76 if cnt++; cnt != 1 { 77 return fmt.Errorf("bad lock; count: %d", cnt) 78 } 79 return nil 80 } 81 rcs[i].release = func() error { 82 mu.Lock() 83 defer mu.Unlock() 84 if err := m.Unlock(ctx); err != nil { 85 return err 86 } 87 cnt = 0 88 return nil 89 } 90 } 91 // each client creates 1 key from NewMutex() and delete it from Unlock() 92 // a round involves in 2*len(rcs) requests. 93 doRounds(rcs, rounds, 2*len(rcs)) 94 }