]> gitweb.michael.orlitzky.com - dead/htsn-import.git/blob - src/Main.hs
Add a new module, TSN.XML.AutoRacingSchedule, and its tests.
[dead/htsn-import.git] / src / Main.hs
1 {-# LANGUAGE DoAndIfThenElse #-}
2 {-# LANGUAGE NoMonomorphismRestriction #-}
3 module Main
4 where
5
6 -- System imports.
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 (
13 withSqliteConn )
14 import Database.Groundhog.Postgresql (
15 withPostgresqlConn )
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 (
23 ArrowXml,
24 IOStateArrow,
25 XmlTree,
26 (>>>),
27 (/>),
28 getAttrl,
29 getText,
30 hasName,
31 readDocument,
32 runX,
33 unpickleDoc )
34
35 -- Local imports.
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 ),
43 from_rc )
44 import Network.Services.TSN.Report (
45 report_info,
46 report_error )
47 import TSN.DbImport ( DbImport(..), ImportResult(..) )
48 import qualified TSN.XML.AutoRacingSchedule as AutoRacingSchedule (
49 pickle_message )
50 import qualified TSN.XML.Heartbeat as Heartbeat ( verify )
51 import qualified TSN.XML.Injuries as Injuries ( pickle_message )
52 import qualified TSN.XML.InjuriesDetail as InjuriesDetail ( pickle_message )
53 import qualified TSN.XML.News as News ( pickle_message )
54 import qualified TSN.XML.Odds as Odds ( pickle_message )
55 import qualified TSN.XML.Weather as Weather ( pickle_message )
56 import Xml ( DtdName(..), parse_opts )
57
58
59 -- | This is where most of the work happens. This function is called
60 -- on every file that we would like to import. It determines which
61 -- importer to use based on the DTD, attempts to process the file,
62 -- and then returns whether or not it was successful. If the file
63 -- was processed, 'True' is returned. Otherwise, 'False' is
64 -- returned.
65 --
66 -- The implementation is straightforward with one exception: since
67 -- we are already in arrow world with HXT, the @import_with_dtd@
68 -- function is lifted to an 'Arrow' as well with 'arr'. This
69 -- prevents us from having to do a bunch of unwrapping and
70 -- rewrapping with the associated error checking.
71 --
72 import_file :: Configuration -- ^ A configuration object needed for the
73 -- 'backend' and 'connection_string'.
74
75 -> FilePath -- ^ The path of the XML file to import.
76
77 -> IO Bool -- ^ True if we processed the file, False otherwise.
78 import_file cfg path = do
79 results <- parse_and_import `catch` exception_handler
80 case results of
81 [] -> do
82 -- One of the arrows returned "nothing."
83 report_error $ "Unable to determine DTD for file " ++ path ++ "."
84 return False
85 (ImportFailed errmsg:_) -> do
86 report_error errmsg
87 return False
88 (ImportSkipped infomsg:_) -> do
89 -- We processed the message but didn't import anything. Return
90 -- "success" so that the XML file is deleted.
91 report_info infomsg
92 return True
93 (ImportSucceeded:_) -> do
94 report_info $ "Successfully imported " ++ path ++ "."
95 return True
96 (ImportUnsupported infomsg:_) -> do
97 -- For now we return "success" for these too, since we know we don't
98 -- support a bunch of DTDs and we want them to get deleted.
99 report_info infomsg
100 return True
101 where
102 -- | This will catch *any* exception, even the ones thrown by
103 -- Haskell's 'error' (which should never occur under normal
104 -- circumstances).
105 exception_handler :: SomeException -> IO [ImportResult]
106 exception_handler e = do
107 report_error (show e)
108 let errdesc = "Failed to import file " ++ path ++ "."
109 -- Return a nonempty list so we don't claim incorrectly that
110 -- we couldn't parse the DTD.
111 return [ImportFailed errdesc]
112
113 -- | An arrow that reads a document into an 'XmlTree'.
114 readA :: IOStateArrow s a XmlTree
115 readA = readDocument parse_opts path
116
117 -- | An arrow which parses the doctype "SYSTEM" of an 'XmlTree'.
118 -- We use these to determine the parser to use.
119 dtdnameA :: ArrowXml a => a XmlTree DtdName
120 dtdnameA = getAttrl >>> hasName "doctype-SYSTEM" /> getText >>^ DtdName
121
122 -- | Combine the arrows above as well as the function below
123 -- (arrowized with 'arr') into an IO action that does everything
124 -- (parses and then runs the import on what was parsed).
125 --
126 -- The result of runX has type IO [IO ImportResult]. We thus use
127 -- bind (>>=) and sequence to combine all of the IOs into one
128 -- big one outside of the list.
129 parse_and_import :: IO [ImportResult]
130 parse_and_import =
131 runX (readA >>> (dtdnameA &&& returnA) >>> (arr import_with_dtd))
132 >>=
133 sequence
134
135 -- | Takes a ('DtdName', 'XmlTree') pair and uses the 'DtdName'
136 -- to determine which function to call on the 'XmlTree'.
137 import_with_dtd :: (DtdName, XmlTree) -> IO ImportResult
138 import_with_dtd (DtdName dtd,xml)
139 -- We special-case the heartbeat so it doesn't have to run in
140 -- the database monad.
141 | dtd == "Heartbeat.dtd" = Heartbeat.verify xml
142 | otherwise =
143 -- We need NoMonomorphismRestriction here.
144 if backend cfg == Postgres
145 then withPostgresqlConn cs $ runDbConn importer
146 else withSqliteConn cs $ runDbConn importer
147 where
148 -- | Pull the real connection String out of the configuration.
149 cs :: String
150 cs = get_connection_string $ connection_string cfg
151
152 -- | Convenience; we use this everywhere below in 'importer'.
153 migrate_and_import m = dbmigrate m >> dbimport m
154
155 importer
156 | dtd == "Auto_Racing_Schedule_XML.dtd" = do
157 let m = unpickleDoc AutoRacingSchedule.pickle_message xml
158 let errmsg = "Could not unpickle Auto_Racing_Schedule_XML."
159 maybe (return $ ImportFailed errmsg) migrate_and_import m
160
161 | dtd == "injuriesxml.dtd" = do
162 let m = unpickleDoc Injuries.pickle_message xml
163 let errmsg = "Could not unpickle injuriesxml."
164 maybe (return $ ImportFailed errmsg) migrate_and_import m
165
166 | dtd == "Injuries_Detail_XML.dtd" = do
167 let m = unpickleDoc InjuriesDetail.pickle_message xml
168 let errmsg = "Could not unpickle Injuries_Detail_XML."
169 maybe (return $ ImportFailed errmsg) migrate_and_import m
170
171
172 | dtd == "newsxml.dtd" = do
173 let m = unpickleDoc News.pickle_message xml
174 let errmsg = "Could not unpickle newsxml."
175 maybe (return $ ImportFailed errmsg) migrate_and_import m
176
177 | dtd == "Odds_XML.dtd" = do
178 let m = unpickleDoc Odds.pickle_message xml
179 let errmsg = "Could not unpickle Odds_XML."
180 maybe (return $ ImportFailed errmsg) migrate_and_import m
181
182 | dtd == "weatherxml.dtd" = do
183 let m = unpickleDoc Weather.pickle_message xml
184 let errmsg = "Could not unpickle weatherxml."
185 maybe (return $ ImportFailed errmsg) migrate_and_import m
186
187 | otherwise = do
188 let infomsg =
189 "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
190 return $ ImportUnsupported infomsg
191
192
193 -- | Entry point of the program. It twiddles some knobs for
194 -- configuration options and then calls 'import_file' on each XML
195 -- file given on the command-line.
196 --
197 -- Any file successfully processed is then optionally removed, and
198 -- we're done.
199 --
200 main :: IO ()
201 main = do
202 rc_cfg <- OC.from_rc
203 cmd_cfg <- get_args
204
205 -- Merge the config file options with the command-line ones,
206 -- prefering the command-line ones.
207 let opt_config = rc_cfg <> cmd_cfg
208
209 -- Update a default config with any options that have been set in
210 -- either the config file or on the command-line. We initialize
211 -- logging before the missing parameter checks below so that we can
212 -- log the errors.
213 let cfg = (def :: Configuration) `merge_optional` opt_config
214 init_logging (log_level cfg) (log_file cfg) (syslog cfg)
215
216 -- Check the optional config for missing required options.
217 when (null $ OC.xml_files opt_config) $ do
218 report_error "No XML files given."
219 exitWith (ExitFailure exit_no_xml_files)
220
221 -- We don't do this in parallel (for now?) to keep the error
222 -- messages nice and linear.
223 results <- mapM (import_file cfg) (OC.xml_files opt_config)
224
225 -- Zip the results with the files list to find out which ones can be
226 -- deleted.
227 let result_pairs = zip (OC.xml_files opt_config) results
228 let victims = [ p | (p, True) <- result_pairs ]
229 let processed_count = length victims
230 report_info $ "Processed " ++ (show processed_count) ++ " document(s) total."
231 when (remove cfg) $ mapM_ (kill True) victims
232
233 where
234 -- | Wrap these two actions into one function so that we don't
235 -- report that the file was removed if the exception handler is
236 -- run.
237 remove_and_report path = do
238 removeFile path
239 report_info $ "Removed processed file " ++ path ++ "."
240
241 -- | Try to remove @path@ and potentially try again.
242 kill try_again path =
243 (remove_and_report path) `catchIOError` exception_handler
244 where
245 -- | A wrapper around threadDelay which takes seconds instead of
246 -- microseconds as its argument.
247 thread_sleep :: Int -> IO ()
248 thread_sleep seconds = do
249 let microseconds = seconds * (10 ^ (6 :: Int))
250 threadDelay microseconds
251
252 -- | If we can't remove the file, report that, and try once
253 -- more after waiting a few seconds.
254 exception_handler :: IOError -> IO ()
255 exception_handler e = do
256 report_error (show e)
257 report_error $ "Failed to remove imported file " ++ path ++ "."
258 if try_again then do
259 report_info "Waiting 5 seconds to attempt removal again..."
260 thread_sleep 5
261 kill False path
262 else
263 report_info $ "Giving up on " ++ path ++ "."