lease.go 1.9 KB

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