root / src / Ganeti / Locking / Allocation.hs @ 1243b689
History | View | Annotate | Download (16.7 kB)
1 |
{-| Implementation of lock allocation. |
---|---|
2 |
|
3 |
-} |
4 |
|
5 |
{- |
6 |
|
7 |
Copyright (C) 2014 Google Inc. |
8 |
|
9 |
This program is free software; you can redistribute it and/or modify |
10 |
it under the terms of the GNU General Public License as published by |
11 |
the Free Software Foundation; either version 2 of the License, or |
12 |
(at your option) any later version. |
13 |
|
14 |
This program is distributed in the hope that it will be useful, but |
15 |
WITHOUT ANY WARRANTY; without even the implied warranty of |
16 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
17 |
General Public License for more details. |
18 |
|
19 |
You should have received a copy of the GNU General Public License |
20 |
along with this program; if not, write to the Free Software |
21 |
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
22 |
02110-1301, USA. |
23 |
|
24 |
-} |
25 |
|
26 |
module Ganeti.Locking.Allocation |
27 |
( LockAllocation |
28 |
, emptyAllocation |
29 |
, OwnerState(..) |
30 |
, lockOwners |
31 |
, listLocks |
32 |
, LockRequest(..) |
33 |
, requestExclusive |
34 |
, requestShared |
35 |
, requestRelease |
36 |
, updateLocks |
37 |
, freeLocks |
38 |
, freeLocksPredicate |
39 |
, downGradePredicate |
40 |
, intersectLocks |
41 |
, opportunisticLockUnion |
42 |
) where |
43 |
|
44 |
import Control.Applicative (liftA2, (<$>), (<*>)) |
45 |
import Control.Arrow (second, (***)) |
46 |
import Control.Monad |
47 |
import Data.Foldable (for_, find) |
48 |
import Data.List (sort) |
49 |
import qualified Data.Map as M |
50 |
import Data.Maybe (fromMaybe) |
51 |
import qualified Data.Set as S |
52 |
import qualified Text.JSON as J |
53 |
|
54 |
import Ganeti.BasicTypes |
55 |
import Ganeti.JSON (toArray) |
56 |
import Ganeti.Locking.Types |
57 |
|
58 |
{- |
59 |
|
60 |
This module is parametric in the type of locks and lock owners. |
61 |
While we only state minimal requirements for the types, we will |
62 |
consistently use the type variable 'a' for the type of locks and |
63 |
the variable 'b' for the type of the lock owners throughout this |
64 |
module. |
65 |
|
66 |
-} |
67 |
|
68 |
-- | Data type describing the way a lock can be owned. |
69 |
data OwnerState = OwnShared | OwnExclusive deriving (Ord, Eq, Show) |
70 |
|
71 |
-- | Type describing indirect ownership on a lock. We keep the set |
72 |
-- of all (lock, owner)-pairs for locks that are implied in the given |
73 |
-- lock, annotated with the type of ownership (shared or exclusive). |
74 |
type IndirectOwners a b = M.Map (a, b) OwnerState |
75 |
|
76 |
-- | The state of a lock that is taken. Besides the state of the lock |
77 |
-- itself, we also keep track of all other lock allocation that affect |
78 |
-- the given lock by means of implication. |
79 |
data AllocationState a b = Exclusive b (IndirectOwners a b) |
80 |
| Shared (S.Set b) (IndirectOwners a b) |
81 |
deriving (Eq, Show) |
82 |
|
83 |
-- | Compute the set of indirect owners from the information about |
84 |
-- indirect ownership. |
85 |
indirectOwners :: (Ord a, Ord b) => M.Map (a, b) OwnerState -> S.Set b |
86 |
indirectOwners = S.map snd . M.keysSet |
87 |
|
88 |
-- | Compute the (zero or one-elment) set of exclusive indirect owners. |
89 |
indirectExclusives :: (Ord a, Ord b) => M.Map (a, b) OwnerState -> S.Set b |
90 |
indirectExclusives = indirectOwners . M.filter (== OwnExclusive) |
91 |
|
92 |
{-| Representation of a Lock allocation |
93 |
|
94 |
To keep queries for locks efficient, we keep two |
95 |
associations, with the invariant that they fit |
96 |
together: the association from locks to their |
97 |
allocation state, and the association from an |
98 |
owner to the set of locks owned. As we do not |
99 |
export the constructor, the problem of keeping |
100 |
this invariant reduces to only exporting functions |
101 |
that keep the invariant. |
102 |
|
103 |
-} |
104 |
|
105 |
data LockAllocation a b = |
106 |
LockAllocation { laLocks :: M.Map a (AllocationState a b) |
107 |
, laOwned :: M.Map b (M.Map a OwnerState) |
108 |
} |
109 |
deriving (Eq, Show) |
110 |
|
111 |
-- | A state with all locks being free. |
112 |
emptyAllocation :: (Ord a, Ord b) => LockAllocation a b |
113 |
emptyAllocation = |
114 |
LockAllocation { laLocks = M.empty |
115 |
, laOwned = M.empty |
116 |
} |
117 |
|
118 |
-- | Obtain the list of all owners holding at least a single lock. |
119 |
lockOwners :: Ord b => LockAllocation a b -> [b] |
120 |
lockOwners = M.keys . laOwned |
121 |
|
122 |
-- | Obtain the locks held by a given owner. The locks are reported |
123 |
-- as a map from the owned locks to the form of ownership (OwnShared |
124 |
-- or OwnExclusive). |
125 |
listLocks :: Ord b => b -> LockAllocation a b -> M.Map a OwnerState |
126 |
listLocks owner = fromMaybe M.empty . M.lookup owner . laOwned |
127 |
|
128 |
-- | Data Type describing a change request on a single lock. |
129 |
data LockRequest a = LockRequest { lockAffected :: a |
130 |
, lockRequestType :: Maybe OwnerState |
131 |
} |
132 |
deriving (Eq, Show) |
133 |
|
134 |
-- | Lock request for an exclusive lock. |
135 |
requestExclusive :: a -> LockRequest a |
136 |
requestExclusive lock = LockRequest { lockAffected = lock |
137 |
, lockRequestType = Just OwnExclusive } |
138 |
|
139 |
-- | Lock request for a shared lock. |
140 |
requestShared :: a -> LockRequest a |
141 |
requestShared lock = LockRequest { lockAffected = lock |
142 |
, lockRequestType = Just OwnShared } |
143 |
|
144 |
-- | Request to release a lock. |
145 |
requestRelease :: a -> LockRequest a |
146 |
requestRelease lock = LockRequest { lockAffected = lock |
147 |
, lockRequestType = Nothing } |
148 |
|
149 |
-- | Update the Allocation state of a lock according to a given |
150 |
-- function. |
151 |
updateAllocState :: (Ord a, Ord b) |
152 |
=> (Maybe (AllocationState a b) -> AllocationState a b) |
153 |
-> LockAllocation a b -> a -> LockAllocation a b |
154 |
updateAllocState f state lock = |
155 |
let locks' = M.alter (find (/= Shared S.empty M.empty) . Just . f) |
156 |
lock (laLocks state) |
157 |
in state { laLocks = locks' } |
158 |
|
159 |
-- | Internal function to update the state according to a single |
160 |
-- lock request, assuming all prerequisites are met. |
161 |
updateLock :: (Ord a, Ord b) |
162 |
=> b |
163 |
-> LockAllocation a b -> LockRequest a -> LockAllocation a b |
164 |
updateLock owner state (LockRequest lock (Just OwnExclusive)) = |
165 |
let locks = laLocks state |
166 |
lockstate' = case M.lookup lock locks of |
167 |
Just (Exclusive _ i) -> Exclusive owner i |
168 |
Just (Shared _ i) -> Exclusive owner i |
169 |
Nothing -> Exclusive owner M.empty |
170 |
locks' = M.insert lock lockstate' locks |
171 |
ownersLocks' = M.insert lock OwnExclusive $ listLocks owner state |
172 |
owned' = M.insert owner ownersLocks' $ laOwned state |
173 |
in state { laLocks = locks', laOwned = owned' } |
174 |
updateLock owner state (LockRequest lock (Just OwnShared)) = |
175 |
let ownersLocks' = M.insert lock OwnShared $ listLocks owner state |
176 |
owned' = M.insert owner ownersLocks' $ laOwned state |
177 |
locks = laLocks state |
178 |
lockState' = case M.lookup lock locks of |
179 |
Just (Exclusive _ i) -> Shared (S.singleton owner) i |
180 |
Just (Shared s i) -> Shared (S.insert owner s) i |
181 |
_ -> Shared (S.singleton owner) M.empty |
182 |
locks' = M.insert lock lockState' locks |
183 |
in state { laLocks = locks', laOwned = owned' } |
184 |
updateLock owner state (LockRequest lock Nothing) = |
185 |
let ownersLocks' = M.delete lock $ listLocks owner state |
186 |
owned = laOwned state |
187 |
owned' = if M.null ownersLocks' |
188 |
then M.delete owner owned |
189 |
else M.insert owner ownersLocks' owned |
190 |
update (Just (Exclusive x i)) = if x == owner |
191 |
then Shared S.empty i |
192 |
else Exclusive x i |
193 |
update (Just (Shared s i)) = Shared (S.delete owner s) i |
194 |
update Nothing = Shared S.empty M.empty |
195 |
in updateAllocState update (state { laOwned = owned' }) lock |
196 |
|
197 |
-- | Update the set of indirect ownerships of a lock by the given function. |
198 |
updateIndirectSet :: (Ord a, Ord b) |
199 |
=> (IndirectOwners a b -> IndirectOwners a b) |
200 |
-> LockAllocation a b -> a -> LockAllocation a b |
201 |
updateIndirectSet f = |
202 |
let update (Just (Exclusive x i)) = Exclusive x (f i) |
203 |
update (Just (Shared s i)) = Shared s (f i) |
204 |
update Nothing = Shared S.empty (f M.empty) |
205 |
in updateAllocState update |
206 |
|
207 |
-- | Update all indirect onwerships of a given lock. |
208 |
updateIndirects :: (Lock a, Ord b) |
209 |
=> b |
210 |
-> LockAllocation a b -> LockRequest a -> LockAllocation a b |
211 |
updateIndirects owner state req = |
212 |
let lock = lockAffected req |
213 |
fn = case lockRequestType req of |
214 |
Nothing -> M.delete (lock, owner) |
215 |
Just tp -> M.insert (lock, owner) tp |
216 |
in foldl (updateIndirectSet fn) state $ lockImplications lock |
217 |
|
218 |
-- | Update the locks of an owner according to the given request. Return |
219 |
-- the pair of the new state and the result of the operation, which is the |
220 |
-- the set of owners on which the operation was blocked on. so an empty set is |
221 |
-- success, and the state is updated if, and only if, the returned set is emtpy. |
222 |
-- In that way, it can be used in atomicModifyIORef. |
223 |
updateLocks :: (Lock a, Ord b) |
224 |
=> b |
225 |
-> [LockRequest a] |
226 |
-> LockAllocation a b -> (LockAllocation a b, Result (S.Set b)) |
227 |
updateLocks owner reqs state = genericResult ((,) state . Bad) (second Ok) $ do |
228 |
unless ((==) (length reqs) . S.size . S.fromList $ map lockAffected reqs) |
229 |
. runListHead (return ()) |
230 |
(fail . (++) "Inconsitent requests for lock " . show) $ do |
231 |
r <- reqs |
232 |
r' <- reqs |
233 |
guard $ r /= r' |
234 |
guard $ lockAffected r == lockAffected r' |
235 |
return $ lockAffected r |
236 |
let current = listLocks owner state |
237 |
unless (M.null current) $ do |
238 |
let (highest, _) = M.findMax current |
239 |
notHolding = not |
240 |
. any (uncurry (==) . ((M.lookup `flip` current) *** Just)) |
241 |
orderViolation l = fail $ "Order violation: requesting " ++ show l |
242 |
++ " while holding " ++ show highest |
243 |
for_ reqs $ \req -> case req of |
244 |
LockRequest lock (Just OwnExclusive) |
245 |
| lock < highest && notHolding ((,) <$> lock : lockImplications lock |
246 |
<*> [OwnExclusive]) |
247 |
-> orderViolation lock |
248 |
LockRequest lock (Just OwnShared) |
249 |
| lock < highest && notHolding ((,) <$> lock : lockImplications lock |
250 |
<*> [OwnExclusive, OwnShared]) |
251 |
-> orderViolation lock |
252 |
_ -> Ok () |
253 |
let sharedsHeld = M.keysSet $ M.filter (== OwnShared) current |
254 |
exclusivesRequested = map lockAffected |
255 |
. filter ((== Just OwnExclusive) . lockRequestType) |
256 |
$ reqs |
257 |
runListHead (return ()) fail $ do |
258 |
x <- exclusivesRequested |
259 |
i <- lockImplications x |
260 |
guard $ S.member i sharedsHeld |
261 |
return $ "Order violation: requesting exclusively " ++ show x |
262 |
++ " while holding a shared lock on the group lock " ++ show i |
263 |
++ " it belongs to." |
264 |
let blockedOn (LockRequest _ Nothing) = S.empty |
265 |
blockedOn (LockRequest lock (Just OwnExclusive)) = |
266 |
case M.lookup lock (laLocks state) of |
267 |
Just (Exclusive x i) -> |
268 |
S.singleton x `S.union` indirectOwners i |
269 |
Just (Shared xs i) -> |
270 |
xs `S.union` indirectOwners i |
271 |
_ -> S.empty |
272 |
blockedOn (LockRequest lock (Just OwnShared)) = |
273 |
case M.lookup lock (laLocks state) of |
274 |
Just (Exclusive x i) -> |
275 |
S.singleton x `S.union` indirectExclusives i |
276 |
Just (Shared _ i) -> indirectExclusives i |
277 |
_ -> S.empty |
278 |
let indirectBlocked Nothing _ = S.empty |
279 |
indirectBlocked (Just OwnShared) lock = |
280 |
case M.lookup lock (laLocks state) of |
281 |
Just (Exclusive x _) -> S.singleton x |
282 |
_ -> S.empty |
283 |
indirectBlocked (Just OwnExclusive) lock = |
284 |
case M.lookup lock (laLocks state) of |
285 |
Just (Exclusive x _) -> S.singleton x |
286 |
Just (Shared xs _) -> xs |
287 |
_ -> S.empty |
288 |
let direct = S.unions $ map blockedOn reqs |
289 |
indirect = reqs >>= \req -> |
290 |
map (indirectBlocked (lockRequestType req)) |
291 |
. lockImplications $ lockAffected req |
292 |
let blocked = S.delete owner . S.unions $ direct:indirect |
293 |
let state' = foldl (updateLock owner) state reqs |
294 |
state'' = foldl (updateIndirects owner) state' reqs |
295 |
return (if S.null blocked then state'' else state, blocked) |
296 |
|
297 |
-- | Manipluate all locks of the owner with a given property. |
298 |
manipulateLocksPredicate :: (Lock a, Ord b) |
299 |
=> (a -> LockRequest a) |
300 |
-> (a -> Bool) |
301 |
-> b -> LockAllocation a b -> LockAllocation a b |
302 |
manipulateLocksPredicate req prop owner state = |
303 |
fst . flip (updateLocks owner) state . map req |
304 |
. filter prop |
305 |
. M.keys |
306 |
$ listLocks owner state |
307 |
|
308 |
-- | Compute the state after an owner releases all its locks that |
309 |
-- satisfy a certain property. |
310 |
freeLocksPredicate :: (Lock a, Ord b) |
311 |
=> (a -> Bool) |
312 |
-> LockAllocation a b -> b -> LockAllocation a b |
313 |
freeLocksPredicate prop = flip $ manipulateLocksPredicate requestRelease prop |
314 |
|
315 |
-- | Compute the state after an onwer releases all its locks. |
316 |
freeLocks :: (Lock a, Ord b) => LockAllocation a b -> b -> LockAllocation a b |
317 |
freeLocks = freeLocksPredicate (const True) |
318 |
|
319 |
-- | Downgrade to shared all locks held that satisfy a given predicate. |
320 |
downGradePredicate :: (Lock a, Ord b) |
321 |
=> (a -> Bool) |
322 |
-> b -> LockAllocation a b -> LockAllocation a b |
323 |
downGradePredicate = manipulateLocksPredicate requestShared |
324 |
|
325 |
-- | Restrict the locks of a user to a given set. |
326 |
intersectLocks :: (Lock a, Ord b) => b -> [a] |
327 |
-> LockAllocation a b -> LockAllocation a b |
328 |
intersectLocks owner locks state = |
329 |
let lockset = S.fromList locks |
330 |
toFree = filter (not . flip S.member lockset) |
331 |
. M.keys $ listLocks owner state |
332 |
in fst $ updateLocks owner (map requestRelease toFree) state |
333 |
|
334 |
-- | Opportunistically allocate locks for a given user; return the set |
335 |
-- of actually acquired. The signature is chosen to be suitable for |
336 |
-- atomicModifyIORef. |
337 |
opportunisticLockUnion :: (Lock a, Ord b) |
338 |
=> b -> [(a, OwnerState)] |
339 |
-> LockAllocation a b -> (LockAllocation a b, S.Set a) |
340 |
opportunisticLockUnion owner reqs state = |
341 |
let locks = listLocks owner state |
342 |
reqs' = sort $ filter (uncurry (<) . (flip M.lookup locks *** Just)) reqs |
343 |
maybeAllocate (s, success) (lock, ownstate) = |
344 |
let (s', result) = updateLocks owner |
345 |
[(if ownstate == OwnShared |
346 |
then requestShared |
347 |
else requestExclusive) lock] |
348 |
s |
349 |
in (s', if result == Ok S.empty then lock:success else success) |
350 |
in second S.fromList $ foldl maybeAllocate (state, []) reqs' |
351 |
|
352 |
{-| Serializaiton of Lock Allocations |
353 |
|
354 |
To serialize a lock allocation, we only remember which owner holds |
355 |
which locks at which level (shared or exclusive). From this information, |
356 |
everything else can be reconstructed, simply using updateLocks. |
357 |
-} |
358 |
|
359 |
instance J.JSON OwnerState where |
360 |
showJSON OwnShared = J.showJSON "shared" |
361 |
showJSON OwnExclusive = J.showJSON "exclusive" |
362 |
readJSON (J.JSString x) = let s = J.fromJSString x |
363 |
in case s of |
364 |
"shared" -> J.Ok OwnShared |
365 |
"exclusive" -> J.Ok OwnExclusive |
366 |
_ -> J.Error $ "Unknown owner type " ++ s |
367 |
readJSON _ = J.Error "Owner type not encoded as a string" |
368 |
|
369 |
-- | Read a lock-ownerstate pair from JSON. |
370 |
readLockOwnerstate :: (J.JSON a) => J.JSValue -> J.Result (a, OwnerState) |
371 |
readLockOwnerstate (J.JSArray [x, y]) = liftA2 (,) (J.readJSON x) (J.readJSON y) |
372 |
readLockOwnerstate x = fail $ "lock-ownerstate pairs are encoded as arrays" |
373 |
++ " of length 2, but found " ++ show x |
374 |
|
375 |
-- | Read an owner-lock pair from JSON. |
376 |
readOwnerLock :: (J.JSON a, J.JSON b) |
377 |
=> J.JSValue -> J.Result (b, [(a, OwnerState)]) |
378 |
readOwnerLock (J.JSArray [x, J.JSArray ys]) = |
379 |
liftA2 (,) (J.readJSON x) (mapM readLockOwnerstate ys) |
380 |
readOwnerLock x = fail $ "Expected pair of owner and list of owned locks," |
381 |
++ " but found " ++ show x |
382 |
|
383 |
-- | Transform a lock-ownerstate pair into a LockRequest. |
384 |
toRequest :: (a, OwnerState) -> LockRequest a |
385 |
toRequest (a, OwnExclusive) = requestExclusive a |
386 |
toRequest (a, OwnShared) = requestShared a |
387 |
|
388 |
-- | Obtain a LockAllocation from a given owner-locks list. |
389 |
-- The obtained allocation is the one obtained if the respective owners |
390 |
-- requested their locks sequentially. |
391 |
allocationFromOwners :: (Lock a, Ord b, Show b) |
392 |
=> [(b, [(a, OwnerState)])] |
393 |
-> J.Result (LockAllocation a b) |
394 |
allocationFromOwners = |
395 |
let allocateOneOwner s (o, req) = do |
396 |
let (s', result) = updateLocks o (map toRequest req) s |
397 |
when (result /= Ok S.empty) . fail |
398 |
. (++) ("Inconsistent lock status for " ++ show o ++ ": ") |
399 |
$ case result of |
400 |
Bad err -> err |
401 |
Ok blocked -> "blocked on " ++ show (S.toList blocked) |
402 |
return s' |
403 |
in foldM allocateOneOwner emptyAllocation |
404 |
|
405 |
instance (Lock a, J.JSON a, Ord b, J.JSON b, Show b) |
406 |
=> J.JSON (LockAllocation a b) where |
407 |
showJSON = J.showJSON . M.toList . M.map M.toList . laOwned |
408 |
readJSON x = do |
409 |
xs <- toArray x |
410 |
owned <- mapM readOwnerLock xs |
411 |
allocationFromOwners owned |