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