lease.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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) LeaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) error {
  37. conn := lp.client.ActiveConnection()
  38. ctx, cancel := context.WithCancel(stream.Context())
  39. lc, err := pb.NewLeaseClient(conn).LeaseKeepAlive(ctx)
  40. if err != nil {
  41. cancel()
  42. return err
  43. }
  44. go func() {
  45. // Cancel the context attached to lc to unblock lc.Recv when
  46. // this routine returns on error.
  47. defer cancel()
  48. for {
  49. // stream.Recv will be unblock when the loop in the parent routine
  50. // returns on error.
  51. rr, err := stream.Recv()
  52. if err != nil {
  53. return
  54. }
  55. err = lc.Send(rr)
  56. if err != nil {
  57. return
  58. }
  59. }
  60. }()
  61. for {
  62. rr, err := lc.Recv()
  63. if err != nil {
  64. return err
  65. }
  66. err = stream.Send(rr)
  67. if err != nil {
  68. return err
  69. }
  70. }
  71. }