summaryrefslogtreecommitdiff
path: root/libpod/lock/file_lock_manager.go
blob: adcc42d4eae3b85048d2d82d5f006c5cbd685982 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package lock

import (
	"github.com/containers/libpod/v2/libpod/lock/file"
)

// FileLockManager manages shared memory locks.
type FileLockManager struct {
	locks *file.FileLocks
}

// NewFileLockManager makes a new FileLockManager at the specified directory.
func NewFileLockManager(lockPath string) (Manager, error) {
	locks, err := file.CreateFileLock(lockPath)
	if err != nil {
		return nil, err
	}

	manager := new(FileLockManager)
	manager.locks = locks

	return manager, nil
}

// OpenFileLockManager opens an existing FileLockManager at the specified directory.
func OpenFileLockManager(path string) (Manager, error) {
	locks, err := file.OpenFileLock(path)
	if err != nil {
		return nil, err
	}

	manager := new(FileLockManager)
	manager.locks = locks

	return manager, nil
}

// AllocateLock allocates a new lock from the manager.
func (m *FileLockManager) AllocateLock() (Locker, error) {
	semIndex, err := m.locks.AllocateLock()
	if err != nil {
		return nil, err
	}

	lock := new(FileLock)
	lock.lockID = semIndex
	lock.manager = m

	return lock, nil
}

// AllocateAndRetrieveLock allocates the lock with the given ID and returns it.
// If the lock is already allocated, error.
func (m *FileLockManager) AllocateAndRetrieveLock(id uint32) (Locker, error) {
	lock := new(FileLock)
	lock.lockID = id
	lock.manager = m

	if err := m.locks.AllocateGivenLock(id); err != nil {
		return nil, err
	}

	return lock, nil
}

// RetrieveLock retrieves a lock from the manager given its ID.
func (m *FileLockManager) RetrieveLock(id uint32) (Locker, error) {
	lock := new(FileLock)
	lock.lockID = id
	lock.manager = m

	return lock, nil
}

// FreeAllLocks frees all locks in the manager.
// This function is DANGEROUS. Please read the full comment in locks.go before
// trying to use it.
func (m *FileLockManager) FreeAllLocks() error {
	return m.locks.DeallocateAllLocks()
}

// FileLock is an individual shared memory lock.
type FileLock struct {
	lockID  uint32
	manager *FileLockManager
}

// ID returns the ID of the lock.
func (l *FileLock) ID() uint32 {
	return l.lockID
}

// Lock acquires the lock.
func (l *FileLock) Lock() {
	if err := l.manager.locks.LockFileLock(l.lockID); err != nil {
		panic(err.Error())
	}
}

// Unlock releases the lock.
func (l *FileLock) Unlock() {
	if err := l.manager.locks.UnlockFileLock(l.lockID); err != nil {
		panic(err.Error())
	}
}

// Free releases the lock, allowing it to be reused.
func (l *FileLock) Free() error {
	return l.manager.locks.DeallocateLock(l.lockID)
}