lease.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 grpcproxy
  15. import (
  16. "golang.org/x/net/context"
  17. "github.com/coreos/etcd/clientv3"
  18. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  19. )
  20. type leaseProxy struct {
  21. client *clientv3.Client
  22. }
  23. func NewLeaseProxy(c *clientv3.Client) pb.LeaseServer {
  24. return &leaseProxy{
  25. client: c,
  26. }
  27. }
  28. func (lp *leaseProxy) LeaseGrant(ctx context.Context, cr *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) {
  29. conn := lp.client.ActiveConnection()
  30. return pb.NewLeaseClient(conn).LeaseGrant(ctx, cr)
  31. }
  32. func (lp *leaseProxy) LeaseRevoke(ctx context.Context, rr *pb.LeaseRevokeRequest) (*pb.LeaseRevokeResponse, error) {
  33. conn := lp.client.ActiveConnection()
  34. return pb.NewLeaseClient(conn).LeaseRevoke(ctx, rr)
  35. }
  36. func (lp *leaseProxy) LeaseTimeToLive(ctx context.Context, rr *pb.LeaseTimeToLiveRequest) (*pb.LeaseTimeToLiveResponse, error) {
  37. conn := lp.client.ActiveConnection()
  38. return pb.NewLeaseClient(conn).LeaseTimeToLive(ctx, rr)
  39. }
  40. func (lp *leaseProxy) LeaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) error {
  41. conn := lp.client.ActiveConnection()
  42. ctx, cancel := context.WithCancel(stream.Context())
  43. lc, err := pb.NewLeaseClient(conn).LeaseKeepAlive(ctx)
  44. if err != nil {
  45. cancel()
  46. return err
  47. }
  48. go func() {
  49. // Cancel the context attached to lc to unblock lc.Recv when
  50. // this routine returns on error.
  51. defer cancel()
  52. for {
  53. // stream.Recv will be unblock when the loop in the parent routine
  54. // returns on error.
  55. rr, err := stream.Recv()
  56. if err != nil {
  57. return
  58. }
  59. err = lc.Send(rr)
  60. if err != nil {
  61. return
  62. }
  63. }
  64. }()
  65. for {
  66. rr, err := lc.Recv()
  67. if err != nil {
  68. return err
  69. }
  70. err = stream.Send(rr)
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. }