Statistics
| Branch: | Tag: | Revision:

root / test / hs / Test / Ganeti / JQueue.hs @ 76b4ac58

History | View | Annotate | Download (11.6 kB)

1
{-# LANGUAGE TemplateHaskell #-}
2

    
3
{-| Unittests for the job queue functionality.
4

    
5
-}
6

    
7
{-
8

    
9
Copyright (C) 2012, 2013 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 Test.Ganeti.JQueue (testJQueue) where
29

    
30
import Control.Applicative
31
import Control.Monad (when)
32
import Data.Char (isAscii)
33
import Data.List (nub, sort)
34
import System.Directory
35
import System.FilePath
36
import System.IO.Temp
37
import System.Posix.Files
38
import Test.HUnit
39
import Test.QuickCheck as QuickCheck
40
import Test.QuickCheck.Monadic
41
import Text.JSON
42

    
43
import Test.Ganeti.TestCommon
44
import Test.Ganeti.TestHelper
45
import Test.Ganeti.Types ()
46
import Test.Ganeti.OpCodes
47

    
48
import Ganeti.BasicTypes
49
import qualified Ganeti.Constants as C
50
import Ganeti.JQueue
51
import Ganeti.OpCodes
52
import Ganeti.Path
53
import Ganeti.Types as Types
54

    
55
{-# ANN module "HLint: ignore Use camelCase" #-}
56

    
57
-- * Helpers
58

    
59
-- | noTimestamp in Just form.
60
justNoTs :: Maybe Timestamp
61
justNoTs = Just noTimestamp
62

    
63
-- | Generates a simple queued opcode.
64
genQueuedOpCode :: Gen QueuedOpCode
65
genQueuedOpCode =
66
  QueuedOpCode <$> pure (ValidOpCode $ wrapOpCode OpClusterQuery) <*>
67
    arbitrary <*> pure JSNull <*> pure [] <*>
68
    choose (C.opPrioLowest, C.opPrioHighest) <*>
69
    pure justNoTs <*> pure justNoTs <*> pure justNoTs
70

    
71
-- | Generates an static, empty job.
72
emptyJob :: (Monad m) => m QueuedJob
73
emptyJob = do
74
  jid0 <- makeJobId 0
75
  return $ QueuedJob jid0 [] justNoTs justNoTs justNoTs Nothing Nothing
76

    
77
-- | Generates a job ID.
78
genJobId :: Gen JobId
79
genJobId = do
80
  p <- arbitrary::Gen (Types.NonNegative Int)
81
  makeJobId $ fromNonNegative p
82

    
83
-- * Test cases
84

    
85
-- | Tests default priority value.
86
case_JobPriorityDef :: Assertion
87
case_JobPriorityDef = do
88
  ej <- emptyJob
89
  assertEqual "for default priority" C.opPrioDefault $ calcJobPriority ej
90

    
91
-- | Test arbitrary priorities.
92
prop_JobPriority :: Property
93
prop_JobPriority =
94
  forAll (listOf1 (genQueuedOpCode `suchThat`
95
                   (not . opStatusFinalized . qoStatus))) $ \ops -> do
96
  jid0 <- makeJobId 0
97
  let job = QueuedJob jid0 ops justNoTs justNoTs justNoTs Nothing Nothing
98
  calcJobPriority job ==? minimum (map qoPriority ops)
99

    
100
-- | Tests default job status.
101
case_JobStatusDef :: Assertion
102
case_JobStatusDef = do
103
  ej <- emptyJob
104
  assertEqual "for job status" JOB_STATUS_SUCCESS $ calcJobStatus ej
105

    
106
-- | Test some job status properties.
107
prop_JobStatus :: Property
108
prop_JobStatus =
109
  forAll genJobId $ \jid ->
110
  forAll genQueuedOpCode $ \op ->
111
  let job1 = QueuedJob jid [op] justNoTs justNoTs justNoTs Nothing Nothing
112
      st1 = calcJobStatus job1
113
      op_succ = op { qoStatus = OP_STATUS_SUCCESS }
114
      op_err  = op { qoStatus = OP_STATUS_ERROR }
115
      op_cnl  = op { qoStatus = OP_STATUS_CANCELING }
116
      op_cnd  = op { qoStatus = OP_STATUS_CANCELED }
117
      -- computes status for a job with an added opcode before
118
      st_pre_op pop = calcJobStatus (job1 { qjOps = pop:qjOps job1 })
119
      -- computes status for a job with an added opcode after
120
      st_post_op pop = calcJobStatus (job1 { qjOps = qjOps job1 ++ [pop] })
121
  in conjoin
122
     [ printTestCase "pre-success doesn't change status"
123
       (st_pre_op op_succ ==? st1)
124
     , printTestCase "post-success doesn't change status"
125
       (st_post_op op_succ ==? st1)
126
     , printTestCase "pre-error is error"
127
       (st_pre_op op_err ==? JOB_STATUS_ERROR)
128
     , printTestCase "pre-canceling is canceling"
129
       (st_pre_op op_cnl ==? JOB_STATUS_CANCELING)
130
     , printTestCase "pre-canceled is canceled"
131
       (st_pre_op op_cnd ==? JOB_STATUS_CANCELED)
132
     ]
133

    
134
-- | Tests job status equivalence with Python. Very similar to OpCodes test.
135
case_JobStatusPri_py_equiv :: Assertion
136
case_JobStatusPri_py_equiv = do
137
  let num_jobs = 2000::Int
138
  jobs <- genSample (vectorOf num_jobs $ do
139
                       num_ops <- choose (1, 5)
140
                       ops <- vectorOf num_ops genQueuedOpCode
141
                       jid <- genJobId
142
                       return $ QueuedJob jid ops justNoTs justNoTs justNoTs
143
                                          Nothing Nothing)
144
  let serialized = encode jobs
145
  -- check for non-ASCII fields, usually due to 'arbitrary :: String'
146
  mapM_ (\job -> when (any (not . isAscii) (encode job)) .
147
                 assertFailure $ "Job has non-ASCII fields: " ++ show job
148
        ) jobs
149
  py_stdout <-
150
     runPython "from ganeti import jqueue\n\
151
               \from ganeti import serializer\n\
152
               \import sys\n\
153
               \job_data = serializer.Load(sys.stdin.read())\n\
154
               \decoded = [jqueue._QueuedJob.Restore(None, o, False, False)\n\
155
               \           for o in job_data]\n\
156
               \encoded = [(job.CalcStatus(), job.CalcPriority())\n\
157
               \           for job in decoded]\n\
158
               \print serializer.Dump(encoded)" serialized
159
     >>= checkPythonResult
160
  let deserialised = decode py_stdout::Text.JSON.Result [(String, Int)]
161
  decoded <- case deserialised of
162
               Text.JSON.Ok jobs' -> return jobs'
163
               Error msg ->
164
                 assertFailure ("Unable to decode jobs: " ++ msg)
165
                 -- this already raised an exception, but we need it
166
                 -- for proper types
167
                 >> fail "Unable to decode jobs"
168
  assertEqual "Mismatch in number of returned jobs"
169
    (length decoded) (length jobs)
170
  mapM_ (\(py_sp, job) ->
171
           let hs_sp = (jobStatusToRaw $ calcJobStatus job,
172
                        calcJobPriority job)
173
           in assertEqual ("Different result after encoding/decoding for " ++
174
                           show job) hs_sp py_sp
175
        ) $ zip decoded jobs
176

    
177
-- | Tests listing of Job ids.
178
prop_ListJobIDs :: Property
179
prop_ListJobIDs = monadicIO $ do
180
  let extractJobIDs :: (Show e, Monad m) => m (GenericResult e a) -> m a
181
      extractJobIDs = (>>= genericResult (fail . show) return)
182
  jobs <- pick $ resize 10 (listOf1 genJobId `suchThat` (\l -> l == nub l))
183
  (e, f, g) <-
184
    run . withSystemTempDirectory "jqueue-test." $ \tempdir -> do
185
    empty_dir <- extractJobIDs $ getJobIDs [tempdir]
186
    mapM_ (\jid -> writeFile (tempdir </> jobFileName jid) "") jobs
187
    full_dir <- extractJobIDs $ getJobIDs [tempdir]
188
    invalid_dir <- getJobIDs [tempdir </> "no-such-dir"]
189
    return (empty_dir, sortJobIDs full_dir, invalid_dir)
190
  stop $ conjoin [ printTestCase "empty directory" $ e ==? []
191
                 , printTestCase "directory with valid names" $
192
                   f ==? sortJobIDs jobs
193
                 , printTestCase "invalid directory" $ isBad g
194
                 ]
195

    
196
-- | Tests loading jobs from disk.
197
prop_LoadJobs :: Property
198
prop_LoadJobs = monadicIO $ do
199
  ops <- pick $ resize 5 (listOf1 genQueuedOpCode)
200
  jid <- pick genJobId
201
  let job = QueuedJob jid ops justNoTs justNoTs justNoTs Nothing Nothing
202
      job_s = encode job
203
  -- check that jobs in the right directories are parsed correctly
204
  (missing, current, archived, missing_current, broken) <-
205
    run  . withSystemTempDirectory "jqueue-test." $ \tempdir -> do
206
    let load a = loadJobFromDisk tempdir a jid
207
        live_path = liveJobFile tempdir jid
208
        arch_path = archivedJobFile tempdir jid
209
    createDirectory $ tempdir </> jobQueueArchiveSubDir
210
    createDirectory $ dropFileName arch_path
211
    -- missing job
212
    missing <- load True
213
    writeFile live_path job_s
214
    -- this should exist
215
    current <- load False
216
    removeFile live_path
217
    writeFile arch_path job_s
218
    -- this should exist (archived)
219
    archived <- load True
220
    -- this should be missing
221
    missing_current <- load False
222
    removeFile arch_path
223
    writeFile live_path "invalid job"
224
    broken <- load True
225
    return (missing, current, archived, missing_current, broken)
226
  stop $ conjoin [ missing ==? noSuchJob
227
                 , current ==? Ganeti.BasicTypes.Ok (job, False)
228
                 , archived ==? Ganeti.BasicTypes.Ok (job, True)
229
                 , missing_current ==? noSuchJob
230
                 , printTestCase "broken job" (isBad broken)
231
                 ]
232

    
233
-- | Tests computing job directories. Creates random directories,
234
-- files and stale symlinks in a directory, and checks that we return
235
-- \"the right thing\".
236
prop_DetermineDirs :: Property
237
prop_DetermineDirs = monadicIO $ do
238
  count <- pick $ choose (2, 10)
239
  nums <- pick $ genUniquesList count
240
          (arbitrary::Gen (QuickCheck.Positive Int))
241
  let (valid, invalid) = splitAt (count `div` 2) $
242
                         map (\(QuickCheck.Positive i) -> show i) nums
243
  (tempdir, non_arch, with_arch, invalid_root) <-
244
    run  . withSystemTempDirectory "jqueue-test." $ \tempdir -> do
245
    let arch_dir = tempdir </> jobQueueArchiveSubDir
246
    createDirectory arch_dir
247
    mapM_ (createDirectory . (arch_dir </>)) valid
248
    mapM_ (\p -> writeFile (arch_dir </> p) "") invalid
249
    mapM_ (\p -> createSymbolicLink "/dev/null/no/such/file"
250
                 (arch_dir </> p <.> "missing")) invalid
251
    non_arch <- determineJobDirectories tempdir False
252
    with_arch <- determineJobDirectories tempdir True
253
    invalid_root <- determineJobDirectories (tempdir </> "no-such-subdir") True
254
    return (tempdir, non_arch, with_arch, invalid_root)
255
  let arch_dir = tempdir </> jobQueueArchiveSubDir
256
  stop $ conjoin [ non_arch ==? [tempdir]
257
                 , sort with_arch ==? sort (tempdir:map (arch_dir </>) valid)
258
                 , invalid_root ==? [tempdir </> "no-such-subdir"]
259
                 ]
260

    
261
-- | Tests the JSON serialisation for 'InputOpCode'.
262
prop_InputOpCode :: MetaOpCode -> Int -> Property
263
prop_InputOpCode meta i =
264
  conjoin [ readJSON (showJSON valid)   ==? Text.JSON.Ok valid
265
          , readJSON (showJSON invalid) ==? Text.JSON.Ok invalid
266
          ]
267
    where valid = ValidOpCode meta
268
          invalid = InvalidOpCode (showJSON i)
269

    
270
-- | Tests 'extractOpSummary'.
271
prop_extractOpSummary :: MetaOpCode -> Int -> Property
272
prop_extractOpSummary meta i =
273
  conjoin [ printTestCase "valid opcode" $
274
            extractOpSummary (ValidOpCode meta)      ==? summary
275
          , printTestCase "invalid opcode, correct object" $
276
            extractOpSummary (InvalidOpCode jsobj)   ==? summary
277
          , printTestCase "invalid opcode, empty object" $
278
            extractOpSummary (InvalidOpCode emptyo)  ==? invalid
279
          , printTestCase "invalid opcode, object with invalid OP_ID" $
280
            extractOpSummary (InvalidOpCode invobj)  ==? invalid
281
          , printTestCase "invalid opcode, not jsobject" $
282
            extractOpSummary (InvalidOpCode jsinval) ==? invalid
283
          ]
284
    where summary = opSummary (metaOpCode meta)
285
          jsobj = showJSON $ toJSObject [("OP_ID",
286
                                          showJSON ("OP_" ++ summary))]
287
          emptyo = showJSON $ toJSObject ([]::[(String, JSValue)])
288
          invobj = showJSON $ toJSObject [("OP_ID", showJSON False)]
289
          jsinval = showJSON i
290
          invalid = "INVALID_OP"
291

    
292
testSuite "JQueue"
293
            [ 'case_JobPriorityDef
294
            , 'prop_JobPriority
295
            , 'case_JobStatusDef
296
            , 'prop_JobStatus
297
            , 'case_JobStatusPri_py_equiv
298
            , 'prop_ListJobIDs
299
            , 'prop_LoadJobs
300
            , 'prop_DetermineDirs
301
            , 'prop_InputOpCode
302
            , 'prop_extractOpSummary
303
            ]