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