lease_renewer_command.go 2.3 KB

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