Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / JQueue.hs @ fb8d8645

History | View | Annotate | Download (22.3 kB)

1 aa79e62e Iustin Pop
{-# LANGUAGE TemplateHaskell #-}
2 aa79e62e Iustin Pop
3 aa79e62e Iustin Pop
{-| Implementation of the job queue.
4 aa79e62e Iustin Pop
5 aa79e62e Iustin Pop
-}
6 aa79e62e Iustin Pop
7 aa79e62e Iustin Pop
{-
8 aa79e62e Iustin Pop
9 aa79e62e Iustin Pop
Copyright (C) 2010, 2012 Google Inc.
10 aa79e62e Iustin Pop
11 aa79e62e Iustin Pop
This program is free software; you can redistribute it and/or modify
12 aa79e62e Iustin Pop
it under the terms of the GNU General Public License as published by
13 aa79e62e Iustin Pop
the Free Software Foundation; either version 2 of the License, or
14 aa79e62e Iustin Pop
(at your option) any later version.
15 aa79e62e Iustin Pop
16 aa79e62e Iustin Pop
This program is distributed in the hope that it will be useful, but
17 aa79e62e Iustin Pop
WITHOUT ANY WARRANTY; without even the implied warranty of
18 aa79e62e Iustin Pop
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 aa79e62e Iustin Pop
General Public License for more details.
20 aa79e62e Iustin Pop
21 aa79e62e Iustin Pop
You should have received a copy of the GNU General Public License
22 aa79e62e Iustin Pop
along with this program; if not, write to the Free Software
23 aa79e62e Iustin Pop
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 aa79e62e Iustin Pop
02110-1301, USA.
25 aa79e62e Iustin Pop
26 aa79e62e Iustin Pop
-}
27 aa79e62e Iustin Pop
28 aa79e62e Iustin Pop
module Ganeti.JQueue
29 aa79e62e Iustin Pop
    ( QueuedOpCode(..)
30 aa79e62e Iustin Pop
    , QueuedJob(..)
31 aa79e62e Iustin Pop
    , InputOpCode(..)
32 4b49a72b Klaus Aehlig
    , queuedOpCodeFromMetaOpCode
33 1c1132f4 Klaus Aehlig
    , queuedJobFromOpCodes
34 a7ab381a Klaus Aehlig
    , changeOpCodePriority
35 a6b33b72 Klaus Aehlig
    , changeJobPriority
36 363dc9d6 Klaus Aehlig
    , cancelQueuedJob
37 aa79e62e Iustin Pop
    , Timestamp
38 ae66f3a9 Klaus Aehlig
    , fromClockTime
39 aa79e62e Iustin Pop
    , noTimestamp
40 c3a70209 Klaus Aehlig
    , currentTimestamp
41 8b5a4b9a Klaus Aehlig
    , advanceTimestamp
42 2af22d70 Klaus Aehlig
    , setReceivedTimestamp
43 aa79e62e Iustin Pop
    , opStatusFinalized
44 aa79e62e Iustin Pop
    , extractOpSummary
45 aa79e62e Iustin Pop
    , calcJobStatus
46 02e40b13 Klaus Aehlig
    , jobStarted
47 847df9e9 Klaus Aehlig
    , jobFinalized
48 370f63be Klaus Aehlig
    , jobArchivable
49 aa79e62e Iustin Pop
    , calcJobPriority
50 aa79e62e Iustin Pop
    , jobFileName
51 aa79e62e Iustin Pop
    , liveJobFile
52 aa79e62e Iustin Pop
    , archivedJobFile
53 aa79e62e Iustin Pop
    , determineJobDirectories
54 aa79e62e Iustin Pop
    , getJobIDs
55 aa79e62e Iustin Pop
    , sortJobIDs
56 aa79e62e Iustin Pop
    , loadJobFromDisk
57 aa79e62e Iustin Pop
    , noSuchJob
58 cef3f99f Klaus Aehlig
    , readSerialFromDisk
59 ae858516 Klaus Aehlig
    , allocateJobIds
60 ae858516 Klaus Aehlig
    , allocateJobId
61 b498ed42 Klaus Aehlig
    , writeJobToDisk
62 9fd653a4 Klaus Aehlig
    , replicateManyJobs
63 1b94c0db Klaus Aehlig
    , isQueueOpen
64 ac0c5c6d Klaus Aehlig
    , startJobs
65 47c3c7b1 Klaus Aehlig
    , cancelJob
66 f23daea8 Klaus Aehlig
    , queueDirPermissions
67 c867cfe1 Klaus Aehlig
    , archiveJobs
68 aa79e62e Iustin Pop
    ) where
69 aa79e62e Iustin Pop
70 370f63be Klaus Aehlig
import Control.Applicative (liftA2, (<|>))
71 8b5a4b9a Klaus Aehlig
import Control.Arrow (first, second)
72 c867cfe1 Klaus Aehlig
import Control.Concurrent (forkIO)
73 ae858516 Klaus Aehlig
import Control.Concurrent.MVar
74 aa79e62e Iustin Pop
import Control.Exception
75 aa79e62e Iustin Pop
import Control.Monad
76 557f5dad Klaus Aehlig
import Data.Functor ((<$))
77 aa79e62e Iustin Pop
import Data.List
78 4b49a72b Klaus Aehlig
import Data.Maybe
79 aa79e62e Iustin Pop
import Data.Ord (comparing)
80 aa79e62e Iustin Pop
-- workaround what seems to be a bug in ghc 7.4's TH shadowing code
81 557f5dad Klaus Aehlig
import Prelude hiding (id, log)
82 aa79e62e Iustin Pop
import System.Directory
83 aa79e62e Iustin Pop
import System.FilePath
84 aa79e62e Iustin Pop
import System.IO.Error (isDoesNotExistError)
85 aa79e62e Iustin Pop
import System.Posix.Files
86 c3a70209 Klaus Aehlig
import System.Time
87 aa79e62e Iustin Pop
import qualified Text.JSON
88 aa79e62e Iustin Pop
import Text.JSON.Types
89 aa79e62e Iustin Pop
90 aa79e62e Iustin Pop
import Ganeti.BasicTypes
91 c867cfe1 Klaus Aehlig
import qualified Ganeti.Config as Config
92 aa79e62e Iustin Pop
import qualified Ganeti.Constants as C
93 47c3c7b1 Klaus Aehlig
import Ganeti.Errors (ErrorResult)
94 aa79e62e Iustin Pop
import Ganeti.JSON
95 aa79e62e Iustin Pop
import Ganeti.Logging
96 493d6920 Klaus Aehlig
import Ganeti.Luxi
97 c867cfe1 Klaus Aehlig
import Ganeti.Objects (ConfigData, Node)
98 aa79e62e Iustin Pop
import Ganeti.OpCodes
99 aa79e62e Iustin Pop
import Ganeti.Path
100 b5a96995 Klaus Aehlig
import Ganeti.Rpc (executeRpcCall, ERpcError, logRpcErrors,
101 c867cfe1 Klaus Aehlig
                   RpcCallJobqueueUpdate(..), RpcCallJobqueueRename(..))
102 aa79e62e Iustin Pop
import Ganeti.THH
103 aa79e62e Iustin Pop
import Ganeti.Types
104 cef3f99f Klaus Aehlig
import Ganeti.Utils
105 77676415 Klaus Aehlig
import Ganeti.VCluster (makeVirtualPath)
106 aa79e62e Iustin Pop
107 aa79e62e Iustin Pop
-- * Data types
108 aa79e62e Iustin Pop
109 c3a70209 Klaus Aehlig
-- | The ganeti queue timestamp type. It represents the time as the pair
110 c3a70209 Klaus Aehlig
-- of seconds since the epoch and microseconds since the beginning of the
111 c3a70209 Klaus Aehlig
-- second.
112 aa79e62e Iustin Pop
type Timestamp = (Int, Int)
113 aa79e62e Iustin Pop
114 aa79e62e Iustin Pop
-- | Missing timestamp type.
115 aa79e62e Iustin Pop
noTimestamp :: Timestamp
116 aa79e62e Iustin Pop
noTimestamp = (-1, -1)
117 aa79e62e Iustin Pop
118 ae66f3a9 Klaus Aehlig
-- | Obtain a Timestamp from a given clock time
119 ae66f3a9 Klaus Aehlig
fromClockTime :: ClockTime -> Timestamp
120 ae66f3a9 Klaus Aehlig
fromClockTime (TOD ctime pico) =
121 ae66f3a9 Klaus Aehlig
  (fromIntegral ctime, fromIntegral $ pico `div` 1000000)
122 ae66f3a9 Klaus Aehlig
123 c3a70209 Klaus Aehlig
-- | Get the current time in the job-queue timestamp format.
124 c3a70209 Klaus Aehlig
currentTimestamp :: IO Timestamp
125 ae66f3a9 Klaus Aehlig
currentTimestamp = fromClockTime `liftM` getClockTime
126 c3a70209 Klaus Aehlig
127 8b5a4b9a Klaus Aehlig
-- | From a given timestamp, obtain the timestamp of the
128 8b5a4b9a Klaus Aehlig
-- time that is the given number of seconds later.
129 8b5a4b9a Klaus Aehlig
advanceTimestamp :: Int -> Timestamp -> Timestamp
130 8b5a4b9a Klaus Aehlig
advanceTimestamp = first . (+)
131 8b5a4b9a Klaus Aehlig
132 aa79e62e Iustin Pop
-- | An input opcode.
133 aa79e62e Iustin Pop
data InputOpCode = ValidOpCode MetaOpCode -- ^ OpCode was parsed successfully
134 aa79e62e Iustin Pop
                 | InvalidOpCode JSValue  -- ^ Invalid opcode
135 aa79e62e Iustin Pop
                   deriving (Show, Eq)
136 aa79e62e Iustin Pop
137 aa79e62e Iustin Pop
-- | JSON instance for 'InputOpCode', trying to parse it and if
138 aa79e62e Iustin Pop
-- failing, keeping the original JSValue.
139 aa79e62e Iustin Pop
instance Text.JSON.JSON InputOpCode where
140 aa79e62e Iustin Pop
  showJSON (ValidOpCode mo) = Text.JSON.showJSON mo
141 aa79e62e Iustin Pop
  showJSON (InvalidOpCode inv) = inv
142 aa79e62e Iustin Pop
  readJSON v = case Text.JSON.readJSON v of
143 aa79e62e Iustin Pop
                 Text.JSON.Error _ -> return $ InvalidOpCode v
144 aa79e62e Iustin Pop
                 Text.JSON.Ok mo -> return $ ValidOpCode mo
145 aa79e62e Iustin Pop
146 aa79e62e Iustin Pop
-- | Invalid opcode summary.
147 aa79e62e Iustin Pop
invalidOp :: String
148 aa79e62e Iustin Pop
invalidOp = "INVALID_OP"
149 aa79e62e Iustin Pop
150 aa79e62e Iustin Pop
-- | Tries to extract the opcode summary from an 'InputOpCode'. This
151 aa79e62e Iustin Pop
-- duplicates some functionality from the 'opSummary' function in
152 aa79e62e Iustin Pop
-- "Ganeti.OpCodes".
153 aa79e62e Iustin Pop
extractOpSummary :: InputOpCode -> String
154 aa79e62e Iustin Pop
extractOpSummary (ValidOpCode metaop) = opSummary $ metaOpCode metaop
155 aa79e62e Iustin Pop
extractOpSummary (InvalidOpCode (JSObject o)) =
156 aa79e62e Iustin Pop
  case fromObjWithDefault (fromJSObject o) "OP_ID" ("OP_" ++ invalidOp) of
157 aa79e62e Iustin Pop
    Just s -> drop 3 s -- drop the OP_ prefix
158 aa79e62e Iustin Pop
    Nothing -> invalidOp
159 aa79e62e Iustin Pop
extractOpSummary _ = invalidOp
160 aa79e62e Iustin Pop
161 aa79e62e Iustin Pop
$(buildObject "QueuedOpCode" "qo"
162 aa79e62e Iustin Pop
  [ simpleField "input"           [t| InputOpCode |]
163 aa79e62e Iustin Pop
  , simpleField "status"          [t| OpStatus    |]
164 aa79e62e Iustin Pop
  , simpleField "result"          [t| JSValue     |]
165 aa79e62e Iustin Pop
  , defaultField [| [] |] $
166 aa79e62e Iustin Pop
    simpleField "log"             [t| [(Int, Timestamp, ELogType, JSValue)] |]
167 aa79e62e Iustin Pop
  , simpleField "priority"        [t| Int         |]
168 aa79e62e Iustin Pop
  , optionalNullSerField $
169 aa79e62e Iustin Pop
    simpleField "start_timestamp" [t| Timestamp   |]
170 aa79e62e Iustin Pop
  , optionalNullSerField $
171 aa79e62e Iustin Pop
    simpleField "exec_timestamp"  [t| Timestamp   |]
172 aa79e62e Iustin Pop
  , optionalNullSerField $
173 aa79e62e Iustin Pop
    simpleField "end_timestamp"   [t| Timestamp   |]
174 aa79e62e Iustin Pop
  ])
175 aa79e62e Iustin Pop
176 aa79e62e Iustin Pop
$(buildObject "QueuedJob" "qj"
177 aa79e62e Iustin Pop
  [ simpleField "id"                 [t| JobId          |]
178 aa79e62e Iustin Pop
  , simpleField "ops"                [t| [QueuedOpCode] |]
179 aa79e62e Iustin Pop
  , optionalNullSerField $
180 aa79e62e Iustin Pop
    simpleField "received_timestamp" [t| Timestamp      |]
181 aa79e62e Iustin Pop
  , optionalNullSerField $
182 aa79e62e Iustin Pop
    simpleField "start_timestamp"    [t| Timestamp      |]
183 aa79e62e Iustin Pop
  , optionalNullSerField $
184 aa79e62e Iustin Pop
    simpleField "end_timestamp"      [t| Timestamp      |]
185 aa79e62e Iustin Pop
  ])
186 aa79e62e Iustin Pop
187 4b49a72b Klaus Aehlig
-- | Convenience function to obtain a QueuedOpCode from a MetaOpCode
188 4b49a72b Klaus Aehlig
queuedOpCodeFromMetaOpCode :: MetaOpCode -> QueuedOpCode
189 4b49a72b Klaus Aehlig
queuedOpCodeFromMetaOpCode op =
190 4b49a72b Klaus Aehlig
  QueuedOpCode { qoInput = ValidOpCode op
191 4b49a72b Klaus Aehlig
               , qoStatus = OP_STATUS_QUEUED
192 4b49a72b Klaus Aehlig
               , qoPriority = opSubmitPriorityToRaw . opPriority . metaParams
193 4b49a72b Klaus Aehlig
                              $ op
194 4b49a72b Klaus Aehlig
               , qoLog = []
195 4b49a72b Klaus Aehlig
               , qoResult = JSNull
196 4b49a72b Klaus Aehlig
               , qoStartTimestamp = Nothing
197 4b49a72b Klaus Aehlig
               , qoEndTimestamp = Nothing
198 4b49a72b Klaus Aehlig
               , qoExecTimestamp = Nothing
199 4b49a72b Klaus Aehlig
               }
200 4b49a72b Klaus Aehlig
201 1c1132f4 Klaus Aehlig
-- | From a job-id and a list of op-codes create a job. This is
202 1c1132f4 Klaus Aehlig
-- the pure part of job creation, as allocating a new job id
203 1c1132f4 Klaus Aehlig
-- lives in IO.
204 1c1132f4 Klaus Aehlig
queuedJobFromOpCodes :: (Monad m) => JobId -> [MetaOpCode] -> m QueuedJob
205 1c1132f4 Klaus Aehlig
queuedJobFromOpCodes jobid ops = do
206 1c1132f4 Klaus Aehlig
  ops' <- mapM (`resolveDependencies` jobid) ops
207 1c1132f4 Klaus Aehlig
  return QueuedJob { qjId = jobid
208 1c1132f4 Klaus Aehlig
                   , qjOps = map queuedOpCodeFromMetaOpCode ops'
209 1c1132f4 Klaus Aehlig
                   , qjReceivedTimestamp = Nothing 
210 1c1132f4 Klaus Aehlig
                   , qjStartTimestamp = Nothing
211 1c1132f4 Klaus Aehlig
                   , qjEndTimestamp = Nothing
212 1c1132f4 Klaus Aehlig
                   }
213 1c1132f4 Klaus Aehlig
214 2af22d70 Klaus Aehlig
-- | Attach a received timestamp to a Queued Job.
215 2af22d70 Klaus Aehlig
setReceivedTimestamp :: Timestamp -> QueuedJob -> QueuedJob
216 2af22d70 Klaus Aehlig
setReceivedTimestamp ts job = job { qjReceivedTimestamp = Just ts }
217 2af22d70 Klaus Aehlig
218 a7ab381a Klaus Aehlig
-- | Change the priority of a QueuedOpCode, if it is not already
219 a7ab381a Klaus Aehlig
-- finalized.
220 a7ab381a Klaus Aehlig
changeOpCodePriority :: Int -> QueuedOpCode -> QueuedOpCode
221 a7ab381a Klaus Aehlig
changeOpCodePriority prio op =
222 a7ab381a Klaus Aehlig
  if qoStatus op > OP_STATUS_RUNNING
223 a7ab381a Klaus Aehlig
     then op
224 a7ab381a Klaus Aehlig
     else op { qoPriority = prio }
225 a7ab381a Klaus Aehlig
226 363dc9d6 Klaus Aehlig
-- | Set the state of a QueuedOpCode to canceled.
227 363dc9d6 Klaus Aehlig
cancelOpCode :: Timestamp -> QueuedOpCode -> QueuedOpCode
228 363dc9d6 Klaus Aehlig
cancelOpCode now op =
229 363dc9d6 Klaus Aehlig
  op { qoStatus = OP_STATUS_CANCELED, qoEndTimestamp = Just now }
230 363dc9d6 Klaus Aehlig
231 a6b33b72 Klaus Aehlig
-- | Change the priority of a job, i.e., change the priority of the
232 a6b33b72 Klaus Aehlig
-- non-finalized opcodes.
233 a6b33b72 Klaus Aehlig
changeJobPriority :: Int -> QueuedJob -> QueuedJob
234 a6b33b72 Klaus Aehlig
changeJobPriority prio job =
235 a6b33b72 Klaus Aehlig
  job { qjOps = map (changeOpCodePriority prio) $ qjOps job }
236 a6b33b72 Klaus Aehlig
237 363dc9d6 Klaus Aehlig
-- | Transform a QueuedJob that has not been started into its canceled form.
238 363dc9d6 Klaus Aehlig
cancelQueuedJob :: Timestamp -> QueuedJob -> QueuedJob
239 363dc9d6 Klaus Aehlig
cancelQueuedJob now job =
240 363dc9d6 Klaus Aehlig
  let ops' = map (cancelOpCode now) $ qjOps job
241 363dc9d6 Klaus Aehlig
  in job { qjOps = ops', qjEndTimestamp = Just now}
242 363dc9d6 Klaus Aehlig
243 aa79e62e Iustin Pop
-- | Job file prefix.
244 aa79e62e Iustin Pop
jobFilePrefix :: String
245 aa79e62e Iustin Pop
jobFilePrefix = "job-"
246 aa79e62e Iustin Pop
247 aa79e62e Iustin Pop
-- | Computes the filename for a given job ID.
248 aa79e62e Iustin Pop
jobFileName :: JobId -> FilePath
249 aa79e62e Iustin Pop
jobFileName jid = jobFilePrefix ++ show (fromJobId jid)
250 aa79e62e Iustin Pop
251 aa79e62e Iustin Pop
-- | Parses a job ID from a file name.
252 aa79e62e Iustin Pop
parseJobFileId :: (Monad m) => FilePath -> m JobId
253 aa79e62e Iustin Pop
parseJobFileId path =
254 aa79e62e Iustin Pop
  case stripPrefix jobFilePrefix path of
255 aa79e62e Iustin Pop
    Nothing -> fail $ "Job file '" ++ path ++
256 aa79e62e Iustin Pop
                      "' doesn't have the correct prefix"
257 aa79e62e Iustin Pop
    Just suffix -> makeJobIdS suffix
258 aa79e62e Iustin Pop
259 aa79e62e Iustin Pop
-- | Computes the full path to a live job.
260 aa79e62e Iustin Pop
liveJobFile :: FilePath -> JobId -> FilePath
261 aa79e62e Iustin Pop
liveJobFile rootdir jid = rootdir </> jobFileName jid
262 aa79e62e Iustin Pop
263 aa79e62e Iustin Pop
-- | Computes the full path to an archives job. BROKEN.
264 aa79e62e Iustin Pop
archivedJobFile :: FilePath -> JobId -> FilePath
265 aa79e62e Iustin Pop
archivedJobFile rootdir jid =
266 aa79e62e Iustin Pop
  let subdir = show (fromJobId jid `div` C.jstoreJobsPerArchiveDirectory)
267 aa79e62e Iustin Pop
  in rootdir </> jobQueueArchiveSubDir </> subdir </> jobFileName jid
268 aa79e62e Iustin Pop
269 aa79e62e Iustin Pop
-- | Map from opcode status to job status.
270 aa79e62e Iustin Pop
opStatusToJob :: OpStatus -> JobStatus
271 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_QUEUED    = JOB_STATUS_QUEUED
272 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_WAITING   = JOB_STATUS_WAITING
273 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_SUCCESS   = JOB_STATUS_SUCCESS
274 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_RUNNING   = JOB_STATUS_RUNNING
275 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_CANCELING = JOB_STATUS_CANCELING
276 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_CANCELED  = JOB_STATUS_CANCELED
277 aa79e62e Iustin Pop
opStatusToJob OP_STATUS_ERROR     = JOB_STATUS_ERROR
278 aa79e62e Iustin Pop
279 aa79e62e Iustin Pop
-- | Computes a queued job's status.
280 aa79e62e Iustin Pop
calcJobStatus :: QueuedJob -> JobStatus
281 aa79e62e Iustin Pop
calcJobStatus QueuedJob { qjOps = ops } =
282 aa79e62e Iustin Pop
  extractOpSt (map qoStatus ops) JOB_STATUS_QUEUED True
283 aa79e62e Iustin Pop
    where
284 aa79e62e Iustin Pop
      terminalStatus OP_STATUS_ERROR     = True
285 aa79e62e Iustin Pop
      terminalStatus OP_STATUS_CANCELING = True
286 aa79e62e Iustin Pop
      terminalStatus OP_STATUS_CANCELED  = True
287 aa79e62e Iustin Pop
      terminalStatus _                   = False
288 aa79e62e Iustin Pop
      softStatus     OP_STATUS_SUCCESS   = True
289 aa79e62e Iustin Pop
      softStatus     OP_STATUS_QUEUED    = True
290 aa79e62e Iustin Pop
      softStatus     _                   = False
291 aa79e62e Iustin Pop
      extractOpSt [] _ True = JOB_STATUS_SUCCESS
292 aa79e62e Iustin Pop
      extractOpSt [] d False = d
293 aa79e62e Iustin Pop
      extractOpSt (x:xs) d old_all
294 aa79e62e Iustin Pop
           | terminalStatus x = opStatusToJob x -- abort recursion
295 aa79e62e Iustin Pop
           | softStatus x     = extractOpSt xs d new_all -- continue unchanged
296 aa79e62e Iustin Pop
           | otherwise        = extractOpSt xs (opStatusToJob x) new_all
297 aa79e62e Iustin Pop
           where new_all = x == OP_STATUS_SUCCESS && old_all
298 aa79e62e Iustin Pop
299 02e40b13 Klaus Aehlig
-- | Determine if a job has started
300 02e40b13 Klaus Aehlig
jobStarted :: QueuedJob -> Bool
301 02e40b13 Klaus Aehlig
jobStarted = (> JOB_STATUS_QUEUED) . calcJobStatus
302 02e40b13 Klaus Aehlig
303 847df9e9 Klaus Aehlig
-- | Determine if a job is finalised.
304 847df9e9 Klaus Aehlig
jobFinalized :: QueuedJob -> Bool
305 847df9e9 Klaus Aehlig
jobFinalized = (> JOB_STATUS_RUNNING) . calcJobStatus
306 847df9e9 Klaus Aehlig
307 370f63be Klaus Aehlig
-- | Determine if a job is finalized and its timestamp is before
308 370f63be Klaus Aehlig
-- a given time.
309 370f63be Klaus Aehlig
jobArchivable :: Timestamp -> QueuedJob -> Bool
310 370f63be Klaus Aehlig
jobArchivable ts = liftA2 (&&) jobFinalized 
311 370f63be Klaus Aehlig
  $ maybe False (< ts)
312 370f63be Klaus Aehlig
    .  liftA2 (<|>) qjEndTimestamp qjStartTimestamp
313 370f63be Klaus Aehlig
314 aa79e62e Iustin Pop
-- | Determine whether an opcode status is finalized.
315 aa79e62e Iustin Pop
opStatusFinalized :: OpStatus -> Bool
316 aa79e62e Iustin Pop
opStatusFinalized = (> OP_STATUS_RUNNING)
317 aa79e62e Iustin Pop
318 aa79e62e Iustin Pop
-- | Compute a job's priority.
319 aa79e62e Iustin Pop
calcJobPriority :: QueuedJob -> Int
320 aa79e62e Iustin Pop
calcJobPriority QueuedJob { qjOps = ops } =
321 aa79e62e Iustin Pop
  helper . map qoPriority $ filter (not . opStatusFinalized . qoStatus) ops
322 aa79e62e Iustin Pop
    where helper [] = C.opPrioDefault
323 aa79e62e Iustin Pop
          helper ps = minimum ps
324 aa79e62e Iustin Pop
325 aa79e62e Iustin Pop
-- | Log but ignore an 'IOError'.
326 aa79e62e Iustin Pop
ignoreIOError :: a -> Bool -> String -> IOError -> IO a
327 aa79e62e Iustin Pop
ignoreIOError a ignore_noent msg e = do
328 aa79e62e Iustin Pop
  unless (isDoesNotExistError e && ignore_noent) .
329 aa79e62e Iustin Pop
    logWarning $ msg ++ ": " ++ show e
330 aa79e62e Iustin Pop
  return a
331 aa79e62e Iustin Pop
332 aa79e62e Iustin Pop
-- | Compute the list of existing archive directories. Note that I/O
333 aa79e62e Iustin Pop
-- exceptions are swallowed and ignored.
334 aa79e62e Iustin Pop
allArchiveDirs :: FilePath -> IO [FilePath]
335 aa79e62e Iustin Pop
allArchiveDirs rootdir = do
336 aa79e62e Iustin Pop
  let adir = rootdir </> jobQueueArchiveSubDir
337 aa79e62e Iustin Pop
  contents <- getDirectoryContents adir `Control.Exception.catch`
338 aa79e62e Iustin Pop
               ignoreIOError [] False
339 aa79e62e Iustin Pop
                 ("Failed to list queue directory " ++ adir)
340 aa79e62e Iustin Pop
  let fpaths = map (adir </>) $ filter (not . ("." `isPrefixOf`)) contents
341 aa79e62e Iustin Pop
  filterM (\path ->
342 aa79e62e Iustin Pop
             liftM isDirectory (getFileStatus (adir </> path))
343 aa79e62e Iustin Pop
               `Control.Exception.catch`
344 aa79e62e Iustin Pop
               ignoreIOError False True
345 aa79e62e Iustin Pop
                 ("Failed to stat archive path " ++ path)) fpaths
346 aa79e62e Iustin Pop
347 aa79e62e Iustin Pop
-- | Build list of directories containing job files. Note: compared to
348 aa79e62e Iustin Pop
-- the Python version, this doesn't ignore a potential lost+found
349 aa79e62e Iustin Pop
-- file.
350 aa79e62e Iustin Pop
determineJobDirectories :: FilePath -> Bool -> IO [FilePath]
351 aa79e62e Iustin Pop
determineJobDirectories rootdir archived = do
352 aa79e62e Iustin Pop
  other <- if archived
353 aa79e62e Iustin Pop
             then allArchiveDirs rootdir
354 aa79e62e Iustin Pop
             else return []
355 aa79e62e Iustin Pop
  return $ rootdir:other
356 aa79e62e Iustin Pop
357 3cecd73c Michele Tartara
-- Function equivalent to the \'sequence\' function, that cannot be used because
358 3cecd73c Michele Tartara
-- of library version conflict on Lucid.
359 3cecd73c Michele Tartara
-- FIXME: delete this and just use \'sequence\' instead when Lucid compatibility
360 3cecd73c Michele Tartara
-- will not be required anymore.
361 3cecd73c Michele Tartara
sequencer :: [Either IOError [JobId]] -> Either IOError [[JobId]]
362 3cecd73c Michele Tartara
sequencer l = fmap reverse $ foldl seqFolder (Right []) l
363 3cecd73c Michele Tartara
364 3cecd73c Michele Tartara
-- | Folding function for joining multiple [JobIds] into one list.
365 3cecd73c Michele Tartara
seqFolder :: Either IOError [[JobId]]
366 3cecd73c Michele Tartara
          -> Either IOError [JobId]
367 3cecd73c Michele Tartara
          -> Either IOError [[JobId]]
368 3cecd73c Michele Tartara
seqFolder (Left e) _ = Left e
369 3cecd73c Michele Tartara
seqFolder (Right _) (Left e) = Left e
370 3cecd73c Michele Tartara
seqFolder (Right l) (Right el) = Right $ el:l
371 3cecd73c Michele Tartara
372 aa79e62e Iustin Pop
-- | Computes the list of all jobs in the given directories.
373 be0cb2d7 Michele Tartara
getJobIDs :: [FilePath] -> IO (Either IOError [JobId])
374 3cecd73c Michele Tartara
getJobIDs paths = liftM (fmap concat . sequencer) (mapM getDirJobIDs paths)
375 aa79e62e Iustin Pop
376 aa79e62e Iustin Pop
-- | Sorts the a list of job IDs.
377 aa79e62e Iustin Pop
sortJobIDs :: [JobId] -> [JobId]
378 aa79e62e Iustin Pop
sortJobIDs = sortBy (comparing fromJobId)
379 aa79e62e Iustin Pop
380 aa79e62e Iustin Pop
-- | Computes the list of jobs in a given directory.
381 be0cb2d7 Michele Tartara
getDirJobIDs :: FilePath -> IO (Either IOError [JobId])
382 aa79e62e Iustin Pop
getDirJobIDs path = do
383 be0cb2d7 Michele Tartara
  either_contents <-
384 be0cb2d7 Michele Tartara
    try (getDirectoryContents path) :: IO (Either IOError [FilePath])
385 be0cb2d7 Michele Tartara
  case either_contents of
386 be0cb2d7 Michele Tartara
    Left e -> do
387 be0cb2d7 Michele Tartara
      logWarning $ "Failed to list job directory " ++ path ++ ": " ++ show e
388 be0cb2d7 Michele Tartara
      return $ Left e
389 be0cb2d7 Michele Tartara
    Right contents -> do
390 be0cb2d7 Michele Tartara
      let jids = foldl (\ids file ->
391 be0cb2d7 Michele Tartara
                         case parseJobFileId file of
392 be0cb2d7 Michele Tartara
                           Nothing -> ids
393 be0cb2d7 Michele Tartara
                           Just new_id -> new_id:ids) [] contents
394 be0cb2d7 Michele Tartara
      return . Right $ reverse jids
395 aa79e62e Iustin Pop
396 aa79e62e Iustin Pop
-- | Reads the job data from disk.
397 aa79e62e Iustin Pop
readJobDataFromDisk :: FilePath -> Bool -> JobId -> IO (Maybe (String, Bool))
398 aa79e62e Iustin Pop
readJobDataFromDisk rootdir archived jid = do
399 aa79e62e Iustin Pop
  let live_path = liveJobFile rootdir jid
400 aa79e62e Iustin Pop
      archived_path = archivedJobFile rootdir jid
401 aa79e62e Iustin Pop
      all_paths = if archived
402 aa79e62e Iustin Pop
                    then [(live_path, False), (archived_path, True)]
403 aa79e62e Iustin Pop
                    else [(live_path, False)]
404 aa79e62e Iustin Pop
  foldM (\state (path, isarchived) ->
405 aa79e62e Iustin Pop
           liftM (\r -> Just (r, isarchived)) (readFile path)
406 aa79e62e Iustin Pop
             `Control.Exception.catch`
407 aa79e62e Iustin Pop
             ignoreIOError state True
408 aa79e62e Iustin Pop
               ("Failed to read job file " ++ path)) Nothing all_paths
409 aa79e62e Iustin Pop
410 aa79e62e Iustin Pop
-- | Failed to load job error.
411 aa79e62e Iustin Pop
noSuchJob :: Result (QueuedJob, Bool)
412 aa79e62e Iustin Pop
noSuchJob = Bad "Can't load job file"
413 aa79e62e Iustin Pop
414 aa79e62e Iustin Pop
-- | Loads a job from disk.
415 aa79e62e Iustin Pop
loadJobFromDisk :: FilePath -> Bool -> JobId -> IO (Result (QueuedJob, Bool))
416 aa79e62e Iustin Pop
loadJobFromDisk rootdir archived jid = do
417 aa79e62e Iustin Pop
  raw <- readJobDataFromDisk rootdir archived jid
418 aa79e62e Iustin Pop
  -- note: we need some stricness below, otherwise the wrapping in a
419 aa79e62e Iustin Pop
  -- Result will create too much lazyness, and not close the file
420 aa79e62e Iustin Pop
  -- descriptors for the individual jobs
421 aa79e62e Iustin Pop
  return $! case raw of
422 aa79e62e Iustin Pop
             Nothing -> noSuchJob
423 aa79e62e Iustin Pop
             Just (str, arch) ->
424 aa79e62e Iustin Pop
               liftM (\qj -> (qj, arch)) .
425 aa79e62e Iustin Pop
               fromJResult "Parsing job file" $ Text.JSON.decode str
426 cef3f99f Klaus Aehlig
427 b498ed42 Klaus Aehlig
-- | Write a job to disk.
428 b498ed42 Klaus Aehlig
writeJobToDisk :: FilePath -> QueuedJob -> IO (Result ())
429 b498ed42 Klaus Aehlig
writeJobToDisk rootdir job = do
430 b498ed42 Klaus Aehlig
  let filename = liveJobFile rootdir . qjId $ job
431 b498ed42 Klaus Aehlig
      content = Text.JSON.encode . Text.JSON.showJSON $ job
432 b498ed42 Klaus Aehlig
  tryAndLogIOError (atomicWriteFile filename content)
433 b498ed42 Klaus Aehlig
                   ("Failed to write " ++ filename) Ok
434 b498ed42 Klaus Aehlig
435 b5a96995 Klaus Aehlig
-- | Replicate a job to all master candidates.
436 b5a96995 Klaus Aehlig
replicateJob :: FilePath -> [Node] -> QueuedJob -> IO [(Node, ERpcError ())]
437 b5a96995 Klaus Aehlig
replicateJob rootdir mastercandidates job = do
438 b5a96995 Klaus Aehlig
  let filename = liveJobFile rootdir . qjId $ job
439 b5a96995 Klaus Aehlig
      content = Text.JSON.encode . Text.JSON.showJSON $ job
440 77676415 Klaus Aehlig
  filename' <- makeVirtualPath filename
441 557f5dad Klaus Aehlig
  callresult <- executeRpcCall mastercandidates
442 77676415 Klaus Aehlig
                  $ RpcCallJobqueueUpdate filename' content
443 557f5dad Klaus Aehlig
  let result = map (second (() <$)) callresult
444 b5a96995 Klaus Aehlig
  logRpcErrors result
445 b5a96995 Klaus Aehlig
  return result
446 b5a96995 Klaus Aehlig
447 9fd653a4 Klaus Aehlig
-- | Replicate many jobs to all master candidates.
448 9fd653a4 Klaus Aehlig
replicateManyJobs :: FilePath -> [Node] -> [QueuedJob] -> IO ()
449 9fd653a4 Klaus Aehlig
replicateManyJobs rootdir mastercandidates =
450 9fd653a4 Klaus Aehlig
  mapM_ (replicateJob rootdir mastercandidates)
451 9fd653a4 Klaus Aehlig
452 cef3f99f Klaus Aehlig
-- | Read the job serial number from disk.
453 cef3f99f Klaus Aehlig
readSerialFromDisk :: IO (Result JobId)
454 cef3f99f Klaus Aehlig
readSerialFromDisk = do
455 cef3f99f Klaus Aehlig
  filename <- jobQueueSerialFile
456 cef3f99f Klaus Aehlig
  tryAndLogIOError (readFile filename) "Failed to read serial file"
457 cef3f99f Klaus Aehlig
                   (makeJobIdS . rStripSpace)
458 ae858516 Klaus Aehlig
459 ae858516 Klaus Aehlig
-- | Allocate new job ids.
460 ae858516 Klaus Aehlig
-- To avoid races while accessing the serial file, the threads synchronize
461 ae858516 Klaus Aehlig
-- over a lock, as usual provided by an MVar.
462 ae858516 Klaus Aehlig
allocateJobIds :: [Node] -> MVar () -> Int -> IO (Result [JobId])
463 ae858516 Klaus Aehlig
allocateJobIds mastercandidates lock n =
464 ae858516 Klaus Aehlig
  if n <= 0
465 ae858516 Klaus Aehlig
    then return . Bad $ "Can only allocate positive number of job ids"
466 ae858516 Klaus Aehlig
    else do
467 ae858516 Klaus Aehlig
      takeMVar lock
468 ae858516 Klaus Aehlig
      rjobid <- readSerialFromDisk
469 ae858516 Klaus Aehlig
      case rjobid of
470 ae858516 Klaus Aehlig
        Bad s -> do
471 ae858516 Klaus Aehlig
          putMVar lock ()
472 ae858516 Klaus Aehlig
          return . Bad $ s
473 ae858516 Klaus Aehlig
        Ok jid -> do
474 ae858516 Klaus Aehlig
          let current = fromJobId jid
475 ae858516 Klaus Aehlig
              serial_content = show (current + n) ++  "\n"
476 ae858516 Klaus Aehlig
          serial <- jobQueueSerialFile
477 ae858516 Klaus Aehlig
          write_result <- try $ atomicWriteFile serial serial_content
478 ae858516 Klaus Aehlig
                          :: IO (Either IOError ())
479 ae858516 Klaus Aehlig
          case write_result of
480 ae858516 Klaus Aehlig
            Left e -> do
481 f7819050 Klaus Aehlig
              putMVar lock ()
482 ae858516 Klaus Aehlig
              let msg = "Failed to write serial file: " ++ show e
483 ae858516 Klaus Aehlig
              logError msg
484 ae858516 Klaus Aehlig
              return . Bad $ msg 
485 ae858516 Klaus Aehlig
            Right () -> do
486 77676415 Klaus Aehlig
              serial' <- makeVirtualPath serial
487 ae858516 Klaus Aehlig
              _ <- executeRpcCall mastercandidates
488 77676415 Klaus Aehlig
                     $ RpcCallJobqueueUpdate serial' serial_content
489 f7819050 Klaus Aehlig
              putMVar lock ()
490 ae858516 Klaus Aehlig
              return $ mapM makeJobId [(current+1)..(current+n)]
491 ae858516 Klaus Aehlig
492 ae858516 Klaus Aehlig
-- | Allocate one new job id.
493 ae858516 Klaus Aehlig
allocateJobId :: [Node] -> MVar () -> IO (Result JobId)
494 ae858516 Klaus Aehlig
allocateJobId mastercandidates lock = do
495 ae858516 Klaus Aehlig
  jids <- allocateJobIds mastercandidates lock 1
496 ae858516 Klaus Aehlig
  return (jids >>= monadicThe "Failed to allocate precisely one Job ID")
497 1b94c0db Klaus Aehlig
498 1b94c0db Klaus Aehlig
-- | Decide if job queue is open
499 1b94c0db Klaus Aehlig
isQueueOpen :: IO Bool
500 1b94c0db Klaus Aehlig
isQueueOpen = liftM not (jobQueueDrainFile >>= doesFileExist)
501 493d6920 Klaus Aehlig
502 ac0c5c6d Klaus Aehlig
-- | Start enqueued jobs, currently by handing them over to masterd.
503 ac0c5c6d Klaus Aehlig
startJobs :: [QueuedJob] -> IO ()
504 ac0c5c6d Klaus Aehlig
startJobs jobs = do
505 493d6920 Klaus Aehlig
  socketpath <- defaultMasterSocket
506 d605e261 Petr Pudlak
  client <- getLuxiClient socketpath
507 493d6920 Klaus Aehlig
  pickupResults <- mapM (flip callMethod client . PickupJob . qjId) jobs
508 493d6920 Klaus Aehlig
  let failures = map show $ justBad pickupResults
509 493d6920 Klaus Aehlig
  unless (null failures)
510 493d6920 Klaus Aehlig
   . logWarning . (++) "Failed to notify masterd: " . commaJoin $ failures
511 47c3c7b1 Klaus Aehlig
512 47c3c7b1 Klaus Aehlig
-- | Try to cancel a job that has already been handed over to execution,
513 47c3c7b1 Klaus Aehlig
-- currently by asking masterd to cancel it.
514 47c3c7b1 Klaus Aehlig
cancelJob :: JobId -> IO (ErrorResult JSValue)
515 47c3c7b1 Klaus Aehlig
cancelJob jid = do
516 47c3c7b1 Klaus Aehlig
  socketpath <- defaultMasterSocket
517 47c3c7b1 Klaus Aehlig
  client <- getLuxiClient socketpath
518 47c3c7b1 Klaus Aehlig
  callMethod (CancelJob jid) client
519 c867cfe1 Klaus Aehlig
520 f23daea8 Klaus Aehlig
-- | Permissions for the archive directories.
521 f23daea8 Klaus Aehlig
queueDirPermissions :: FilePermissions
522 f23daea8 Klaus Aehlig
queueDirPermissions = FilePermissions { fpOwner = Just C.masterdUser
523 f23daea8 Klaus Aehlig
                                      , fpGroup = Just C.daemonsGroup
524 f23daea8 Klaus Aehlig
                                      , fpPermissions = 0o0750
525 f23daea8 Klaus Aehlig
                                      }
526 f23daea8 Klaus Aehlig
527 c867cfe1 Klaus Aehlig
-- | Try, at most until the given endtime, to archive some of the given
528 c867cfe1 Klaus Aehlig
-- jobs, if they are older than the specified cut-off time; also replicate
529 c867cfe1 Klaus Aehlig
-- archival of the additional jobs. Return the pair of the number of jobs
530 c867cfe1 Klaus Aehlig
-- archived, and the number of jobs remaining int he queue, asuming the
531 c867cfe1 Klaus Aehlig
-- given numbers about the not considered jobs.
532 c867cfe1 Klaus Aehlig
archiveSomeJobsUntil :: ([JobId] -> IO ()) -- ^ replication function
533 c867cfe1 Klaus Aehlig
                        -> FilePath -- ^ queue root directory
534 c867cfe1 Klaus Aehlig
                        -> ClockTime -- ^ Endtime
535 c867cfe1 Klaus Aehlig
                        -> Timestamp -- ^ cut-off time for archiving jobs
536 c867cfe1 Klaus Aehlig
                        -> Int -- ^ number of jobs alread archived
537 c867cfe1 Klaus Aehlig
                        -> [JobId] -- ^ Additional jobs to replicate
538 c867cfe1 Klaus Aehlig
                        -> [JobId] -- ^ List of job-ids still to consider
539 c867cfe1 Klaus Aehlig
                        -> IO (Int, Int)
540 c867cfe1 Klaus Aehlig
archiveSomeJobsUntil replicateFn _ _ _ arch torepl [] = do
541 c867cfe1 Klaus Aehlig
  unless (null torepl) . (>> return ())
542 c867cfe1 Klaus Aehlig
   . forkIO $ replicateFn torepl
543 c867cfe1 Klaus Aehlig
  return (arch, 0)
544 c867cfe1 Klaus Aehlig
545 c867cfe1 Klaus Aehlig
archiveSomeJobsUntil replicateFn qDir endt cutt arch torepl (jid:jids) = do
546 c867cfe1 Klaus Aehlig
  let archiveMore = archiveSomeJobsUntil replicateFn qDir endt cutt
547 c867cfe1 Klaus Aehlig
      continue = archiveMore arch torepl jids
548 c867cfe1 Klaus Aehlig
      jidname = show $ fromJobId jid
549 c867cfe1 Klaus Aehlig
  time <- getClockTime
550 c867cfe1 Klaus Aehlig
  if time >= endt
551 c867cfe1 Klaus Aehlig
    then do
552 c867cfe1 Klaus Aehlig
      _ <- forkIO $ replicateFn torepl
553 c867cfe1 Klaus Aehlig
      return (arch, length (jid:jids))
554 c867cfe1 Klaus Aehlig
    else do
555 c867cfe1 Klaus Aehlig
      logDebug $ "Inspecting job " ++ jidname ++ " for archival"
556 c867cfe1 Klaus Aehlig
      loadResult <- loadJobFromDisk qDir False jid
557 c867cfe1 Klaus Aehlig
      case loadResult of
558 c867cfe1 Klaus Aehlig
        Bad _ -> continue
559 c867cfe1 Klaus Aehlig
        Ok (job, _) -> 
560 c867cfe1 Klaus Aehlig
          if jobArchivable cutt job
561 c867cfe1 Klaus Aehlig
            then do
562 c867cfe1 Klaus Aehlig
              let live = liveJobFile qDir jid
563 c867cfe1 Klaus Aehlig
                  archive = archivedJobFile qDir jid
564 0c09ecc2 Klaus Aehlig
              renameResult <- safeRenameFile queueDirPermissions
565 0c09ecc2 Klaus Aehlig
                                live archive
566 c867cfe1 Klaus Aehlig
              case renameResult of                   
567 c867cfe1 Klaus Aehlig
                Bad s -> do
568 c867cfe1 Klaus Aehlig
                  logWarning $ "Renaming " ++ live ++ " to " ++ archive
569 c867cfe1 Klaus Aehlig
                                 ++ " failed unexpectedly: " ++ s
570 c867cfe1 Klaus Aehlig
                  continue
571 c867cfe1 Klaus Aehlig
                Ok () -> do
572 c867cfe1 Klaus Aehlig
                  let torepl' = jid:torepl
573 c867cfe1 Klaus Aehlig
                  if length torepl' >= 10
574 c867cfe1 Klaus Aehlig
                    then do
575 c867cfe1 Klaus Aehlig
                      _ <- forkIO $ replicateFn torepl'
576 c867cfe1 Klaus Aehlig
                      archiveMore (arch + 1) [] jids
577 c867cfe1 Klaus Aehlig
                    else archiveMore (arch + 1) torepl' jids
578 c867cfe1 Klaus Aehlig
            else continue
579 c867cfe1 Klaus Aehlig
                   
580 c867cfe1 Klaus Aehlig
-- | Archive jobs older than the given time, but do not exceed the timeout for
581 c867cfe1 Klaus Aehlig
-- carrying out this task.
582 c867cfe1 Klaus Aehlig
archiveJobs :: ConfigData -- ^ cluster configuration
583 c867cfe1 Klaus Aehlig
               -> Int  -- ^ time the job has to be in the past in order
584 c867cfe1 Klaus Aehlig
                       -- to be archived
585 c867cfe1 Klaus Aehlig
               -> Int -- ^ timeout
586 c867cfe1 Klaus Aehlig
               -> [JobId] -- ^ jobs to consider
587 c867cfe1 Klaus Aehlig
               -> IO (Int, Int)
588 c867cfe1 Klaus Aehlig
archiveJobs cfg age timeout jids = do
589 c867cfe1 Klaus Aehlig
  now <- getClockTime
590 c867cfe1 Klaus Aehlig
  qDir <- queueDir
591 c867cfe1 Klaus Aehlig
  let endtime = addToClockTime (noTimeDiff { tdSec = timeout }) now
592 c867cfe1 Klaus Aehlig
      cuttime = if age < 0 then noTimestamp
593 c867cfe1 Klaus Aehlig
                           else advanceTimestamp (- age) (fromClockTime now)
594 c867cfe1 Klaus Aehlig
      mcs = Config.getMasterCandidates cfg
595 c867cfe1 Klaus Aehlig
      replicateFn jobs = do
596 c867cfe1 Klaus Aehlig
        let olds = map (liveJobFile qDir) jobs
597 c867cfe1 Klaus Aehlig
            news = map (archivedJobFile qDir) jobs
598 c867cfe1 Klaus Aehlig
        _ <- executeRpcCall mcs . RpcCallJobqueueRename $ zip olds news
599 c867cfe1 Klaus Aehlig
        return ()
600 c867cfe1 Klaus Aehlig
  archiveSomeJobsUntil replicateFn qDir endtime cuttime 0 [] jids