1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
|
{- hpodder component
Copyright (C) 2006-2008 John Goerzen <jgoerzen@complete.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : DownloadQueue
Copyright : Copyright (C) 2006-2008 John Goerzen
License : GNU GPL, version 2 or above
Maintainer : John Goerzen <jgoerzen@complete.org>
Stability : provisional
Portability: portable
Written by John Goerzen, jgoerzen\@complete.org
-}
module DownloadQueue(DownloadEntry(..),
DownloadQueue(..),
DLAction(..),
easyDownloads,
runDownloads
) where
import Download
import System.Cmd.Utils
import Data.Maybe.Utils
import System.Posix.Process
import Database.HDBC(handleSqlError)
import Config
import System.Log.Logger
import Text.Printf
import System.Exit
import System.IO
import System.Directory
import System.Posix.Files
import System.Posix.Signals
import Data.Hash.MD5
import Data.Progress.Tracker
import Data.Progress.Meter
import Data.Quantity
import Network.URI
import Data.List
import Control.Concurrent.MVar
import Control.Concurrent
import Data.Char
import Control.Monad(when)
d = debugM "downloadqueue"
i = infoM "downloadqueue"
data DownloadEntry a =
DownloadEntry {dlurl :: String,
dlname :: String,
usertok :: a,
dlprogress :: Progress}
data DownloadQueue a =
DownloadQueue {pendingHosts :: [(String, [DownloadEntry a])],
-- activeDownloads :: (DownloadEntry, DownloadTok),
basePath :: FilePath,
allowResume :: Bool,
callbackFunc :: (DownloadEntry a -> DLAction -> IO ()),
completedDownloads :: [(DownloadEntry a, DownloadTok, Result)]}
data DLAction = DLStarted DownloadTok | DLEnded (DownloadTok, ProcessStatus, Result, String)
deriving (Eq, Show)
groupByHost :: [DownloadEntry a] -> [(String, [DownloadEntry a])]
groupByHost dllist =
combineGroups .
groupBy (\(host1, _) (host2, _) -> host1 == host2) . sortBy sortfunc .
map (\(x, y) -> (map toLower x, y)) . -- lowercase the hostnames
map conv $ dllist
where sortfunc (a, _) (b, _) = compare a b
conv de = case parseURI (dlurl de) of
Nothing -> ("", de)
Just x -> case uriAuthority x of
Nothing -> ("", de)
Just ua -> (uriRegName ua, de)
combineGroups :: [[(String, DownloadEntry a)]] -> [(String, [DownloadEntry a])]
combineGroups [] = []
combineGroups (x:xs) =
(fst . head $ x, map snd x) : combineGroups xs
easyDownloads :: String -- ^ Name for tracker
-> IO FilePath -- ^ Function to get base dir
-> Bool -- ^ Allow resuming
-> (Progress -> IO [DownloadEntry a]) -- ^ Function to get DLentries
-> (Progress -> ProgressMeter -> DownloadEntry a -> DownloadTok -> IO ()) -- ^ Callback when downloads starts
-> (Progress -> ProgressMeter -> DownloadEntry a -> DownloadTok -> ProcessStatus -> Result -> IO ()) -- ^ Callback that gets called after the download is complete
-> IO ()
easyDownloads ptname bdfunc allowresume getentryfunc procStart procFinish =
do maxthreads <- getMaxThreads
progressinterval <- getProgressInterval
basedir <- bdfunc
pt <- newProgress ptname 0
meter <- newMeter pt "B" 80 (renderNums binaryOpts 0)
meterthread <- autoDisplayMeter meter progressinterval
(displayMeter stdout)
dlentries <- getentryfunc pt
runDownloads (callback pt meter) basedir allowresume dlentries
maxthreads
killAutoDisplayMeter meter meterthread
finishP pt
displayMeter stdout meter
putStrLn ""
where callback pt meter dlentry (DLStarted dltok) =
do addComponent meter (dlprogress dlentry)
procStart pt meter dlentry dltok
callback pt meter dlentry (DLEnded (dltok, status, result, msg)) =
do removeComponent meter (dlname dlentry)
when (msg /= "")
(writeMeterString stderr meter $
" *** " ++ dlname dlentry ++ ": Message on " ++
tokurl dltok ++ ":\n" ++ msg ++ "\n")
procFinish pt meter dlentry dltok status result
finishP (dlprogress dlentry)
runDownloads :: (DownloadEntry a -> DLAction -> IO ()) -> -- Callback when a download starts or stops
FilePath -> -- Base path
Bool -> -- Whether or not to allow resume
[DownloadEntry a] -> -- Items to download
Int -> -- Max number of download threads
IO [(DownloadEntry a, DownloadTok, Result)] -- The completed DLs
runDownloads callbackfunc basefp resumeOK delist maxthreads =
do oldsigs <- blocksignals
--print (map (\(h, el) -> (h, map dlurl el)) $ groupByHost delist)
dqmvar <- newMVar $ DownloadQueue {pendingHosts = groupByHost delist,
completedDownloads = [],
basePath = basefp,
allowResume = resumeOK,
callbackFunc = callbackfunc}
semaphore <- newQSem 0 -- Used by threads to signal they're done
mapM_ (\_ -> forkIO (handleSqlError $ childthread dqmvar semaphore)) [1..maxthreads]
mapM_ (\_ -> waitQSem semaphore) [1..maxthreads]
restoresignals oldsigs
withMVar dqmvar (\dq -> return (completedDownloads dq))
childthread :: MVar (DownloadQueue a) -> QSem -> IO ()
childthread dqmvar semaphore =
do workdata <- getworkdata
if length(workdata) == 0
then signalQSem semaphore -- We're done!
else do processChildWorkData workdata
childthread dqmvar semaphore -- And look for more hosts
where getworkdata = modifyMVar dqmvar $ \dq ->
do case pendingHosts dq of
[] -> return (dq, [])
(x:xs) -> return (dq {pendingHosts = xs}, snd x)
getProcessStatusWithDelay pid =
do status <- getProcessStatus False False pid
case status of
Nothing -> do threadDelay 1000000
getProcessStatusWithDelay pid
Just x -> return x
processChildWorkData [] = return []
processChildWorkData (x:xs) =
do (basefp, resumeOK, callback) <- withMVar dqmvar
(\dq -> return (basePath dq, allowResume dq,
callbackFunc dq))
dltok <- startGetURL (dlurl x) basefp resumeOK
callback x (DLStarted dltok)
status <- getProcessStatusWithDelay (tokpid dltok)
result <- finishGetURL dltok status
messages <- readFile (tokpath dltok ++ ".msg")
-- Add to the completed DLs list. Also do callback here
-- so it's within the lock. Handy to prevent simultaneous
-- DB updates.
modifyMVar_ dqmvar $ \dq ->
do callback x (DLEnded (dltok, status, result, messages))
-- Delete the messages file now that we don't
-- care about it anymore
catch (removeFile (tokpath dltok ++ ".msg"))
(\_ -> return ())
return (dq {completedDownloads =
(x, dltok, result) :
completedDownloads dq})
processChildWorkData xs -- Do the next one
blocksignals =
do let sigset = addSignal sigCHLD emptySignalSet
oldset <- getSignalMask
blockSignals sigset
return oldset
restoresignals = setSignalMask
|