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.Heartbeat as Heartbeat ( dtd, verify )
52 import qualified TSN.XML.Injuries as Injuries ( dtd, pickle_message )
53 import qualified TSN.XML.InjuriesDetail as InjuriesDetail (
56 import qualified TSN.XML.News as News ( dtd, pickle_message )
57 import qualified TSN.XML.Odds as Odds ( dtd, pickle_message )
58 import qualified TSN.XML.Scores as Scores ( dtd, pickle_message )
59 import qualified TSN.XML.Weather as Weather ( dtd, pickle_message )
60 import Xml ( DtdName(..), parse_opts )
63 -- | This is where most of the work happens. This function is called
64 -- on every file that we would like to import. It determines which
65 -- importer to use based on the DTD, attempts to process the file,
66 -- and then returns whether or not it was successful. If the file
67 -- was processed, 'True' is returned. Otherwise, 'False' is
70 -- The implementation is straightforward with one exception: since
71 -- we are already in arrow world with HXT, the @import_with_dtd@
72 -- function is lifted to an 'Arrow' as well with 'arr'. This
73 -- prevents us from having to do a bunch of unwrapping and
74 -- rewrapping with the associated error checking.
76 import_file :: Configuration -- ^ A configuration object needed for the
77 -- 'backend' and 'connection_string'.
79 -> FilePath -- ^ The path of the XML file to import.
81 -> IO Bool -- ^ True if we processed the file, False otherwise.
82 import_file cfg path = do
83 results <- parse_and_import `catch` exception_handler
86 -- One of the arrows returned "nothing."
87 report_error $ "Unable to determine DTD for file " ++ path ++ "."
89 (ImportFailed errmsg:_) -> do
92 (ImportSkipped infomsg:_) -> do
93 -- We processed the message but didn't import anything. Return
94 -- "success" so that the XML file is deleted.
97 (ImportSucceeded:_) -> do
98 report_info $ "Successfully imported " ++ path ++ "."
100 (ImportUnsupported infomsg:_) -> do
101 -- For now we return "success" for these too, since we know we don't
102 -- support a bunch of DTDs and we want them to get deleted.
106 -- | This will catch *any* exception, even the ones thrown by
107 -- Haskell's 'error' (which should never occur under normal
109 exception_handler :: SomeException -> IO [ImportResult]
110 exception_handler e = do
111 report_error (show e)
112 let errdesc = "Failed to import file " ++ path ++ "."
113 -- Return a nonempty list so we don't claim incorrectly that
114 -- we couldn't parse the DTD.
115 return [ImportFailed errdesc]
117 -- | An arrow that reads a document into an 'XmlTree'.
118 readA :: IOStateArrow s a XmlTree
119 readA = readDocument parse_opts path
121 -- | An arrow which parses the doctype "SYSTEM" of an 'XmlTree'.
122 -- We use these to determine the parser to use.
123 dtdnameA :: ArrowXml a => a XmlTree DtdName
124 dtdnameA = getAttrl >>> hasName "doctype-SYSTEM" /> getText >>^ DtdName
126 -- | Combine the arrows above as well as the function below
127 -- (arrowized with 'arr') into an IO action that does everything
128 -- (parses and then runs the import on what was parsed).
130 -- The result of runX has type IO [IO ImportResult]. We thus use
131 -- bind (>>=) and sequence to combine all of the IOs into one
132 -- big one outside of the list.
133 parse_and_import :: IO [ImportResult]
135 runX (readA >>> (dtdnameA &&& returnA) >>> (arr import_with_dtd))
139 -- | Takes a ('DtdName', 'XmlTree') pair and uses the 'DtdName'
140 -- to determine which function to call on the 'XmlTree'.
141 import_with_dtd :: (DtdName, XmlTree) -> IO ImportResult
142 import_with_dtd (DtdName dtd,xml)
143 -- We special-case the heartbeat so it doesn't have to run in
144 -- the database monad.
145 | dtd == Heartbeat.dtd = Heartbeat.verify xml
147 -- We need NoMonomorphismRestriction here.
148 if backend cfg == Postgres
149 then withPostgresqlConn cs $ runDbConn importer
150 else withSqliteConn cs $ runDbConn importer
152 -- | Pull the real connection String out of the configuration.
155 cs = get_connection_string $ connection_string cfg
157 -- | Convenience; we use this everywhere below in 'importer'.
159 migrate_and_import m = dbmigrate m >> dbimport m
162 | dtd == AutoRacingSchedule.dtd = do
163 let m = unpickleDoc AutoRacingSchedule.pickle_message xml
164 maybe (return $ ImportFailed errmsg) migrate_and_import m
166 | dtd == Injuries.dtd = do
167 let m = unpickleDoc Injuries.pickle_message xml
168 maybe (return $ ImportFailed errmsg) migrate_and_import m
170 | dtd == InjuriesDetail.dtd = do
171 let m = unpickleDoc InjuriesDetail.pickle_message xml
172 maybe (return $ ImportFailed errmsg) migrate_and_import m
175 | dtd == News.dtd = do
176 let m = unpickleDoc News.pickle_message xml
177 maybe (return $ ImportFailed errmsg) migrate_and_import m
179 | dtd == Odds.dtd = do
180 let m = unpickleDoc Odds.pickle_message xml
181 maybe (return $ ImportFailed errmsg) migrate_and_import m
183 | dtd == Scores.dtd = do
184 let m = unpickleDoc Scores.pickle_message xml
185 maybe (return $ ImportFailed errmsg) migrate_and_import m
187 | dtd == Weather.dtd = do
188 let m = unpickleDoc Weather.pickle_message xml
189 maybe (return $ ImportFailed errmsg) migrate_and_import m
193 "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
194 return $ ImportUnsupported infomsg
197 errmsg = "Could not unpickle " ++ dtd ++ "."
200 -- | Entry point of the program. It twiddles some knobs for
201 -- configuration options and then calls 'import_file' on each XML
202 -- file given on the command-line.
204 -- Any file successfully processed is then optionally removed, and
212 -- Merge the config file options with the command-line ones,
213 -- prefering the command-line ones.
214 let opt_config = rc_cfg <> cmd_cfg
216 -- Update a default config with any options that have been set in
217 -- either the config file or on the command-line. We initialize
218 -- logging before the missing parameter checks below so that we can
220 let cfg = (def :: Configuration) `merge_optional` opt_config
221 init_logging (log_level cfg) (log_file cfg) (syslog cfg)
223 -- Check the optional config for missing required options.
224 when (null $ OC.xml_files opt_config) $ do
225 report_error "No XML files given."
226 exitWith (ExitFailure exit_no_xml_files)
228 -- We don't do this in parallel (for now?) to keep the error
229 -- messages nice and linear.
230 results <- mapM (import_file cfg) (OC.xml_files opt_config)
232 -- Zip the results with the files list to find out which ones can be
234 let result_pairs = zip (OC.xml_files opt_config) results
235 let victims = [ p | (p, True) <- result_pairs ]
236 let processed_count = length victims
237 report_info $ "Processed " ++ (show processed_count) ++ " document(s) total."
238 when (remove cfg) $ mapM_ (kill True) victims
241 -- | Wrap these two actions into one function so that we don't
242 -- report that the file was removed if the exception handler is
244 remove_and_report path = do
246 report_info $ "Removed processed file " ++ path ++ "."
248 -- | Try to remove @path@ and potentially try again.
249 kill try_again path =
250 (remove_and_report path) `catchIOError` exception_handler
252 -- | A wrapper around threadDelay which takes seconds instead of
253 -- microseconds as its argument.
254 thread_sleep :: Int -> IO ()
255 thread_sleep seconds = do
256 let microseconds = seconds * (10 ^ (6 :: Int))
257 threadDelay microseconds
259 -- | If we can't remove the file, report that, and try once
260 -- more after waiting a few seconds.
261 exception_handler :: IOError -> IO ()
262 exception_handler e = do
263 report_error (show e)
264 report_error $ "Failed to remove imported file " ++ path ++ "."
266 report_info "Waiting 5 seconds to attempt removal again..."
270 report_info $ "Giving up on " ++ path ++ "."