2020-02-17 14:37:49 +00:00
|
|
|
package csimanager
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// volumeUsageTracker tracks the allocations that depend on a given volume
|
|
|
|
type volumeUsageTracker struct {
|
|
|
|
// state is a map of volumeUsageKey to a slice of allocation ids
|
|
|
|
state map[volumeUsageKey][]string
|
|
|
|
stateMu sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func newVolumeUsageTracker() *volumeUsageTracker {
|
|
|
|
return &volumeUsageTracker{
|
|
|
|
state: make(map[volumeUsageKey][]string),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type volumeUsageKey struct {
|
2020-04-02 20:04:56 +00:00
|
|
|
id string
|
2020-02-17 14:37:49 +00:00
|
|
|
usageOpts UsageOptions
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *volumeUsageTracker) allocsForKey(key volumeUsageKey) []string {
|
|
|
|
return v.state[key]
|
|
|
|
}
|
|
|
|
|
2020-04-02 20:04:56 +00:00
|
|
|
func (v *volumeUsageTracker) appendAlloc(key volumeUsageKey, allocID string) {
|
2020-02-17 14:37:49 +00:00
|
|
|
allocs := v.allocsForKey(key)
|
2020-04-02 20:04:56 +00:00
|
|
|
allocs = append(allocs, allocID)
|
2020-02-17 14:37:49 +00:00
|
|
|
v.state[key] = allocs
|
|
|
|
}
|
|
|
|
|
2020-04-02 20:04:56 +00:00
|
|
|
func (v *volumeUsageTracker) removeAlloc(key volumeUsageKey, needle string) {
|
2020-02-17 14:37:49 +00:00
|
|
|
allocs := v.allocsForKey(key)
|
|
|
|
var newAllocs []string
|
|
|
|
for _, allocID := range allocs {
|
2020-04-02 20:04:56 +00:00
|
|
|
if allocID != needle {
|
2020-02-17 14:37:49 +00:00
|
|
|
newAllocs = append(newAllocs, allocID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(newAllocs) == 0 {
|
|
|
|
delete(v.state, key)
|
|
|
|
} else {
|
|
|
|
v.state[key] = newAllocs
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-02 20:04:56 +00:00
|
|
|
func (v *volumeUsageTracker) Claim(allocID, volID string, usage *UsageOptions) {
|
2020-02-17 14:37:49 +00:00
|
|
|
v.stateMu.Lock()
|
|
|
|
defer v.stateMu.Unlock()
|
|
|
|
|
2020-04-02 20:04:56 +00:00
|
|
|
key := volumeUsageKey{id: volID, usageOpts: *usage}
|
|
|
|
v.appendAlloc(key, allocID)
|
2020-02-17 14:37:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Free removes the allocation from the state list for the given alloc. If the
|
|
|
|
// alloc is the last allocation for the volume then it returns true.
|
2020-04-02 20:04:56 +00:00
|
|
|
func (v *volumeUsageTracker) Free(allocID, volID string, usage *UsageOptions) bool {
|
2020-02-17 14:37:49 +00:00
|
|
|
v.stateMu.Lock()
|
|
|
|
defer v.stateMu.Unlock()
|
|
|
|
|
2020-04-02 20:04:56 +00:00
|
|
|
key := volumeUsageKey{id: volID, usageOpts: *usage}
|
|
|
|
v.removeAlloc(key, allocID)
|
2020-02-17 14:37:49 +00:00
|
|
|
allocs := v.allocsForKey(key)
|
|
|
|
return len(allocs) == 0
|
|
|
|
}
|