lock.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2017 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 v3lock
  15. import (
  16. "context"
  17. "go.etcd.io/etcd/clientv3"
  18. "go.etcd.io/etcd/clientv3/concurrency"
  19. "go.etcd.io/etcd/etcdserver/api/v3lock/v3lockpb"
  20. )
  21. type lockServer struct {
  22. c *clientv3.Client
  23. }
  24. func NewLockServer(c *clientv3.Client) v3lockpb.LockServer {
  25. return &lockServer{c}
  26. }
  27. func (ls *lockServer) Lock(ctx context.Context, req *v3lockpb.LockRequest) (*v3lockpb.LockResponse, error) {
  28. s, err := concurrency.NewSession(
  29. ls.c,
  30. concurrency.WithLease(clientv3.LeaseID(req.Lease)),
  31. concurrency.WithContext(ctx),
  32. )
  33. if err != nil {
  34. return nil, err
  35. }
  36. s.Orphan()
  37. m := concurrency.NewMutex(s, string(req.Name))
  38. if err = m.Lock(ctx); err != nil {
  39. return nil, err
  40. }
  41. return &v3lockpb.LockResponse{Header: m.Header(), Key: []byte(m.Key())}, nil
  42. }
  43. func (ls *lockServer) Unlock(ctx context.Context, req *v3lockpb.UnlockRequest) (*v3lockpb.UnlockResponse, error) {
  44. resp, err := ls.c.Delete(ctx, string(req.Key))
  45. if err != nil {
  46. return nil, err
  47. }
  48. return &v3lockpb.UnlockResponse{Header: resp.Header}, nil
  49. }