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.AutoRacingSchedule as AutoRacingSchedule (
51 import qualified TSN.XML.GameInfo as GameInfo ( dtds, parse_xml )
52 import qualified TSN.XML.Heartbeat as Heartbeat ( dtd, verify )
53 import qualified TSN.XML.Injuries as Injuries ( dtd, pickle_message )
54 import qualified TSN.XML.InjuriesDetail as InjuriesDetail (
57 import qualified TSN.XML.News as News ( dtd, pickle_message )
58 import qualified TSN.XML.Odds as Odds ( dtd, pickle_message )
59 import qualified TSN.XML.Scores as Scores ( dtd, pickle_message )
60 import qualified TSN.XML.SportInfo as SportInfo ( dtds, parse_xml )
61 import qualified TSN.XML.Weather as Weather ( dtd, pickle_message )
62 import Xml ( DtdName(..), parse_opts )
65 -- | This is where most of the work happens. This function is called
66 -- on every file that we would like to import. It determines which
67 -- importer to use based on the DTD, attempts to process the file,
68 -- and then returns whether or not it was successful. If the file
69 -- was processed, 'True' is returned. Otherwise, 'False' is
72 -- The implementation is straightforward with one exception: since
73 -- we are already in arrow world with HXT, the @import_with_dtd@
74 -- function is lifted to an 'Arrow' as well with 'arr'. This
75 -- prevents us from having to do a bunch of unwrapping and
76 -- rewrapping with the associated error checking.
78 import_file :: Configuration -- ^ A configuration object needed for the
79 -- 'backend' and 'connection_string'.
81 -> FilePath -- ^ The path of the XML file to import.
83 -> IO Bool -- ^ True if we processed the file, False otherwise.
84 import_file cfg path = do
85 results <- parse_and_import `catch` exception_handler
88 -- One of the arrows returned "nothing."
89 report_error $ "Unable to determine DTD for file " ++ path ++ "."
91 (ImportFailed errmsg:_) -> do
94 (ImportSkipped infomsg:_) -> do
95 -- We processed the message but didn't import anything. Return
96 -- "success" so that the XML file is deleted.
99 (ImportSucceeded:_) -> do
100 report_info $ "Successfully imported " ++ path ++ "."
102 (ImportUnsupported infomsg:_) -> do
103 -- For now we return "success" for these too, since we know we don't
104 -- support a bunch of DTDs and we want them to get deleted.
108 -- | This will catch *any* exception, even the ones thrown by
109 -- Haskell's 'error' (which should never occur under normal
111 exception_handler :: SomeException -> IO [ImportResult]
112 exception_handler e = do
113 report_error (show e)
114 let errdesc = "Failed to import file " ++ path ++ "."
115 -- Return a nonempty list so we don't claim incorrectly that
116 -- we couldn't parse the DTD.
117 return [ImportFailed errdesc]
119 -- | An arrow that reads a document into an 'XmlTree'.
120 readA :: IOStateArrow s a XmlTree
121 readA = readDocument parse_opts path
123 -- | An arrow which parses the doctype "SYSTEM" of an 'XmlTree'.
124 -- We use these to determine the parser to use.
125 dtdnameA :: ArrowXml a => a XmlTree DtdName
126 dtdnameA = getAttrl >>> hasName "doctype-SYSTEM" /> getText >>^ DtdName
128 -- | Combine the arrows above as well as the function below
129 -- (arrowized with 'arr') into an IO action that does everything
130 -- (parses and then runs the import on what was parsed).
132 -- The result of runX has type IO [IO ImportResult]. We thus use
133 -- bind (>>=) and sequence to combine all of the IOs into one
134 -- big one outside of the list.
135 parse_and_import :: IO [ImportResult]
137 runX (readA >>> (dtdnameA &&& returnA) >>> (arr import_with_dtd))
141 -- | Takes a ('DtdName', 'XmlTree') pair and uses the 'DtdName'
142 -- to determine which function to call on the 'XmlTree'.
143 import_with_dtd :: (DtdName, XmlTree) -> IO ImportResult
144 import_with_dtd (DtdName dtd,xml)
145 -- We special-case the heartbeat so it doesn't have to run in
146 -- the database monad.
147 | dtd == Heartbeat.dtd = Heartbeat.verify xml
149 -- We need NoMonomorphismRestriction here.
150 if backend cfg == Postgres
151 then withPostgresqlConn cs $ runDbConn importer
152 else withSqliteConn cs $ runDbConn importer
154 -- | Pull the real connection String out of the configuration.
157 cs = get_connection_string $ connection_string cfg
159 -- | Convenience; we use this everywhere below in 'importer'.
161 migrate_and_import m = dbmigrate m >> dbimport m
164 | dtd == AutoRacingSchedule.dtd = do
165 let m = unpickleDoc AutoRacingSchedule.pickle_message xml
166 maybe (return $ ImportFailed errmsg) migrate_and_import m
168 -- GameInfo and SportInfo appear least in the guards
169 | dtd == Injuries.dtd = do
170 let m = unpickleDoc Injuries.pickle_message xml
171 maybe (return $ ImportFailed errmsg) migrate_and_import m
173 | dtd == InjuriesDetail.dtd = do
174 let m = unpickleDoc InjuriesDetail.pickle_message xml
175 maybe (return $ ImportFailed errmsg) migrate_and_import m
178 | dtd == News.dtd = do
179 let m = unpickleDoc News.pickle_message xml
180 maybe (return $ ImportFailed errmsg) migrate_and_import m
182 | dtd == Odds.dtd = do
183 let m = unpickleDoc Odds.pickle_message xml
184 maybe (return $ ImportFailed errmsg) migrate_and_import m
186 | dtd == Scores.dtd = do
187 let m = unpickleDoc Scores.pickle_message xml
188 maybe (return $ ImportFailed errmsg) migrate_and_import m
190 -- SportInfo and GameInfo appear least in the guards
191 | dtd == Weather.dtd = do
192 let m = unpickleDoc Weather.pickle_message xml
193 maybe (return $ ImportFailed errmsg) migrate_and_import m
195 | dtd `elem` GameInfo.dtds = do
196 let either_m = GameInfo.parse_xml dtd xml
198 -- This might give us a slightly better error
199 -- message than the default 'errmsg'.
200 Left err -> return $ ImportFailed err
201 Right m -> migrate_and_import m
203 | dtd `elem` SportInfo.dtds = do
204 let either_m = SportInfo.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
213 "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
214 return $ ImportUnsupported infomsg
217 errmsg = "Could not unpickle " ++ dtd ++ "."
220 -- | Entry point of the program. It twiddles some knobs for
221 -- configuration options and then calls 'import_file' on each XML
222 -- file given on the command-line.
224 -- Any file successfully processed is then optionally removed, and
232 -- Merge the config file options with the command-line ones,
233 -- prefering the command-line ones.
234 let opt_config = rc_cfg <> cmd_cfg
236 -- Update a default config with any options that have been set in
237 -- either the config file or on the command-line. We initialize
238 -- logging before the missing parameter checks below so that we can
240 let cfg = (def :: Configuration) `merge_optional` opt_config
241 init_logging (log_level cfg) (log_file cfg) (syslog cfg)
243 -- Check the optional config for missing required options.
244 when (null $ OC.xml_files opt_config) $ do
245 report_error "No XML files given."
246 exitWith (ExitFailure exit_no_xml_files)
248 -- We don't do this in parallel (for now?) to keep the error
249 -- messages nice and linear.
250 results <- mapM (import_file cfg) (OC.xml_files opt_config)
252 -- Zip the results with the files list to find out which ones can be
254 let result_pairs = zip (OC.xml_files opt_config) results
255 let victims = [ p | (p, True) <- result_pairs ]
256 let processed_count = length victims
257 report_info $ "Processed " ++ (show processed_count) ++ " document(s) total."
258 when (remove cfg) $ mapM_ (kill True) victims
261 -- | Wrap these two actions into one function so that we don't
262 -- report that the file was removed if the exception handler is
264 remove_and_report path = do
266 report_info $ "Removed processed file " ++ path ++ "."
268 -- | Try to remove @path@ and potentially try again.
269 kill try_again path =
270 (remove_and_report path) `catchIOError` exception_handler
272 -- | A wrapper around threadDelay which takes seconds instead of
273 -- microseconds as its argument.
274 thread_sleep :: Int -> IO ()
275 thread_sleep seconds = do
276 let microseconds = seconds * (10 ^ (6 :: Int))
277 threadDelay microseconds
279 -- | If we can't remove the file, report that, and try once
280 -- more after waiting a few seconds.
281 exception_handler :: IOError -> IO ()
282 exception_handler e = do
283 report_error (show e)
284 report_error $ "Failed to remove imported file " ++ path ++ "."
286 report_info "Waiting 5 seconds to attempt removal again..."
290 report_info $ "Giving up on " ++ path ++ "."