github.com/lfch/etcd-io/tests/v3@v3.0.0-20221004140520-eac99acd3e9d/functional/runner/lease_renewer_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 "log" 21 "time" 22 23 clientv3 "github.com/lfch/etcd-io/client/v3" 24 25 "github.com/spf13/cobra" 26 "google.golang.org/grpc/codes" 27 "google.golang.org/grpc/status" 28 ) 29 30 var ( 31 leaseTTL int64 32 ) 33 34 // NewLeaseRenewerCommand returns the cobra command for "lease-renewer runner". 35 func NewLeaseRenewerCommand() *cobra.Command { 36 cmd := &cobra.Command{ 37 Use: "lease-renewer", 38 Short: "Performs lease renew operation", 39 Run: runLeaseRenewerFunc, 40 } 41 cmd.Flags().Int64Var(&leaseTTL, "ttl", 5, "lease's ttl") 42 return cmd 43 } 44 45 func runLeaseRenewerFunc(cmd *cobra.Command, args []string) { 46 if len(args) > 0 { 47 ExitWithError(ExitBadArgs, errors.New("lease-renewer does not take any argument")) 48 } 49 50 eps := endpointsFromFlag(cmd) 51 c := newClient(eps, dialTimeout) 52 ctx := context.Background() 53 54 for { 55 var ( 56 l *clientv3.LeaseGrantResponse 57 lk *clientv3.LeaseKeepAliveResponse 58 err error 59 ) 60 for { 61 l, err = c.Lease.Grant(ctx, leaseTTL) 62 if err == nil { 63 break 64 } 65 } 66 expire := time.Now().Add(time.Duration(l.TTL-1) * time.Second) 67 68 for { 69 lk, err = c.Lease.KeepAliveOnce(ctx, l.ID) 70 if ev, ok := status.FromError(err); ok && ev.Code() == codes.NotFound { 71 if time.Since(expire) < 0 { 72 log.Fatalf("bad renew! exceeded: %v", time.Since(expire)) 73 } 74 log.Fatalf("lost lease %d, expire: %v\n", l.ID, expire) 75 } 76 77 if err != nil { 78 continue 79 } 80 expire = time.Now().Add(time.Duration(lk.TTL-1) * time.Second) 81 log.Printf("renewed lease %d, expire: %v\n", lk.ID, expire) 82 time.Sleep(time.Duration(lk.TTL-2) * time.Second) 83 } 84 } 85 }