lease.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2016 CoreOS, Inc.
  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 v3rpc
  15. import (
  16. "io"
  17. "github.com/coreos/etcd/etcdserver"
  18. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. "github.com/coreos/etcd/lease"
  21. "golang.org/x/net/context"
  22. )
  23. type LeaseServer struct {
  24. le etcdserver.Lessor
  25. }
  26. func NewLeaseServer(le etcdserver.Lessor) pb.LeaseServer {
  27. return &LeaseServer{le: le}
  28. }
  29. func (ls *LeaseServer) LeaseCreate(ctx context.Context, cr *pb.LeaseCreateRequest) (*pb.LeaseCreateResponse, error) {
  30. resp, err := ls.le.LeaseCreate(ctx, cr)
  31. if err == lease.ErrLeaseExists {
  32. return nil, rpctypes.ErrLeaseExist
  33. }
  34. return resp, err
  35. }
  36. func (ls *LeaseServer) LeaseRevoke(ctx context.Context, rr *pb.LeaseRevokeRequest) (*pb.LeaseRevokeResponse, error) {
  37. r, err := ls.le.LeaseRevoke(ctx, rr)
  38. if err != nil {
  39. return nil, rpctypes.ErrLeaseNotFound
  40. }
  41. return r, nil
  42. }
  43. func (ls *LeaseServer) LeaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) error {
  44. for {
  45. req, err := stream.Recv()
  46. if err == io.EOF {
  47. return nil
  48. }
  49. if err != nil {
  50. return err
  51. }
  52. ttl, err := ls.le.LeaseRenew(lease.LeaseID(req.ID))
  53. if err == lease.ErrLeaseNotFound {
  54. return rpctypes.ErrLeaseNotFound
  55. }
  56. if err != nil && err != lease.ErrLeaseNotFound {
  57. return err
  58. }
  59. resp := &pb.LeaseKeepAliveResponse{ID: req.ID, TTL: ttl}
  60. err = stream.Send(resp)
  61. if err != nil {
  62. return err
  63. }
  64. }
  65. }