1 {-# LANGUAGE DoAndIfThenElse #-}
2 {-# LANGUAGE NoMonomorphismRestriction #-}
7 import Control.Arrow ( (&&&), (>>^), arr, returnA )
8 import Control.Concurrent ( threadDelay )
9 import Control.Exception ( SomeException, catch )
10 import Control.Monad ( when )
11 import Database.Groundhog.Generic ( runDbConn )
12 import Database.Groundhog.Sqlite (
14 import Database.Groundhog.Postgresql (
16 import Data.Monoid ( (<>) )
17 import Network.Services.TSN.Logging ( init_logging )
18 import System.Console.CmdArgs ( def )
19 import System.Directory ( removeFile )
20 import System.Exit ( exitWith, ExitCode (ExitFailure) )
21 import System.IO.Error ( catchIOError )
22 import Text.XML.HXT.Core (
36 import Backend ( Backend(..) )
37 import CommandLine ( get_args )
38 import Configuration ( Configuration(..), merge_optional )
39 import ConnectionString ( ConnectionString(..) )
40 import ExitCodes ( exit_no_xml_files )
41 import qualified OptionalConfiguration as OC (
42 OptionalConfiguration ( xml_files ),
44 import Network.Services.TSN.Report (
47 import TSN.DbImport ( DbImport(..), ImportResult(..) )
48 import qualified TSN.XML.AutoRacingResults as AutoRacingResults (
51 import qualified TSN.XML.AutoRacingSchedule as AutoRacingSchedule (
54 import qualified TSN.XML.GameInfo as GameInfo ( dtds, parse_xml )
55 import qualified TSN.XML.Heartbeat as Heartbeat ( dtd, verify )
56 import qualified TSN.XML.Injuries as Injuries ( dtd, pickle_message )
57 import qualified TSN.XML.InjuriesDetail as InjuriesDetail (
60 import qualified TSN.XML.JFile as JFile ( dtd, pickle_message )
61 import qualified TSN.XML.News as News ( dtd, pickle_message )
62 import qualified TSN.XML.Odds as Odds ( dtd, pickle_message )
63 import qualified TSN.XML.Scores as Scores ( dtd, pickle_message )
64 import qualified TSN.XML.SportInfo as SportInfo ( dtds, parse_xml )
65 import qualified TSN.XML.Weather as Weather ( dtd, pickle_message )
66 import Xml ( DtdName(..), parse_opts )
69 -- | This is where most of the work happens. This function is called
70 -- on every file that we would like to import. It determines which
71 -- importer to use based on the DTD, attempts to process the file,
72 -- and then returns whether or not it was successful. If the file
73 -- was processed, 'True' is returned. Otherwise, 'False' is
76 -- The implementation is straightforward with one exception: since
77 -- we are already in arrow world with HXT, the @import_with_dtd@
78 -- function is lifted to an 'Arrow' as well with 'arr'. This
79 -- prevents us from having to do a bunch of unwrapping and
80 -- rewrapping with the associated error checking.
82 import_file :: Configuration -- ^ A configuration object needed for the
83 -- 'backend' and 'connection_string'.
85 -> FilePath -- ^ The path of the XML file to import.
87 -> IO Bool -- ^ True if we processed the file, False otherwise.
88 import_file cfg path = do
89 results <- parse_and_import `catch` exception_handler
92 -- One of the arrows returned "nothing."
93 report_error $ "Unable to determine DTD for file " ++ path ++ "."
95 (ImportFailed errmsg:_) -> do
98 (ImportSkipped infomsg:_) -> do
99 -- We processed the message but didn't import anything. Return
100 -- "success" so that the XML file is deleted.
103 (ImportSucceeded:_) -> do
104 report_info $ "Successfully imported " ++ path ++ "."
106 (ImportUnsupported infomsg:_) -> do
107 -- For now we return "success" for these too, since we know we don't
108 -- support a bunch of DTDs and we want them to get deleted.
112 -- | This will catch *any* exception, even the ones thrown by
113 -- Haskell's 'error' (which should never occur under normal
115 exception_handler :: SomeException -> IO [ImportResult]
116 exception_handler e = do
117 report_error (show e)
118 let errdesc = "Failed to import file " ++ path ++ "."
119 -- Return a nonempty list so we don't claim incorrectly that
120 -- we couldn't parse the DTD.
121 return [ImportFailed errdesc]
123 -- | An arrow that reads a document into an 'XmlTree'.
124 readA :: IOStateArrow s a XmlTree
125 readA = readDocument parse_opts path
127 -- | An arrow which parses the doctype "SYSTEM" of an 'XmlTree'.
128 -- We use these to determine the parser to use.
129 dtdnameA :: ArrowXml a => a XmlTree DtdName
130 dtdnameA = getAttrl >>> hasName "doctype-SYSTEM" /> getText >>^ DtdName
132 -- | Combine the arrows above as well as the function below
133 -- (arrowized with 'arr') into an IO action that does everything
134 -- (parses and then runs the import on what was parsed).
136 -- The result of runX has type IO [IO ImportResult]. We thus use
137 -- bind (>>=) and sequence to combine all of the IOs into one
138 -- big one outside of the list.
139 parse_and_import :: IO [ImportResult]
141 runX (readA >>> (dtdnameA &&& returnA) >>> (arr import_with_dtd))
145 -- | Takes a ('DtdName', 'XmlTree') pair and uses the 'DtdName'
146 -- to determine which function to call on the 'XmlTree'.
147 import_with_dtd :: (DtdName, XmlTree) -> IO ImportResult
148 import_with_dtd (DtdName dtd,xml)
149 -- We special-case the heartbeat so it doesn't have to run in
150 -- the database monad.
151 | dtd == Heartbeat.dtd = Heartbeat.verify xml
153 -- We need NoMonomorphismRestriction here.
154 if backend cfg == Postgres
155 then withPostgresqlConn cs $ runDbConn importer
156 else withSqliteConn cs $ runDbConn importer
158 -- | Pull the real connection String out of the configuration.
161 cs = get_connection_string $ connection_string cfg
163 -- | Convenience; we use this everywhere below in 'importer'.
165 migrate_and_import m = dbmigrate m >> dbimport m
167 -- | The error message we return if unpickling fails.
169 errmsg = "Could not unpickle " ++ dtd ++ "."
171 -- | Try to migrate and import using the given pickler @f@;
172 -- if it works, return the result. Otherwise, return an
173 -- 'ImportFailed' along with our error message.
176 (return $ ImportFailed errmsg)
181 | dtd == AutoRacingResults.dtd =
182 go AutoRacingResults.pickle_message
184 | dtd == AutoRacingSchedule.dtd =
185 go AutoRacingSchedule.pickle_message
187 -- GameInfo and SportInfo appear last in the guards
188 | dtd == Injuries.dtd = go Injuries.pickle_message
190 | dtd == InjuriesDetail.dtd = go InjuriesDetail.pickle_message
192 | dtd == JFile.dtd = go JFile.pickle_message
194 | dtd == News.dtd = go News.pickle_message
196 | dtd == Odds.dtd = go Odds.pickle_message
198 | dtd == Scores.dtd = go Scores.pickle_message
200 -- SportInfo and GameInfo appear last in the guards
201 | dtd == Weather.dtd = go Weather.pickle_message
203 | dtd `elem` GameInfo.dtds = do
204 let either_m = GameInfo.parse_xml dtd xml
206 -- This might give us a slightly better error
207 -- message than the default 'errmsg'.
208 Left err -> return $ ImportFailed err
209 Right m -> migrate_and_import m
211 | dtd `elem` SportInfo.dtds = do
212 let either_m = SportInfo.parse_xml dtd xml
214 -- This might give us a slightly better error
215 -- message than the default 'errmsg'.
216 Left err -> return $ ImportFailed err
217 Right m -> migrate_and_import m
221 "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
222 return $ ImportUnsupported infomsg
226 -- | Entry point of the program. It twiddles some knobs for
227 -- configuration options and then calls 'import_file' on each XML
228 -- file given on the command-line.
230 -- Any file successfully processed is then optionally removed, and
238 -- Merge the config file options with the command-line ones,
239 -- prefering the command-line ones.
240 let opt_config = rc_cfg <> cmd_cfg
242 -- Update a default config with any options that have been set in
243 -- either the config file or on the command-line. We initialize
244 -- logging before the missing parameter checks below so that we can
246 let cfg = (def :: Configuration) `merge_optional` opt_config
247 init_logging (log_level cfg) (log_file cfg) (syslog cfg)
249 -- Check the optional config for missing required options.
250 when (null $ OC.xml_files opt_config) $ do
251 report_error "No XML files given."
252 exitWith (ExitFailure exit_no_xml_files)
254 -- We don't do this in parallel (for now?) to keep the error
255 -- messages nice and linear.
256 results <- mapM (import_file cfg) (OC.xml_files opt_config)
258 -- Zip the results with the files list to find out which ones can be
260 let result_pairs = zip (OC.xml_files opt_config) results
261 let victims = [ p | (p, True) <- result_pairs ]
262 let processed_count = length victims
263 report_info $ "Processed " ++ (show processed_count) ++ " document(s) total."
264 when (remove cfg) $ mapM_ (kill True) victims
267 -- | Wrap these two actions into one function so that we don't
268 -- report that the file was removed if the exception handler is
270 remove_and_report path = do
272 report_info $ "Removed processed file " ++ path ++ "."
274 -- | Try to remove @path@ and potentially try again.
275 kill try_again path =
276 (remove_and_report path) `catchIOError` exception_handler
278 -- | A wrapper around threadDelay which takes seconds instead of
279 -- microseconds as its argument.
280 thread_sleep :: Int -> IO ()
281 thread_sleep seconds = do
282 let microseconds = seconds * (10 ^ (6 :: Int))
283 threadDelay microseconds
285 -- | If we can't remove the file, report that, and try once
286 -- more after waiting a few seconds.
287 exception_handler :: IOError -> IO ()
288 exception_handler e = do
289 report_error (show e)
290 report_error $ "Failed to remove imported file " ++ path ++ "."
292 report_info "Waiting 5 seconds to attempt removal again..."
296 report_info $ "Giving up on " ++ path ++ "."