root / src / Ganeti / JQueue.hs @ 363dc9d6
History | View | Annotate | Download (17.2 kB)
1 |
{-# LANGUAGE TemplateHaskell #-} |
---|---|
2 |
|
3 |
{-| Implementation of the job queue. |
4 |
|
5 |
-} |
6 |
|
7 |
{- |
8 |
|
9 |
Copyright (C) 2010, 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.JQueue |
29 |
( QueuedOpCode(..) |
30 |
, QueuedJob(..) |
31 |
, InputOpCode(..) |
32 |
, queuedOpCodeFromMetaOpCode |
33 |
, queuedJobFromOpCodes |
34 |
, cancelQueuedJob |
35 |
, Timestamp |
36 |
, noTimestamp |
37 |
, currentTimestamp |
38 |
, setReceivedTimestamp |
39 |
, opStatusFinalized |
40 |
, extractOpSummary |
41 |
, calcJobStatus |
42 |
, jobStarted |
43 |
, jobFinalized |
44 |
, calcJobPriority |
45 |
, jobFileName |
46 |
, liveJobFile |
47 |
, archivedJobFile |
48 |
, determineJobDirectories |
49 |
, getJobIDs |
50 |
, sortJobIDs |
51 |
, loadJobFromDisk |
52 |
, noSuchJob |
53 |
, readSerialFromDisk |
54 |
, allocateJobIds |
55 |
, allocateJobId |
56 |
, writeJobToDisk |
57 |
, replicateManyJobs |
58 |
, isQueueOpen |
59 |
, startJobs |
60 |
, cancelJob |
61 |
) where |
62 |
|
63 |
import Control.Arrow (second) |
64 |
import Control.Concurrent.MVar |
65 |
import Control.Exception |
66 |
import Control.Monad |
67 |
import Data.Functor ((<$)) |
68 |
import Data.List |
69 |
import Data.Maybe |
70 |
import Data.Ord (comparing) |
71 |
-- workaround what seems to be a bug in ghc 7.4's TH shadowing code |
72 |
import Prelude hiding (id, log) |
73 |
import System.Directory |
74 |
import System.FilePath |
75 |
import System.IO.Error (isDoesNotExistError) |
76 |
import System.Posix.Files |
77 |
import System.Time |
78 |
import qualified Text.JSON |
79 |
import Text.JSON.Types |
80 |
|
81 |
import Ganeti.BasicTypes |
82 |
import qualified Ganeti.Constants as C |
83 |
import Ganeti.Errors (ErrorResult) |
84 |
import Ganeti.JSON |
85 |
import Ganeti.Logging |
86 |
import Ganeti.Luxi |
87 |
import Ganeti.Objects (Node) |
88 |
import Ganeti.OpCodes |
89 |
import Ganeti.Path |
90 |
import Ganeti.Rpc (executeRpcCall, ERpcError, logRpcErrors, |
91 |
RpcCallJobqueueUpdate(..)) |
92 |
import Ganeti.THH |
93 |
import Ganeti.Types |
94 |
import Ganeti.Utils |
95 |
|
96 |
-- * Data types |
97 |
|
98 |
-- | The ganeti queue timestamp type. It represents the time as the pair |
99 |
-- of seconds since the epoch and microseconds since the beginning of the |
100 |
-- second. |
101 |
type Timestamp = (Int, Int) |
102 |
|
103 |
-- | Missing timestamp type. |
104 |
noTimestamp :: Timestamp |
105 |
noTimestamp = (-1, -1) |
106 |
|
107 |
-- | Get the current time in the job-queue timestamp format. |
108 |
currentTimestamp :: IO Timestamp |
109 |
currentTimestamp = do |
110 |
TOD ctime pico <- getClockTime |
111 |
return (fromIntegral ctime, fromIntegral $ pico `div` 1000000) |
112 |
|
113 |
-- | An input opcode. |
114 |
data InputOpCode = ValidOpCode MetaOpCode -- ^ OpCode was parsed successfully |
115 |
| InvalidOpCode JSValue -- ^ Invalid opcode |
116 |
deriving (Show, Eq) |
117 |
|
118 |
-- | JSON instance for 'InputOpCode', trying to parse it and if |
119 |
-- failing, keeping the original JSValue. |
120 |
instance Text.JSON.JSON InputOpCode where |
121 |
showJSON (ValidOpCode mo) = Text.JSON.showJSON mo |
122 |
showJSON (InvalidOpCode inv) = inv |
123 |
readJSON v = case Text.JSON.readJSON v of |
124 |
Text.JSON.Error _ -> return $ InvalidOpCode v |
125 |
Text.JSON.Ok mo -> return $ ValidOpCode mo |
126 |
|
127 |
-- | Invalid opcode summary. |
128 |
invalidOp :: String |
129 |
invalidOp = "INVALID_OP" |
130 |
|
131 |
-- | Tries to extract the opcode summary from an 'InputOpCode'. This |
132 |
-- duplicates some functionality from the 'opSummary' function in |
133 |
-- "Ganeti.OpCodes". |
134 |
extractOpSummary :: InputOpCode -> String |
135 |
extractOpSummary (ValidOpCode metaop) = opSummary $ metaOpCode metaop |
136 |
extractOpSummary (InvalidOpCode (JSObject o)) = |
137 |
case fromObjWithDefault (fromJSObject o) "OP_ID" ("OP_" ++ invalidOp) of |
138 |
Just s -> drop 3 s -- drop the OP_ prefix |
139 |
Nothing -> invalidOp |
140 |
extractOpSummary _ = invalidOp |
141 |
|
142 |
$(buildObject "QueuedOpCode" "qo" |
143 |
[ simpleField "input" [t| InputOpCode |] |
144 |
, simpleField "status" [t| OpStatus |] |
145 |
, simpleField "result" [t| JSValue |] |
146 |
, defaultField [| [] |] $ |
147 |
simpleField "log" [t| [(Int, Timestamp, ELogType, JSValue)] |] |
148 |
, simpleField "priority" [t| Int |] |
149 |
, optionalNullSerField $ |
150 |
simpleField "start_timestamp" [t| Timestamp |] |
151 |
, optionalNullSerField $ |
152 |
simpleField "exec_timestamp" [t| Timestamp |] |
153 |
, optionalNullSerField $ |
154 |
simpleField "end_timestamp" [t| Timestamp |] |
155 |
]) |
156 |
|
157 |
$(buildObject "QueuedJob" "qj" |
158 |
[ simpleField "id" [t| JobId |] |
159 |
, simpleField "ops" [t| [QueuedOpCode] |] |
160 |
, optionalNullSerField $ |
161 |
simpleField "received_timestamp" [t| Timestamp |] |
162 |
, optionalNullSerField $ |
163 |
simpleField "start_timestamp" [t| Timestamp |] |
164 |
, optionalNullSerField $ |
165 |
simpleField "end_timestamp" [t| Timestamp |] |
166 |
]) |
167 |
|
168 |
-- | Convenience function to obtain a QueuedOpCode from a MetaOpCode |
169 |
queuedOpCodeFromMetaOpCode :: MetaOpCode -> QueuedOpCode |
170 |
queuedOpCodeFromMetaOpCode op = |
171 |
QueuedOpCode { qoInput = ValidOpCode op |
172 |
, qoStatus = OP_STATUS_QUEUED |
173 |
, qoPriority = opSubmitPriorityToRaw . opPriority . metaParams |
174 |
$ op |
175 |
, qoLog = [] |
176 |
, qoResult = JSNull |
177 |
, qoStartTimestamp = Nothing |
178 |
, qoEndTimestamp = Nothing |
179 |
, qoExecTimestamp = Nothing |
180 |
} |
181 |
|
182 |
-- | From a job-id and a list of op-codes create a job. This is |
183 |
-- the pure part of job creation, as allocating a new job id |
184 |
-- lives in IO. |
185 |
queuedJobFromOpCodes :: (Monad m) => JobId -> [MetaOpCode] -> m QueuedJob |
186 |
queuedJobFromOpCodes jobid ops = do |
187 |
ops' <- mapM (`resolveDependencies` jobid) ops |
188 |
return QueuedJob { qjId = jobid |
189 |
, qjOps = map queuedOpCodeFromMetaOpCode ops' |
190 |
, qjReceivedTimestamp = Nothing |
191 |
, qjStartTimestamp = Nothing |
192 |
, qjEndTimestamp = Nothing |
193 |
} |
194 |
|
195 |
-- | Attach a received timestamp to a Queued Job. |
196 |
setReceivedTimestamp :: Timestamp -> QueuedJob -> QueuedJob |
197 |
setReceivedTimestamp ts job = job { qjReceivedTimestamp = Just ts } |
198 |
|
199 |
-- | Set the state of a QueuedOpCode to canceled. |
200 |
cancelOpCode :: Timestamp -> QueuedOpCode -> QueuedOpCode |
201 |
cancelOpCode now op = |
202 |
op { qoStatus = OP_STATUS_CANCELED, qoEndTimestamp = Just now } |
203 |
|
204 |
-- | Transform a QueuedJob that has not been started into its canceled form. |
205 |
cancelQueuedJob :: Timestamp -> QueuedJob -> QueuedJob |
206 |
cancelQueuedJob now job = |
207 |
let ops' = map (cancelOpCode now) $ qjOps job |
208 |
in job { qjOps = ops', qjEndTimestamp = Just now} |
209 |
|
210 |
-- | Job file prefix. |
211 |
jobFilePrefix :: String |
212 |
jobFilePrefix = "job-" |
213 |
|
214 |
-- | Computes the filename for a given job ID. |
215 |
jobFileName :: JobId -> FilePath |
216 |
jobFileName jid = jobFilePrefix ++ show (fromJobId jid) |
217 |
|
218 |
-- | Parses a job ID from a file name. |
219 |
parseJobFileId :: (Monad m) => FilePath -> m JobId |
220 |
parseJobFileId path = |
221 |
case stripPrefix jobFilePrefix path of |
222 |
Nothing -> fail $ "Job file '" ++ path ++ |
223 |
"' doesn't have the correct prefix" |
224 |
Just suffix -> makeJobIdS suffix |
225 |
|
226 |
-- | Computes the full path to a live job. |
227 |
liveJobFile :: FilePath -> JobId -> FilePath |
228 |
liveJobFile rootdir jid = rootdir </> jobFileName jid |
229 |
|
230 |
-- | Computes the full path to an archives job. BROKEN. |
231 |
archivedJobFile :: FilePath -> JobId -> FilePath |
232 |
archivedJobFile rootdir jid = |
233 |
let subdir = show (fromJobId jid `div` C.jstoreJobsPerArchiveDirectory) |
234 |
in rootdir </> jobQueueArchiveSubDir </> subdir </> jobFileName jid |
235 |
|
236 |
-- | Map from opcode status to job status. |
237 |
opStatusToJob :: OpStatus -> JobStatus |
238 |
opStatusToJob OP_STATUS_QUEUED = JOB_STATUS_QUEUED |
239 |
opStatusToJob OP_STATUS_WAITING = JOB_STATUS_WAITING |
240 |
opStatusToJob OP_STATUS_SUCCESS = JOB_STATUS_SUCCESS |
241 |
opStatusToJob OP_STATUS_RUNNING = JOB_STATUS_RUNNING |
242 |
opStatusToJob OP_STATUS_CANCELING = JOB_STATUS_CANCELING |
243 |
opStatusToJob OP_STATUS_CANCELED = JOB_STATUS_CANCELED |
244 |
opStatusToJob OP_STATUS_ERROR = JOB_STATUS_ERROR |
245 |
|
246 |
-- | Computes a queued job's status. |
247 |
calcJobStatus :: QueuedJob -> JobStatus |
248 |
calcJobStatus QueuedJob { qjOps = ops } = |
249 |
extractOpSt (map qoStatus ops) JOB_STATUS_QUEUED True |
250 |
where |
251 |
terminalStatus OP_STATUS_ERROR = True |
252 |
terminalStatus OP_STATUS_CANCELING = True |
253 |
terminalStatus OP_STATUS_CANCELED = True |
254 |
terminalStatus _ = False |
255 |
softStatus OP_STATUS_SUCCESS = True |
256 |
softStatus OP_STATUS_QUEUED = True |
257 |
softStatus _ = False |
258 |
extractOpSt [] _ True = JOB_STATUS_SUCCESS |
259 |
extractOpSt [] d False = d |
260 |
extractOpSt (x:xs) d old_all |
261 |
| terminalStatus x = opStatusToJob x -- abort recursion |
262 |
| softStatus x = extractOpSt xs d new_all -- continue unchanged |
263 |
| otherwise = extractOpSt xs (opStatusToJob x) new_all |
264 |
where new_all = x == OP_STATUS_SUCCESS && old_all |
265 |
|
266 |
-- | Determine if a job has started |
267 |
jobStarted :: QueuedJob -> Bool |
268 |
jobStarted = (> JOB_STATUS_QUEUED) . calcJobStatus |
269 |
|
270 |
-- | Determine if a job is finalised. |
271 |
jobFinalized :: QueuedJob -> Bool |
272 |
jobFinalized = (> JOB_STATUS_RUNNING) . calcJobStatus |
273 |
|
274 |
-- | Determine whether an opcode status is finalized. |
275 |
opStatusFinalized :: OpStatus -> Bool |
276 |
opStatusFinalized = (> OP_STATUS_RUNNING) |
277 |
|
278 |
-- | Compute a job's priority. |
279 |
calcJobPriority :: QueuedJob -> Int |
280 |
calcJobPriority QueuedJob { qjOps = ops } = |
281 |
helper . map qoPriority $ filter (not . opStatusFinalized . qoStatus) ops |
282 |
where helper [] = C.opPrioDefault |
283 |
helper ps = minimum ps |
284 |
|
285 |
-- | Log but ignore an 'IOError'. |
286 |
ignoreIOError :: a -> Bool -> String -> IOError -> IO a |
287 |
ignoreIOError a ignore_noent msg e = do |
288 |
unless (isDoesNotExistError e && ignore_noent) . |
289 |
logWarning $ msg ++ ": " ++ show e |
290 |
return a |
291 |
|
292 |
-- | Compute the list of existing archive directories. Note that I/O |
293 |
-- exceptions are swallowed and ignored. |
294 |
allArchiveDirs :: FilePath -> IO [FilePath] |
295 |
allArchiveDirs rootdir = do |
296 |
let adir = rootdir </> jobQueueArchiveSubDir |
297 |
contents <- getDirectoryContents adir `Control.Exception.catch` |
298 |
ignoreIOError [] False |
299 |
("Failed to list queue directory " ++ adir) |
300 |
let fpaths = map (adir </>) $ filter (not . ("." `isPrefixOf`)) contents |
301 |
filterM (\path -> |
302 |
liftM isDirectory (getFileStatus (adir </> path)) |
303 |
`Control.Exception.catch` |
304 |
ignoreIOError False True |
305 |
("Failed to stat archive path " ++ path)) fpaths |
306 |
|
307 |
-- | Build list of directories containing job files. Note: compared to |
308 |
-- the Python version, this doesn't ignore a potential lost+found |
309 |
-- file. |
310 |
determineJobDirectories :: FilePath -> Bool -> IO [FilePath] |
311 |
determineJobDirectories rootdir archived = do |
312 |
other <- if archived |
313 |
then allArchiveDirs rootdir |
314 |
else return [] |
315 |
return $ rootdir:other |
316 |
|
317 |
-- Function equivalent to the \'sequence\' function, that cannot be used because |
318 |
-- of library version conflict on Lucid. |
319 |
-- FIXME: delete this and just use \'sequence\' instead when Lucid compatibility |
320 |
-- will not be required anymore. |
321 |
sequencer :: [Either IOError [JobId]] -> Either IOError [[JobId]] |
322 |
sequencer l = fmap reverse $ foldl seqFolder (Right []) l |
323 |
|
324 |
-- | Folding function for joining multiple [JobIds] into one list. |
325 |
seqFolder :: Either IOError [[JobId]] |
326 |
-> Either IOError [JobId] |
327 |
-> Either IOError [[JobId]] |
328 |
seqFolder (Left e) _ = Left e |
329 |
seqFolder (Right _) (Left e) = Left e |
330 |
seqFolder (Right l) (Right el) = Right $ el:l |
331 |
|
332 |
-- | Computes the list of all jobs in the given directories. |
333 |
getJobIDs :: [FilePath] -> IO (Either IOError [JobId]) |
334 |
getJobIDs paths = liftM (fmap concat . sequencer) (mapM getDirJobIDs paths) |
335 |
|
336 |
-- | Sorts the a list of job IDs. |
337 |
sortJobIDs :: [JobId] -> [JobId] |
338 |
sortJobIDs = sortBy (comparing fromJobId) |
339 |
|
340 |
-- | Computes the list of jobs in a given directory. |
341 |
getDirJobIDs :: FilePath -> IO (Either IOError [JobId]) |
342 |
getDirJobIDs path = do |
343 |
either_contents <- |
344 |
try (getDirectoryContents path) :: IO (Either IOError [FilePath]) |
345 |
case either_contents of |
346 |
Left e -> do |
347 |
logWarning $ "Failed to list job directory " ++ path ++ ": " ++ show e |
348 |
return $ Left e |
349 |
Right contents -> do |
350 |
let jids = foldl (\ids file -> |
351 |
case parseJobFileId file of |
352 |
Nothing -> ids |
353 |
Just new_id -> new_id:ids) [] contents |
354 |
return . Right $ reverse jids |
355 |
|
356 |
-- | Reads the job data from disk. |
357 |
readJobDataFromDisk :: FilePath -> Bool -> JobId -> IO (Maybe (String, Bool)) |
358 |
readJobDataFromDisk rootdir archived jid = do |
359 |
let live_path = liveJobFile rootdir jid |
360 |
archived_path = archivedJobFile rootdir jid |
361 |
all_paths = if archived |
362 |
then [(live_path, False), (archived_path, True)] |
363 |
else [(live_path, False)] |
364 |
foldM (\state (path, isarchived) -> |
365 |
liftM (\r -> Just (r, isarchived)) (readFile path) |
366 |
`Control.Exception.catch` |
367 |
ignoreIOError state True |
368 |
("Failed to read job file " ++ path)) Nothing all_paths |
369 |
|
370 |
-- | Failed to load job error. |
371 |
noSuchJob :: Result (QueuedJob, Bool) |
372 |
noSuchJob = Bad "Can't load job file" |
373 |
|
374 |
-- | Loads a job from disk. |
375 |
loadJobFromDisk :: FilePath -> Bool -> JobId -> IO (Result (QueuedJob, Bool)) |
376 |
loadJobFromDisk rootdir archived jid = do |
377 |
raw <- readJobDataFromDisk rootdir archived jid |
378 |
-- note: we need some stricness below, otherwise the wrapping in a |
379 |
-- Result will create too much lazyness, and not close the file |
380 |
-- descriptors for the individual jobs |
381 |
return $! case raw of |
382 |
Nothing -> noSuchJob |
383 |
Just (str, arch) -> |
384 |
liftM (\qj -> (qj, arch)) . |
385 |
fromJResult "Parsing job file" $ Text.JSON.decode str |
386 |
|
387 |
-- | Write a job to disk. |
388 |
writeJobToDisk :: FilePath -> QueuedJob -> IO (Result ()) |
389 |
writeJobToDisk rootdir job = do |
390 |
let filename = liveJobFile rootdir . qjId $ job |
391 |
content = Text.JSON.encode . Text.JSON.showJSON $ job |
392 |
tryAndLogIOError (atomicWriteFile filename content) |
393 |
("Failed to write " ++ filename) Ok |
394 |
|
395 |
-- | Replicate a job to all master candidates. |
396 |
replicateJob :: FilePath -> [Node] -> QueuedJob -> IO [(Node, ERpcError ())] |
397 |
replicateJob rootdir mastercandidates job = do |
398 |
let filename = liveJobFile rootdir . qjId $ job |
399 |
content = Text.JSON.encode . Text.JSON.showJSON $ job |
400 |
callresult <- executeRpcCall mastercandidates |
401 |
$ RpcCallJobqueueUpdate filename content |
402 |
let result = map (second (() <$)) callresult |
403 |
logRpcErrors result |
404 |
return result |
405 |
|
406 |
-- | Replicate many jobs to all master candidates. |
407 |
replicateManyJobs :: FilePath -> [Node] -> [QueuedJob] -> IO () |
408 |
replicateManyJobs rootdir mastercandidates = |
409 |
mapM_ (replicateJob rootdir mastercandidates) |
410 |
|
411 |
-- | Read the job serial number from disk. |
412 |
readSerialFromDisk :: IO (Result JobId) |
413 |
readSerialFromDisk = do |
414 |
filename <- jobQueueSerialFile |
415 |
tryAndLogIOError (readFile filename) "Failed to read serial file" |
416 |
(makeJobIdS . rStripSpace) |
417 |
|
418 |
-- | Allocate new job ids. |
419 |
-- To avoid races while accessing the serial file, the threads synchronize |
420 |
-- over a lock, as usual provided by an MVar. |
421 |
allocateJobIds :: [Node] -> MVar () -> Int -> IO (Result [JobId]) |
422 |
allocateJobIds mastercandidates lock n = |
423 |
if n <= 0 |
424 |
then return . Bad $ "Can only allocate positive number of job ids" |
425 |
else do |
426 |
takeMVar lock |
427 |
rjobid <- readSerialFromDisk |
428 |
case rjobid of |
429 |
Bad s -> do |
430 |
putMVar lock () |
431 |
return . Bad $ s |
432 |
Ok jid -> do |
433 |
let current = fromJobId jid |
434 |
serial_content = show (current + n) ++ "\n" |
435 |
serial <- jobQueueSerialFile |
436 |
write_result <- try $ atomicWriteFile serial serial_content |
437 |
:: IO (Either IOError ()) |
438 |
case write_result of |
439 |
Left e -> do |
440 |
putMVar lock () |
441 |
let msg = "Failed to write serial file: " ++ show e |
442 |
logError msg |
443 |
return . Bad $ msg |
444 |
Right () -> do |
445 |
_ <- executeRpcCall mastercandidates |
446 |
$ RpcCallJobqueueUpdate serial serial_content |
447 |
putMVar lock () |
448 |
return $ mapM makeJobId [(current+1)..(current+n)] |
449 |
|
450 |
-- | Allocate one new job id. |
451 |
allocateJobId :: [Node] -> MVar () -> IO (Result JobId) |
452 |
allocateJobId mastercandidates lock = do |
453 |
jids <- allocateJobIds mastercandidates lock 1 |
454 |
return (jids >>= monadicThe "Failed to allocate precisely one Job ID") |
455 |
|
456 |
-- | Decide if job queue is open |
457 |
isQueueOpen :: IO Bool |
458 |
isQueueOpen = liftM not (jobQueueDrainFile >>= doesFileExist) |
459 |
|
460 |
-- | Start enqueued jobs, currently by handing them over to masterd. |
461 |
startJobs :: [QueuedJob] -> IO () |
462 |
startJobs jobs = do |
463 |
socketpath <- defaultMasterSocket |
464 |
client <- getLuxiClient socketpath |
465 |
pickupResults <- mapM (flip callMethod client . PickupJob . qjId) jobs |
466 |
let failures = map show $ justBad pickupResults |
467 |
unless (null failures) |
468 |
. logWarning . (++) "Failed to notify masterd: " . commaJoin $ failures |
469 |
|
470 |
-- | Try to cancel a job that has already been handed over to execution, |
471 |
-- currently by asking masterd to cancel it. |
472 |
cancelJob :: JobId -> IO (ErrorResult JSValue) |
473 |
cancelJob jid = do |
474 |
socketpath <- defaultMasterSocket |
475 |
client <- getLuxiClient socketpath |
476 |
callMethod (CancelJob jid) client |