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