minici-0.1.10: src/Job.hs
module Job (
Job, DeclaredJob, Job'(..),
JobSet, DeclaredJobSet, JobSet'(..), jobsetJobs,
JobOutput(..),
JobName(..), stringJobName, textJobName,
ArtifactName(..),
JobStatus(..), AnnotatedStatus,
jobStatusFinished, jobStatusFailed,
JobManager(..), newJobManager, cancelAllJobs,
Task(..), TaskId, cancelTask,
runJobs, waitForRemainingTasks,
prepareJob,
getArtifactWorkPath,
copyArtifact,
jobStorageSubdir,
copyRecursive,
copyRecursiveForce,
currentCommitExpr,
branchExpr,
) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.Catch
import Control.Monad.Except
import Control.Monad.IO.Class
import Control.Monad.Reader
import Data.Bifunctor
import Data.List
import Data.Map (Map)
import Data.Map qualified as M
import Data.Maybe
import Data.Set (Set)
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.IO qualified as T
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import System.FilePath.Glob
import System.IO
import System.IO.Error
import System.IO.Temp
import System.Posix.Signals
import System.Process
import Destination
import Expr
import Job.Types
import Output
import Repo
data JobOutput = JobOutput
{ outArtifacts :: [ArtifactOutput]
}
deriving (Eq)
data ArtifactOutput = ArtifactOutput
{ aoutName :: ArtifactName
, aoutWorkPath :: FilePath
, aoutStorePath :: FilePath
}
deriving (Eq)
data JobStatus a
= JobQueued
| JobDuplicate JobId (JobStatus a)
| JobPreviousStatus (JobStatus a)
| JobWaiting [JobName]
| JobRunning
| JobSkipped
| JobError Text
| JobFailed
| JobCancelled
| JobDone a
deriving (Eq)
jobStatusFinished :: JobStatus a -> Bool
jobStatusFinished = \case
JobQueued {} -> False
JobDuplicate _ s -> jobStatusFinished s
JobPreviousStatus s -> jobStatusFinished s
JobWaiting {} -> False
JobRunning {} -> False
_ -> True
jobStatusFailed :: JobStatus a -> Bool
jobStatusFailed = \case
JobDuplicate _ s -> jobStatusFailed s
JobPreviousStatus s -> jobStatusFailed s
JobError {} -> True
JobFailed {} -> True
_ -> False
jobStatusCancelled :: JobStatus a -> Bool
jobStatusCancelled = \case
JobCancelled {} -> True
JobDuplicate _ s -> jobStatusCancelled s
_ -> False
jobResult :: JobStatus a -> Maybe a
jobResult = \case
JobDone x -> Just x
JobDuplicate _ s -> jobResult s
JobPreviousStatus s -> jobResult s
_ -> Nothing
textJobStatus :: JobStatus a -> Text
textJobStatus = \case
JobQueued -> "queued"
JobDuplicate {} -> "duplicate"
JobPreviousStatus s -> textJobStatus s
JobWaiting _ -> "waiting"
JobRunning -> "running"
JobSkipped -> "skipped"
JobError _ -> "error"
JobFailed -> "failed"
JobCancelled -> "cancelled"
JobDone _ -> "done"
readJobStatus :: (MonadIO m) => Text -> m a -> m (Maybe (JobStatus a))
readJobStatus text readResult = case T.lines text of
"queued" : _ -> return (Just JobQueued)
"running" : _ -> return (Just JobRunning)
"skipped" : _ -> return (Just JobSkipped)
"error" : note : _ -> return (Just $ JobError note)
"failed" : _ -> return (Just JobFailed)
"cancelled" : _ -> return (Just JobCancelled)
"done" : _ -> Just . JobDone <$> readResult
_ -> return Nothing
textJobStatusDetails :: JobStatus a -> Text
textJobStatusDetails = \case
JobError err -> err <> "\n"
JobPreviousStatus s -> textJobStatusDetails s
_ -> ""
printStatusError :: MonadIO m => Output -> JobStatus a -> m [ OutputFootnote ]
printStatusError tout = \case
JobError note -> (: []) <$> liftIO (outputFootnote tout note)
_ -> return []
data JobManager = JobManager
{ jmMaxRunningTasks :: Int
, jmDataDir :: FilePath
, jmJobs :: TVar (Map JobId (TVar ManagedJobStatus))
, jmNextTaskId :: TVar TaskId
, jmReadyTasks :: TVar (Set TaskId)
, jmRunningTasks :: TVar (Map TaskId ThreadId)
, jmCancelled :: TVar Bool
, jmOpenStatusUpdates :: TVar Int
}
type AnnotatedStatus = ( JobStatus JobOutput, [ OutputFootnote ] )
data ManagedJobStatus = ManagedJobStatus
{ mjsStatus :: JobStatus JobOutput
, mjsNotes :: [ OutputFootnote ]
, mjsTaskCount :: Int
, mjsThread :: Maybe ThreadId
, mjsSuperseded :: Bool
}
mjsAnnotatedStatus :: ManagedJobStatus -> AnnotatedStatus
mjsAnnotatedStatus ManagedJobStatus {..} = ( mjsStatus, mjsNotes )
data Task = Task
{ taskId :: TaskId
, taskJob :: Job
, taskManagedJob :: TVar ManagedJobStatus
, taskStatus :: STM AnnotatedStatus
}
newtype TaskId = TaskId Int
deriving (Eq, Ord)
data JobCancelledException = JobCancelledException
deriving (Show)
instance Exception JobCancelledException
newtype JobRun a = JobRun (ReaderT (Maybe Handle) (ExceptT (JobStatus JobOutput) IO) a)
deriving
( Functor, Applicative, Monad
, MonadReader (Maybe Handle)
, MonadError (JobStatus JobOutput)
, MonadThrow, MonadCatch, MonadMask
, MonadIO
)
instance MonadFail JobRun where
fail err = do
ask >>= \case
Just logs -> do
liftIO $ hPutStrLn logs err
throwError JobFailed
Nothing -> do
throwError $ JobError $ T.pack err
fromJobRun :: JobRun a -> IO (Either (JobStatus JobOutput) a)
fromJobRun (JobRun act) = runExceptT $ flip runReaderT Nothing $ act
newJobManager :: FilePath -> Int -> IO JobManager
newJobManager jmDataDir jmMaxRunningTasks = do
jmJobs <- newTVarIO M.empty
jmNextTaskId <- newTVarIO (TaskId 0)
jmReadyTasks <- newTVarIO S.empty
jmRunningTasks <- newTVarIO M.empty
jmCancelled <- newTVarIO False
jmOpenStatusUpdates <- newTVarIO 0
return JobManager {..}
cancelAllJobs :: JobManager -> IO ()
cancelAllJobs JobManager {..} = do
threads <- atomically $ do
writeTVar jmCancelled True
M.elems <$> readTVar jmRunningTasks
mapM_ (`throwTo` JobCancelledException) threads
cancelTask :: Task -> IO ()
cancelTask Task {..} = do
mbThread <- atomically $ do
mjs <- readTVar taskManagedJob
let count = mjsTaskCount mjs - 1
writeTVar taskManagedJob mjs { mjsTaskCount = count }
if count <= 0
then return $ mjsThread mjs
else return Nothing
case mbThread of
Just thread -> throwTo thread JobCancelledException
Nothing -> return ()
reserveTaskId :: JobManager -> STM TaskId
reserveTaskId JobManager {..} = do
tid@(TaskId n) <- readTVar jmNextTaskId
writeTVar jmNextTaskId (TaskId (n + 1))
return tid
runManagedJob :: (MonadIO m, MonadMask m) => JobManager -> TaskId -> m a -> m a -> m a
runManagedJob JobManager {..} tid cancel job = bracket acquire release $ \case
True -> cancel
False -> job
where
acquire = (`onException` release False) $ liftIO $ do
atomically $ do
writeTVar jmReadyTasks . S.insert tid =<< readTVar jmReadyTasks
threadId <- myThreadId
atomically $ do
readTVar jmCancelled >>= \case
True -> return True
False -> readTVar jmRunningTasks >>= \case
running | M.size running < jmMaxRunningTasks -> do
(S.minView <$> readTVar jmReadyTasks) >>= \case
Just ( tid', ready ) | tid' == tid -> do
writeTVar jmReadyTasks ready
writeTVar jmRunningTasks $ M.insert tid threadId running
return False
_ -> retry
_ -> retry
release False = liftIO $ atomically $ do
writeTVar jmReadyTasks . S.delete tid =<< readTVar jmReadyTasks
writeTVar jmRunningTasks . M.delete tid =<< readTVar jmRunningTasks
release True = return ()
data PreviousManagedStatus
= NewJob
| DuplicateJob
| RestartedJob
runJobs :: JobManager -> Output -> [ Job ]
-> (JobId -> JobStatus JobOutput -> Bool) -- ^ Rerun condition
-> IO [ Task ]
runJobs mngr@JobManager {..} tout jobs rerun = do
results <- atomically $ do
forM jobs $ \job -> do
tid <- reserveTaskId mngr
managed <- readTVar jmJobs
( job, tid, ) <$> case M.lookup (jobId job) managed of
Just origVar -> do
readTVar origVar >>= \mjs -> if
| mjsStatus mjs == JobCancelled || (mjsTaskCount mjs <= 0 && not (jobStatusFinished (mjsStatus mjs)))
-> do
-- Restart previously cancelled job
statusVar <- newTVar ManagedJobStatus
{ mjsStatus = JobQueued
, mjsNotes = mjsNotes mjs
, mjsTaskCount = 1
, mjsThread = Nothing
, mjsSuperseded = False
}
writeTVar origVar mjs { mjsSuperseded = True }
writeTVar jmJobs $ M.insert (jobId job) statusVar managed
return ( RestartedJob, statusVar )
| otherwise -> do
writeTVar origVar mjs { mjsTaskCount = mjsTaskCount mjs + 1 }
return ( DuplicateJob, origVar )
Nothing -> do
statusVar <- newTVar ManagedJobStatus
{ mjsStatus = JobQueued
, mjsNotes = []
, mjsTaskCount = 1
, mjsThread = Nothing
, mjsSuperseded = False
}
writeTVar jmJobs $ M.insert (jobId job) statusVar managed
return ( NewJob, statusVar )
forM results $ \( taskJob, taskId, ( pms, taskManagedJob ) ) -> do
case pms of
DuplicateJob -> do
let taskStatus = fmap (first (JobDuplicate (jobId taskJob))) $ mjsAnnotatedStatus <$> readTVar taskManagedJob
outputEvent tout $ JobIsDuplicate (jobId taskJob)
return Task {..}
_ -> do
let taskStatus = mjsAnnotatedStatus <$> readTVar taskManagedJob
let handler e = do
( status, notes ) <- if
| Just JobCancelledException <- fromException e -> do
return ( JobCancelled, [] )
| otherwise -> do
let err = T.pack $ displayException e
( JobError err, ) . (: []) <$> outputFootnote tout err
join $ atomically $ do
mjs <- readTVar taskManagedJob
if jobStatusFinished (mjsStatus mjs)
then return $ return ()
else do
writeTVar taskManagedJob mjs { mjsStatus = status, mjsNotes = notes }
return $ do
uninterruptibleMask_ $ do
outputJobFinishedEvent tout taskJob status
handlerInstalled <- newEmptyMVar
void $ forkIO $ do
handle handler $ do
putMVar handlerInstalled ()
mtid <- myThreadId
res <- fromJobRun $ do
join $ liftIO $ atomically $ do
mjs <- readTVar taskManagedJob
if mjsTaskCount mjs <= 0
then return $ throwError JobCancelled
else do
writeTVar taskManagedJob mjs { mjsThread = Just mtid }
return $ return ()
let jdir = jmDataDir </> jobStorageSubdir (jobId taskJob)
pstatus <- case pms of
NewJob -> readStatusFile taskJob jdir
RestartedJob -> return (Just JobCancelled)
case pstatus of
Just status | status /= JobCancelled && not (rerun (jobId taskJob) status) -> do
let status' = JobPreviousStatus status
notes <- printStatusError tout status
liftIO $ atomically $ do
mjs <- readTVar taskManagedJob
writeTVar taskManagedJob mjs { mjsStatus = status', mjsNotes = notes }
return status'
mbStatus -> do
when (isJust mbStatus) $ do
liftIO $ removePathForcibly jdir
liftIO $ outputEvent tout $ JobEnqueued (jobId taskJob)
let extractResult ( tjob, tid, estatus ) = ( tjob, tid, fmap mjsAnnotatedStatus $ readTVar $ snd estatus )
let results' = map extractResult results
uses <- waitForUsedArtifacts taskJob results' taskManagedJob
runManagedJob mngr taskId (return JobCancelled) $ do
liftIO $ atomically $ do
mjs <- readTVar taskManagedJob
writeTVar taskManagedJob $ mjs { mjsStatus = JobRunning, mjsNotes = [] }
liftIO $ outputEvent tout $ JobStarted (jobId taskJob)
prepareJob jmDataDir taskJob $ \checkoutPath -> do
updateStatusFile mngr jdir $ readTVar taskManagedJob
JobDone <$> runJob taskJob uses checkoutPath jdir
let finalStatus = either id id res
mask_ $ do
rnotes <- either (printStatusError tout) (const $ return []) res
atomically $ do
mjs <- readTVar taskManagedJob
writeTVar taskManagedJob mjs
{ mjsStatus = finalStatus, mjsNotes = mjsNotes mjs ++ rnotes }
uninterruptibleMask_ $ do
outputJobFinishedEvent tout taskJob finalStatus
takeMVar handlerInstalled
return Task {..}
waitForRemainingTasks :: JobManager -> IO ()
waitForRemainingTasks JobManager {..} = do
atomically $ do
remainingStatusUpdates <- readTVar jmOpenStatusUpdates
when (remainingStatusUpdates > 0) retry
waitForUsedArtifacts
:: (MonadIO m, MonadError (JobStatus JobOutput) m)
=> Job
-> [ ( Job, TaskId, STM AnnotatedStatus ) ]
-> TVar ManagedJobStatus
-> m [ ( ArtifactSpec Evaluated, ArtifactOutput ) ]
waitForUsedArtifacts job results outVar = do
( origStatus, origNotes ) <- liftIO $ atomically $ mjsAnnotatedStatus <$> readTVar outVar
let ( selfSpecs, artSpecs ) = partition ((jobId job ==) . fst) $ jobRequiredArtifacts job
forM_ selfSpecs $ \( _, artName@(ArtifactName tname) ) -> do
when (not (artName `elem` map fst (jobArtifacts job))) $ do
throwError $ JobError $ "Artifact ‘" <> tname <> "’ not produced by the job"
ujobs <- forM artSpecs $ \( ujobId, uartName ) -> do
case find (\( j, _, _ ) -> jobId j == ujobId) results of
Just ( _, _, var ) -> return ( var, ( ujobId, uartName ))
Nothing -> throwError $ JobError $ "Job ‘" <> textJobId ujobId <> "’ not found"
let loop prev = do
ustatuses <- atomically $ do
ustatuses <- forM ujobs $ \( uoutVar, uartSpec ) -> do
(, uartSpec) <$> uoutVar
when (Just (map fst ustatuses) == prev) retry
let remains = map (fromMaybe (JobName "?") . lastJobNameId . fst . snd) $
filter (not . jobStatusFinished . fst . fst) ustatuses
mjs <- readTVar outVar
writeTVar outVar $ if null remains
then mjs { mjsStatus = origStatus, mjsNotes = origNotes }
else mjs { mjsStatus = JobWaiting remains, mjsNotes = [] }
return ustatuses
if all (jobStatusFinished . fst . fst) ustatuses
then return ustatuses
else loop $ Just $ map fst ustatuses
ustatuses <- liftIO $ loop Nothing
forM ustatuses $ \( ( ustatus, _ ), spec@( tjobId, uartName@(ArtifactName tartName)) ) -> if
| Just out <- jobResult ustatus
-> do
case find ((==uartName) . aoutName) $ outArtifacts out of
Just art -> return ( spec, art )
Nothing -> throwError $ JobError $ "Artifact ‘" <> textJobId tjobId <> "." <> tartName <> "’ not found"
| jobStatusCancelled ustatus
-> throwError JobCancelled
| otherwise
-> throwError JobSkipped
outputJobFinishedEvent :: Output -> Job -> JobStatus a -> IO ()
outputJobFinishedEvent tout job = \case
JobPreviousStatus s -> outputEvent tout $ JobPreviouslyFinished (jobId job) (textJobStatus s)
JobSkipped -> outputEvent tout $ JobWasSkipped (jobId job)
s -> outputEvent tout $ JobFinished (jobId job) (textJobStatus s)
readStatusFile :: (MonadIO m, MonadCatch m) => Job -> FilePath -> m (Maybe (JobStatus JobOutput))
readStatusFile job jdir = do
handleIOError (\_ -> return Nothing) $ do
text <- liftIO $ T.readFile (jdir </> "status")
readJobStatus text $ do
artifacts <- forM (jobArtifacts job) $ \( aoutName@(ArtifactName tname), _ ) -> do
let adir = jdir </> "artifacts" </> T.unpack tname
aoutStorePath = adir </> "data"
aoutWorkPath <- fmap T.unpack $ liftIO $ T.readFile (adir </> "path")
return ArtifactOutput {..}
return JobOutput
{ outArtifacts = artifacts
}
updateStatusFile :: MonadIO m => JobManager -> FilePath -> STM ManagedJobStatus -> m ()
updateStatusFile JobManager {..} jdir getStatus = liftIO $ do
atomically $ writeTVar jmOpenStatusUpdates . (+ 1) =<< readTVar jmOpenStatusUpdates
void $ forkIO $ loop Nothing
where
loop prev = do
ManagedJobStatus {..} <- atomically $ do
mjs@ManagedJobStatus {..} <- getStatus
when (Just mjsStatus == prev && not mjsSuperseded) retry
return mjs
when (not mjsSuperseded) $ do
T.writeFile (jdir </> "status") $ textJobStatus mjsStatus <> "\n" <> textJobStatusDetails mjsStatus
if not (jobStatusFinished mjsStatus) && not mjsSuperseded
then loop $ Just mjsStatus
else atomically $ writeTVar jmOpenStatusUpdates . (subtract 1) =<< readTVar jmOpenStatusUpdates
jobStorageSubdir :: JobId -> FilePath
jobStorageSubdir (JobId jidParts) = "jobs" </> joinPath (map (T.unpack . textJobIdPart) (jidParts))
prepareJob :: (MonadIO m, MonadMask m, MonadFail m) => FilePath -> Job -> (FilePath -> m a) -> m a
prepareJob dir job inner = do
withSystemTempDirectory "minici" $ \checkoutPath -> do
forM_ (jobCheckout job) $ \(JobCheckout tree mbsub dest) -> do
subtree <- maybe return (getSubtree Nothing . makeRelative (treeSubdir tree)) mbsub $ tree
checkoutAt subtree $ checkoutPath </> fromMaybe "" dest
liftIO $ forM_ (jobUses job) $ \( jid, aname ) -> do
either (throwError . userError . T.unpack) pure <=< runExceptT $ do
wpath <- getArtifactWorkPath dir jid aname
let target = checkoutPath </> wpath
liftIO $ createDirectoryIfMissing True $ takeDirectory target
copyArtifact dir jid aname target
let jdir = dir </> jobStorageSubdir (jobId job)
liftIO $ createDirectoryIfMissing True jdir
inner checkoutPath
getArtifactStoredPath :: (MonadIO m, MonadError Text m) => FilePath -> JobId -> ArtifactName -> m FilePath
getArtifactStoredPath storageDir jid@(JobId ids) (ArtifactName aname) = do
let jdir = joinPath $ (storageDir :) $ ("jobs" :) $ map (T.unpack . textJobIdPart) ids
adir = jdir </> "artifacts" </> T.unpack aname
liftIO (doesDirectoryExist jdir) >>= \case
True -> return ()
False -> throwError $ "job ‘" <> textJobId jid <> "’ not yet executed"
liftIO (doesDirectoryExist adir) >>= \case
True -> return ()
False -> throwError $ "artifact ‘" <> aname <> "’ of job ‘" <> textJobId jid <> "’ not found"
return adir
getArtifactWorkPath :: (MonadIO m, MonadError Text m) => FilePath -> JobId -> ArtifactName -> m FilePath
getArtifactWorkPath storageDir jid aname = do
adir <- getArtifactStoredPath storageDir jid aname
liftIO $ readFile (adir </> "path")
copyArtifact :: (MonadIO m, MonadError Text m) => FilePath -> JobId -> ArtifactName -> FilePath -> m ()
copyArtifact storageDir jid aname tpath = do
adir <- getArtifactStoredPath storageDir jid aname
liftIO $ copyRecursive (adir </> "data") tpath
runJob :: Job -> [ ( ArtifactSpec Evaluated, ArtifactOutput) ] -> FilePath -> FilePath -> JobRun JobOutput
runJob job uses checkoutPath jdir = do
bracket (liftIO $ openFile (jdir </> "log") WriteMode) (liftIO . hClose) $ \logs -> local (const $ Just logs) $ do
forM_ (fromMaybe [] $ jobRecipe job) $ \ep -> do
( p, input ) <- case ep of
Left p -> return ( p, "" )
Right script -> do
sh <- fromMaybe "/bin/sh" <$> liftIO (lookupEnv "SHELL")
return ( proc sh [], script )
( Just hin, _, _, hp ) <- liftIO $ createProcess_ "" p
{ cwd = Just checkoutPath
, std_in = CreatePipe
, std_out = UseHandle logs
, std_err = UseHandle logs
, create_group = True
}
Just pid <- liftIO $ getPid hp
liftIO $ void $ forkIO $ do
T.hPutStr hin input
hClose hin
let killCreatedProcessGroup = do
handleJust (\case e | isDoesNotExistError e -> Just (); _ -> Nothing) return $ do
signalProcessGroup sigKILL pid
waitForProcess hp
liftIO (waitForProcess hp `finally` killCreatedProcessGroup) >>= \case
ExitSuccess -> return ()
ExitFailure _ -> throwError JobFailed
artifacts <- forM (jobArtifacts job) $ \( name@(ArtifactName tname), pathPattern ) -> do
let adir = jdir </> "artifacts" </> T.unpack tname
path <- liftIO (globDir1 pathPattern checkoutPath) >>= \case
[ path ] -> return path
found -> fail $
(if null found then "no file" else "multiple files") <> " found matching pattern ‘" <>
decompile pathPattern <> "’ for artifact ‘" <> T.unpack tname <> "’"
let target = adir </> "data"
workPath = makeRelative checkoutPath path
liftIO $ do
createDirectoryIfMissing True $ takeDirectory target
copyRecursiveForce path target
T.writeFile (adir </> "path") $ T.pack workPath
return $ ArtifactOutput
{ aoutName = name
, aoutWorkPath = workPath
, aoutStorePath = target
}
forM_ (jobPush job) $ \JobPush {..} -> do
pushToBranch jpushDestination jpushSource
forM_ (jobPublish job) $ \pub -> do
Just aout <- return $ lookup (jpArtifact pub) $ map (\aout -> ( ( jobId job, aoutName aout ), aout )) artifacts ++ uses
let ppath = case jpPath pub of
Just path
| hasTrailingPathSeparator path -> path </> takeFileName (aoutWorkPath aout)
| otherwise -> path
Nothing -> aoutWorkPath aout
copyToDestination (aoutStorePath aout) (jpDestination pub) ppath
return JobOutput
{ outArtifacts = artifacts
}
currentCommitExpr :: RepoName -> Expr JobSetContext Commit
currentCommitExpr rname =
addDependency [ RepoDependency rname RepoDepCommit ] $
(pure getCommit) <*> (lookup (Just rname) . jscRepoRefs <$> GetContext)
where
getCommit = \case
Nothing -> error $ "currentCommitExpr: repo ‘" <> showRepoName rname <> "’ not found"
Just (RepoRefTree _) -> error $ "currentCommitExpr: expected commit in ‘" <> showRepoName rname <> "’, but got a tree"
Just (RepoRefCommit commit) -> commit
Just (RepoRefTag commit _) -> commit
branchExpr :: RepoName -> Text -> Expr JobSetContext Branch
branchExpr rname bname = pure ((\repo -> Branch repo bname) . fromJust) <*> (lookup (Just rname) . jscRepos <$> GetContext)