Files
podman/libpod/lock/in_memory_locks.go
Matthew Heon d2b77f8b33 Do not make renumber shut down the runtime
The original intent behind the requirement was to ensure that, if
two SHM lock structs were open at the same time, we should not
make such a runtime available to the user, and should clean it up
instead.

It turns out that we don't even need to open a second SHM lock
struct - if we get an error mapping the first one due to a lock
count mismatch, we can just delete it, and it cleans itself up
when it errors. So there's no reason not to return a valid
runtime.

Signed-off-by: Matthew Heon <matthew.heon@pm.me>
2019-02-21 10:51:42 -05:00

103 lines
2.2 KiB
Go

package lock
import (
"sync"
"github.com/pkg/errors"
)
// Mutex holds a single mutex and whether it has been allocated.
type Mutex struct {
id uint32
lock sync.Mutex
allocated bool
}
// ID retrieves the ID of the mutex
func (m *Mutex) ID() uint32 {
return m.id
}
// Lock locks the mutex
func (m *Mutex) Lock() {
m.lock.Lock()
}
// Unlock unlocks the mutex
func (m *Mutex) Unlock() {
m.lock.Unlock()
}
// Free deallocates the mutex to allow its reuse
func (m *Mutex) Free() error {
m.allocated = false
return nil
}
// InMemoryManager is a lock manager that allocates and retrieves local-only
// locks - that is, they are not multiprocess. This lock manager is intended
// purely for unit and integration testing and should not be used in production
// deployments.
type InMemoryManager struct {
locks []*Mutex
numLocks uint32
localLock sync.Mutex
}
// NewInMemoryManager creates a new in-memory lock manager with the given number
// of locks.
func NewInMemoryManager(numLocks uint32) (Manager, error) {
if numLocks == 0 {
return nil, errors.Errorf("must provide a non-zero number of locks!")
}
manager := new(InMemoryManager)
manager.numLocks = numLocks
manager.locks = make([]*Mutex, numLocks)
var i uint32
for i = 0; i < numLocks; i++ {
lock := new(Mutex)
lock.id = i
manager.locks[i] = lock
}
return manager, nil
}
// AllocateLock allocates a lock from the manager.
func (m *InMemoryManager) AllocateLock() (Locker, error) {
m.localLock.Lock()
defer m.localLock.Unlock()
for _, lock := range m.locks {
if !lock.allocated {
lock.allocated = true
return lock, nil
}
}
return nil, errors.Errorf("all locks have been allocated")
}
// RetrieveLock retrieves a lock from the manager.
func (m *InMemoryManager) RetrieveLock(id uint32) (Locker, error) {
if id >= m.numLocks {
return nil, errors.Errorf("given lock ID %d is too large - this manager only supports lock indexes up to %d", id, m.numLocks-1)
}
return m.locks[id], nil
}
// FreeAllLocks frees all locks.
// This function is DANGEROUS. Please read the full comment in locks.go before
// trying to use it.
func (m *InMemoryManager) FreeAllLocks() error {
for _, lock := range m.locks {
lock.allocated = false
}
return nil
}