github.com/fafucoder/cilium@v1.6.11/pkg/endpoint/lock.go (about)

     1  // Copyright 2018 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  package endpoint
    16  
    17  import "fmt"
    18  
    19  // LockAlive returns error if endpoint was removed, locks underlying mutex otherwise
    20  func (e *Endpoint) LockAlive() error {
    21  	e.mutex.Lock()
    22  	if e.IsDisconnecting() {
    23  		e.mutex.Unlock()
    24  		return fmt.Errorf("lock failed: endpoint is in the process of being removed")
    25  	}
    26  	return nil
    27  }
    28  
    29  // Unlock unlocks endpoint mutex
    30  func (e *Endpoint) Unlock() {
    31  	e.mutex.Unlock()
    32  }
    33  
    34  // RLockAlive returns error if endpoint was removed, read locks underlying mutex otherwise
    35  func (e *Endpoint) RLockAlive() error {
    36  	e.mutex.RLock()
    37  	if e.IsDisconnecting() {
    38  		e.mutex.RUnlock()
    39  		return ErrNotAlive
    40  	}
    41  	return nil
    42  }
    43  
    44  // RUnlock read unlocks endpoint mutex
    45  func (e *Endpoint) RUnlock() {
    46  	e.mutex.RUnlock()
    47  }
    48  
    49  // UnconditionalLock should be used only for locking endpoint for
    50  // - setting its state to StateDisconnected or StateInvalid
    51  // - handling regular Lock errors
    52  // - reporting endpoint status (like in LogStatus method)
    53  // Use Lock in all other cases
    54  func (e *Endpoint) UnconditionalLock() {
    55  	e.mutex.Lock()
    56  }
    57  
    58  // UnconditionalRLock should be used only for reporting endpoint state
    59  func (e *Endpoint) UnconditionalRLock() {
    60  	e.mutex.RLock()
    61  }
    62  
    63  // LogDisconnectedMutexAction gets the logger and logs given error with context
    64  func (e *Endpoint) LogDisconnectedMutexAction(err error, context string) {
    65  	e.getLogger().WithError(err).Error(context)
    66  }