sigs.k8s.io/cluster-api@v1.7.1/controllers/remote/keyedmutex.go (about)

     1  /*
     2  Copyright 2021 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package remote
    18  
    19  import (
    20  	"sync"
    21  
    22  	"sigs.k8s.io/controller-runtime/pkg/client"
    23  )
    24  
    25  // keyedMutex is a mutex locking on the key provided to the Lock function.
    26  // Only one caller can hold the lock for a specific key at a time.
    27  // A second Lock call if the lock is already held for a key returns false.
    28  type keyedMutex struct {
    29  	locksMtx sync.Mutex
    30  	locks    map[client.ObjectKey]struct{}
    31  }
    32  
    33  // newKeyedMutex creates a new keyed mutex ready for use.
    34  func newKeyedMutex() *keyedMutex {
    35  	return &keyedMutex{
    36  		locks: make(map[client.ObjectKey]struct{}),
    37  	}
    38  }
    39  
    40  // TryLock locks the passed in key if it's not already locked.
    41  // A second Lock call if the lock is already held for a key returns false.
    42  // In the ClusterCacheTracker case the key is the ObjectKey for a cluster.
    43  func (k *keyedMutex) TryLock(key client.ObjectKey) bool {
    44  	k.locksMtx.Lock()
    45  	defer k.locksMtx.Unlock()
    46  
    47  	// Check if there is already a lock for this key (e.g. Cluster).
    48  	if _, ok := k.locks[key]; ok {
    49  		// There is already a lock, return false.
    50  		return false
    51  	}
    52  
    53  	// Lock doesn't exist yet, create the lock.
    54  	k.locks[key] = struct{}{}
    55  
    56  	return true
    57  }
    58  
    59  // Unlock unlocks the key.
    60  func (k *keyedMutex) Unlock(key client.ObjectKey) {
    61  	k.locksMtx.Lock()
    62  	defer k.locksMtx.Unlock()
    63  
    64  	// Remove the lock if it exists.
    65  	delete(k.locks, key)
    66  }