lease_renewer_command.go 2.2 KB

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