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