Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / QC.hs @ 15e3d31c

History | View | Annotate | Download (57.5 kB)

1
{-# LANGUAGE TemplateHaskell #-}
2

    
3
{-| Unittests for ganeti-htools.
4

    
5
-}
6

    
7
{-
8

    
9
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
10

    
11
This program is free software; you can redistribute it and/or modify
12
it under the terms of the GNU General Public License as published by
13
the Free Software Foundation; either version 2 of the License, or
14
(at your option) any later version.
15

    
16
This program is distributed in the hope that it will be useful, but
17
WITHOUT ANY WARRANTY; without even the implied warranty of
18
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
General Public License for more details.
20

    
21
You should have received a copy of the GNU General Public License
22
along with this program; if not, write to the Free Software
23
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24
02110-1301, USA.
25

    
26
-}
27

    
28
module Ganeti.HTools.QC
29
  ( testUtils
30
  , testPeerMap
31
  , testContainer
32
  , testInstance
33
  , testNode
34
  , testText
35
  , testSimu
36
  , testOpCodes
37
  , testJobs
38
  , testCluster
39
  , testLoader
40
  , testTypes
41
  , testCLI
42
  ) where
43

    
44
import Test.QuickCheck
45
import Text.Printf (printf)
46
import Data.List (findIndex, intercalate, nub, isPrefixOf)
47
import qualified Data.Set as Set
48
import Data.Maybe
49
import Control.Monad
50
import qualified System.Console.GetOpt as GetOpt
51
import qualified Text.JSON as J
52
import qualified Data.Map
53
import qualified Data.IntMap as IntMap
54

    
55
import qualified Ganeti.OpCodes as OpCodes
56
import qualified Ganeti.Jobs as Jobs
57
import qualified Ganeti.Luxi
58
import qualified Ganeti.HTools.CLI as CLI
59
import qualified Ganeti.HTools.Cluster as Cluster
60
import qualified Ganeti.HTools.Container as Container
61
import qualified Ganeti.HTools.ExtLoader
62
import qualified Ganeti.HTools.IAlloc as IAlloc
63
import qualified Ganeti.HTools.Instance as Instance
64
import qualified Ganeti.HTools.JSON as JSON
65
import qualified Ganeti.HTools.Loader as Loader
66
import qualified Ganeti.HTools.Luxi
67
import qualified Ganeti.HTools.Node as Node
68
import qualified Ganeti.HTools.Group as Group
69
import qualified Ganeti.HTools.PeerMap as PeerMap
70
import qualified Ganeti.HTools.Rapi
71
import qualified Ganeti.HTools.Simu as Simu
72
import qualified Ganeti.HTools.Text as Text
73
import qualified Ganeti.HTools.Types as Types
74
import qualified Ganeti.HTools.Utils as Utils
75
import qualified Ganeti.HTools.Version
76
import qualified Ganeti.Constants as C
77

    
78
import qualified Ganeti.HTools.Program as Program
79
import qualified Ganeti.HTools.Program.Hail
80
import qualified Ganeti.HTools.Program.Hbal
81
import qualified Ganeti.HTools.Program.Hscan
82
import qualified Ganeti.HTools.Program.Hspace
83

    
84
import Ganeti.HTools.QCHelper (testSuite)
85

    
86
-- * Constants
87

    
88
-- | Maximum memory (1TiB, somewhat random value).
89
maxMem :: Int
90
maxMem = 1024 * 1024
91

    
92
-- | Maximum disk (8TiB, somewhat random value).
93
maxDsk :: Int
94
maxDsk = 1024 * 1024 * 8
95

    
96
-- | Max CPUs (1024, somewhat random value).
97
maxCpu :: Int
98
maxCpu = 1024
99

    
100
-- | All disk templates (used later)
101
allDiskTemplates :: [Types.DiskTemplate]
102
allDiskTemplates = [minBound..maxBound]
103

    
104
-- | Null iPolicy, and by null we mean very liberal.
105
nullIPolicy = Types.IPolicy
106
  { Types.iPolicyMinSpec = Types.ISpec { Types.iSpecMemorySize = 0
107
                                       , Types.iSpecCpuCount   = 0
108
                                       , Types.iSpecDiskSize   = 0
109
                                       , Types.iSpecDiskCount  = 0
110
                                       , Types.iSpecNicCount   = 0
111
                                       }
112
  , Types.iPolicyMaxSpec = Types.ISpec { Types.iSpecMemorySize = maxBound
113
                                       , Types.iSpecCpuCount   = maxBound
114
                                       , Types.iSpecDiskSize   = maxBound
115
                                       , Types.iSpecDiskCount  = C.maxDisks
116
                                       , Types.iSpecNicCount   = C.maxNics
117
                                       }
118
  , Types.iPolicyStdSpec = Types.ISpec { Types.iSpecMemorySize = Types.unitMem
119
                                       , Types.iSpecCpuCount   = Types.unitCpu
120
                                       , Types.iSpecDiskSize   = Types.unitDsk
121
                                       , Types.iSpecDiskCount  = 1
122
                                       , Types.iSpecNicCount   = 1
123
                                       }
124
  , Types.iPolicyDiskTemplates = [Types.DTDrbd8, Types.DTPlain]
125
  }
126

    
127

    
128
defGroup :: Group.Group
129
defGroup = flip Group.setIdx 0 $
130
             Group.create "default" Types.defaultGroupID Types.AllocPreferred
131
                  nullIPolicy
132

    
133
defGroupList :: Group.List
134
defGroupList = Container.fromList [(Group.idx defGroup, defGroup)]
135

    
136
defGroupAssoc :: Data.Map.Map String Types.Gdx
137
defGroupAssoc = Data.Map.singleton (Group.uuid defGroup) (Group.idx defGroup)
138

    
139
-- * Helper functions
140

    
141
-- | Simple checker for whether OpResult is fail or pass.
142
isFailure :: Types.OpResult a -> Bool
143
isFailure (Types.OpFail _) = True
144
isFailure _ = False
145

    
146
-- | Checks for equality with proper annotation.
147
(==?) :: (Show a, Eq a) => a -> a -> Property
148
(==?) x y = printTestCase
149
            ("Expected equality, but '" ++
150
             show x ++ "' /= '" ++ show y ++ "'") (x == y)
151
infix 3 ==?
152

    
153
-- | Show a message and fail the test.
154
failTest :: String -> Property
155
failTest msg = printTestCase msg False
156

    
157
-- | Update an instance to be smaller than a node.
158
setInstanceSmallerThanNode node inst =
159
  inst { Instance.mem = Node.availMem node `div` 2
160
       , Instance.dsk = Node.availDisk node `div` 2
161
       , Instance.vcpus = Node.availCpu node `div` 2
162
       }
163

    
164
-- | Create an instance given its spec.
165
createInstance mem dsk vcpus =
166
  Instance.create "inst-unnamed" mem dsk vcpus Types.Running [] True (-1) (-1)
167
    Types.DTDrbd8
168

    
169
-- | Create a small cluster by repeating a node spec.
170
makeSmallCluster :: Node.Node -> Int -> Node.List
171
makeSmallCluster node count =
172
  let origname = Node.name node
173
      origalias = Node.alias node
174
      nodes = map (\idx -> node { Node.name = origname ++ "-" ++ show idx
175
                                , Node.alias = origalias ++ "-" ++ show idx })
176
              [1..count]
177
      fn = flip Node.buildPeers Container.empty
178
      namelst = map (\n -> (Node.name n, fn n)) nodes
179
      (_, nlst) = Loader.assignIndices namelst
180
  in nlst
181

    
182
-- | Make a small cluster, both nodes and instances.
183
makeSmallEmptyCluster :: Node.Node -> Int -> Instance.Instance
184
                      -> (Node.List, Instance.List, Instance.Instance)
185
makeSmallEmptyCluster node count inst =
186
  (makeSmallCluster node count, Container.empty,
187
   setInstanceSmallerThanNode node inst)
188

    
189
-- | Checks if a node is "big" enough.
190
isNodeBig :: Int -> Node.Node -> Bool
191
isNodeBig size node = Node.availDisk node > size * Types.unitDsk
192
                      && Node.availMem node > size * Types.unitMem
193
                      && Node.availCpu node > size * Types.unitCpu
194

    
195
canBalance :: Cluster.Table -> Bool -> Bool -> Bool -> Bool
196
canBalance tbl dm im evac = isJust $ Cluster.tryBalance tbl dm im evac 0 0
197

    
198
-- | Assigns a new fresh instance to a cluster; this is not
199
-- allocation, so no resource checks are done.
200
assignInstance :: Node.List -> Instance.List -> Instance.Instance ->
201
                  Types.Idx -> Types.Idx ->
202
                  (Node.List, Instance.List)
203
assignInstance nl il inst pdx sdx =
204
  let pnode = Container.find pdx nl
205
      snode = Container.find sdx nl
206
      maxiidx = if Container.null il
207
                  then 0
208
                  else fst (Container.findMax il) + 1
209
      inst' = inst { Instance.idx = maxiidx,
210
                     Instance.pNode = pdx, Instance.sNode = sdx }
211
      pnode' = Node.setPri pnode inst'
212
      snode' = Node.setSec snode inst'
213
      nl' = Container.addTwo pdx pnode' sdx snode' nl
214
      il' = Container.add maxiidx inst' il
