QC.hs 70.9 KB
Newer Older
1
{-# LANGUAGE TemplateHaskell #-}
2
3
4
5
6
7
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-unused-imports #-}

-- FIXME: should remove the no-warn-unused-imports option, once we get
-- around to testing function from all modules; until then, we keep
-- the (unused) imports here to generate correct coverage (0 for
-- modules we don't use)
8

9
{-| Unittests for ganeti-htools.
Iustin Pop's avatar
Iustin Pop committed
10
11
12
13
14

-}

{-

Iustin Pop's avatar
Iustin Pop committed
15
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

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

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

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

-}

34
module Ganeti.HTools.QC
Iustin Pop's avatar
Iustin Pop committed
35
36
37
38
39
40
  ( testUtils
  , testPeerMap
  , testContainer
  , testInstance
  , testNode
  , testText
41
  , testSimu
Iustin Pop's avatar
Iustin Pop committed
42
43
44
45
46
  , testOpCodes
  , testJobs
  , testCluster
  , testLoader
  , testTypes
47
  , testCLI
Iustin Pop's avatar
Iustin Pop committed
48
  , testJSON
49
  , testLUXI
50
  , testSsconf
Iustin Pop's avatar
Iustin Pop committed
51
  ) where
52
53

import Test.QuickCheck
54
import Text.Printf (printf)
55
import Data.List (intercalate, nub, isPrefixOf)
56
import Data.Maybe
Iustin Pop's avatar
Iustin Pop committed
57
import Control.Monad
Iustin Pop's avatar
Iustin Pop committed
58
import Control.Applicative
Iustin Pop's avatar
Iustin Pop committed
59
import qualified System.Console.GetOpt as GetOpt
Iustin Pop's avatar
Iustin Pop committed
60
import qualified Text.JSON as J
Iustin Pop's avatar
Iustin Pop committed
61
import qualified Data.Map
62
import qualified Data.IntMap as IntMap
Iustin Pop's avatar
Iustin Pop committed
63

Iustin Pop's avatar
Iustin Pop committed
64
65
66
67
import qualified Ganeti.Confd as Confd
import qualified Ganeti.Config as Config
import qualified Ganeti.Daemon as Daemon
import qualified Ganeti.Hash as Hash
68
import qualified Ganeti.Jobs as Jobs
Iustin Pop's avatar
Iustin Pop committed
69
import qualified Ganeti.Logging as Logging
70
import qualified Ganeti.Luxi as Luxi
Iustin Pop's avatar
Iustin Pop committed
71
72
73
74
import qualified Ganeti.Objects as Objects
import qualified Ganeti.OpCodes as OpCodes
import qualified Ganeti.Query2 as Query2
import qualified Ganeti.Runtime as Runtime
75
import qualified Ganeti.Ssconf as Ssconf
76
77
78
import qualified Ganeti.HTools.CLI as CLI
import qualified Ganeti.HTools.Cluster as Cluster
import qualified Ganeti.HTools.Container as Container
Iustin Pop's avatar
Iustin Pop committed
79
import qualified Ganeti.HTools.ExtLoader
Iustin Pop's avatar
Iustin Pop committed
80
import qualified Ganeti.HTools.Group as Group
81
82
import qualified Ganeti.HTools.IAlloc as IAlloc
import qualified Ganeti.HTools.Instance as Instance
83
import qualified Ganeti.HTools.JSON as JSON
84
import qualified Ganeti.HTools.Loader as Loader
85
import qualified Ganeti.HTools.Luxi as HTools.Luxi
86
87
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.PeerMap as PeerMap
88
import qualified Ganeti.HTools.Rapi
89
import qualified Ganeti.HTools.Simu as Simu
90
91
92
import qualified Ganeti.HTools.Text as Text
import qualified Ganeti.HTools.Types as Types
import qualified Ganeti.HTools.Utils as Utils
Iustin Pop's avatar
Iustin Pop committed
93
import qualified Ganeti.HTools.Version
94
import qualified Ganeti.Constants as C
95

96
import qualified Ganeti.HTools.Program as Program
97
98
99
100
101
import qualified Ganeti.HTools.Program.Hail
import qualified Ganeti.HTools.Program.Hbal
import qualified Ganeti.HTools.Program.Hscan
import qualified Ganeti.HTools.Program.Hspace

102
import Ganeti.HTools.QCHelper (testSuite)
Iustin Pop's avatar
Iustin Pop committed
103

104
105
-- * Constants

106
-- | Maximum memory (1TiB, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
107
108
109
maxMem :: Int
maxMem = 1024 * 1024

110
-- | Maximum disk (8TiB, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
111
maxDsk :: Int
Iustin Pop's avatar
Iustin Pop committed
112
maxDsk = 1024 * 1024 * 8
Iustin Pop's avatar
Iustin Pop committed
113

114
-- | Max CPUs (1024, somewhat random value).
Iustin Pop's avatar
Iustin Pop committed
115
116
117
maxCpu :: Int
maxCpu = 1024

118
119
120
121
122
123
124
125
-- | Max vcpu ratio (random value).
maxVcpuRatio :: Double
maxVcpuRatio = 1024.0

-- | Max spindle ratio (random value).
maxSpindleRatio :: Double
maxSpindleRatio = 1024.0

Iustin Pop's avatar
Iustin Pop committed
126
127
128
129
130
131
132
133
134
-- | Max nodes, used just to limit arbitrary instances for smaller
-- opcode definitions (e.g. list of nodes in OpTestDelay).
maxNodes :: Int
maxNodes = 32

-- | Max opcodes or jobs in a submit job and submit many jobs.
maxOpCodes :: Int
maxOpCodes = 16

135
136
137
138
-- | All disk templates (used later)
allDiskTemplates :: [Types.DiskTemplate]
allDiskTemplates = [minBound..maxBound]

139
-- | Null iPolicy, and by null we mean very liberal.
140
nullIPolicy :: Types.IPolicy
141
142
143
144
145
146
nullIPolicy = Types.IPolicy
  { Types.iPolicyMinSpec = Types.ISpec { Types.iSpecMemorySize = 0
                                       , Types.iSpecCpuCount   = 0
                                       , Types.iSpecDiskSize   = 0
                                       , Types.iSpecDiskCount  = 0
                                       , Types.iSpecNicCount   = 0
147
                                       , Types.iSpecSpindleUse = 0
148
149
150
151
152
153
                                       }
  , Types.iPolicyMaxSpec = Types.ISpec { Types.iSpecMemorySize = maxBound
                                       , Types.iSpecCpuCount   = maxBound
                                       , Types.iSpecDiskSize   = maxBound
                                       , Types.iSpecDiskCount  = C.maxDisks
                                       , Types.iSpecNicCount   = C.maxNics
154
                                       , Types.iSpecSpindleUse = maxBound
155
156
157
158
159
160
                                       }
  , Types.iPolicyStdSpec = Types.ISpec { Types.iSpecMemorySize = Types.unitMem
                                       , Types.iSpecCpuCount   = Types.unitCpu
                                       , Types.iSpecDiskSize   = Types.unitDsk
                                       , Types.iSpecDiskCount  = 1
                                       , Types.iSpecNicCount   = 1
161
                                       , Types.iSpecSpindleUse = 1
162
                                       }
163
  , Types.iPolicyDiskTemplates = [minBound..maxBound]
164
165
166
  , Types.iPolicyVcpuRatio = maxVcpuRatio -- somewhat random value, high
                                          -- enough to not impact us
  , Types.iPolicySpindleRatio = maxSpindleRatio
167
168
169
  }


Iustin Pop's avatar
Iustin Pop committed
170
171
defGroup :: Group.Group
defGroup = flip Group.setIdx 0 $
Iustin Pop's avatar
Iustin Pop committed
172
             Group.create "default" Types.defaultGroupID Types.AllocPreferred
173
                  nullIPolicy
Iustin Pop's avatar
Iustin Pop committed
174
175

defGroupList :: Group.List
Iustin Pop's avatar
Iustin Pop committed
176
defGroupList = Container.fromList [(Group.idx defGroup, defGroup)]
Iustin Pop's avatar
Iustin Pop committed
177
178
179
180

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

181
182
-- * Helper functions

183
-- | Simple checker for whether OpResult is fail or pass.
Iustin Pop's avatar
Iustin Pop committed
184
185
186
187
isFailure :: Types.OpResult a -> Bool
isFailure (Types.OpFail _) = True
isFailure _ = False

Iustin Pop's avatar
Iustin Pop committed
188
189
190
191
192
193
194
-- | Checks for equality with proper annotation.
(==?) :: (Show a, Eq a) => a -> a -> Property
(==?) x y = printTestCase
            ("Expected equality, but '" ++
             show x ++ "' /= '" ++ show y ++ "'") (x == y)
infix 3 ==?

Iustin Pop's avatar
Iustin Pop committed
195
196
197
198
-- | Show a message and fail the test.
failTest :: String -> Property
failTest msg = printTestCase msg False

199
-- | Update an instance to be smaller than a node.
200
201
setInstanceSmallerThanNode :: Node.Node
                           -> Instance.Instance -> Instance.Instance
202
setInstanceSmallerThanNode node inst =
Iustin Pop's avatar
Iustin Pop committed
203
204
205
206
  inst { Instance.mem = Node.availMem node `div` 2
       , Instance.dsk = Node.availDisk node `div` 2
       , Instance.vcpus = Node.availCpu node `div` 2
       }
207

208
-- | Create an instance given its spec.
209
createInstance :: Int -> Int -> Int -> Instance.Instance
210
createInstance mem dsk vcpus =
Iustin Pop's avatar
Iustin Pop committed
211
  Instance.create "inst-unnamed" mem dsk vcpus Types.Running [] True (-1) (-1)
212
    Types.DTDrbd8 1
213

214
-- | Create a small cluster by repeating a node spec.
215
216
makeSmallCluster :: Node.Node -> Int -> Node.List
makeSmallCluster node count =
217
218
219
220
221
222
223
  let origname = Node.name node
      origalias = Node.alias node
      nodes = map (\idx -> node { Node.name = origname ++ "-" ++ show idx
                                , Node.alias = origalias ++ "-" ++ show idx })
              [1..count]
      fn = flip Node.buildPeers Container.empty
      namelst = map (\n -> (Node.name n, fn n)) nodes
Iustin Pop's avatar
Iustin Pop committed
224
225
      (_, nlst) = Loader.assignIndices namelst
  in nlst
226

Iustin Pop's avatar
Iustin Pop committed
227
228
229
230
231
232
233
-- | Make a small cluster, both nodes and instances.
makeSmallEmptyCluster :: Node.Node -> Int -> Instance.Instance
                      -> (Node.List, Instance.List, Instance.Instance)
makeSmallEmptyCluster node count inst =
  (makeSmallCluster node count, Container.empty,
   setInstanceSmallerThanNode node inst)

234
-- | Checks if a node is "big" enough.
235
236
isNodeBig :: Int -> Node.Node -> Bool
isNodeBig size node = Node.availDisk node > size * Types.unitDsk
237
238
239
                      && Node.availMem node > size * Types.unitMem
                      && Node.availCpu node > size * Types.unitCpu

240
241
canBalance :: Cluster.Table -> Bool -> Bool -> Bool -> Bool
canBalance tbl dm im evac = isJust $ Cluster.tryBalance tbl dm im evac 0 0
242

243
-- | Assigns a new fresh instance to a cluster; this is not
244
-- allocation, so no resource checks are done.
245
246
247
248
249
250
251
assignInstance :: Node.List -> Instance.List -> Instance.Instance ->
                  Types.Idx -> Types.Idx ->
                  (Node.List, Instance.List)
assignInstance nl il inst pdx sdx =
  let pnode = Container.find pdx nl
      snode = Container.find sdx nl
      maxiidx = if Container.null il
Iustin Pop's avatar
Iustin Pop committed
252
253
                  then 0
                  else fst (Container.findMax il) + 1
254
255
256
257
258
259
260
261
      inst' = inst { Instance.idx = maxiidx,
                     Instance.pNode = pdx, Instance.sNode = sdx }
      pnode' = Node.setPri pnode inst'
      snode' = Node.setSec snode inst'
      nl' = Container.addTwo pdx pnode' sdx snode' nl
      il' = Container.add maxiidx inst' il
  in (nl', il')

262
263
264
265
266
267
268
-- | Generates a list of a given size with non-duplicate elements.
genUniquesList :: (Eq a, Arbitrary a) => Int -> Gen [a]
genUniquesList cnt =
  foldM (\lst _ -> do
           newelem <- arbitrary `suchThat` (`notElem` lst)
           return (newelem:lst)) [] [1..cnt]

269
270
-- | Checks if an instance is mirrored.
isMirrored :: Instance.Instance -> Bool
271
isMirrored = (/= Types.MirrorNone) . Instance.mirrorType
272
273
274
275
276
277
278

-- | Returns the possible change node types for a disk template.
evacModeOptions :: Types.MirrorType -> [Types.EvacMode]
evacModeOptions Types.MirrorNone     = []
evacModeOptions Types.MirrorInternal = [minBound..maxBound] -- DRBD can do all
evacModeOptions Types.MirrorExternal = [Types.ChangePrimary, Types.ChangeAll]

279
280
-- * Arbitrary instances

281
-- | Defines a DNS name.
282
newtype DNSChar = DNSChar { dnsGetChar::Char }
283

284
instance Arbitrary DNSChar where
Iustin Pop's avatar
Iustin Pop committed
285
286
287
  arbitrary = do
    x <- elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
    return (DNSChar x)
288

289
-- | Generates a single name component.
290
291
292
getName :: Gen String
getName = do
  n <- choose (1, 64)
Iustin Pop's avatar
Iustin Pop committed
293
  dn <- vector n
294
295
  return (map dnsGetChar dn)

296
-- | Generates an entire FQDN.
297
298
299
getFQDN :: Gen String
getFQDN = do
  ncomps <- choose (1, 4)
Iustin Pop's avatar
Iustin Pop committed
300
  names <- vectorOf ncomps getName
301
  return $ intercalate "." names
302

Iustin Pop's avatar
Iustin Pop committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
-- | Combinator that generates a 'Maybe' using a sub-combinator.
getMaybe :: Gen a -> Gen (Maybe a)
getMaybe subgen = do
  bool <- arbitrary
  if bool
    then Just <$> subgen
    else return Nothing

-- | Generates a fields list. This uses the same character set as a
-- DNS name (just for simplicity).
getFields :: Gen [String]
getFields = do
  n <- choose (1, 32)
  vectorOf n getName

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
-- | Defines a tag type.
newtype TagChar = TagChar { tagGetChar :: Char }

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

instance Arbitrary TagChar where
  arbitrary = do
    c <- elements tagChar
    return (TagChar c)

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

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

350
instance Arbitrary Types.InstanceStatus where
351
    arbitrary = elements [minBound..maxBound]
352

353
354
355
356
357
358
359
360
361
362
-- | Generates a random instance with maximum disk/mem/cpu values.
genInstanceSmallerThan :: Int -> Int -> Int -> Gen Instance.Instance
genInstanceSmallerThan lim_mem lim_dsk lim_cpu = do
  name <- getFQDN
  mem <- choose (0, lim_mem)
  dsk <- choose (0, lim_dsk)
  run_st <- arbitrary
  pn <- arbitrary
  sn <- arbitrary
  vcpus <- choose (0, lim_cpu)
363
364
  dt <- arbitrary
  return $ Instance.create name mem dsk vcpus run_st [] True pn sn dt 1
365
366
367
368
369
370
371
372

-- | Generates an instance smaller than a node.
genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceSmallerThanNode node =
  genInstanceSmallerThan (Node.availMem node `div` 2)
                         (Node.availDisk node `div` 2)
                         (Node.availCpu node `div` 2)

373
374
-- let's generate a random instance
instance Arbitrary Instance.Instance where
375
  arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu
376

377
378
379
380
381
-- | Generas an arbitrary node based on sizing information.
genNode :: Maybe Int -- ^ Minimum node size in terms of units
        -> Maybe Int -- ^ Maximum node size (when Nothing, bounded
                     -- just by the max... constants)
        -> Gen Node.Node
382
383
genNode min_multiplier max_multiplier = do
  let (base_mem, base_dsk, base_cpu) =
Iustin Pop's avatar
Iustin Pop committed
384
385
386
387
388
        case min_multiplier of
          Just mm -> (mm * Types.unitMem,
                      mm * Types.unitDsk,
                      mm * Types.unitCpu)
          Nothing -> (0, 0, 0)
389
      (top_mem, top_dsk, top_cpu)  =
Iustin Pop's avatar
Iustin Pop committed
390
391
392
393
394
        case max_multiplier of
          Just mm -> (mm * Types.unitMem,
                      mm * Types.unitDsk,
                      mm * Types.unitCpu)
          Nothing -> (maxMem, maxDsk, maxCpu)
395
396
397
398
399
400
401
402
403
  name  <- getFQDN
  mem_t <- choose (base_mem, top_mem)
  mem_f <- choose (base_mem, mem_t)
  mem_n <- choose (0, mem_t - mem_f)
  dsk_t <- choose (base_dsk, top_dsk)
  dsk_f <- choose (base_dsk, dsk_t)
  cpu_t <- choose (base_cpu, top_cpu)
  offl  <- arbitrary
  let n = Node.create name (fromIntegral mem_t) mem_n mem_f
404
          (fromIntegral dsk_t) dsk_f (fromIntegral cpu_t) offl 1 0
Iustin Pop's avatar
Iustin Pop committed
405
406
      n' = Node.setPolicy nullIPolicy n
  return $ Node.buildPeers n' Container.empty
407

408
409
410
411
412
413
414
415
416
-- | Helper function to generate a sane node.
genOnlineNode :: Gen Node.Node
genOnlineNode = do
  arbitrary `suchThat` (\n -> not (Node.offline n) &&
                              not (Node.failN1 n) &&
                              Node.availDisk n > 0 &&
                              Node.availMem n > 0 &&
                              Node.availCpu n > 0)

417
418
-- and a random node
instance Arbitrary Node.Node where
Iustin Pop's avatar
Iustin Pop committed
419
  arbitrary = genNode Nothing Nothing
420

Iustin Pop's avatar
Iustin Pop committed
421
422
-- replace disks
instance Arbitrary OpCodes.ReplaceDisksMode where
423
  arbitrary = elements [minBound..maxBound]
Iustin Pop's avatar
Iustin Pop committed
424
425
426
427
428
429
430
431

instance Arbitrary OpCodes.OpCode where
  arbitrary = do
    op_id <- elements [ "OP_TEST_DELAY"
                      , "OP_INSTANCE_REPLACE_DISKS"
                      , "OP_INSTANCE_FAILOVER"
                      , "OP_INSTANCE_MIGRATE"
                      ]
Iustin Pop's avatar
Iustin Pop committed
432
433
    case op_id of
      "OP_TEST_DELAY" ->
Iustin Pop's avatar
Iustin Pop committed
434
435
        OpCodes.OpTestDelay <$> arbitrary <*> arbitrary
                 <*> resize maxNodes (listOf getFQDN)
Iustin Pop's avatar
Iustin Pop committed
436
      "OP_INSTANCE_REPLACE_DISKS" ->
Iustin Pop's avatar
Iustin Pop committed
437
438
        OpCodes.OpInstanceReplaceDisks <$> getFQDN <*> getMaybe getFQDN <*>
          arbitrary <*> resize C.maxDisks arbitrary <*> getMaybe getName
Iustin Pop's avatar
Iustin Pop committed
439
      "OP_INSTANCE_FAILOVER" ->
Iustin Pop's avatar
Iustin Pop committed
440
441
        OpCodes.OpInstanceFailover <$> getFQDN <*> arbitrary <*>
          getMaybe getFQDN
Iustin Pop's avatar
Iustin Pop committed
442
      "OP_INSTANCE_MIGRATE" ->
Iustin Pop's avatar
Iustin Pop committed
443
444
        OpCodes.OpInstanceMigrate <$> getFQDN <*> arbitrary <*>
          arbitrary <*> arbitrary <*> getMaybe getFQDN
Iustin Pop's avatar
Iustin Pop committed
445
      _ -> fail "Wrong opcode"
Iustin Pop's avatar
Iustin Pop committed
446

447
448
449
450
451
452
instance Arbitrary Jobs.OpStatus where
  arbitrary = elements [minBound..maxBound]

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

453
454
newtype SmallRatio = SmallRatio Double deriving Show
instance Arbitrary SmallRatio where
Iustin Pop's avatar
Iustin Pop committed
455
456
457
  arbitrary = do
    v <- choose (0, 1)
    return $ SmallRatio v
458

459
460
461
462
463
464
instance Arbitrary Types.AllocPolicy where
  arbitrary = elements [minBound..maxBound]

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

465
instance Arbitrary Types.FailMode where
Iustin Pop's avatar
Iustin Pop committed
466
  arbitrary = elements [minBound..maxBound]
467

468
469
470
instance Arbitrary Types.EvacMode where
  arbitrary = elements [minBound..maxBound]

471
instance Arbitrary a => Arbitrary (Types.OpResult a) where
Iustin Pop's avatar
Iustin Pop committed
472
  arbitrary = arbitrary >>= \c ->
Iustin Pop's avatar
Iustin Pop committed
473
              if c
Iustin Pop's avatar
Iustin Pop committed
474
475
                then Types.OpGood <$> arbitrary
                else Types.OpFail <$> arbitrary
476

477
478
instance Arbitrary Types.ISpec where
  arbitrary = do
479
    mem_s <- arbitrary::Gen (NonNegative Int)
480
481
    dsk_c <- arbitrary::Gen (NonNegative Int)
    dsk_s <- arbitrary::Gen (NonNegative Int)
482
483
    cpu_c <- arbitrary::Gen (NonNegative Int)
    nic_c <- arbitrary::Gen (NonNegative Int)
484
    su    <- arbitrary::Gen (NonNegative Int)
485
486
    return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
                       , Types.iSpecCpuCount   = fromIntegral cpu_c
487
488
                       , Types.iSpecDiskSize   = fromIntegral dsk_s
                       , Types.iSpecDiskCount  = fromIntegral dsk_c
489
                       , Types.iSpecNicCount   = fromIntegral nic_c
490
                       , Types.iSpecSpindleUse = fromIntegral su
491
492
                       }

493
494
495
496
497
498
499
500
-- | Generates an ispec bigger than the given one.
genBiggerISpec :: Types.ISpec -> Gen Types.ISpec
genBiggerISpec imin = do
  mem_s <- choose (Types.iSpecMemorySize imin, maxBound)
  dsk_c <- choose (Types.iSpecDiskCount imin, maxBound)
  dsk_s <- choose (Types.iSpecDiskSize imin, maxBound)
  cpu_c <- choose (Types.iSpecCpuCount imin, maxBound)
  nic_c <- choose (Types.iSpecNicCount imin, maxBound)
501
  su    <- choose (Types.iSpecSpindleUse imin, maxBound)
502
503
504
505
506
  return Types.ISpec { Types.iSpecMemorySize = fromIntegral mem_s
                     , Types.iSpecCpuCount   = fromIntegral cpu_c
                     , Types.iSpecDiskSize   = fromIntegral dsk_s
                     , Types.iSpecDiskCount  = fromIntegral dsk_c
                     , Types.iSpecNicCount   = fromIntegral nic_c
507
                     , Types.iSpecSpindleUse = fromIntegral su
508
                     }
509
510
511
512

instance Arbitrary Types.IPolicy where
  arbitrary = do
    imin <- arbitrary
513
514
515
516
    istd <- genBiggerISpec imin
    imax <- genBiggerISpec istd
    num_tmpl <- choose (0, length allDiskTemplates)
    dts  <- genUniquesList num_tmpl
517
518
    vcpu_ratio <- choose (1.0, maxVcpuRatio)
    spindle_ratio <- choose (1.0, maxSpindleRatio)
519
520
521
522
    return Types.IPolicy { Types.iPolicyMinSpec = imin
                         , Types.iPolicyStdSpec = istd
                         , Types.iPolicyMaxSpec = imax
                         , Types.iPolicyDiskTemplates = dts
523
                         , Types.iPolicyVcpuRatio = vcpu_ratio
524
                         , Types.iPolicySpindleRatio = spindle_ratio
525
526
                         }

527
-- * Actual tests
Iustin Pop's avatar
Iustin Pop committed
528

529
530
-- ** Utils tests

531
-- | Helper to generate a small string that doesn't contain commas.
532
genNonCommaString :: Gen [Char]
533
534
535
536
genNonCommaString = do
  size <- choose (0, 20) -- arbitrary max size
  vectorOf size (arbitrary `suchThat` ((/=) ','))

537
538
-- | If the list is not just an empty element, and if the elements do
-- not contain commas, then join+split should be idempotent.
539
prop_Utils_commaJoinSplit :: Property
Iustin Pop's avatar
Iustin Pop committed
540
prop_Utils_commaJoinSplit =
541
542
  forAll (choose (0, 20)) $ \llen ->
  forAll (vectorOf llen genNonCommaString `suchThat` ((/=) [""])) $ \lst ->
Iustin Pop's avatar
Iustin Pop committed
543
  Utils.sepSplit ',' (Utils.commaJoin lst) ==? lst
Iustin Pop's avatar
Iustin Pop committed
544

545
-- | Split and join should always be idempotent.
546
prop_Utils_commaSplitJoin :: [Char] -> Property
Iustin Pop's avatar
Iustin Pop committed
547
prop_Utils_commaSplitJoin s =
Iustin Pop's avatar
Iustin Pop committed
548
  Utils.commaJoin (Utils.sepSplit ',' s) ==? s
549

550
-- | fromObjWithDefault, we test using the Maybe monad and an integer
551
-- value.
552
prop_Utils_fromObjWithDefault :: Integer -> String -> Bool
553
prop_Utils_fromObjWithDefault def_value random_key =
Iustin Pop's avatar
Iustin Pop committed
554
  -- a missing key will be returned with the default
555
  JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
Iustin Pop's avatar
Iustin Pop committed
556
  -- a found key will be returned as is, not with default
557
  JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
Iustin Pop's avatar
Iustin Pop committed
558
       random_key (def_value+1) == Just def_value
559

560
-- | Test that functional if' behaves like the syntactic sugar if.
Iustin Pop's avatar
Iustin Pop committed
561
562
prop_Utils_if'if :: Bool -> Int -> Int -> Gen Prop
prop_Utils_if'if cnd a b =
Iustin Pop's avatar
Iustin Pop committed
563
  Utils.if' cnd a b ==? if cnd then a else b
564

Guido Trotter's avatar
Guido Trotter committed
565
-- | Test basic select functionality
Iustin Pop's avatar
Iustin Pop committed
566
567
568
569
prop_Utils_select :: Int      -- ^ Default result
                  -> [Int]    -- ^ List of False values
                  -> [Int]    -- ^ List of True values
                  -> Gen Prop -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
570
prop_Utils_select def lst1 lst2 =
Iustin Pop's avatar
Iustin Pop committed
571
  Utils.select def (flist ++ tlist) ==? expectedresult
Iustin Pop's avatar
Iustin Pop committed
572
573
574
    where expectedresult = Utils.if' (null lst2) def (head lst2)
          flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
Guido Trotter's avatar
Guido Trotter committed
575
576

-- | Test basic select functionality with undefined default
Iustin Pop's avatar
Iustin Pop committed
577
prop_Utils_select_undefd :: [Int]            -- ^ List of False values
Guido Trotter's avatar
Guido Trotter committed
578
                         -> NonEmptyList Int -- ^ List of True values
Iustin Pop's avatar
Iustin Pop committed
579
                         -> Gen Prop         -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
580
prop_Utils_select_undefd lst1 (NonEmpty lst2) =
Iustin Pop's avatar
Iustin Pop committed
581
  Utils.select undefined (flist ++ tlist) ==? head lst2
Iustin Pop's avatar
Iustin Pop committed
582
583
    where flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
Guido Trotter's avatar
Guido Trotter committed
584
585

-- | Test basic select functionality with undefined list values
Iustin Pop's avatar
Iustin Pop committed
586
prop_Utils_select_undefv :: [Int]            -- ^ List of False values
Guido Trotter's avatar
Guido Trotter committed
587
                         -> NonEmptyList Int -- ^ List of True values
Iustin Pop's avatar
Iustin Pop committed
588
                         -> Gen Prop         -- ^ Test result
Guido Trotter's avatar
Guido Trotter committed
589
prop_Utils_select_undefv lst1 (NonEmpty lst2) =
Iustin Pop's avatar
Iustin Pop committed
590
  Utils.select undefined cndlist ==? head lst2
Iustin Pop's avatar
Iustin Pop committed
591
592
593
    where flist = zip (repeat False) lst1
          tlist = zip (repeat True)  lst2
          cndlist = flist ++ tlist ++ [undefined]
594

595
prop_Utils_parseUnit :: NonNegative Int -> Property
Iustin Pop's avatar
Iustin Pop committed
596
prop_Utils_parseUnit (NonNegative n) =
Iustin Pop's avatar
Iustin Pop committed
597
598
599
600
601
602
603
604
605
606
  Utils.parseUnit (show n) ==? Types.Ok n .&&.
  Utils.parseUnit (show n ++ "m") ==? Types.Ok n .&&.
  Utils.parseUnit (show n ++ "M") ==? Types.Ok (truncate n_mb::Int) .&&.
  Utils.parseUnit (show n ++ "g") ==? Types.Ok (n*1024) .&&.
  Utils.parseUnit (show n ++ "G") ==? Types.Ok (truncate n_gb::Int) .&&.
  Utils.parseUnit (show n ++ "t") ==? Types.Ok (n*1048576) .&&.
  Utils.parseUnit (show n ++ "T") ==? Types.Ok (truncate n_tb::Int) .&&.
  printTestCase "Internal error/overflow?"
    (n_mb >=0 && n_gb >= 0 && n_tb >= 0) .&&.
  property (Types.isBad (Utils.parseUnit (show n ++ "x")::Types.Result Int))
607
  where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024
Iustin Pop's avatar
Iustin Pop committed
608
609
        n_gb = n_mb * 1000
        n_tb = n_gb * 1000
Iustin Pop's avatar
Iustin Pop committed
610

611
-- | Test list for the Utils module.
612
testSuite "Utils"
Iustin Pop's avatar
Iustin Pop committed
613
614
615
616
617
618
619
620
621
            [ 'prop_Utils_commaJoinSplit
            , 'prop_Utils_commaSplitJoin
            , 'prop_Utils_fromObjWithDefault
            , 'prop_Utils_if'if
            , 'prop_Utils_select
            , 'prop_Utils_select_undefd
            , 'prop_Utils_select_undefv
            , 'prop_Utils_parseUnit
            ]
622

623
624
625
-- ** PeerMap tests

-- | Make sure add is idempotent.
626
627
prop_PeerMap_addIdempotent :: PeerMap.PeerMap
                           -> PeerMap.Key -> PeerMap.Elem -> Property
Iustin Pop's avatar
Iustin Pop committed
628
prop_PeerMap_addIdempotent pmap key em =
Iustin Pop's avatar
Iustin Pop committed
629
  fn puniq ==? fn (fn puniq)
630
    where fn = PeerMap.add key em
631
          puniq = PeerMap.accumArray const pmap
632

633
-- | Make sure remove is idempotent.
634
prop_PeerMap_removeIdempotent :: PeerMap.PeerMap -> PeerMap.Key -> Property
635
prop_PeerMap_removeIdempotent pmap key =
Iustin Pop's avatar
Iustin Pop committed
636
  fn puniq ==? fn (fn puniq)
637
    where fn = PeerMap.remove key
638
639
          puniq = PeerMap.accumArray const pmap

640
-- | Make sure a missing item returns 0.
641
prop_PeerMap_findMissing :: PeerMap.PeerMap -> PeerMap.Key -> Property
642
prop_PeerMap_findMissing pmap key =
Iustin Pop's avatar
Iustin Pop committed
643
  PeerMap.find key (PeerMap.remove key puniq) ==? 0
644
    where puniq = PeerMap.accumArray const pmap
645

646
-- | Make sure an added item is found.
647
648
prop_PeerMap_addFind :: PeerMap.PeerMap
                     -> PeerMap.Key -> PeerMap.Elem -> Property
Iustin Pop's avatar
Iustin Pop committed
649
prop_PeerMap_addFind pmap key em =
Iustin Pop's avatar
Iustin Pop committed
650
  PeerMap.find key (PeerMap.add key em puniq) ==? em
651
    where puniq = PeerMap.accumArray const pmap
652

653
-- | Manual check that maxElem returns the maximum indeed, or 0 for null.
654
prop_PeerMap_maxElem :: PeerMap.PeerMap -> Property
655
prop_PeerMap_maxElem pmap =
Iustin Pop's avatar
Iustin Pop committed
656
  PeerMap.maxElem puniq ==? if null puniq then 0
Iustin Pop's avatar
Iustin Pop committed
657
                              else (maximum . snd . unzip) puniq
658
    where puniq = PeerMap.accumArray const pmap
659

660
-- | List of tests for the PeerMap module.
661
testSuite "PeerMap"
Iustin Pop's avatar
Iustin Pop committed
662
663
664
665
666
667
            [ 'prop_PeerMap_addIdempotent
            , 'prop_PeerMap_removeIdempotent
            , 'prop_PeerMap_maxElem
            , 'prop_PeerMap_addFind
            , 'prop_PeerMap_findMissing
            ]
668

669
-- ** Container tests
670

Iustin Pop's avatar
Iustin Pop committed
671
672
-- we silence the following due to hlint bug fixed in later versions
{-# ANN prop_Container_addTwo "HLint: ignore Avoid lambda" #-}
673
prop_Container_addTwo :: [Container.Key] -> Int -> Int -> Bool
674
prop_Container_addTwo cdata i1 i2 =
Iustin Pop's avatar
Iustin Pop committed
675
676
  fn i1 i2 cont == fn i2 i1 cont &&
  fn i1 i2 cont == fn i1 i2 (fn i1 i2 cont)
677
    where cont = foldl (\c x -> Container.add x x c) Container.empty cdata
678
679
          fn x1 x2 = Container.addTwo x1 x1 x2 x2

680
prop_Container_nameOf :: Node.Node -> Property
681
682
683
prop_Container_nameOf node =
  let nl = makeSmallCluster node 1
      fnode = head (Container.elems nl)
Iustin Pop's avatar
Iustin Pop committed
684
  in Container.nameOf nl (Node.idx fnode) ==? Node.name fnode
685

686
-- | We test that in a cluster, given a random node, we can find it by
687
-- its name and alias, as long as all names and aliases are unique,
688
-- and that we fail to find a non-existing name.
689
prop_Container_findByName :: Node.Node -> Property
690
prop_Container_findByName node =
691
692
  forAll (choose (1, 20)) $ \ cnt ->
  forAll (choose (0, cnt - 1)) $ \ fidx ->
693
694
695
696
  forAll (genUniquesList (cnt * 2)) $ \ allnames ->
  forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername ->
  let names = zip (take cnt allnames) (drop cnt allnames)
      nl = makeSmallCluster node cnt
697
698
699
700
701
      nodes = Container.elems nl
      nodes' = map (\((name, alias), nn) -> (Node.idx nn,
                                             nn { Node.name = name,
                                                  Node.alias = alias }))
               $ zip names nodes
Iustin Pop's avatar
Iustin Pop committed
702
      nl' = Container.fromList nodes'
703
704
705
      target = snd (nodes' !! fidx)
  in Container.findByName nl' (Node.name target) == Just target &&
     Container.findByName nl' (Node.alias target) == Just target &&
Iustin Pop's avatar
Iustin Pop committed
706
     isNothing (Container.findByName nl' othername)
707

708
testSuite "Container"
Iustin Pop's avatar
Iustin Pop committed
709
710
711
712
            [ 'prop_Container_addTwo
            , 'prop_Container_nameOf
            , 'prop_Container_findByName
            ]
713

714
715
-- ** Instance tests

716
717
-- Simple instance tests, we only have setter/getters

718
prop_Instance_creat :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
719
prop_Instance_creat inst =
Iustin Pop's avatar
Iustin Pop committed
720
  Instance.name inst ==? Instance.alias inst
Iustin Pop's avatar
Iustin Pop committed
721

722
prop_Instance_setIdx :: Instance.Instance -> Types.Idx -> Property
723
prop_Instance_setIdx inst idx =
Iustin Pop's avatar
Iustin Pop committed
724
  Instance.idx (Instance.setIdx inst idx) ==? idx
725

726
prop_Instance_setName :: Instance.Instance -> String -> Bool
727
prop_Instance_setName inst name =
Iustin Pop's avatar
Iustin Pop committed
728
729
  Instance.name newinst == name &&
  Instance.alias newinst == name
730
    where newinst = Instance.setName inst name
Iustin Pop's avatar
Iustin Pop committed
731

732
prop_Instance_setAlias :: Instance.Instance -> String -> Bool
Iustin Pop's avatar
Iustin Pop committed
733
prop_Instance_setAlias inst name =
Iustin Pop's avatar
Iustin Pop committed
734
735
  Instance.name newinst == Instance.name inst &&
  Instance.alias newinst == name
736
    where newinst = Instance.setAlias inst name
737

738
prop_Instance_setPri :: Instance.Instance -> Types.Ndx -> Property
739
prop_Instance_setPri inst pdx =
Iustin Pop's avatar
Iustin Pop committed
740
  Instance.pNode (Instance.setPri inst pdx) ==? pdx
741

742
prop_Instance_setSec :: Instance.Instance -> Types.Ndx -> Property
743
prop_Instance_setSec inst sdx =
Iustin Pop's avatar
Iustin Pop committed
744
  Instance.sNode (Instance.setSec inst sdx) ==? sdx
745

746
prop_Instance_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool
747
prop_Instance_setBoth inst pdx sdx =
Iustin Pop's avatar
Iustin Pop committed
748
  Instance.pNode si == pdx && Instance.sNode si == sdx
749
    where si = Instance.setBoth inst pdx sdx
750

751
prop_Instance_shrinkMG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
752
prop_Instance_shrinkMG inst =
Iustin Pop's avatar
Iustin Pop committed
753
754
755
756
  Instance.mem inst >= 2 * Types.unitMem ==>
    case Instance.shrinkByType inst Types.FailMem of
      Types.Ok inst' -> Instance.mem inst' == Instance.mem inst - Types.unitMem
      _ -> False
Iustin Pop's avatar
Iustin Pop committed
757

758
prop_Instance_shrinkMF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
759
prop_Instance_shrinkMF inst =
Iustin Pop's avatar
Iustin Pop committed
760
  forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
Iustin Pop's avatar
Iustin Pop committed
761
762
    let inst' = inst { Instance.mem = mem}
    in Types.isBad $ Instance.shrinkByType inst' Types.FailMem
Iustin Pop's avatar
Iustin Pop committed
763

764
prop_Instance_shrinkCG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
765
prop_Instance_shrinkCG inst =
Iustin Pop's avatar
Iustin Pop committed
766
767
768
769
770
  Instance.vcpus inst >= 2 * Types.unitCpu ==>
    case Instance.shrinkByType inst Types.FailCPU of
      Types.Ok inst' ->
        Instance.vcpus inst' == Instance.vcpus inst - Types.unitCpu
      _ -> False
Iustin Pop's avatar
Iustin Pop committed
771

772
prop_Instance_shrinkCF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
773
prop_Instance_shrinkCF inst =
Iustin Pop's avatar
Iustin Pop committed
774
  forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
Iustin Pop's avatar
Iustin Pop committed
775
776
    let inst' = inst { Instance.vcpus = vcpus }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailCPU
Iustin Pop's avatar
Iustin Pop committed
777

778
prop_Instance_shrinkDG :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
779
prop_Instance_shrinkDG inst =
Iustin Pop's avatar
Iustin Pop committed
780
781
782
783
784
  Instance.dsk inst >= 2 * Types.unitDsk ==>
    case Instance.shrinkByType inst Types.FailDisk of
      Types.Ok inst' ->
        Instance.dsk inst' == Instance.dsk inst - Types.unitDsk
      _ -> False
Iustin Pop's avatar
Iustin Pop committed
785

786
prop_Instance_shrinkDF :: Instance.Instance -> Property
Iustin Pop's avatar
Iustin Pop committed
787
prop_Instance_shrinkDF inst =
Iustin Pop's avatar
Iustin Pop committed
788
  forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
Iustin Pop's avatar
Iustin Pop committed
789
790
    let inst' = inst { Instance.dsk = dsk }
    in Types.isBad $ Instance.shrinkByType inst' Types.FailDisk
Iustin Pop's avatar
Iustin Pop committed
791

792
prop_Instance_setMovable :: Instance.Instance -> Bool -> Property
Iustin Pop's avatar
Iustin Pop committed
793
prop_Instance_setMovable inst m =
Iustin Pop's avatar
Iustin Pop committed
794
  Instance.movable inst' ==? m
795
    where inst' = Instance.setMovable inst m
Iustin Pop's avatar
Iustin Pop committed
796

797
testSuite "Instance"
Iustin Pop's avatar
Iustin Pop committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
            [ 'prop_Instance_creat
            , 'prop_Instance_setIdx
            , 'prop_Instance_setName
            , 'prop_Instance_setAlias
            , 'prop_Instance_setPri
            , 'prop_Instance_setSec
            , 'prop_Instance_setBoth
            , 'prop_Instance_shrinkMG
            , 'prop_Instance_shrinkMF
            , 'prop_Instance_shrinkCG
            , 'prop_Instance_shrinkCF
            , 'prop_Instance_shrinkDG
            , 'prop_Instance_shrinkDF
            , 'prop_Instance_setMovable
            ]
Iustin Pop's avatar
Iustin Pop committed
813

814
815
816
-- ** Backends

-- *** Text backend tests
817

Iustin Pop's avatar
Iustin Pop committed
818
819
-- Instance text loader tests

820
821
822
823
prop_Text_Load_Instance :: String -> Int -> Int -> Int -> Types.InstanceStatus
                        -> NonEmptyList Char -> [Char]
                        -> NonNegative Int -> NonNegative Int -> Bool
                        -> Types.DiskTemplate -> Int -> Property
Iustin Pop's avatar
Iustin Pop committed
824
825
prop_Text_Load_Instance name mem dsk vcpus status
                        (NonEmpty pnode) snode
826
                        (NonNegative pdx) (NonNegative sdx) autobal dt su =
Iustin Pop's avatar
Iustin Pop committed
827
828
829
830
  pnode /= snode && pdx /= sdx ==>
  let vcpus_s = show vcpus
      dsk_s = show dsk
      mem_s = show mem
831
      su_s = show su
Iustin Pop's avatar
Iustin Pop committed
832
833
      status_s = Types.instanceStatusToRaw status
      ndx = if null snode
Iustin Pop's avatar
Iustin Pop committed
834
              then [(pnode, pdx)]
835
              else [(pnode, pdx), (snode, sdx)]
Iustin Pop's avatar
Iustin Pop committed
836
837
838
839
840
841
      nl = Data.Map.fromList ndx
      tags = ""
      sbal = if autobal then "Y" else "N"
      sdt = Types.diskTemplateToRaw dt
      inst = Text.loadInst nl
             [name, mem_s, dsk_s, vcpus_s, status_s,
842
              sbal, pnode, snode, sdt, tags, su_s]
Iustin Pop's avatar
Iustin Pop committed
843
844
845
846
      fail1 = Text.loadInst nl
              [name, mem_s, dsk_s, vcpus_s, status_s,
               sbal, pnode, pnode, tags]
  in case inst of
Iustin Pop's avatar
Iustin Pop committed
847
       Types.Bad msg -> failTest $ "Failed to load instance: " ++ msg
Iustin Pop's avatar
Iustin Pop committed
848
849
850
851
852
853
854
855
856
857
       Types.Ok (_, i) -> printTestCase "Mismatch in some field while\
                                        \ loading the instance" $
               Instance.name i == name &&
               Instance.vcpus i == vcpus &&
               Instance.mem i == mem &&
               Instance.pNode i == pdx &&
               Instance.sNode i == (if null snode
                                      then Node.noSecondary
                                      else sdx) &&
               Instance.autoBalance i == autobal &&
858
               Instance.spindleUse i == su &&
Iustin Pop's avatar
Iustin Pop committed
859
               Types.isBad fail1
Iustin Pop's avatar
Iustin Pop committed
860

861
prop_Text_Load_InstanceFail :: [(String, Int)] -> [String] -> Property
Iustin Pop's avatar
Iustin Pop committed
862
prop_Text_Load_InstanceFail ktn fields =
863
  length fields /= 10 && length fields /= 11 ==>
Iustin Pop's avatar
Iustin Pop committed
864
    case Text.loadInst nl fields of
Iustin Pop's avatar
Iustin Pop committed
865
      Types.Ok _ -> failTest "Managed to load instance from invalid data"
866
867
      Types.Bad msg -> printTestCase ("Unrecognised error message: " ++ msg) $
                       "Invalid/incomplete instance data: '" `isPrefixOf` msg
868
    where nl = Data.Map.fromList ktn
Iustin Pop's avatar
Iustin Pop committed
869

870
871
prop_Text_Load_Node :: String -> Int -> Int -> Int -> Int -> Int
                    -> Int -> Bool -> Bool
Iustin Pop's avatar
Iustin Pop committed
872
prop_Text_Load_Node name tm nm fm td fd tc fo =
Iustin Pop's avatar
Iustin Pop committed
873
874
875
876
877
878
879
880
881
882
  let conv v = if v < 0
                 then "?"
                 else show v
      tm_s = conv tm
      nm_s = conv nm
      fm_s = conv fm
      td_s = conv td
      fd_s = conv fd
      tc_s = conv tc
      fo_s = if fo
Iustin Pop's avatar
Iustin Pop committed
883
884
               then "Y"
               else "N"
Iustin Pop's avatar
Iustin Pop committed
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
      any_broken = any (< 0) [tm, nm, fm, td, fd, tc]
      gid = Group.uuid defGroup
  in case Text.loadNode defGroupAssoc
       [name, tm_s, nm_s, fm_s, td_s, fd_s, tc_s, fo_s, gid] of
       Nothing -> False
       Just (name', node) ->
         if fo || any_broken
           then Node.offline node
           else Node.name node == name' && name' == name &&
                Node.alias node == name &&
                Node.tMem node == fromIntegral tm &&
                Node.nMem node == nm &&
                Node.fMem node == fm &&
                Node.tDsk node == fromIntegral td &&
                Node.fDsk node == fd &&
                Node.tCpu node == fromIntegral tc
Iustin Pop's avatar
Iustin Pop committed
901

902
prop_Text_Load_NodeFail :: [String] -> Property
Iustin Pop's avatar
Iustin Pop committed
903
prop_Text_Load_NodeFail fields =
Iustin Pop's avatar
Iustin Pop committed
904
  length fields /= 8 ==> isNothing $ Text.loadNode Data.Map.empty fields
Iustin Pop's avatar
Iustin Pop committed
905

906
prop_Text_NodeLSIdempotent :: Node.Node -> Property
907
prop_Text_NodeLSIdempotent node =
Iustin Pop's avatar
Iustin Pop committed
908
  (Text.loadNode defGroupAssoc.
909
       Utils.sepSplit '|' . Text.serializeNode defGroupList) n ==?
Iustin Pop's avatar
Iustin Pop committed
910
  Just (Node.name n, n)
911
    -- override failN1 to what loadNode returns by default
912
913
    where n = Node.setPolicy Types.defIPolicy $
              node { Node.failN1 = True, Node.offline = False }
914

915
prop_Text_ISpecIdempotent :: Types.ISpec -> Property
916
917
918
prop_Text_ISpecIdempotent ispec =
  case Text.loadISpec "dummy" . Utils.sepSplit ',' .
       Text.serializeISpec $ ispec of
Iustin Pop's avatar
Iustin Pop committed
919
    Types.Bad msg -> failTest $ "Failed to load ispec: " ++ msg
920
921
    Types.Ok ispec' -> ispec ==? ispec'

922
prop_Text_IPolicyIdempotent :: Types.IPolicy -> Property
923
924
925
prop_Text_IPolicyIdempotent ipol =
  case Text.loadIPolicy . Utils.sepSplit '|' $
       Text.serializeIPolicy owner ipol of
Iustin Pop's avatar
Iustin Pop committed
926
    Types.