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