Debian Codegraph @

test/hs/Test/Ganeti/HTools/Cluster.hs

raw
1 {-# LANGUAGE TemplateHaskell #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
3
4 {-| Unittests for ganeti-htools.
5
6 -}
7
8 {-
9
10 Copyright (C) 2009, 2010, 2011, 2012 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.HTools.Cluster (testHTools_Cluster) where
39
40 import Test.QuickCheck hiding (Result)
41
42 import Control.Monad (liftM)
43 import qualified Data.IntMap as IntMap
44 import Data.Maybe
45
46 import Test.Ganeti.TestHelper
47 import Test.Ganeti.TestCommon
48 import Test.Ganeti.TestHTools
49 import Test.Ganeti.HTools.Instance ( genInstanceSmallerThanNode
50 , genInstanceMaybeBiggerThanNode )
51 import Test.Ganeti.HTools.Node (genOnlineNode, genNode)
52
53 import Ganeti.BasicTypes
54 import qualified Ganeti.HTools.AlgorithmParams as Alg
55 import qualified Ganeti.HTools.Backend.IAlloc as IAlloc
56 import qualified Ganeti.HTools.Cluster as Cluster
57 import qualified Ganeti.HTools.Cluster.AllocationSolution as AllocSol
58 import qualified Ganeti.HTools.Cluster.Evacuate as Evacuate
59 import qualified Ganeti.HTools.Cluster.Metrics as Metrics
60 import qualified Ganeti.HTools.Cluster.Utils as ClusterUtils
61 import qualified Ganeti.HTools.Container as Container
62 import qualified Ganeti.HTools.Group as Group
63 import qualified Ganeti.HTools.Instance as Instance
64 import qualified Ganeti.HTools.Node as Node
65 import qualified Ganeti.HTools.Types as Types
66 import qualified Ganeti.Types as Types (EvacMode(..))
67
68 {-# ANN module "HLint: ignore Use camelCase" #-}
69
70 -- * Helpers
71
72 -- | Make a small cluster, both nodes and instances.
73 makeSmallEmptyCluster :: Node.Node -> Int -> Instance.Instance
74 -> (Node.List, Instance.List, Instance.Instance)
75 makeSmallEmptyCluster node count inst =
76 (makeSmallCluster node count, Container.empty,
77 setInstanceSmallerThanNode node inst)
78
79 -- | Checks if a node is "big" enough.
80 isNodeBig :: Int -> Node.Node -> Bool
81 isNodeBig size node = Node.availDisk node > size * Types.unitDsk
82 && Node.availMem node > size * Types.unitMem
83 && Node.availCpu node > size * Types.unitCpu
84
85 canBalance :: Cluster.Table -> Bool -> Bool -> Bool -> Bool
86 canBalance tbl@(Cluster.Table _ _ ini_cv _) dm im evac =
87 maybe False (\(Cluster.Table _ _ fin_cv _) -> ini_cv - fin_cv > 1e-12)
88 $ Cluster.tryBalance (Alg.defaultOptions { Alg.algMinGain = 0.0
89 , Alg.algMinGainLimit = 0.0
90 , Alg.algDiskMoves = dm
91 , Alg.algInstanceMoves = im
92 , Alg.algEvacMode = evac}) tbl
93
94 -- | Assigns a new fresh instance to a cluster; this is not
95 -- allocation, so no resource checks are done.
96 assignInstance :: Node.List -> Instance.List -> Instance.Instance ->
97 Types.Idx -> Types.Idx ->
98 (Node.List, Instance.List)
99 assignInstance nl il inst pdx sdx =
100 let pnode = Container.find pdx nl
101 snode = Container.find sdx nl
102 maxiidx = if Container.null il
103 then 0
104 else fst (Container.findMax il) + 1
105 inst' = inst { Instance.idx = maxiidx,
106 Instance.pNode = pdx, Instance.sNode = sdx }
107 pnode' = Node.setPri pnode inst'
108 snode' = Node.setSec snode inst'
109 nl' = Container.addTwo pdx pnode' sdx snode' nl
110 il' = Container.add maxiidx inst' il
111 in (nl', il')
112
113 -- | Checks if an instance is mirrored.
114 isMirrored :: Instance.Instance -> Bool
115 isMirrored = (/= Types.MirrorNone) . Instance.mirrorType
116
117 -- | Returns the possible change node types for a disk template.
118 evacModeOptions :: Types.MirrorType -> [Types.EvacMode]
119 evacModeOptions Types.MirrorNone = []
120 evacModeOptions Types.MirrorInternal = [minBound..maxBound] -- DRBD can do all
121 evacModeOptions Types.MirrorExternal = [Types.ChangePrimary, Types.ChangeAll]
122
123 -- * Test cases
124
125 -- | Check that the cluster score is close to zero for a homogeneous
126 -- cluster.
127 prop_Score_Zero :: Node.Node -> Property
128 prop_Score_Zero node =
129 forAll (choose (1, 1024)) $ \count ->
130 (not (Node.offline node) && not (Node.failN1 node) && (count > 0) &&
131 (Node.tDsk node > 0) && (Node.tMem node > 0) &&
132 (Node.tSpindles node > 0) && (Node.tCpu node > 0)) ==>
133 let fn = Node.buildPeers node Container.empty
134 nlst = replicate count fn
135 score = Metrics.compCVNodes nlst
136 -- we can't say == 0 here as the floating point errors accumulate;
137 -- this should be much lower than the default score in CLI.hs
138 in score <= 1e-12
139
140 -- | Check that cluster stats are sane.
141 prop_CStats_sane :: Property
142 prop_CStats_sane =
143 forAll (choose (1, 1024)) $ \count ->
144 forAll genOnlineNode $ \node ->
145 let fn = Node.buildPeers node Container.empty
146 nlst = zip [1..] $ replicate count fn::[(Types.Ndx, Node.Node)]
147 nl = Container.fromList nlst
148 cstats = Cluster.totalResources nl
149 in Cluster.csAdsk cstats >= 0 &&
150 Cluster.csAdsk cstats <= Cluster.csFdsk cstats
151
152 -- | Check that one instance is allocated correctly on an empty cluster,
153 -- without rebalances needed.
154 prop_Alloc_sane :: Instance.Instance -> Property
155 prop_Alloc_sane inst =
156 forAll (choose (5, 20)) $ \count ->
157 forAll genOnlineNode $ \node ->
158 let (nl, il, inst') = makeSmallEmptyCluster node count inst
159 reqnodes = Instance.requiredNodes $ Instance.diskTemplate inst
160 opts = Alg.defaultOptions
161 in case Cluster.genAllocNodes Alg.defaultOptions
162 defGroupList nl reqnodes True >>=
163 Cluster.tryAlloc opts nl il inst' of
164 Bad msg -> failTest msg
165 Ok as ->
166 case AllocSol.asSolution as of
167 Nothing -> failTest "Failed to allocate, empty solution"
168 Just (xnl, xi, _, cv) ->
169 let il' = Container.add (Instance.idx xi) xi il
170 tbl = Cluster.Table xnl il' cv []
171 in counterexample "Cluster can be balanced after allocation"
172 (not (canBalance tbl True True False)) .&&.
173 counterexample "Solution score differs from actual node list"
174 (abs (Metrics.compCV xnl - cv) < 1e-12)
175
176 -- | Checks that on a 2-5 node cluster, we can allocate a random
177 -- instance spec via tiered allocation (whatever the original instance
178 -- spec), on either one or two nodes. Furthermore, we test that
179 -- computed allocation statistics are correct.
180 prop_CanTieredAlloc :: Property
181 prop_CanTieredAlloc =
182 forAll (choose (2, 5)) $ \count ->
183 forAll (liftM (Node.setPolicy Types.defIPolicy)
184 (genOnlineNode `suchThat` isNodeBig 5)) $ \node ->
185 forAll (genInstanceMaybeBiggerThanNode node) $ \inst ->
186 let nl = makeSmallCluster node count
187 il = Container.empty
188 rqnodes = Instance.requiredNodes $ Instance.diskTemplate inst
189 allocnodes = Cluster.genAllocNodes Alg.defaultOptions
190 defGroupList nl rqnodes True
191 opts = Alg.defaultOptions
192 in case allocnodes >>= \allocnodes' ->
193 Cluster.tieredAlloc opts nl il (Just 5) inst allocnodes' [] [] of
194 Bad msg -> failTest $ "Failed to tiered alloc: " ++ msg
195 Ok (_, nl', il', ixes, cstats) ->
196 let (ai_alloc, ai_pool, ai_unav) =
197 Cluster.computeAllocationDelta
198 (Cluster.totalResources nl)
199 (Cluster.totalResources nl')
200 all_nodes fn = sum $ map fn (Container.elems nl)
201 all_res fn = sum $ map fn [ai_alloc, ai_pool, ai_unav]
202 in conjoin
203 [ counterexample "No instances allocated" $ not (null ixes)
204 , IntMap.size il' ==? length ixes
205 , length ixes ==? length cstats
206 , all_res Types.allocInfoVCpus ==? all_nodes Node.hiCpu
207 , all_res Types.allocInfoNCpus ==? all_nodes Node.tCpu
208 , all_res Types.allocInfoMem ==? truncate (all_nodes Node.tMem)
209 , all_res Types.allocInfoDisk ==? truncate (all_nodes Node.tDsk)
210 ]
211
212 -- | Helper function to create a cluster with the given range of nodes
213 -- and allocate an instance on it.
214 genClusterAlloc :: Int -> Node.Node -> Instance.Instance
215 -> Result (Node.List, Instance.List, Instance.Instance)
216 genClusterAlloc count node inst =
217 let nl = makeSmallCluster node count
218 reqnodes = Instance.requiredNodes $ Instance.diskTemplate inst
219 opts = Alg.defaultOptions
220 in case Cluster.genAllocNodes Alg.defaultOptions
221 defGroupList nl reqnodes True >>=
222 Cluster.tryAlloc opts nl Container.empty inst of
223 Bad msg -> Bad $ "Can't allocate: " ++ msg
224 Ok as ->
225 case AllocSol.asSolution as of
226 Nothing -> Bad "Empty solution?"
227 Just (xnl, xi, _, _) ->
228 let xil = Container.add (Instance.idx xi) xi Container.empty
229 in Ok (xnl, xil, xi)
230
231 -- | Checks that on a 4-8 node cluster, once we allocate an instance,
232 -- we can also relocate it.
233 prop_AllocRelocate :: Property
234 prop_AllocRelocate =
235 forAll (choose (4, 8)) $ \count ->
236 forAll (genOnlineNode `suchThat` isNodeBig 4) $ \node ->
237 forAll (genInstanceSmallerThanNode node `suchThat` isMirrored) $ \inst ->
238 case genClusterAlloc count node inst of
239 Bad msg -> failTest msg
240 Ok (nl, il, inst') ->
241 case IAlloc.processRelocate Alg.defaultOptions defGroupList nl il
242 (Instance.idx inst) 1
243 [(if Instance.diskTemplate inst' == Types.DTDrbd8
244 then Instance.sNode
245 else Instance.pNode) inst'] of
246 Ok _ -> passTest
247 Bad msg -> failTest $ "Failed to relocate: " ++ msg
248
249 -- | Helper property checker for the result of a nodeEvac or
250 -- changeGroup operation.
251 check_EvacMode :: Group.Group -> Instance.Instance
252 -> Result (Node.List, Instance.List, Evacuate.EvacSolution)
253 -> Property
254 check_EvacMode grp inst result =
255 case result of
256 Bad msg -> failTest $ "Couldn't evacuate/change group:" ++ msg
257 Ok (_, _, es) ->
258 let moved = Evacuate.esMoved es
259 failed = Evacuate.esFailed es
260 opcodes = not . null $ Evacuate.esOpCodes es
261 in conjoin
262 [ failmsg ("'failed' not empty: " ++ show failed) (null failed)
263 , failmsg "'opcodes' is null" opcodes
264 , case moved of
265 [(idx', gdx, _)] ->
266 failmsg "invalid instance moved" (idx == idx') .&&.
267 failmsg "wrong target group" (gdx == Group.idx grp)
268 v -> failmsg ("invalid solution: " ++ show v) False
269 ]
270 where failmsg :: String -> Bool -> Property
271 failmsg msg = counterexample ("Failed to evacuate: " ++ msg)
272 idx = Instance.idx inst
273
274 -- | Checks that on a 4-8 node cluster, once we allocate an instance,
275 -- we can also node-evacuate it.
276 prop_AllocEvacuate :: Property
277 prop_AllocEvacuate =
278 forAll (choose (4, 8)) $ \count ->
279 forAll (genOnlineNode `suchThat` isNodeBig 4) $ \node ->
280 forAll (genInstanceSmallerThanNode node `suchThat` isMirrored) $ \inst ->
281 case genClusterAlloc count node inst of
282 Bad msg -> failTest msg
283 Ok (nl, il, inst') ->
284 conjoin . map (\mode -> check_EvacMode defGroup inst' $
285 Evacuate.tryNodeEvac Alg.defaultOptions
286 defGroupList nl il mode
287 [Instance.idx inst']) .
288 evacModeOptions .
289 Instance.mirrorType $ inst'
290
291 -- | Checks that on a 4-8 node cluster with two node groups, once we
292 -- allocate an instance on the first node group, we can also change
293 -- its group.
294 prop_AllocChangeGroup :: Property
295 prop_AllocChangeGroup =
296 forAll (choose (4, 8)) $ \count ->
297 forAll (genOnlineNode `suchThat` isNodeBig 4) $ \node ->
298 forAll (genInstanceSmallerThanNode node `suchThat` isMirrored) $ \inst ->
299 case genClusterAlloc count node inst of
300 Bad msg -> failTest msg
301 Ok (nl, il, inst') ->
302 -- we need to add a second node group and nodes to the cluster
303 let nl2 = Container.elems $ makeSmallCluster node count
304 grp2 = Group.setIdx defGroup (Group.idx defGroup + 1)
305 maxndx = maximum . map Node.idx $ nl2
306 nl3 = map (\n -> n { Node.group = Group.idx grp2
307 , Node.idx = Node.idx n + maxndx }) nl2
308 nl4 = Container.fromList . map (\n -> (Node.idx n, n)) $ nl3
309 gl' = Container.add (Group.idx grp2) grp2 defGroupList
310 nl' = IntMap.union nl nl4
311 opts = Alg.defaultOptions
312 in check_EvacMode grp2 inst' $
313 Cluster.tryChangeGroup opts gl' nl' il [] [Instance.idx inst']
314
315 -- | Check that allocating multiple instances on a cluster, then
316 -- adding an empty node, results in a valid rebalance.
317 prop_AllocBalance :: Property
318 prop_AllocBalance =
319 forAll (genNode (Just 5) (Just 128)) $ \node ->
320 forAll (choose (3, 5)) $ \count ->
321 not (Node.offline node) && not (Node.failN1 node) ==>
322 let nl = makeSmallCluster node count
323 hnode = snd $ IntMap.findMax nl
324 nl' = IntMap.deleteMax nl
325 il = Container.empty
326 allocnodes = Cluster.genAllocNodes Alg.defaultOptions
327 defGroupList nl' 2 True
328 i_templ = createInstance Types.unitMem Types.unitDsk Types.unitCpu
329 opts = Alg.defaultOptions
330 in case allocnodes >>= \allocnodes' ->
331 Cluster.iterateAlloc opts nl' il (Just 5) i_templ allocnodes' [] [] of
332 Bad msg -> failTest $ "Failed to allocate: " ++ msg
333 Ok (_, _, _, [], _) -> failTest "Failed to allocate: no instances"
334 Ok (_, xnl, il', _, _) ->
335 let ynl = Container.add (Node.idx hnode) hnode xnl
336 cv = Metrics.compCV ynl
337 tbl = Cluster.Table ynl il' cv []
338 in counterexample "Failed to rebalance" $
339 canBalance tbl True True False
340
341 -- | Checks consistency.
342 prop_CheckConsistency :: Node.Node -> Instance.Instance -> Bool
343 prop_CheckConsistency node inst =
344 let nl = makeSmallCluster node 3
345 (node1, node2, node3) =
346 case Container.elems nl of
347 [a, b, c] -> (a, b, c)
348 l -> error $ "Invalid node list out of makeSmallCluster/3: " ++
349 show l
350 node3' = node3 { Node.group = 1 }
351 nl' = Container.add (Node.idx node3') node3' nl
352 inst1 = Instance.setBoth inst (Node.idx node1) (Node.idx node2)
353 inst2 = Instance.setBoth inst (Node.idx node1) Node.noSecondary
354 inst3 = Instance.setBoth inst (Node.idx node1) (Node.idx node3)
355 ccheck = Cluster.findSplitInstances nl' . Container.fromList
356 in null (ccheck [(0, inst1)]) &&
357 null (ccheck [(0, inst2)]) &&
358 (not . null $ ccheck [(0, inst3)])
359
360 -- | For now, we only test that we don't lose instances during the split.
361 prop_SplitCluster :: Node.Node -> Instance.Instance -> Property
362 prop_SplitCluster node inst =
363 forAll (choose (0, 100)) $ \icnt ->
364 let nl = makeSmallCluster node 2
365 (nl', il') = foldl (\(ns, is) _ -> assignInstance ns is inst 0 1)
366 (nl, Container.empty) [1..icnt]
367 gni = ClusterUtils.splitCluster nl' il'
368 in sum (map (Container.size . snd . snd) gni) == icnt &&
369 all (\(guuid, (nl'', _)) -> all ((== guuid) . Node.group)
370 (Container.elems nl'')) gni
371
372 -- | Helper function to check if we can allocate an instance on a
373 -- given node list. Successful allocation is denoted by 'Nothing',
374 -- otherwise the 'Just' value will contain the error message.
375 canAllocOn :: Node.List -> Int -> Instance.Instance -> Maybe String
376 canAllocOn nl reqnodes inst =
377 case Cluster.genAllocNodes Alg.defaultOptions
378 defGroupList nl reqnodes True >>=
379 Cluster.tryAlloc Alg.defaultOptions nl Container.empty inst of
380 Bad msg -> Just $ "Can't allocate: " ++ msg
381 Ok as ->
382 case AllocSol.asSolution as of
383 Nothing -> Just $ "No allocation solution; failures: " ++
384 show (AllocSol.collapseFailures $ AllocSol.asFailures as)
385 Just _ -> Nothing
386
387 -- | Checks that allocation obeys minimum and maximum instance
388 -- policies. The unittest generates a random node, duplicates it /count/
389 -- times, and generates a random instance that can be allocated on
390 -- this mini-cluster; it then checks that after applying a policy that
391 -- the instance doesn't fits, the allocation fails.
392 prop_AllocPolicy :: Property
393 prop_AllocPolicy =
394 forAll genOnlineNode $ \node ->
395 forAll (choose (5, 20)) $ \count ->
396 forAll (genInstanceSmallerThanNode node) $ \inst ->
397 forAll (arbitrary `suchThat`
398 (isBad . flip (Instance.instMatchesPolicy inst)
399 (Node.exclStorage node))) $ \ipol ->
400 let rqn = Instance.requiredNodes $ Instance.diskTemplate inst
401 node' = Node.setPolicy ipol node
402 nl = makeSmallCluster node' count
403 in counterexample "Allocation check:"
404 (isNothing (canAllocOn (makeSmallCluster node count) rqn inst)) .&&.
405 counterexample "Policy failure check:" (isJust $ canAllocOn nl rqn inst)
406
407 testSuite "HTools/Cluster"
408 [ 'prop_Score_Zero
409 , 'prop_CStats_sane
410 , 'prop_Alloc_sane
411 , 'prop_CanTieredAlloc
412 , 'prop_AllocRelocate
413 , 'prop_AllocEvacuate
414 , 'prop_AllocChangeGroup
415 , 'prop_AllocBalance
416 , 'prop_CheckConsistency
417 , 'prop_SplitCluster
418 , 'prop_AllocPolicy
419 ]