215
  in (nl', il')
216

    
217
-- | Generates a list of a given size with non-duplicate elements.
218
genUniquesList :: (Eq a, Arbitrary a) => Int -> Gen [a]
219
genUniquesList cnt =
220
  foldM (\lst _ -> do
221
           newelem <- arbitrary `suchThat` (`notElem` lst)
222
           return (newelem:lst)) [] [1..cnt]
223

    
224
-- * Arbitrary instances
225

    
226
-- | Defines a DNS name.
227
newtype DNSChar = DNSChar { dnsGetChar::Char }
228

    
229
instance Arbitrary DNSChar where
230
  arbitrary = do
231
    x <- elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
232
    return (DNSChar x)
233

    
234
-- | Generates a single name component.
235
getName :: Gen String
236
getName = do
237
  n <- choose (1, 64)
238
  dn <- vector n::Gen [DNSChar]
239
  return (map dnsGetChar dn)
240

    
241
-- | Generates an entire FQDN.
242
getFQDN :: Gen String
243
getFQDN = do
244
  ncomps <- choose (1, 4)
245
  names <- mapM (const getName) [1..ncomps::Int]
246
  return $ intercalate "." names
247

    
248
-- | Defines a tag type.
249
newtype TagChar = TagChar { tagGetChar :: Char }
250

    
251
-- | All valid tag chars. This doesn't need to match _exactly_
252
-- Ganeti's own tag regex, just enough for it to be close.
253
tagChar :: [Char]
254
tagChar = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ".+*/:@-"
255

    
256
instance Arbitrary TagChar where
257
  arbitrary = do
258
    c <- elements tagChar
259
    return (TagChar c)
260

    
261
-- | Generates a tag
262
genTag :: Gen [TagChar]
263
genTag = do
264
  -- the correct value would be C.maxTagLen, but that's way too
265
  -- verbose in unittests, and at the moment I don't see any possible
266
  -- bugs with longer tags and the way we use tags in htools
267
  n <- choose (1, 10)
268
  vector n
269

    
270
-- | Generates a list of tags (correctly upper bounded).
271
genTags :: Gen [String]
272
genTags = do
273
  -- the correct value would be C.maxTagsPerObj, but per the comment
274
  -- in genTag, we don't use tags enough in htools to warrant testing
275
  -- such big values
276
  n <- choose (0, 10::Int)
277
  tags <- mapM (const genTag) [1..n]
278
  return $ map (map tagGetChar) tags
279

    
280
instance Arbitrary Types.InstanceStatus where
281
    arbitrary = elements [minBound..maxBound]
282

    
283
-- | Generates a random instance with maximum disk/mem/cpu values.
284
genInstanceSmallerThan :: Int -> Int -> Int -> Gen Instance.Instance
285
genInstanceSmallerThan lim_mem lim_dsk lim_cpu = do
286
  name <- getFQDN
287
  mem <- choose (0, lim_mem)
288
  dsk <- choose (0, lim_dsk)
289
  run_st <- arbitrary
290
  pn <- arbitrary
291
  sn <- arbitrary
292
  vcpus <- choose (0, lim_cpu)
293
  return $ Instance.create name mem dsk vcpus run_st [] True pn sn
294
         Types.DTDrbd8
295

    
296
-- | Generates an instance smaller than a node.
297
genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance
298
genInstanceSmallerThanNode node =
299
  genInstanceSmallerThan (Node.availMem node `div` 2)
300
                         (Node.availDisk node `div` 2)
301
                         (Node.availCpu node `div` 2)
302

    
303
-- let's generate a random instance
304
instance Arbitrary Instance.Instance where
305
  arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu
306

    
307
-- | Generas an arbitrary node based on sizing information.
308
genNode :: Maybe Int -- ^ Minimum node size in terms of units
309
        -> Maybe Int -- ^ Maximum node size (when Nothing, bounded
310
                     -- just by the max... constants)
311
        -> Gen Node.Node
312
genNode min_multiplier max_multiplier = do
313
  let (base_mem, base_dsk, base_cpu) =
314
        case min_multiplier of
315
          Just mm -> (mm * Types.unitMem,
316
                      mm * Types.unitDsk,
317
                      mm * Types.unitCpu)
318
          Nothing -> (0, 0, 0)
319
      (top_mem, top_dsk, top_cpu)  =
320
        case max_multiplier of
321
          Just mm -> (mm * Types.unitMem,
322
                      mm * Types.unitDsk,
323
                      mm * Types.unitCpu)
324
          Nothing -> (maxMem, maxDsk, maxCpu)
325
  name  <- getFQDN
326
  mem_t <- choose (base_mem, top_mem)
327
  mem_f <- choose (base_mem, mem_t)
328
  mem_n <- choose (0, mem_t - mem_f)
329
  dsk_t <- choose (base_dsk, top_dsk)
330
  dsk_f <- choose (base_dsk, dsk_t)
331
  cpu_t <- choose (base_cpu, top_cpu)
332
  offl  <- arbitrary
333
  let n = Node.create name (fromIntegral mem_t) mem_n mem_f
334
          (fromIntegral dsk_t) dsk_f (fromIntegral cpu_t) offl 0
335
      n' = Node.setPolicy nullIPolicy n
336
  return $ Node.buildPeers n' Container.empty
337

    
338
-- | Helper function to generate a sane node.
339
genOnlineNode :: Gen Node.Node
340
genOnlineNode = do
341
  arbitrary `suchThat` (\n -> not (Node.offline n) &&
342
                              not (Node.failN1 n) &&
343
                              Node.availDisk n > 0 &&
344
                              Node.availMem n > 0 &&
345
                              Node.availCpu n > 0)
346

    
347
-- and a random node
348
instance Arbitrary Node.Node where
349
  arbitrary = genNode Nothing Nothing
350

    
351
-- replace disks
352
instance Arbitrary OpCodes.ReplaceDisksMode where
353
  arbitrary = elements [minBound..maxBound]
354

    
355
instance Arbitrary OpCodes.OpCode where
356
  arbitrary = do
357
    op_id <- elements [ "OP_TEST_DELAY"
358
                      , "OP_INSTANCE_REPLACE_DISKS"
359
                      , "OP_INSTANCE_FAILOVER"
360
                      , "OP_INSTANCE_MIGRATE"
361
                      ]
362
    case op_id of
363
      "OP_TEST_DELAY" ->
364
        liftM3 OpCodes.OpTestDelay arbitrary arbitrary arbitrary
365
      "OP_INSTANCE_REPLACE_DISKS" ->
366
        liftM5 OpCodes.OpInstanceReplaceDisks arbitrary arbitrary
367
          arbitrary arbitrary arbitrary
368
      "OP_INSTANCE_FAILOVER" ->
369
        liftM3 OpCodes.OpInstanceFailover arbitrary arbitrary
370
          arbitrary
371
      "OP_INSTANCE_MIGRATE" ->
372
        liftM5 OpCodes.OpInstanceMigrate arbitrary arbitrary
373
          arbitrary arbitrary arbitrary
374
      _ -> fail "Wrong opcode"
375

    
376
instance Arbitrary Jobs.OpStatus where
377
  arbitrary = elements [minBound..maxBound]
378

    
379
instance Arbitrary Jobs.JobStatus where
380
  arbitrary = elements [minBound..maxBound]
381

    
382
newtype SmallRatio = SmallRatio Double deriving Show
383
instance Arbitrary SmallRatio where
384
  arbitrary = do
385
    v <- choose (0, 1)
386
    return $ SmallRatio v
387

    
388
instance Arbitrary Types.AllocPolicy where
389
  arbitrary = elements [minBound..maxBound]
390

    
391
instance Arbitrary Types.DiskTemplate where
392
  arbitrary = elements [minBound..maxBound]
393

    
394
instance Arbitrary Types.FailMode where
395
  arbitrary = elements [minBound..maxBound]
396

    
397
instance Arbitrary Types.EvacMode where
398
  arbitrary = elements [minBound..maxBound]
399

    
400
instance Arbitrary a => Arbitrary (Types.OpResult a) where
401
  arbitrary = arbitrary >>= \c ->
402
              if c
403
                then liftM Types.OpGood arbitrary
404
                else liftM Types.OpFail arbitrary
405

    
406
instance Arbitrary Types.ISpec where
407
  arbitrary = do
408
    mem_s <- arbitrary::Gen (NonNegative Int)
409
    dsk_c <- arbitrary::Gen (NonNegative Int)
410
    dsk_s <- arbitrary::Gen (NonNegative Int)
411
    cpu_c <- arbitrary::Gen (NonNegative Int)
412
    nic_c <- arbitrary::Gen (NonNegative Int)
413
    return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
414
                       , Types.iSpecCpuCount   = fromIntegral cpu_c
415
                       , Types.iSpecDiskSize   = fromIntegral dsk_s
416
                       , Types.iSpecDiskCount  = fromIntegral dsk_c
417
                       , Types.iSpecNicCount   = fromIntegral nic_c
418
                       }
419

    
420
-- | Generates an ispec bigger than the given one.
421
genBiggerISpec :: Types.ISpec -> Gen Types.ISpec
422
genBiggerISpec imin = do
423
  mem_s <- choose (Types.iSpecMemorySize imin, maxBound)
424
  dsk_c <- choose (Types.iSpecDiskCount imin, maxBound)
