lease_renewer.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "context"
  17. "fmt"
  18. "log"
  19. "time"
  20. "github.com/coreos/etcd/clientv3"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/codes"
  23. )
  24. func runLeaseRenewer(getClient getClientFunc) {
  25. c := getClient()
  26. ctx := context.Background()
  27. for {
  28. var (
  29. l *clientv3.LeaseGrantResponse
  30. lk *clientv3.LeaseKeepAliveResponse
  31. err error
  32. )
  33. for {
  34. l, err = c.Lease.Grant(ctx, 5)
  35. if err == nil {
  36. break
  37. }
  38. }
  39. expire := time.Now().Add(time.Duration(l.TTL-1) * time.Second)
  40. for {
  41. lk, err = c.Lease.KeepAliveOnce(ctx, l.ID)
  42. if grpc.Code(err) == codes.NotFound {
  43. if time.Since(expire) < 0 {
  44. log.Printf("bad renew! exceeded: %v", time.Since(expire))
  45. for {
  46. lk, err = c.Lease.KeepAliveOnce(ctx, l.ID)
  47. fmt.Println(lk, err)
  48. time.Sleep(time.Second)
  49. }
  50. }
  51. log.Printf("lost lease %d, expire: %v\n", l.ID, expire)
  52. break
  53. }
  54. if err != nil {
  55. continue
  56. }
  57. expire = time.Now().Add(time.Duration(lk.TTL-1) * time.Second)
  58. log.Printf("renewed lease %d, expire: %v\n", lk.ID, expire)
  59. time.Sleep(time.Duration(lk.TTL-2) * time.Second)
  60. }
  61. }
  62. }