git-annex/Assistant/Threads/Committer.hs

265 lines
8.5 KiB
Haskell
Raw Normal View History

2012-06-19 06:40:21 +00:00
{- git-annex assistant commit thread
2012-06-13 16:36:33 +00:00
-
- Copyright 2012 Joey Hess <joey@kitenet.net>
2012-06-23 05:20:40 +00:00
-
- Licensed under the GNU GPL version 3 or higher.
2012-06-13 16:36:33 +00:00
-}
{-# LANGUAGE CPP, BangPatterns #-}
2012-06-25 20:10:10 +00:00
module Assistant.Threads.Committer where
2012-06-13 16:36:33 +00:00
import Assistant.Common
2012-06-19 06:40:21 +00:00
import Assistant.Changes
2012-10-29 23:30:23 +00:00
import Assistant.Types.Changes
2012-06-22 17:39:44 +00:00
import Assistant.Commits
import Assistant.Alert
2012-10-30 18:34:48 +00:00
import Assistant.DaemonStatus
2012-06-25 20:10:10 +00:00
import Assistant.Threads.Watcher
import Assistant.TransferQueue
import Logs.Transfer
2012-06-13 16:36:33 +00:00
import qualified Annex.Queue
import qualified Git.Command
2012-06-19 06:40:21 +00:00
import qualified Git.HashObject
import qualified Git.LsFiles
import qualified Git.Version
2012-06-19 06:40:21 +00:00
import Git.Types
import qualified Command.Add
import Utility.ThreadScheduler
import qualified Utility.Lsof as Lsof
2012-06-19 06:40:21 +00:00
import qualified Utility.DirWatcher as DirWatcher
import Types.KeySource
import Config
import Annex.Exception
2012-06-13 16:36:33 +00:00
import Data.Time.Clock
import Data.Tuple.Utils
import qualified Data.Set as S
import Data.Either
2012-06-13 16:36:33 +00:00
{- This thread makes git commits at appropriate times. -}
2012-10-29 15:40:22 +00:00
commitThread :: NamedThread
commitThread = NamedThread "Committer" $ do
delayadd <- liftAnnex $
maybe delayaddDefault (Just . Seconds) . readish
<$> getConfig (annexConfig "delayadd") ""
2012-10-29 15:40:22 +00:00
runEvery (Seconds 1) <~> do
-- We already waited one second as a simple rate limiter.
-- Next, wait until at least one change is available for
-- processing.
2012-10-29 23:30:23 +00:00
changes <- getChanges
-- Now see if now's a good time to commit.
2012-10-29 15:40:22 +00:00
time <- liftIO getCurrentTime
if shouldCommit time changes
then do
2012-10-29 15:40:22 +00:00
readychanges <- handleAdds delayadd changes
if shouldCommit time readychanges
then do
2012-10-29 15:40:22 +00:00
debug
[ "committing"
, show (length readychanges)
, "changes"
]
2012-10-29 20:49:47 +00:00
void $ alertWhile commitAlert $
2012-10-29 15:40:22 +00:00
liftAnnex commitStaged
2012-10-29 23:35:18 +00:00
recordCommit
else refill readychanges
else refill changes
2012-10-29 15:40:22 +00:00
where
refill [] = noop
refill cs = do
debug ["delaying commit of", show (length cs), "changes"]
2012-10-29 23:30:23 +00:00
refillChanges cs
2012-06-13 16:36:33 +00:00
run current branch merge in annex monad I was seeing some interesting crashes after the previous commit, when making file changes slightly faster than the assistant could keep up. error: Ref refs/heads/master is at 7074f8e0a11110c532d06746e334f2fec6af6ab4 but expected 95ea86008d72a40d97a81cfc8fb47a0da92166bd fatal: cannot lock HEAD ref Committer crashed: git commit [Param "--allow-empty-message",Param "-m",Param "",Param "--allow-empty",Param "--quiet"] failed Pusher crashed: thread blocked indefinitely in an STM transaction Clearly the the merger ended up running at the same time as the committer, and with both modifying HEAD the committer crashed. I fixed that by making the Merger run its merge inside the annex monad, which avoids it running concurrently with other git operations. Also by making the committer not crash if git fails. What I don't understand is why the pusher then crashed with a STM deadlock. That must be in either the DaemonStatusHandle or the FailedPushMap, and the latter is only used by the pusher. Did the committer's crash somehow break STM? The BlockedIndefinitelyOnSTM exception is described as: -- |The thread is waiting to retry an STM transaction, but there are no -- other references to any @TVar@s involved, so it can't ever continue. If the Committer had a reference to a TVar and crashed, I can sort of see this leading to that exception.. The crash was quite easy to reproduce after the previous commit, but after making the above change, I have yet to see it again. Here's hoping.
2012-09-18 01:32:30 +00:00
commitStaged :: Annex Bool
2012-06-13 16:36:33 +00:00
commitStaged = do
{- This could fail if there's another commit being made by
- something else. -}
v <- tryAnnex Annex.Queue.flush
case v of
Left _ -> return False
Right _ -> do
void $ inRepo $ Git.Command.runBool "commit" $ nomessage
[ Param "--quiet"
{- Avoid running the usual git-annex pre-commit hook;
- watch does the same symlink fixing, and we don't want
- to deal with unlocked files in these commits. -}
, Param "--no-verify"
]
{- Empty commits may be made if tree changes cancel
- each other out, etc. Git returns nonzero on those,
- so don't propigate out commit failures. -}
return True
2012-10-29 15:40:22 +00:00
where
nomessage ps
| Git.Version.older "1.7.2" = Param "-m"
: Param "autocommit" : ps
| otherwise = Param "--allow-empty-message"
: Param "-m" : Param "" : ps
2012-06-13 16:36:33 +00:00
{- Decide if now is a good time to make a commit.
- Note that the list of change times has an undefined order.
-
- Current strategy: If there have been 10 changes within the past second,
2012-06-13 16:36:33 +00:00
- a batch activity is taking place, so wait for later.
-}
shouldCommit :: UTCTime -> [Change] -> Bool
shouldCommit now changes
| len == 0 = False
| len > 10000 = True -- avoid bloating queue too much
| length (filter thisSecond changes) < 10 = True
| otherwise = False -- batch activity
2012-10-29 15:40:22 +00:00
where
len = length changes
thisSecond c = now `diffUTCTime` changeTime c <= 1
{- OSX needs a short delay after a file is added before locking it down,
- as pasting a file seems to try to set file permissions or otherwise
- access the file after closing it. -}
delayaddDefault :: Maybe Seconds
#ifdef darwin_HOST_OS
delayaddDefault = Just $ Seconds 1
#else
delayaddDefault = Nothing
#endif
{- If there are PendingAddChanges, or InProcessAddChanges, the files
- have not yet actually been added to the annex, and that has to be done
- now, before committing.
-
- Deferring the adds to this point causes batches to be bundled together,
- which allows faster checking with lsof that the files are not still open
- for write by some other process, and faster checking with git-ls-files
- that the files are not already checked into git.
-
- When a file is added, Inotify will notice the new symlink. So this waits
- for additional Changes to arrive, so that the symlink has hopefully been
- staged before returning, and will be committed immediately.
-
- OTOH, for kqueue, eventsCoalesce, so instead the symlink is directly
- created and staged.
-
- Returns a list of all changes that are ready to be committed.
- Any pending adds that are not ready yet are put back into the ChangeChan,
- where they will be retried later.
-}
2012-10-29 15:40:22 +00:00
handleAdds :: Maybe Seconds -> [Change] -> Assistant [Change]
handleAdds delayadd cs = returnWhen (null incomplete) $ do
let (pending, inprocess) = partition isPendingAddChange incomplete
pending' <- findnew pending
2012-10-29 15:40:22 +00:00
(postponed, toadd) <- partitionEithers <$> safeToAdd delayadd pending' inprocess
unless (null postponed) $
2012-10-29 23:30:23 +00:00
refillChanges postponed
returnWhen (null toadd) $ do
added <- catMaybes <$> forM toadd add
2012-09-13 04:57:52 +00:00
if DirWatcher.eventsCoalesce || null added
then return $ added ++ otherchanges
else do
2012-10-29 23:30:23 +00:00
r <- handleAdds delayadd =<< getChanges
return $ r ++ added ++ otherchanges
2012-10-29 15:40:22 +00:00
where
(incomplete, otherchanges) = partition (\c -> isPendingAddChange c || isInProcessAddChange c) cs
2012-10-29 15:40:22 +00:00
findnew [] = return []
findnew pending@(exemplar:_) = do
(!newfiles, cleanup) <- liftAnnex $
inRepo (Git.LsFiles.notInRepo False $ map changeFile pending)
void $ liftIO cleanup
-- note: timestamp info is lost here
let ts = changeTime exemplar
return $ map (PendingAddChange ts) newfiles
returnWhen c a
| c = return otherchanges
| otherwise = a
2012-10-29 15:40:22 +00:00
add :: Change -> Assistant (Maybe Change)
add change@(InProcessAddChange { keySource = ks }) = do
2012-10-29 20:49:47 +00:00
alertWhile' (addFileAlert $ keyFilename ks) $
liftM ret $ catchMaybeIO <~> do
sanitycheck ks $ do
key <- liftAnnex $ do
showStart "add" $ keyFilename ks
Command.Add.ingest ks
done (finishedChange change) (keyFilename ks) key
2012-10-29 15:40:22 +00:00
where
{- Add errors tend to be transient and will be automatically
- dealt with, so don't pass to the alert code. -}
ret (Just j@(Just _)) = (True, j)
ret _ = (True, Nothing)
2012-10-29 20:49:47 +00:00
add _ = return Nothing
2012-10-29 15:40:22 +00:00
done _ _ Nothing = do
liftAnnex showEndFail
return Nothing
done change file (Just key) = do
link <- liftAnnex $ Command.Add.link file key True
when DirWatcher.eventsCoalesce $
liftAnnex $ do
2012-06-19 06:40:21 +00:00
sha <- inRepo $
Git.HashObject.hashObject BlobObject link
stageSymlink file sha
2012-10-29 15:40:22 +00:00
showEndOk
queueTransfers Next key (Just file) Upload
2012-10-29 15:40:22 +00:00
return $ Just change
2012-10-29 15:40:22 +00:00
{- Check that the keysource's keyFilename still exists,
- and is still a hard link to its contentLocation,
- before ingesting it. -}
sanitycheck keysource a = do
fs <- liftIO $ getSymbolicLinkStatus $ keyFilename keysource
ks <- liftIO $ getSymbolicLinkStatus $ contentLocation keysource
if deviceID ks == deviceID fs && fileID ks == fileID fs
then a
else return Nothing
{- Files can Either be Right to be added now,
- or are unsafe, and must be Left for later.
-
- Check by running lsof on the temp directory, which
- the KeySources are locked down in.
-}
2012-10-29 15:40:22 +00:00
safeToAdd :: Maybe Seconds -> [Change] -> [Change] -> Assistant [Either Change Change]
safeToAdd _ [] [] = return []
safeToAdd delayadd pending inprocess = do
maybe noop (liftIO . threadDelaySeconds) delayadd
liftAnnex $ do
keysources <- mapM Command.Add.lockDown (map changeFile pending)
let inprocess' = map mkinprocess (zip pending keysources)
tmpdir <- fromRepo gitAnnexTmpDir
openfiles <- S.fromList . map fst3 . filter openwrite <$>
liftIO (Lsof.queryDir tmpdir)
let checked = map (check openfiles) $ inprocess ++ inprocess'
{- If new events are received when files are closed,
- there's no need to retry any changes that cannot
- be done now. -}
if DirWatcher.closingTracked
then do
mapM_ canceladd $ lefts checked
allRight $ rights checked
else return checked
2012-10-29 15:40:22 +00:00
where
check openfiles change@(InProcessAddChange { keySource = ks })
| S.member (contentLocation ks) openfiles = Left change
check _ change = Right change
2012-10-29 15:40:22 +00:00
mkinprocess (c, ks) = InProcessAddChange
{ changeTime = changeTime c
, keySource = ks
}
2012-10-29 15:40:22 +00:00
canceladd (InProcessAddChange { keySource = ks }) = do
warning $ keyFilename ks
++ " still has writers, not adding"
-- remove the hard link
void $ liftIO $ tryIO $ removeFile $ contentLocation ks
canceladd _ = noop
2012-10-29 15:40:22 +00:00
openwrite (_file, mode, _pid) =
mode == Lsof.OpenWriteOnly || mode == Lsof.OpenReadWrite
2012-10-29 15:40:22 +00:00
allRight = return . map Right