github.com/looshlee/beatles@v0.0.0-20220727174639-742810ab631c/pkg/kvstore/lock_test.go (about)

     1  // Copyright 2019 Authors of Cilium
     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  // +build !privileged_tests
    16  
    17  package kvstore
    18  
    19  import (
    20  	"context"
    21  	"time"
    22  
    23  	"github.com/pborman/uuid"
    24  	. "gopkg.in/check.v1"
    25  )
    26  
    27  func (s *independentSuite) TestLocalLock(c *C) {
    28  	prefix := "locktest/"
    29  	path := prefix + "foo"
    30  
    31  	backup := staleLockTimeout
    32  	defer func() { staleLockTimeout = backup }()
    33  	staleLockTimeout = 5 * time.Millisecond
    34  
    35  	locks := pathLocks{lockPaths: map[string]lockOwner{}}
    36  
    37  	// Acquie lock1
    38  	id1, err := locks.lock(context.Background(), path)
    39  	c.Assert(err, IsNil)
    40  
    41  	// Ensure that staleLockTimeout has passed
    42  	time.Sleep(staleLockTimeout * 2)
    43  	locks.runGC()
    44  
    45  	// Acquire lock on same path, must unlock local use
    46  	id2, err := locks.lock(context.Background(), path)
    47  	c.Assert(err, IsNil)
    48  
    49  	// Unlock lock1, this should be a no-op
    50  	locks.unlock(path, id1)
    51  
    52  	owner, ok := locks.lockPaths[path]
    53  	c.Assert(ok, Equals, true)
    54  	c.Assert(uuid.Equal(owner.id, id2), Equals, true)
    55  
    56  	// Unlock lock2, this should be a no-op
    57  	locks.unlock(path, id2)
    58  }
    59  
    60  func (s *independentSuite) TestLocalLockCancel(c *C) {
    61  	path := "locktest/foo"
    62  	locks := pathLocks{lockPaths: map[string]lockOwner{}}
    63  	// grab lock to ensure that 2nd lock attempt needs to retry and can be
    64  	// cancelled
    65  	id1, err := locks.lock(context.Background(), path)
    66  	c.Assert(err, IsNil)
    67  	defer locks.unlock(path, id1)
    68  	ctx, cancel := context.WithCancel(context.Background())
    69  	cancel()
    70  	_, err = locks.lock(ctx, path)
    71  	c.Assert(err, Not(IsNil))
    72  }