2016-07-20 01:37:28 +00:00
|
|
|
package locksutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2019-02-06 02:01:18 +00:00
|
|
|
|
2019-04-12 21:54:35 +00:00
|
|
|
"github.com/hashicorp/vault/sdk/helper/cryptoutil"
|
2016-07-20 01:37:28 +00:00
|
|
|
)
|
|
|
|
|
2017-03-07 16:21:32 +00:00
|
|
|
const (
|
|
|
|
LockCount = 256
|
|
|
|
)
|
2016-07-20 08:48:35 +00:00
|
|
|
|
2017-03-07 16:21:32 +00:00
|
|
|
type LockEntry struct {
|
|
|
|
sync.RWMutex
|
|
|
|
}
|
2016-08-30 20:36:58 +00:00
|
|
|
|
2018-03-20 18:54:10 +00:00
|
|
|
// CreateLocks returns an array so that the locks can be iterated over in
|
2017-11-30 14:43:07 +00:00
|
|
|
// order.
|
|
|
|
//
|
|
|
|
// This is only threadsafe if a process is using a single lock, or iterating
|
2018-03-20 18:54:10 +00:00
|
|
|
// over the entire lock slice in order. Using a consistent order avoids
|
2017-11-30 14:43:07 +00:00
|
|
|
// deadlocks because you can never have the following:
|
|
|
|
//
|
|
|
|
// Lock A, Lock B
|
|
|
|
// Lock B, Lock A
|
|
|
|
//
|
|
|
|
// Where process 1 is now deadlocked trying to lock B, and process 2 deadlocked trying to lock A
|
2017-03-07 16:21:32 +00:00
|
|
|
func CreateLocks() []*LockEntry {
|
|
|
|
ret := make([]*LockEntry, LockCount)
|
|
|
|
for i := range ret {
|
|
|
|
ret[i] = new(LockEntry)
|
2016-07-20 01:37:28 +00:00
|
|
|
}
|
2017-03-07 16:21:32 +00:00
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
func LockIndexForKey(key string) uint8 {
|
2019-02-06 02:01:18 +00:00
|
|
|
return uint8(cryptoutil.Blake2b256Hash(key)[0])
|
2017-03-07 16:21:32 +00:00
|
|
|
}
|
2016-07-20 08:48:35 +00:00
|
|
|
|
2017-03-07 16:21:32 +00:00
|
|
|
func LockForKey(locks []*LockEntry, key string) *LockEntry {
|
|
|
|
return locks[LockIndexForKey(key)]
|
2016-07-20 01:37:28 +00:00
|
|
|
}
|
2017-11-30 14:43:07 +00:00
|
|
|
|
|
|
|
func LocksForKeys(locks []*LockEntry, keys []string) []*LockEntry {
|
|
|
|
lockIndexes := make(map[uint8]struct{}, len(keys))
|
|
|
|
for _, k := range keys {
|
|
|
|
lockIndexes[LockIndexForKey(k)] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
locksToReturn := make([]*LockEntry, 0, len(keys))
|
|
|
|
for i, l := range locks {
|
|
|
|
if _, ok := lockIndexes[uint8(i)]; ok {
|
|
|
|
locksToReturn = append(locksToReturn, l)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return locksToReturn
|
|
|
|
}
|