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