Debian Codegraph @

test/hs/Test/Ganeti/Locking/Waiting.hs

raw
1 {-# LANGUAGE TemplateHaskell #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
3
4 {-| Tests for lock waiting structure.
5
6 -}
7
8 {-
9
10 Copyright (C) 2014 Google Inc.
11 All rights reserved.
12
13 Redistribution and use in source and binary forms, with or without
14 modification, are permitted provided that the following conditions are
15 met:
16
17 1. Redistributions of source code must retain the above copyright notice,
18 this list of conditions and the following disclaimer.
19
20 2. Redistributions in binary form must reproduce the above copyright
21 notice, this list of conditions and the following disclaimer in the
22 documentation and/or other materials provided with the distribution.
23
24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
28 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
36 -}
37
38 module Test.Ganeti.Locking.Waiting (testLocking_Waiting) where
39
40 import Control.Applicative (liftA2)
41 import Control.Monad (liftM)
42 import qualified Data.Map as M
43 import qualified Data.Set as S
44 import qualified Text.JSON as J
45
46 import Test.QuickCheck
47
48 import Test.Ganeti.TestCommon
49 import Test.Ganeti.TestHelper
50 import Test.Ganeti.Locking.Allocation (TestLock, TestOwner, requestSucceeded)
51
52 import Ganeti.BasicTypes (isBad, genericResult, runListHead)
53 import Ganeti.Locking.Allocation (LockRequest, listLocks)
54 import qualified Ganeti.Locking.Allocation as L
55 import Ganeti.Locking.Types (Lock)
56 import Ganeti.Locking.Waiting
57
58 {-
59
60 Ganeti.Locking.Waiting is polymorphic in the types of locks, lock owners,
61 and priorities. So we can use much simpler types here than Ganeti's
62 real locks and lock owners, knowning that polymorphic functions cannot
63 exploit the simplicity of the types they're deling with. To avoid code
64 duplication, we use the test structure from Test.Ganeti.Locking.Allocation.
65
66 -}
67
68 {-
69
70 All states of a LockWaiting ever available outside the module can be
71 obtained from @emptyWaiting@ applying one of the update operations.
72
73 -}
74
75 data UpdateRequest a b c = Update b [LockRequest a]
76 | UpdateWaiting c b [LockRequest a]
77 | RemovePending b
78 | IntersectRequest b [a]
79 | OpportunisticUnion b [(a, L.OwnerState)]
80 deriving Show
81
82 instance (Arbitrary a, Arbitrary b, Arbitrary c)
83 => Arbitrary (UpdateRequest a b c) where
84 arbitrary =
85 frequency [ (2, Update <$> arbitrary <*> (choose (1, 4) >>= vector))
86 , (4, UpdateWaiting <$> arbitrary <*> arbitrary
87 <*> (choose (1, 4) >>= vector))
88 , (1, RemovePending <$> arbitrary)
89 , (1, IntersectRequest <$> arbitrary
90 <*> (choose (1, 4) >>= vector))
91 , (1, OpportunisticUnion <$> arbitrary
92 <*> (choose (1, 4) >>= vector))
93 ]
94
95 -- | Transform an UpdateRequest into the corresponding state transformer.
96 asWaitingTrans :: (Lock a, Ord b, Ord c)
97 => LockWaiting a b c -> UpdateRequest a b c -> LockWaiting a b c
98 asWaitingTrans state (Update owner req) = fst $ updateLocks owner req state
99 asWaitingTrans state (UpdateWaiting prio owner req) =
100 fst $ updateLocksWaiting prio owner req state
101 asWaitingTrans state (RemovePending owner) = removePendingRequest owner state
102 asWaitingTrans state (IntersectRequest owner locks) =
103 fst $ intersectLocks locks owner state
104 asWaitingTrans state (OpportunisticUnion owner locks) =
105 fst $ opportunisticLockUnion owner locks state
106
107
108 -- | Fold a sequence of requests to transform a waiting strucutre onto the
109 -- empty waiting. As we consider all exported transformations, any waiting
110 -- structure can be obtained this way.
111 foldUpdates :: (Lock a, Ord b, Ord c)
112 => [UpdateRequest a b c] -> LockWaiting a b c
113 foldUpdates = foldl asWaitingTrans emptyWaiting
114
115 instance (Arbitrary a, Lock a, Arbitrary b, Ord b, Arbitrary c, Ord c)
116 => Arbitrary (LockWaiting a b c) where
117 arbitrary = foldUpdates <$> (choose (0, 8) >>= vector)
118
119 -- | Verify that an owner with a pending request cannot make any
120 -- changes to the lock structure.
121 prop_NoActionWithPendingRequests :: Property
122 prop_NoActionWithPendingRequests =
123 forAll (arbitrary :: Gen TestOwner) $ \a ->
124 forAll ((arbitrary :: Gen (LockWaiting TestLock TestOwner Integer))
125 `suchThat` (S.member a . getPendingOwners)) $ \state ->
126 forAll (arbitrary :: Gen [LockRequest TestLock]) $ \req ->
127 forAll arbitrary $ \prio ->
128 counterexample "Owners with pending requests may not update locks"
129 . all (isBad . fst . snd)
130 $ [updateLocks, updateLocksWaiting prio] <*> [a] <*> [req] <*> [state]
131
132 -- | Quantifier for blocked requests. Quantifies over the generic situation
133 -- that there is a state, an owner, and a request that is blocked for that
134 -- owner. To obtain such a situation, we use the fact that there must be a
135 -- different owner having at least one lock.
136 forAllBlocked :: (Testable prop)
137 => (LockWaiting TestLock TestOwner Integer -- State
138 -> TestOwner -- The owner of the blocked request
139 -> Integer -- The priority
140 -> [LockRequest TestLock] -- Request
141 -> prop)
142 -> Property
143 forAllBlocked predicate =
144 forAll (arbitrary :: Gen TestOwner) $ \a ->
145 forAll (arbitrary :: Gen Integer) $ \prio ->
146 forAll (arbitrary `suchThat` (/=) a) $ \b ->
147 forAll ((arbitrary :: Gen (LockWaiting TestLock TestOwner Integer))
148 `suchThat` foldl (liftA2 (&&)) (const True)
149 [ not . S.member a . getPendingOwners
150 , M.null . listLocks a . getAllocation
151 , not . M.null . listLocks b . getAllocation]) $ \state ->
152 forAll ((arbitrary :: Gen [LockRequest TestLock])
153 `suchThat` (genericResult (const False) (not . S.null)
154 . fst . snd . flip (updateLocksWaiting prio a) state))
155 $ \req ->
156 predicate state a prio req
157
158 -- | Verify that an owner has a pending request after a waiting request
159 -- not fullfilled immediately.
160 prop_WaitingRequestsGetPending :: Property
161 prop_WaitingRequestsGetPending =
162 forAllBlocked $ \state owner prio req ->
163 counterexample "After a not immediately fulfilled waiting request, owner\
164 \ must have a pending request"
165 . S.member owner . getPendingOwners . fst
166 $ updateLocksWaiting prio owner req state
167
168 -- | Verify that pending requests get fullfilled once all blockers release
169 -- their resources.
170 prop_PendingGetFulfilledEventually :: Property
171 prop_PendingGetFulfilledEventually =
172 forAllBlocked $ \state owner prio req ->
173 let oldpending = getPendingOwners state
174 (state', (resultBlockers, _)) = updateLocksWaiting prio owner req state
175 blockers = genericResult (const S.empty) id resultBlockers
176 state'' = S.foldl (\s a -> fst $ releaseResources a s) state'
177 $ S.union oldpending blockers
178 finallyOwned = listLocks owner $ getAllocation state''
179 in counterexample "After all blockers and old pending owners give up their\
180 \ resources, a pending request must be granted\
181 \ automatically"
182 $ all (requestSucceeded finallyOwned) req
183
184 -- | Verify that the owner of a pending request gets notified once all blockers
185 -- release their resources.
186 prop_PendingGetNotifiedEventually :: Property
187 prop_PendingGetNotifiedEventually =
188 forAllBlocked $ \state owner prio req ->
189 let oldpending = getPendingOwners state
190 (state', (resultBlockers, _)) = updateLocksWaiting prio owner req state
191 blockers = genericResult (const S.empty) id resultBlockers
192 releaseOneOwner (s, tonotify) o =
193 let (s', newnotify) = releaseResources o s
194 in (s', newnotify `S.union` tonotify)
195 (_, notified) = S.foldl releaseOneOwner (state', S.empty)
196 $ S.union oldpending blockers
197 in counterexample "After all blockers and old pending owners give up their\
198 \ resources, a pending owner must be notified"
199 $ S.member owner notified
200
201 -- | Verify that some progress is made after the direct blockers give up their
202 -- locks. Note that we cannot guarantee that the original requester gets its
203 -- request granted, as someone else might have a more important priority.
204 prop_Progress :: Property
205 prop_Progress =
206 forAllBlocked $ \state owner prio req ->
207 let (state', (resultBlockers, _)) = updateLocksWaiting prio owner req state
208 blockers = genericResult (const S.empty) id resultBlockers
209 releaseOneOwner (s, tonotify) o =
210 let (s', newnotify) = releaseResources o s
211 in (s', newnotify `S.union` tonotify)
212 (_, notified) = S.foldl releaseOneOwner (state', S.empty) blockers
213 in counterexample "Some progress must be made after all blockers release\
214 \ their locks"
215 . not . S.null $ notified S.\\ blockers
216
217 -- | Verify that the notifications send out are sound, i.e., upon notification
218 -- the requests actually are fulfilled. To be sure to have at least one
219 -- notification we, again, use the scenario that a request is blocked and then
220 -- all the blockers release their resources.
221 prop_ProgressSound :: Property
222 prop_ProgressSound =
223 forAllBlocked $ \state owner prio req ->
224 let (state', (resultBlockers, _)) = updateLocksWaiting prio owner req state
225 blockers = genericResult (const S.empty) id resultBlockers
226 releaseOneOwner (s, tonotify) o =
227 let (s', newnotify) = releaseResources o s
228 in (s', newnotify `S.union` tonotify)
229 (state'', notified) = S.foldl releaseOneOwner (state', S.empty) blockers
230 requestFulfilled o =
231 runListHead False
232 (\(_, _, r) ->
233 all (requestSucceeded . listLocks o $ getAllocation state'') r)
234 . S.toList . S.filter (\(_, b, _) -> b == o)
235 . getPendingRequests $ state'
236 in counterexample "If an owner gets notified, his request must be satisfied"
237 . all requestFulfilled . S.toList $ notified S.\\ blockers
238
239 -- | Verify that all pending requests are valid and cannot be fulfilled in
240 -- the underlying lock allocation.
241 prop_PendingJustified :: Property
242 prop_PendingJustified =
243 forAll ((arbitrary :: Gen (LockWaiting TestLock TestOwner Integer))
244 `suchThat` (not . S.null . getPendingRequests)) $ \state ->
245 let isJustified (_, b, req) =
246 genericResult (const False) (not . S.null) . snd
247 . L.updateLocks b req $ getAllocation state
248 in counterexample "Pending requests must be good and not fulfillable"
249 . all isJustified . S.toList $ getPendingRequests state
250
251 -- | Verify that `updateLocks` is idempotent, except that in the repetition,
252 -- no waiters are notified.
253 prop_UpdateIdempotent :: Property
254 prop_UpdateIdempotent =
255 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
256 forAll (arbitrary :: Gen TestOwner) $ \owner ->
257 forAll (arbitrary :: Gen [LockRequest TestLock]) $ \req ->
258 let (state', (answer', _)) = updateLocks owner req state
259 (state'', (answer'', nfy)) = updateLocks owner req state'
260 in conjoin [ counterexample ("repeated updateLocks waiting gave different\
261 \ answers: " ++ show answer' ++ " /= "
262 ++ show answer'') $ answer' == answer''
263 , counterexample "updateLocks not idempotent"
264 $ extRepr state' == extRepr state''
265 , counterexample ("notifications (" ++ show nfy ++ ") on replay")
266 $ S.null nfy
267 ]
268
269 -- | Verify that extRepr . fromExtRepr = id for all valid extensional
270 -- representations.
271 prop_extReprPreserved :: Property
272 prop_extReprPreserved =
273 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
274 let rep = extRepr state
275 rep' = extRepr $ fromExtRepr rep
276 in counterexample "a lock waiting obtained from an extensional representation\
277 \ must have the same extensional representation"
278 $ rep' == rep
279
280 -- | Verify that any state is indistinguishable from its canonical version
281 -- (i.e., the one obtained from the extensional representation) with respect
282 -- to updateLocks.
283 prop_SimulateUpdateLocks :: Property
284 prop_SimulateUpdateLocks =
285 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
286 forAll (arbitrary :: Gen TestOwner) $ \owner ->
287 forAll (arbitrary :: Gen [LockRequest TestLock]) $ \req ->
288 let state' = fromExtRepr $ extRepr state
289 (finState, (result, notify)) = updateLocks owner req state
290 (finState', (result', notify')) = updateLocks owner req state'
291 in counterexample "extRepr-equal states must behave equal on updateLocks"
292 $ and [ result == result'
293 , notify == notify'
294 , extRepr finState == extRepr finState'
295 ]
296 -- | Verify that any state is indistinguishable from its canonical version
297 -- (i.e., the one obtained from the extensional representation) with respect
298 -- to updateLocksWaiting.
299 prop_SimulateUpdateLocksWaiting :: Property
300 prop_SimulateUpdateLocksWaiting =
301 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
302 forAll (arbitrary :: Gen TestOwner) $ \owner ->
303 forAll (arbitrary :: Gen Integer) $ \prio ->
304 forAll (arbitrary :: Gen [LockRequest TestLock]) $ \req ->
305 let state' = fromExtRepr $ extRepr state
306 (finState, (result, notify)) = updateLocksWaiting prio owner req state
307 (finState', (result', notify')) = updateLocksWaiting prio owner req state'
308 in counterexample "extRepr-equal states must behave equal on updateLocks"
309 $ and [ result == result'
310 , notify == notify'
311 , extRepr finState == extRepr finState'
312 ]
313
314 -- | Verify that if a requestor has no pending requests, `safeUpdateWaiting`
315 -- conincides with `updateLocksWaiting`.
316 prop_SafeUpdateWaitingCorrect :: Property
317 prop_SafeUpdateWaitingCorrect =
318 forAll (arbitrary :: Gen TestOwner) $ \owner ->
319 forAll ((arbitrary :: Gen (LockWaiting TestLock TestOwner Integer))
320 `suchThat` (not . hasPendingRequest owner)) $ \state ->
321 forAll (arbitrary :: Gen Integer) $ \prio ->
322 forAll (arbitrary :: Gen [LockRequest TestLock]) $ \req ->
323 let (state', answer') = updateLocksWaiting prio owner req state
324 (state'', answer'') = safeUpdateLocksWaiting prio owner req state
325 in conjoin [ counterexample ("safeUpdateLocksWaiting gave different answer: "
326 ++ show answer' ++ " /= " ++ show answer'')
327 $ answer' == answer''
328 , counterexample ("safeUpdateLocksWaiting gave different states\
329 \ after answer " ++ show answer' ++ ": "
330 ++ show (extRepr state') ++ " /= "
331 ++ show (extRepr state''))
332 $ extRepr state' == extRepr state''
333 ]
334
335 -- | Verify that `safeUpdateLocksWaiting` is idempotent, that in the repetition
336 -- no notifications are done.
337 prop_SafeUpdateWaitingIdempotent :: Property
338 prop_SafeUpdateWaitingIdempotent =
339 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
340 forAll (arbitrary :: Gen TestOwner) $ \owner ->
341 forAll (arbitrary :: Gen Integer) $ \prio ->
342 forAll (arbitrary :: Gen [LockRequest TestLock]) $ \req ->
343 let (state', (answer', _)) = safeUpdateLocksWaiting prio owner req state
344 (state'', (answer'', nfy)) = safeUpdateLocksWaiting prio owner req state'
345 in conjoin [ counterexample ("repeated safeUpdateLocks waiting gave different\
346 \ answers: " ++ show answer' ++ " /= "
347 ++ show answer'') $ answer' == answer''
348 , counterexample "safeUpdateLocksWaiting not idempotent"
349 $ extRepr state' == extRepr state''
350 , counterexample ("notifications (" ++ show nfy ++ ") on replay")
351 $ S.null nfy
352 ]
353
354 -- | Verify that for LockWaiting we have readJSON . showJSON is extensionally
355 -- equivalent to Ok.
356 prop_ReadShow :: Property
357 prop_ReadShow =
358 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
359 (liftM extRepr . J.readJSON $ J.showJSON state) ==? (J.Ok $ extRepr state)
360
361 -- | Verify that opportunistic union only increases the locks held.
362 prop_OpportunisticMonotone :: Property
363 prop_OpportunisticMonotone =
364 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
365 forAll (arbitrary :: Gen TestOwner) $ \a ->
366 forAll ((choose (1,3) >>= vector) :: Gen [(TestLock, L.OwnerState)]) $ \req ->
367 let (state', _) = opportunisticLockUnion a req state
368 oldOwned = listLocks a $ getAllocation state
369 oldLocks = M.keys oldOwned
370 newOwned = listLocks a $ getAllocation state'
371 in counterexample "Opportunistic union may only increase the set of locks\
372 \ held"
373 . flip all oldLocks $ \lock ->
374 M.lookup lock newOwned >= M.lookup lock oldOwned
375
376 -- | Verify the result list of the opportunistic union: if a lock is not in
377 -- the result that, than its state has not changed, and if it is, it is as
378 -- requested. The latter property is tested in that liberal way, so that we
379 -- really can take arbitrary requests, including those that require both, shared
380 -- and exlusive state for the same lock.
381 prop_OpportunisticAnswer :: Property
382 prop_OpportunisticAnswer =
383 forAll (arbitrary :: Gen (LockWaiting TestLock TestOwner Integer)) $ \state ->
384 forAll (arbitrary :: Gen TestOwner) $ \a ->
385 forAll ((choose (1,3) >>= vector) :: Gen [(TestLock, L.OwnerState)]) $ \req ->
386 let (state', (result, _)) = opportunisticLockUnion a req state
387 oldOwned = listLocks a $ getAllocation state
388 newOwned = listLocks a $ getAllocation state'
389 involvedLocks = M.keys oldOwned ++ map fst req
390 in conjoin [ counterexample ("Locks not in the answer set " ++ show result
391 ++ " may not be changed, but found "
392 ++ show state')
393 . flip all involvedLocks $ \lock ->
394 (lock `elem` result)
395 || (M.lookup lock oldOwned == M.lookup lock newOwned)
396 , counterexample ("Locks not in the answer set " ++ show result
397 ++ " must be as requested, but found "
398 ++ show state')
399 . flip all involvedLocks $ \lock ->
400 notElem lock result
401 || maybe False (flip elem req . (,) lock)
402 (M.lookup lock newOwned)
403 ]
404
405
406 testSuite "Locking/Waiting"
407 [ 'prop_NoActionWithPendingRequests
408 , 'prop_WaitingRequestsGetPending
409 , 'prop_PendingGetFulfilledEventually
410 , 'prop_PendingGetNotifiedEventually
411 , 'prop_Progress
412 , 'prop_ProgressSound
413 , 'prop_PendingJustified
414 , 'prop_extReprPreserved
415 , 'prop_UpdateIdempotent
416 , 'prop_SimulateUpdateLocks
417 , 'prop_SimulateUpdateLocksWaiting
418 , 'prop_ReadShow
419 , 'prop_SafeUpdateWaitingCorrect
420 , 'prop_SafeUpdateWaitingIdempotent
421 , 'prop_OpportunisticMonotone
422 , 'prop_OpportunisticAnswer
423 ]