425
  dsk_s <- choose (Types.iSpecDiskSize imin, maxBound)
426
  cpu_c <- choose (Types.iSpecCpuCount imin, maxBound)
427
  nic_c <- choose (Types.iSpecNicCount imin, maxBound)
428
  return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
429
                     , Types.iSpecCpuCount   = fromIntegral cpu_c
430
                     , Types.iSpecDiskSize   = fromIntegral dsk_s
431
                     , Types.iSpecDiskCount  = fromIntegral dsk_c
432
                     , Types.iSpecNicCount   = fromIntegral nic_c
433
                     }
434

    
435
instance Arbitrary Types.IPolicy where
436
  arbitrary = do
437
    imin <- arbitrary
438
    istd <- genBiggerISpec imin
439
    imax <- genBiggerISpec istd
440
    num_tmpl <- choose (0, length allDiskTemplates)
441
    dts  <- genUniquesList num_tmpl
442
    return Types.IPolicy { Types.iPolicyMinSpec = imin
443
                         , Types.iPolicyStdSpec = istd
444
                         , Types.iPolicyMaxSpec = imax
445
                         , Types.iPolicyDiskTemplates = dts
446
                         }
447

    
448
-- * Actual tests
449

    
450
-- ** Utils tests
451

    
452
-- | If the list is not just an empty element, and if the elements do
453
-- not contain commas, then join+split should be idempotent.
454
prop_Utils_commaJoinSplit =
455
  forAll (arbitrary `suchThat`
456
          (\l -> l /= [""] && all (notElem ',') l )) $ \lst ->
457
  Utils.sepSplit ',' (Utils.commaJoin lst) ==? lst
458

    
459
-- | Split and join should always be idempotent.
460
prop_Utils_commaSplitJoin s =
461
  Utils.commaJoin (Utils.sepSplit ',' s) ==? s
462

    
463
-- | fromObjWithDefault, we test using the Maybe monad and an integer
464
-- value.
465
prop_Utils_fromObjWithDefault def_value random_key =
466
  -- a missing key will be returned with the default
467
  JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
468
  -- a found key will be returned as is, not with default
469
  JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
470
       random_key (def_value+1) == Just def_value
471
    where _types = def_value :: Integer
472

    
473
-- | Test that functional if' behaves like the syntactic sugar if.
474
prop_Utils_if'if :: Bool -> Int -> Int -> Gen Prop
475
prop_Utils_if'if cnd a b =
476
  Utils.if' cnd a b ==? if cnd then a else b
477

    
478
-- | Test basic select functionality
479
prop_Utils_select :: Int      -- ^ Default result
480
                  -> [Int]    -- ^ List of False values
481
                  -> [Int]    -- ^ List of True values
482
                  -> Gen Prop -- ^ Test result
483
prop_Utils_select def lst1 lst2 =
484
  Utils.select def (flist ++ tlist) ==? expectedresult
485
    where expectedresult = Utils.if' (null lst2) def (head lst2)
486
          flist = zip (repeat False) lst1
487
          tlist = zip (repeat True)  lst2
488

    
489
-- | Test basic select functionality with undefined default
490
prop_Utils_select_undefd :: [Int]            -- ^ List of False values
491
                         -> NonEmptyList Int -- ^ List of True values
492
                         -> Gen Prop         -- ^ Test result
493
prop_Utils_select_undefd lst1 (NonEmpty lst2) =
494
  Utils.select undefined (flist ++ tlist) ==? head lst2
495
    where flist = zip (repeat False) lst1
496
          tlist = zip (repeat True)  lst2
497

    
498
-- | Test basic select functionality with undefined list values
499
prop_Utils_select_undefv :: [Int]            -- ^ List of False values
500
                         -> NonEmptyList Int -- ^ List of True values
501
                         -> Gen Prop         -- ^ Test result
502
prop_Utils_select_undefv lst1 (NonEmpty lst2) =
503
  Utils.select undefined cndlist ==? head lst2
504
    where flist = zip (repeat False) lst1
505
          tlist = zip (repeat True)  lst2
506
          cndlist = flist ++ tlist ++ [undefined]
507

    
508
prop_Utils_parseUnit (NonNegative n) =
509
  Utils.parseUnit (show n) == Types.Ok n &&
510
  Utils.parseUnit (show n ++ "m") == Types.Ok n &&
511
  (case Utils.parseUnit (show n ++ "M") of
512
     Types.Ok m -> if n > 0
513
                     then m < n  -- for positive values, X MB is < than X MiB
514
                     else m == 0 -- but for 0, 0 MB == 0 MiB
515
     Types.Bad _ -> False) &&
516
  Utils.parseUnit (show n ++ "g") == Types.Ok (n*1024) &&
517
  Utils.parseUnit (show n ++ "t") == Types.Ok (n*1048576) &&
518
  Types.isBad (Utils.parseUnit (show n ++ "x")::Types.Result Int)
519
    where _types = n::Int
520

    
521
-- | Test list for the Utils module.
522
testSuite "Utils"
523
            [ 'prop_Utils_commaJoinSplit
524
            , 'prop_Utils_commaSplitJoin
525
            , 'prop_Utils_fromObjWithDefault
526
            , 'prop_Utils_if'if
527
            , 'prop_Utils_select
528
            , 'prop_Utils_select_undefd
529
            , 'prop_Utils_select_undefv
530
            , 'prop_Utils_parseUnit
531
            ]
532

    
533
-- ** PeerMap tests
534

    
535
-- | Make sure add is idempotent.
536
prop_PeerMap_addIdempotent pmap key em =
537
  fn puniq ==? fn (fn puniq)
538
    where _types = (pmap::PeerMap.PeerMap,
539
                    key::PeerMap.Key, em::PeerMap.Elem)
540
          fn = PeerMap.add key em
541
          puniq = PeerMap.accumArray const pmap
542

    
543
-- | Make sure remove is idempotent.
544
prop_PeerMap_removeIdempotent pmap key =
545
  fn puniq ==? fn (fn puniq)
546
    where _types = (pmap::PeerMap.PeerMap, key::PeerMap.Key)
547
          fn = PeerMap.remove key
548
          puniq = PeerMap.accumArray const pmap
549

    
550
-- | Make sure a missing item returns 0.
551
prop_PeerMap_findMissing pmap key =
552
  PeerMap.find key (PeerMap.remove key puniq) ==? 0
553
    where _types = (pmap::PeerMap.PeerMap, key::PeerMap.Key)
554
          puniq = PeerMap.accumArray const pmap
555

    
556
-- | Make sure an added item is found.
557
prop_PeerMap_addFind pmap key em =
558
  PeerMap.find key (PeerMap.add key em puniq) ==? em
559
    where _types = (pmap::PeerMap.PeerMap,
560
                    key::PeerMap.Key, em::PeerMap.Elem)
561
          puniq = PeerMap.accumArray const pmap
562

    
563
-- | Manual check that maxElem returns the maximum indeed, or 0 for null.
564
prop_PeerMap_maxElem pmap =
565
  PeerMap.maxElem puniq ==? if null puniq then 0
566
                              else (maximum . snd . unzip) puniq
567
    where _types = pmap::PeerMap.PeerMap
568
          puniq = PeerMap.accumArray const pmap
569

    
570
-- | List of tests for the PeerMap module.
571
testSuite "PeerMap"
572
            [ 'prop_PeerMap_addIdempotent
573
            , 'prop_PeerMap_removeIdempotent
574
            , 'prop_PeerMap_maxElem
575
            , 'prop_PeerMap_addFind
576
            , 'prop_PeerMap_findMissing
577
            ]
578

    
579
-- ** Container tests
580

    
581
-- we silence the following due to hlint bug fixed in later versions
582
{-# ANN prop_Container_addTwo "HLint: ignore Avoid lambda" #-}
583
prop_Container_addTwo cdata i1 i2 =
584
  fn i1 i2 cont == fn i2 i1 cont &&
585
  fn i1 i2 cont == fn i1 i2 (fn i1 i2 cont)
586
    where _types = (cdata::[Int],
587
                    i1::Int, i2::Int)
588
          cont = foldl (\c x -> Container.add x x c) Container.empty cdata
589
          fn x1 x2 = Container.addTwo x1 x1 x2 x2
590

    
591
prop_Container_nameOf node =
592
  let nl = makeSmallCluster node 1
593
      fnode = head (Container.elems nl)
594
  in Container.nameOf nl (Node.idx fnode) ==? Node.name fnode
595

    
596
-- | We test that in a cluster, given a random node, we can find it by
597
-- its name and alias, as long as all names and aliases are unique,
598
-- and that we fail to find a non-existing name.
599
prop_Container_findByName node =
600
  forAll (choose (1, 20)) $ \ cnt ->
601
  forAll (choose (0, cnt - 1)) $ \ fidx ->
602
  forAll (genUniquesList (cnt * 2)) $ \ allnames ->
603
  forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername ->
604
  let names = zip (take cnt allnames) (drop cnt allnames)
605
      nl = makeSmallCluster node cnt
606
      nodes = Container.elems nl
607
      nodes' = map (\((name, alias), nn) -> (Node.idx nn,
608
                                             nn { Node.name = name,
609
                                                  Node.alias = alias }))
610
               $ zip names nodes
611
      nl' = Container.fromList nodes'
