go.etcd.io/etcd@v3.3.27+incompatible/etcdserver/api/v3lock/lock.go (about)

     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  
    15  package v3lock
    16  
    17  import (
    18  	"context"
    19  
    20  	"github.com/coreos/etcd/clientv3"
    21  	"github.com/coreos/etcd/clientv3/concurrency"
    22  	"github.com/coreos/etcd/etcdserver/api/v3lock/v3lockpb"
    23  )
    24  
    25  type lockServer struct {
    26  	c *clientv3.Client
    27  }
    28  
    29  func NewLockServer(c *clientv3.Client) v3lockpb.LockServer {
    30  	return &lockServer{c}
    31  }
    32  
    33  func (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  
    50  func (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  }