612
      target = snd (nodes' !! fidx)
613
  in Container.findByName nl' (Node.name target) == Just target &&
614
     Container.findByName nl' (Node.alias target) == Just target &&
615
     isNothing (Container.findByName nl' othername)
616

    
617
testSuite "Container"
618
            [ 'prop_Container_addTwo
619
            , 'prop_Container_nameOf
620
            , 'prop_Container_findByName
621
            ]
622

    
623
-- ** Instance tests
624

    
625
-- Simple instance tests, we only have setter/getters
626

    
627
prop_Instance_creat inst =
628
  Instance.name inst ==? Instance.alias inst
629

    
630
prop_Instance_setIdx inst idx =
631
  Instance.idx (Instance.setIdx inst idx) ==? idx
632
    where _types = (inst::Instance.Instance, idx::Types.Idx)
633

    
634
prop_Instance_setName inst name =
635
  Instance.name newinst == name &&
636
  Instance.alias newinst == name
637
    where _types = (inst::Instance.Instance, name::String)
638
          newinst = Instance.setName inst name
639

    
640
prop_Instance_setAlias inst name =
641
  Instance.name newinst == Instance.name inst &&
642
  Instance.alias newinst == name
643
    where _types = (inst::Instance.Instance, name::String)
644
          newinst = Instance.setAlias inst name
645

    
646
prop_Instance_setPri inst pdx =
647
  Instance.pNode (Instance.setPri inst pdx) ==? pdx
648
    where _types = (inst::Instance.Instance, pdx::Types.Ndx)
649

    
650
prop_Instance_setSec inst sdx =
651
  Instance.sNode (Instance.setSec inst sdx) ==? sdx
652
    where _types = (inst::Instance.Instance, sdx::Types.Ndx)
653

    
654
prop_Instance_setBoth inst pdx sdx =
655
  Instance.pNode si == pdx && Instance.sNode si == sdx
656
    where _types = (inst::Instance.Instance, pdx::Types.Ndx, sdx::Types.Ndx)
657
          si = Instance.setBoth inst pdx sdx
658

    
659
prop_Instance_shrinkMG inst =
660
  Instance.mem inst >= 2 * Types.unitMem ==>
661
    case Instance.shrinkByType inst Types.FailMem of
662
      Types.Ok inst' -> Instance.mem inst' == Instance.mem inst - Types.unitMem
663
      _ -> False
664

    
665
prop_Instance_shrinkMF inst =
666
  forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
667
    let inst' = inst { Instance.mem = mem}
668
    in Types.isBad $ Instance.shrinkByType inst' Types.FailMem
669

    
670
prop_Instance_shrinkCG inst =
671
  Instance.vcpus inst >= 2 * Types.unitCpu ==>
672
    case Instance.shrinkByType inst Types.FailCPU of
673
      Types.Ok inst' ->
674
        Instance.vcpus inst' == Instance.vcpus inst - Types.unitCpu
675
      _ -> False
676

    
677
prop_Instance_shrinkCF inst =
678
  forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
679
    let inst' = inst { Instance.vcpus = vcpus }
680
    in Types.isBad $ Instance.shrinkByType inst' Types.FailCPU
681

    
682
prop_Instance_shrinkDG inst =
683
  Instance.dsk inst >= 2 * Types.unitDsk ==>
684
    case Instance.shrinkByType inst Types.FailDisk of
685
      Types.Ok inst' ->
686
        Instance.dsk inst' == Instance.dsk inst - Types.unitDsk
687
      _ -> False
688

    
689
prop_Instance_shrinkDF inst =
690
  forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
691
    let inst' = inst { Instance.dsk = dsk }
692
    in Types.isBad $ Instance.shrinkByType inst' Types.FailDisk
693

    
694
prop_Instance_setMovable inst m =
695
  Instance.movable inst' ==? m
696
    where inst' = Instance.setMovable inst m
697

    
698
testSuite "Instance"
699
            [ 'prop_Instance_creat
700
            , 'prop_Instance_setIdx
701
            , 'prop_Instance_setName
702
            , 'prop_Instance_setAlias
703
            , 'prop_Instance_setPri
704
            , 'prop_Instance_setSec
705
            , 'prop_Instance_setBoth
706
            , 'prop_Instance_shrinkMG
707
            , 'prop_Instance_shrinkMF
708
            , 'prop_Instance_shrinkCG
709
            , 'prop_Instance_shrinkCF
710
            , 'prop_Instance_shrinkDG
711
            , 'prop_Instance_shrinkDF
712
            , 'prop_Instance_setMovable
713
            ]
714

    
715
-- ** Backends
716

    
717
-- *** Text backend tests
718

    
719
-- Instance text loader tests
720

    
721
prop_Text_Load_Instance name mem dsk vcpus status
722
                        (NonEmpty pnode) snode
723
                        (NonNegative pdx) (NonNegative sdx) autobal dt =
724
  pnode /= snode && pdx /= sdx ==>
725
  let vcpus_s = show vcpus
726
      dsk_s = show dsk
727
      mem_s = show mem
728
      status_s = Types.instanceStatusToRaw status
729
      ndx = if null snode
730
              then [(pnode, pdx)]
731
              else [(pnode, pdx), (snode, sdx)]
732
      nl = Data.Map.fromList ndx
733
      tags = ""
734
      sbal = if autobal then "Y" else "N"
735
      sdt = Types.diskTemplateToRaw dt
736
      inst = Text.loadInst nl
737
             [name, mem_s, dsk_s, vcpus_s, status_s,
738
              sbal, pnode, snode, sdt, tags]
739
      fail1 = Text.loadInst nl
740
              [name, mem_s, dsk_s, vcpus_s, status_s,
741
               sbal, pnode, pnode, tags]
742
      _types = ( name::String, mem::Int, dsk::Int
743
               , vcpus::Int, status::Types.InstanceStatus
744
               , snode::String
745
               , autobal::Bool)
746
  in case inst of
747
       Types.Bad msg -> failTest $ "Failed to load instance: " ++ msg
748
       Types.Ok (_, i) -> printTestCase "Mismatch in some field while\
749
                                        \ loading the instance" $
750
               Instance.name i == name &&
751
               Instance.vcpus i == vcpus &&
752
               Instance.mem i == mem &&
753
               Instance.pNode i == pdx &&
754
               Instance.sNode i == (if null snode
755
                                      then Node.noSecondary
756
                                      else sdx) &&
757
               Instance.autoBalance i == autobal &&
758
               Types.isBad fail1
759

    
760
prop_Text_Load_InstanceFail ktn fields =
761
  length fields /= 10 ==>
762
    case Text.loadInst nl fields of
763
      Types.Ok _ -> failTest "Managed to load instance from invalid data"
764
      Types.Bad msg -> printTestCase ("Unrecognised error message: " ++ msg) $
765
                       "Invalid/incomplete instance data: '" `isPrefixOf` msg
766
    where nl = Data.Map.fromList ktn
767

    
768
prop_Text_Load_Node name tm nm fm td fd tc fo =
769
  let conv v = if v < 0
770
                 then "?"
771
                 else show v
772
      tm_s = conv tm
773
      nm_s = conv nm
774
      fm_s = conv fm
775
      td_s = conv td
776
      fd_s = conv fd
777
      tc_s = conv tc
778
      fo_s = if fo
779
               then "Y"
780
               else "N"
781
      any_broken = any (< 0) [tm, nm, fm, td, fd, tc]
782
      gid = Group.uuid defGroup
783
  in case Text.loadNode defGroupAssoc
784
       [name, tm_s, nm_s, fm_s, td_s, fd_s, tc_s, fo_s, gid] of
785
       Nothing -> False
786
       Just (name', node) ->
787
         if fo || any_broken
788
           then Node.offline node
789
           else Node.name node == name' && name' == name &&
790
                Node.alias node == name &&
791
                Node.tMem node == fromIntegral tm &&
792
                Node.nMem node == nm &&
793
                Node.fMem node == fm &&
794
                Node.tDsk node == fromIntegral td &&
795
                Node.fDsk node == fd &&
796
                Node.tCpu node == fromIntegral tc
797

    
798
prop_Text_Load_NodeFail fields =
799
  length fields /= 8 ==> isNothing $ Text.loadNode Data.Map.empty fields
800

    
801
prop_Text_NodeLSIdempotent node =
802
  (Text.loadNode defGroupAssoc.
803
       Utils.sepSplit '|' . Text.serializeNode defGroupList) n ==
804
  Just (Node.name n, n)
805
    -- override failN1 to what loadNode returns by default
806
    where n = node { Node.failN1 = True, Node.offline = False
807
                   , Node.iPolicy = Types.defIPolicy }
808

    
809
prop_Text_ISpecIdempotent ispec =
810
  case Text.loadISpec "dummy" . Utils.sepSplit ',' .
811
       Text.serializeISpec $ ispec of
812
    Types.Bad msg -> failTest $ "Failed to load ispec: " ++ msg
813
    Types.Ok ispec' -> ispec ==? ispec'
814

    
815
prop_Text_IPolicyIdempotent ipol =
816
  case Text.loadIPolicy . Utils.sepSplit '|' $
817
       Text.serializeIPolicy owner ipol of
818
    Types.Bad msg -> failTest $ "Failed to load ispec: " ++ msg
819
    Types.Ok res -> (owner, ipol) ==? res
820
  where owner = "dummy"
821

    
822
-- | This property, while being in the text tests, does more than just
823
-- test end-to-end the serialisation and loading back workflow; it
824
-- also tests the Loader.mergeData and the actuall
825
-- Cluster.iterateAlloc (for well-behaving w.r.t. instance
826
-- allocations, not for the business logic). As such, it's a quite
827
-- complex and slow test, and that's the reason we restrict it to
828
-- small cluster sizes.
829
prop_Text_CreateSerialise =
830
  forAll genTags $ \ctags ->
831
  forAll (choose (1, 2)) $ \reqnodes ->
832
  forAll (choose (1, 20)) $ \maxiter ->
833
  forAll (choose (2, 10)) $ \count ->
834
  forAll genOnlineNode $ \node ->
835
  forAll (genInstanceSmallerThanNode node) $ \inst ->
836
  let inst' = Instance.setMovable inst (reqnodes == 2)
837
      nl = makeSmallCluster node count
838
  in case Cluster.genAllocNodes defGroupList nl reqnodes True >>= \allocn ->
839
     Cluster.iterateAlloc nl Container.empty (Just maxiter) inst' allocn [] []
840
     of
841
       Types.Bad msg -> failTest $ "Failed to allocate: " ++ msg
842
       Types.Ok (_, _, _, [], _) -> printTestCase
843
                                    "Failed to allocate: no allocations" False
844
       Types.Ok (_, nl', il', _, _) ->
845
         let cdata = Loader.ClusterData defGroupList nl' il' ctags
846
                     Types.defIPolicy
847
             saved = Text.serializeCluster cdata
848
         in case Text.parseData saved >>= Loader.mergeData [] [] [] [] of
849
              Types.Bad msg -> failTest $ "Failed to load/merge: " ++ msg
850
              Types.Ok (Loader.ClusterData gl2 nl2 il2 ctags2 cpol2) ->
851
                ctags ==? ctags2 .&&.
852
                Types.defIPolicy ==? cpol2 .&&.
853
                il' ==? il2 .&&.
854
                defGroupList ==? gl2 .&&.
855
                nl' ==? nl2
856

    
857
testSuite "Text"
858
            [ 'prop_Text_Load_Instance
859
            , 'prop_Text_Load_InstanceFail
860
            , 'prop_Text_Load_Node
861
            , 'prop_Text_Load_NodeFail
862
            , 'prop_Text_NodeLSIdempotent
863
            , 'prop_Text_ISpecIdempotent
864
            , 'prop_Text_IPolicyIdempotent
865
            , 'prop_Text_CreateSerialise
866
            ]
867

    
868
-- *** Simu backend
869

    
870
-- | Generates a tuple of specs for simulation.
871
genSimuSpec :: Gen (String, Int, Int, Int, Int)
872
genSimuSpec = do
873
  pol <- elements [C.allocPolicyPreferred,
874
                   C.allocPolicyLastResort, C.allocPolicyUnallocable,
875
                  "p", "a", "u"]
876
 -- should be reasonable (nodes/group), bigger values only complicate
877
 -- the display of failed tests, and we don't care (in this particular
878
 -- test) about big node groups
879
  nodes <- choose (0, 20)
880
  dsk <- choose (0, maxDsk)
881
  mem <- choose (0, maxMem)
882
  cpu <- choose (0, maxCpu)
883
  return (pol, nodes, dsk, mem, cpu)
884

    
885
-- | Checks that given a set of corrects specs, we can load them
886
-- successfully, and that at high-level the values look right.
887
prop_SimuLoad =
888
  forAll (choose (0, 10)) $ \ngroups ->
889
  forAll (replicateM ngroups genSimuSpec) $ \specs ->
890
  let strspecs = map (\(p, n, d, m, c) -> printf "%s,%d,%d,%d,%d"
891
                                          p n d m c::String) specs
892
      totnodes = sum $ map (\(_, n, _, _, _) -> n) specs
893
      mdc_in = concatMap (\(_, n, d, m, c) ->
894
                            replicate n (fromIntegral m, fromIntegral d,
895
                                         fromIntegral c,
896
                                         fromIntegral m, fromIntegral d)) specs
897
  in case Simu.parseData strspecs of
898
       Types.Bad msg -> failTest $ "Failed to load specs: " ++ msg
899
       Types.Ok (Loader.ClusterData gl nl il tags ipol) ->
900
         let nodes = map snd $ IntMap.toAscList nl
901
             nidx = map Node.idx nodes
902
             mdc_out = map (\n -> (Node.tMem n, Node.tDsk n, Node.tCpu n,
903
                                   Node.fMem n, Node.fDsk n)) nodes
904
         in
905
         Container.size gl ==? ngroups .&&.
906
         Container.size nl ==? totnodes .&&.
907
         Container.size il ==? 0 .&&.
908
         length tags ==? 0 .&&.
909
         ipol ==? Types.defIPolicy .&&.
910
         nidx ==? [1..totnodes] .&&.
911
         mdc_in ==? mdc_out .&&.
912
         map Group.iPolicy (Container.elems gl) ==?
913
             replicate ngroups Types.defIPolicy
914

    
915
testSuite "Simu"
916
            [ 'prop_SimuLoad
917
            ]
918

    
919
-- ** Node tests
920

    
921
prop_Node_setAlias node name =
922
  Node.name newnode == Node.name node &&
923
  Node.alias newnode == name
924
    where _types = (node::Node.Node, name::String)
925
          newnode = Node.setAlias node name
926

    
927
prop_Node_setOffline node status =
928
  Node.offline newnode ==? status
929
    where newnode = Node.setOffline node status
930

    
931
prop_Node_setXmem node xm =
932
  Node.xMem newnode ==? xm
933
    where newnode = Node.setXmem node xm
934

    
935
prop_Node_setMcpu node mc =
936
  Node.mCpu newnode ==? mc
937
    where newnode = Node.setMcpu node mc
938

    
939
-- | Check that an instance add with too high memory or disk will be
940
-- rejected.
941
prop_Node_addPriFM node inst =
942
  Instance.mem inst >= Node.fMem node && not (Node.failN1 node) &&
943
  not (Instance.instanceOffline inst) ==>
944
  case Node.addPri node inst'' of
945
    Types.OpFail Types.FailMem -> True
946
    _ -> False
947
  where _types = (node::Node.Node, inst::Instance.Instance)
948
        inst' = setInstanceSmallerThanNode node inst
949
        inst'' = inst' { Instance.mem = Instance.mem inst }
950

    
951
prop_Node_addPriFD node inst =
952
  Instance.dsk inst >= Node.fDsk node && not (Node.failN1 node) ==>
953
    case Node.addPri node inst'' of
954
      Types.OpFail Types.FailDisk -> True
955
      _ -> False
956
    where _types = (node::Node.Node, inst::Instance.Instance)
957
          inst' = setInstanceSmallerThanNode node inst
958
          inst'' = inst' { Instance.dsk = Instance.dsk inst }
959

    
960
prop_Node_addPriFC (Positive extra) =
961
  forAll genOnlineNode $ \node ->
962
  forAll (arbitrary `suchThat` Instance.instanceNotOffline) $ \inst ->
963
  let inst' = setInstanceSmallerThanNode node inst
964
      inst'' = inst' { Instance.vcpus = Node.availCpu node + extra }
965
  in case Node.addPri node inst'' of
966
       Types.OpFail Types.FailCPU -> property True
967
       v -> failTest $ "Expected OpFail FailCPU, but got " ++ show v
968

    
969
-- | Check that an instance add with too high memory or disk will be
970
-- rejected.
971
prop_Node_addSec node inst pdx =
972
  ((Instance.mem inst >= (Node.fMem node - Node.rMem node) &&
973
    not (Instance.instanceOffline inst)) ||
974
   Instance.dsk inst >= Node.fDsk node) &&
975
  not (Node.failN1 node) ==>
976
      isFailure (Node.addSec node inst pdx)
977
        where _types = (node::Node.Node, inst::Instance.Instance, pdx::Int)
978

    
979
-- | Check that an offline instance with reasonable disk size but
980
-- extra mem/cpu can always be added.
981
prop_Node_addOffline (NonNegative extra_mem) (NonNegative extra_cpu) pdx =
982
  forAll genOnlineNode $ \node ->
983
  forAll (genInstanceSmallerThanNode node) $ \inst ->
984
  let inst' = inst { Instance.runSt = Types.AdminOffline
985
                   , Instance.mem = Node.availMem node + extra_mem
986
                   , Instance.vcpus = Node.availCpu node + extra_cpu }
987
  in case (Node.addPri node inst', Node.addSec node inst' pdx) of
988
       (Types.OpGood _, Types.OpGood _) -> property True
989
       v -> failTest $ "Expected OpGood/OpGood, but got: " ++ show v
990

    
991
-- | Checks for memory reservation changes.
992
prop_Node_rMem inst =
993
  not (Instance.instanceOffline inst) ==>
994
  forAll (arbitrary `suchThat` ((> Types.unitMem) . Node.fMem)) $ \node ->
995
  -- ab = auto_balance, nb = non-auto_balance
996
  -- we use -1 as the primary node of the instance
997
  let inst' = inst { Instance.pNode = -1, Instance.autoBalance = True }
998
      inst_ab = setInstanceSmallerThanNode node inst'
999
      inst_nb = inst_ab { Instance.autoBalance = False }
1000
      -- now we have the two instances, identical except the
1001
      -- autoBalance attribute
1002
      orig_rmem = Node.rMem node
1003
      inst_idx = Instance.idx inst_ab
1004
      node_add_ab = Node.addSec node inst_ab (-1)
1005
      node_add_nb = Node.addSec node inst_nb (-1)
1006
      node_del_ab = liftM (`Node.removeSec` inst_ab) node_add_ab
1007
      node_del_nb = liftM (`Node.removeSec` inst_nb) node_add_nb
1008
  in case (node_add_ab, node_add_nb, node_del_ab, node_del_nb) of
1009
       (Types.OpGood a_ab, Types.OpGood a_nb,
1010
        Types.OpGood d_ab, Types.OpGood d_nb) ->
1011
         printTestCase "Consistency checks failed" $
1012
           Node.rMem a_ab >  orig_rmem &&
1013
           Node.rMem a_ab - orig_rmem == Instance.mem inst_ab &&
1014
           Node.rMem a_nb == orig_rmem &&
1015
           Node.rMem d_ab == orig_rmem &&
1016
           Node.rMem d_nb == orig_rmem &&
1017
           -- this is not related to rMem, but as good a place to
1018
           -- test as any
1019
           inst_idx `elem` Node.sList a_ab &&
1020
           inst_idx `notElem` Node.sList d_ab
1021
       x -> failTest $ "Failed to add/remove instances: " ++ show x
1022

    
1023
-- | Check mdsk setting.
1024
prop_Node_setMdsk node mx =
1025
  Node.loDsk node' >= 0 &&
1026
  fromIntegral (Node.loDsk node') <= Node.tDsk node &&
1027
  Node.availDisk node' >= 0 &&
1028
  Node.availDisk node' <= Node.fDsk node' &&
1029
  fromIntegral (Node.availDisk node') <= Node.tDsk node' &&
1030
  Node.mDsk node' == mx'
1031
    where _types = (node::Node.Node, mx::SmallRatio)
1032
          node' = Node.setMdsk node mx'
1033
          SmallRatio mx' = mx
1034

    
1035
-- Check tag maps
1036
prop_Node_tagMaps_idempotent =
1037
  forAll genTags $ \tags ->
1038
  Node.delTags (Node.addTags m tags) tags ==? m
1039
    where m = Data.Map.empty
1040

    
1041
prop_Node_tagMaps_reject =
1042
  forAll (genTags `suchThat` (not . null)) $ \tags ->
1043
  let m = Node.addTags Data.Map.empty tags
1044
  in all (\t -> Node.rejectAddTags m [t]) tags
1045

    
1046
prop_Node_showField node =
1047
  forAll (elements Node.defaultFields) $ \ field ->
1048
  fst (Node.showHeader field) /= Types.unknownField &&
1049
  Node.showField node field /= Types.unknownField
1050

    
1051
prop_Node_computeGroups nodes =
1052
  let ng = Node.computeGroups nodes
1053
      onlyuuid = map fst ng
1054
  in length nodes == sum (map (length . snd) ng) &&
1055
     all (\(guuid, ns) -> all ((== guuid) . Node.group) ns) ng &&
1056
     length (nub onlyuuid) == length onlyuuid &&
1057
     (null nodes || not (null ng))
1058

    
1059
testSuite "Node"
1060
            [ 'prop_Node_setAlias
1061
            , 'prop_Node_setOffline
1062
            , 'prop_Node_setMcpu
1063
            , 'prop_Node_setXmem
1064
            , 'prop_Node_addPriFM
1065
            , 'prop_Node_addPriFD
1066
            , 'prop_Node_addPriFC
1067
            , 'prop_Node_addSec
1068
            , 'prop_Node_addOffline
1069
            , 'prop_Node_rMem
1070
            , 'prop_Node_setMdsk
1071
            , 'prop_Node_tagMaps_idempotent
1072
            , 'prop_Node_tagMaps_reject
1073
            , 'prop_Node_showField
1074
            , 'prop_Node_computeGroups
1075
            ]
1076

    
1077
-- ** Cluster tests
1078

    
1079
-- | Check that the cluster score is close to zero for a homogeneous
1080
-- cluster.
1081
prop_Score_Zero node =
1082
  forAll (choose (1, 1024)) $ \count ->
1083
    (not (Node.offline node) && not (Node.failN1 node) && (count > 0) &&
1084
     (Node.tDsk node > 0) && (Node.tMem node > 0)) ==>
1085
  let fn = Node.buildPeers node Container.empty
1086
      nlst = replicate count fn
1087
      score = Cluster.compCVNodes nlst
1088
  -- we can't say == 0 here as the floating point errors accumulate;
1089
  -- this should be much lower than the default score in CLI.hs
1090
  in score <= 1e-12
1091

    
1092
-- | Check that cluster stats are sane.
1093
prop_CStats_sane =
1094
  forAll (choose (1, 1024)) $ \count ->
1095
  forAll genOnlineNode $ \node ->
1096
  let fn = Node.buildPeers node Container.empty
1097
      nlst = zip [1..] $ replicate count fn::[(Types.Ndx, Node.Node)]
1098
      nl = Container.fromList nlst
1099
      cstats = Cluster.totalResources nl
1100
  in Cluster.csAdsk cstats >= 0 &&
1101
     Cluster.csAdsk cstats <= Cluster.csFdsk cstats
1102

    
1103
-- | Check that one instance is allocated correctly, without
1104
-- rebalances needed.
1105
prop_ClusterAlloc_sane inst =
1106
  forAll (choose (5, 20)) $ \count ->
1107
  forAll genOnlineNode $ \node ->
1108
  let (nl, il, inst') = makeSmallEmptyCluster node count inst
1109
  in case Cluster.genAllocNodes defGroupList nl 2 True >>=
1110
     Cluster.tryAlloc nl il inst' of
1111
       Types.Bad _ -> False
1112
       Types.Ok as ->
1113
         case Cluster.asSolution as of
1114
           Nothing -> False
1115
           Just (xnl, xi, _, cv) ->
1116
             let il' = Container.add (Instance.idx xi) xi il
1117
                 tbl = Cluster.Table xnl il' cv []
1118
             in not (canBalance tbl True True False)
1119

    
1120
-- | Checks that on a 2-5 node cluster, we can allocate a random
1121
-- instance spec via tiered allocation (whatever the original instance
1122
-- spec), on either one or two nodes.
1123
prop_ClusterCanTieredAlloc inst =
1124
  forAll (choose (2, 5)) $ \count ->
1125
  forAll (choose (1, 2)) $ \rqnodes ->
1126
  forAll (genOnlineNode `suchThat` (isNodeBig 4)) $ \node ->
1127
  let nl = makeSmallCluster node count
1128
      il = Container.empty
1129
      allocnodes = Cluster.genAllocNodes defGroupList nl rqnodes True
1130
  in case allocnodes >>= \allocnodes' ->
1131
    Cluster.tieredAlloc nl il (Just 1) inst allocnodes' [] [] of
1132
       Types.Bad _ -> False
1133
       Types.Ok (_, _, il', ixes, cstats) -> not (null ixes) &&
1134
                                             IntMap.size il' == length ixes &&
1135
                                             length ixes == length cstats
1136

    
1137
-- | Helper function to create a cluster with the given range of nodes
1138
-- and allocate an instance on it.
1139
genClusterAlloc count node inst =
1140
  let nl = makeSmallCluster node count
1141
  in case Cluster.genAllocNodes defGroupList nl 2 True >>=
1142
     Cluster.tryAlloc nl Container.empty inst of
1143
       Types.Bad _ -> Types.Bad "Can't allocate"
1144
       Types.Ok as ->
1145
         case Cluster.asSolution as of
1146
           Nothing -> Types.Bad "Empty solution?"
1147
           Just (xnl, xi, _, _) ->
1148
             let xil = Container.add (Instance.idx xi) xi Container.empty
1149
             in Types.Ok (xnl, xil, xi)
1150

    
1151
-- | Checks that on a 4-8 node cluster, once we allocate an instance,
1152
-- we can also relocate it.
1153
prop_ClusterAllocRelocate =
1154
  forAll (choose (4, 8)) $ \count ->
1155
  forAll (genOnlineNode `suchThat` (isNodeBig 4)) $ \node ->
1156
  forAll (genInstanceSmallerThanNode node) $ \inst ->
1157
  case genClusterAlloc count node inst of
1158
    Types.Bad msg -> failTest msg
1159
    Types.Ok (nl, il, inst') ->
1160
      case IAlloc.processRelocate defGroupList nl il
1161
             (Instance.idx inst) 1 [Instance.sNode inst'] of
1162
        Types.Ok _ -> printTestCase "??" True  -- huh, how to make
1163
                                               -- this nicer...
1164
        Types.Bad msg -> failTest $ "Failed to relocate: " ++ msg
1165

    
1166
-- | Helper property checker for the result of a nodeEvac or
1167
-- changeGroup operation.
1168
check_EvacMode grp inst result =
1169
  case result of
1170
    Types.Bad msg -> failTest $ "Couldn't evacuate/change group:" ++ msg
1171
    Types.Ok (_, _, es) ->
1172
      let moved = Cluster.esMoved es
1173
          failed = Cluster.esFailed es
1174
          opcodes = not . null $ Cluster.esOpCodes es
1175
      in failmsg ("'failed' not empty: " ++ show failed) (null failed) .&&.
1176
         failmsg "'opcodes' is null" opcodes .&&.
1177
         case moved of
1178
           [(idx', gdx, _)] -> failmsg "invalid instance moved" (idx == idx')
1179
                               .&&.
1180
                               failmsg "wrong target group"
1181
                                         (gdx == Group.idx grp)
1182
           v -> failmsg  ("invalid solution: " ++ show v) False
1183
  where failmsg = \msg -> printTestCase ("Failed to evacuate: " ++ msg)
1184
        idx = Instance.idx inst
1185

    
1186
-- | Checks that on a 4-8 node cluster, once we allocate an instance,
1187
-- we can also node-evacuate it.
1188
prop_ClusterAllocEvacuate =
1189
  forAll (choose (4, 8)) $ \count ->
1190
  forAll (genOnlineNode `suchThat` (isNodeBig 4)) $ \node ->
1191
  forAll (genInstanceSmallerThanNode node) $ \inst ->
1192
  case genClusterAlloc count node inst of
1193
    Types.Bad msg -> failTest msg
1194
    Types.Ok (nl, il, inst') ->
1195
      conjoin $ map (\mode -> check_EvacMode defGroup inst' $
1196
                              Cluster.tryNodeEvac defGroupList nl il mode
1197
                                [Instance.idx inst']) [minBound..maxBound]
1198

    
1199
-- | Checks that on a 4-8 node cluster with two node groups, once we
1200
-- allocate an instance on the first node group, we can also change
1201
-- its group.
1202
prop_ClusterAllocChangeGroup =
1203
  forAll (choose (4, 8)) $ \count ->
1204
  forAll (genOnlineNode `suchThat` (isNodeBig 4)) $ \node ->
1205
  forAll (genInstanceSmallerThanNode node) $ \inst ->
1206
  case genClusterAlloc count node inst of
1207
    Types.Bad msg -> failTest msg
1208
    Types.Ok (nl, il, inst') ->
1209
      -- we need to add a second node group and nodes to the cluster
1210
      let nl2 = Container.elems $ makeSmallCluster node count
1211
          grp2 = Group.setIdx defGroup (Group.idx defGroup + 1)
1212
          maxndx = maximum . map Node.idx $ nl2
1213
          nl3 = map (\n -> n { Node.group = Group.idx grp2
1214
                             , Node.idx = Node.idx n + maxndx }) nl2
1215
          nl4 = Container.fromList . map (\n -> (Node.idx n, n)) $ nl3
1216
          gl' = Container.add (Group.idx grp2) grp2 defGroupList
1217
          nl' = IntMap.union nl nl4
1218
      in check_EvacMode grp2 inst' $
1219
         Cluster.tryChangeGroup gl' nl' il [] [Instance.idx inst']
1220

    
1221
-- | Check that allocating multiple instances on a cluster, then
1222
-- adding an empty node, results in a valid rebalance.
1223
prop_ClusterAllocBalance =
1224
  forAll (genNode (Just 5) (Just 128)) $ \node ->
1225
  forAll (choose (3, 5)) $ \count ->
1226
  not (Node.offline node) && not (Node.failN1 node) ==>
1227
  let nl = makeSmallCluster node count
1228
      (hnode, nl') = IntMap.deleteFindMax nl
1229
      il = Container.empty
1230
      allocnodes = Cluster.genAllocNodes defGroupList nl' 2 True
1231
      i_templ = createInstance Types.unitMem Types.unitDsk Types.unitCpu
1232
  in case allocnodes >>= \allocnodes' ->
1233
    Cluster.iterateAlloc nl' il (Just 5) i_templ allocnodes' [] [] of
1234
       Types.Bad msg -> failTest $ "Failed to allocate: " ++ msg
1235
       Types.Ok (_, _, _, [], _) -> failTest "Failed to allocate: no instances"
1236
       Types.Ok (_, xnl, il', _, _) ->
1237
         let ynl = Container.add (Node.idx hnode) hnode xnl
1238
             cv = Cluster.compCV ynl
1239
             tbl = Cluster.Table ynl il' cv []
1240
         in printTestCase "Failed to rebalance" $
1241
            canBalance tbl True True False
1242

    
1243
-- | Checks consistency.
1244
prop_ClusterCheckConsistency node inst =
1245
  let nl = makeSmallCluster node 3
1246
      [node1, node2, node3] = Container.elems nl
1247
      node3' = node3 { Node.group = 1 }
1248
      nl' = Container.add (Node.idx node3') node3' nl
1249
      inst1 = Instance.setBoth inst (Node.idx node1) (Node.idx node2)
1250
      inst2 = Instance.setBoth inst (Node.idx node1) Node.noSecondary
1251
      inst3 = Instance.setBoth inst (Node.idx node1) (Node.idx node3)
1252
      ccheck = Cluster.findSplitInstances nl' . Container.fromList
1253
  in null (ccheck [(0, inst1)]) &&
1254
     null (ccheck [(0, inst2)]) &&
1255
     (not . null $ ccheck [(0, inst3)])
1256

    
1257
-- | For now, we only test that we don't lose instances during the split.
1258
prop_ClusterSplitCluster node inst =
1259
  forAll (choose (0, 100)) $ \icnt ->
1260
  let nl = makeSmallCluster node 2
1261
      (nl', il') = foldl (\(ns, is) _ -> assignInstance ns is inst 0 1)
1262
                   (nl, Container.empty) [1..icnt]
1263
      gni = Cluster.splitCluster nl' il'
1264
  in sum (map (Container.size . snd . snd) gni) == icnt &&
1265
     all (\(guuid, (nl'', _)) -> all ((== guuid) . Node.group)
1266
                                 (Container.elems nl'')) gni
1267

    
1268
-- | Helper function to check if we can allocate an instance on a
1269
-- given node list.
1270
canAllocOn :: Node.List -> Int -> Instance.Instance -> Bool
1271
canAllocOn nl reqnodes inst =
1272
  case Cluster.genAllocNodes defGroupList nl reqnodes True >>=
1273
       Cluster.tryAlloc nl (Container.empty) inst of
1274
       Types.Bad _ -> False
1275
       Types.Ok as ->
1276
         case Cluster.asSolution as of
1277
           Nothing -> False
1278
           Just _ -> True
1279

    
1280
-- | Checks that allocation obeys minimum and maximum instance
1281
-- policies. The unittest generates a random node, duplicates it count
1282
-- times, and generates a random instance that can be allocated on
1283
-- this mini-cluster; it then checks that after applying a policy that
1284
-- the instance doesn't fits, the allocation fails.
1285
prop_ClusterAllocPolicy node =
1286
  -- rqn is the required nodes (1 or 2)
1287
  forAll (choose (1, 2)) $ \rqn ->
1288
  forAll (choose (5, 20)) $ \count ->
1289
  forAll (arbitrary `suchThat` (canAllocOn (makeSmallCluster node count) rqn))
1290
         $ \inst ->
1291
  forAll (arbitrary `suchThat` (isFailure .
1292
                                Instance.instMatchesPolicy inst)) $ \ipol ->
1293
  let node' = Node.setPolicy ipol node
1294
      nl = makeSmallCluster node' count
1295
  in not $ canAllocOn nl rqn inst
1296

    
1297
testSuite "Cluster"
1298
            [ 'prop_Score_Zero
1299
            , 'prop_CStats_sane
1300
            , 'prop_ClusterAlloc_sane
1301
            , 'prop_ClusterCanTieredAlloc
1302
            , 'prop_ClusterAllocRelocate
1303
            , 'prop_ClusterAllocEvacuate
1304
            , 'prop_ClusterAllocChangeGroup
1305
            , 'prop_ClusterAllocBalance
1306
            , 'prop_ClusterCheckConsistency
1307
            , 'prop_ClusterSplitCluster
1308
            , 'prop_ClusterAllocPolicy
1309
            ]
1310

    
1311
-- ** OpCodes tests
1312

    
1313
-- | Check that opcode serialization is idempotent.
1314
prop_OpCodes_serialization op =
1315
  case J.readJSON (J.showJSON op) of
1316
    J.Error e -> failTest $ "Cannot deserialise: " ++ e
1317
    J.Ok op' -> op ==? op'
1318
  where _types = op::OpCodes.OpCode
1319

    
1320
testSuite "OpCodes"
1321
            [ 'prop_OpCodes_serialization ]
1322

    
1323
-- ** Jobs tests
1324

    
1325
-- | Check that (queued) job\/opcode status serialization is idempotent.
1326
prop_OpStatus_serialization os =
1327
  case J.readJSON (J.showJSON os) of
1328
    J.Error e -> failTest $ "Cannot deserialise: " ++ e
1329
    J.Ok os' -> os ==? os'
1330
  where _types = os::Jobs.OpStatus
1331

    
1332
prop_JobStatus_serialization js =
1333
  case J.readJSON (J.showJSON js) of
1334
    J.Error e -> failTest $ "Cannot deserialise: " ++ e
1335
    J.Ok js' -> js ==? js'
1336
  where _types = js::Jobs.JobStatus
1337

    
1338
testSuite "Jobs"
1339
            [ 'prop_OpStatus_serialization
1340
            , 'prop_JobStatus_serialization
1341
            ]
1342

    
1343
-- ** Loader tests
1344

    
1345
prop_Loader_lookupNode ktn inst node =
1346
  Loader.lookupNode nl inst node ==? Data.Map.lookup node nl
1347
    where nl = Data.Map.fromList ktn
1348

    
1349
prop_Loader_lookupInstance kti inst =
1350
  Loader.lookupInstance il inst ==? Data.Map.lookup inst il
1351
    where il = Data.Map.fromList kti
1352

    
1353
prop_Loader_assignIndices =
1354
  -- generate nodes with unique names
1355
  forAll (arbitrary `suchThat`
1356
          (\nodes ->
1357
             let names = map Node.name nodes
1358
             in length names == length (nub names))) $ \nodes ->
1359
  let (nassoc, kt) =
1360
        Loader.assignIndices (map (\n -> (Node.name n, n)) nodes)
1361
  in Data.Map.size nassoc == length nodes &&
1362
     Container.size kt == length nodes &&
1363
     if not (null nodes)
1364
       then maximum (IntMap.keys kt) == length nodes - 1
1365
       else True
1366

    
1367
-- | Checks that the number of primary instances recorded on the nodes
1368
-- is zero.
1369
prop_Loader_mergeData ns =
1370
  let na = Container.fromList $ map (\n -> (Node.idx n, n)) ns
1371
  in case Loader.mergeData [] [] [] []
1372
         (Loader.emptyCluster {Loader.cdNodes = na}) of
1373
    Types.Bad _ -> False
1374
    Types.Ok (Loader.ClusterData _ nl il _ _) ->
1375
      let nodes = Container.elems nl
1376
          instances = Container.elems il
1377
      in (sum . map (length . Node.pList)) nodes == 0 &&
1378
         null instances
1379

    
1380
-- | Check that compareNameComponent on equal strings works.
1381
prop_Loader_compareNameComponent_equal :: String -> Bool
1382
prop_Loader_compareNameComponent_equal s =
1383
  Loader.compareNameComponent s s ==
1384
    Loader.LookupResult Loader.ExactMatch s
1385

    
1386
-- | Check that compareNameComponent on prefix strings works.
1387
prop_Loader_compareNameComponent_prefix :: NonEmptyList Char -> String -> Bool
1388
prop_Loader_compareNameComponent_prefix (NonEmpty s1) s2 =
1389
  Loader.compareNameComponent (s1 ++ "." ++ s2) s1 ==
1390
    Loader.LookupResult Loader.PartialMatch s1
1391

    
1392
testSuite "Loader"
1393
            [ 'prop_Loader_lookupNode
1394
            , 'prop_Loader_lookupInstance
1395
            , 'prop_Loader_assignIndices
1396
            , 'prop_Loader_mergeData
1397
            , 'prop_Loader_compareNameComponent_equal
1398
            , 'prop_Loader_compareNameComponent_prefix
1399
            ]
1400

    
1401
-- ** Types tests
1402

    
1403
prop_Types_AllocPolicy_serialisation apol =
1404
  case J.readJSON (J.showJSON apol) of
1405
    J.Ok p -> p ==? apol
1406
    J.Error s -> failTest $ "Failed to deserialise: " ++ s
1407
      where _types = apol::Types.AllocPolicy
1408

    
1409
prop_Types_DiskTemplate_serialisation dt =
1410
  case J.readJSON (J.showJSON dt) of
1411
    J.Ok p -> p ==? dt
1412
    J.Error s -> failTest $ "Failed to deserialise: " ++ s
1413
      where _types = dt::Types.DiskTemplate
1414

    
1415
prop_Types_ISpec_serialisation ispec =
1416
  case J.readJSON (J.showJSON ispec) of
1417
    J.Ok p -> p ==? ispec
1418
    J.Error s -> failTest $ "Failed to deserialise: " ++ s
1419
      where _types = ispec::Types.ISpec
1420

    
1421
prop_Types_IPolicy_serialisation ipol =
1422
  case J.readJSON (J.showJSON ipol) of
1423
    J.Ok p -> p ==? ipol
1424
    J.Error s -> failTest $ "Failed to deserialise: " ++ s
1425
      where _types = ipol::Types.IPolicy
1426

    
1427
prop_Types_EvacMode_serialisation em =
1428
  case J.readJSON (J.showJSON em) of
1429
    J.Ok p -> p ==? em
1430
    J.Error s -> failTest $ "Failed to deserialise: " ++ s
1431
      where _types = em::Types.EvacMode
1432

    
1433
prop_Types_opToResult op =
1434
  case op of
1435
    Types.OpFail _ -> Types.isBad r
1436
    Types.OpGood v -> case r of
1437
                        Types.Bad _ -> False
1438
                        Types.Ok v' -> v == v'
1439
  where r = Types.opToResult op
1440
        _types = op::Types.OpResult Int
1441

    
1442
prop_Types_eitherToResult ei =
1443
  case ei of
1444
    Left _ -> Types.isBad r
1445
    Right v -> case r of
1446
                 Types.Bad _ -> False
1447
                 Types.Ok v' -> v == v'
1448
    where r = Types.eitherToResult ei
1449
          _types = ei::Either String Int
1450

    
1451
testSuite "Types"
1452
            [ 'prop_Types_AllocPolicy_serialisation
1453
            , 'prop_Types_DiskTemplate_serialisation
1454
            , 'prop_Types_ISpec_serialisation
1455
            , 'prop_Types_IPolicy_serialisation
1456
            , 'prop_Types_EvacMode_serialisation
1457
            , 'prop_Types_opToResult
1458
            , 'prop_Types_eitherToResult
1459
            ]
1460

    
1461
-- ** CLI tests
1462

    
1463
-- | Test correct parsing.
1464
prop_CLI_parseISpec descr dsk mem cpu =
1465
  let str = printf "%d,%d,%d" dsk mem cpu
1466
  in CLI.parseISpecString descr str ==? Types.Ok (Types.RSpec cpu mem dsk)
1467

    
1468
-- | Test parsing failure due to wrong section count.
1469
prop_CLI_parseISpecFail descr =
1470
  forAll (choose (0,100) `suchThat` ((/=) 3)) $ \nelems ->
1471
  forAll (replicateM nelems arbitrary) $ \values ->
1472
  let str = intercalate "," $ map show (values::[Int])
1473
  in case CLI.parseISpecString descr str of
1474
       Types.Ok v -> failTest $ "Expected failure, got " ++ show v
1475
       _ -> property True
1476

    
1477
-- | Test parseYesNo.
1478
prop_CLI_parseYesNo def testval val =
1479
  forAll (elements [val, "yes", "no"]) $ \actual_val ->
1480
  if testval
1481
    then CLI.parseYesNo def Nothing ==? Types.Ok def
1482
    else let result = CLI.parseYesNo def (Just actual_val)
1483
         in if actual_val `elem` ["yes", "no"]
1484
              then result ==? Types.Ok (actual_val == "yes")
1485
              else property $ Types.isBad result
1486

    
1487
-- | Helper to check for correct parsing of string arg.
1488
checkStringArg val (opt, fn) =
1489
  let GetOpt.Option _ longs _ _ = opt
1490
  in case longs of
1491
       [] -> failTest "no long options?"
1492
       cmdarg:_ ->
1493
         case CLI.parseOptsInner ["--" ++ cmdarg ++ "=" ++ val] "prog" [opt] of
1494
           Left e -> failTest $ "Failed to parse option: " ++ show e
1495
           Right (options, _) -> fn options ==? Just val
1496

    
1497
-- | Test a few string arguments.
1498
prop_CLI_StringArg argument =
1499
  let args = [ (CLI.oDataFile,      CLI.optDataFile)
1500
             , (CLI.oDynuFile,      CLI.optDynuFile)
1501
             , (CLI.oSaveCluster,   CLI.optSaveCluster)
1502
             , (CLI.oReplay,        CLI.optReplay)
1503
             , (CLI.oPrintCommands, CLI.optShowCmds)
1504
             , (CLI.oLuxiSocket,    CLI.optLuxi)
1505
             ]
1506
  in conjoin $ map (checkStringArg argument) args
1507

    
1508
-- | Helper to test that a given option is accepted OK with quick exit.
1509
checkEarlyExit name options param =
1510
  case CLI.parseOptsInner [param] name options of
1511
    Left (code, _) -> if code == 0
1512
                          then property True
1513
                          else failTest $ "Program " ++ name ++
1514
                                 " returns invalid code " ++ show code ++
1515
                                 " for option " ++ param
1516
    _ -> failTest $ "Program " ++ name ++ " doesn't consider option " ++
1517
         param ++ " as early exit one"
1518

    
1519
-- | Test that all binaries support some common options. There is
1520
-- nothing actually random about this test...
1521
prop_CLI_stdopts =
1522
  let params = ["-h", "--help", "-V", "--version"]
1523
      opts = map (\(name, (_, o)) -> (name, o)) Program.personalities
1524
      -- apply checkEarlyExit across the cartesian product of params and opts
1525
  in conjoin [checkEarlyExit n o p | p <- params, (n, o) <- opts]
1526

    
1527
testSuite "CLI"
1528
          [ 'prop_CLI_parseISpec
1529
          , 'prop_CLI_parseISpecFail
1530
          , 'prop_CLI_parseYesNo
1531
          , 'prop_CLI_StringArg
1532
          , 'prop_CLI_stdopts
1533
          ]