]> gitweb.michael.orlitzky.com - dead/htsn-import.git/blob - src/Main.hs
Disable TSN.XML.MLBBoxScore in preparation for a release.
[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 = go MLBEarlyLine.pickle_message
221
222 | dtd == News.dtd =
223 -- Some of the newsxml docs are busted in predictable ways.
224 -- We want them to "succeed" so that they're deleted.
225 -- We already know we can't parse them.
226 if News.has_only_single_sms xml
227 then go News.pickle_message
228 else do
229 let msg = "Unsupported newsxml.dtd with multiple SMS " ++
230 "(" ++ path ++ ")"
231 return $ ImportUnsupported msg
232 | dtd == Odds.dtd = go Odds.pickle_message
233
234 | dtd == ScheduleChanges.dtd = go ScheduleChanges.pickle_message
235
236 | dtd == Scores.dtd = go Scores.pickle_message
237
238 -- SportInfo and GameInfo appear last in the guards
239 | dtd == Weather.dtd =
240 -- Some of the weatherxml docs are busted in predictable ways.
241 -- We want them to "succeed" so that they're deleted.
242 -- We already know we can't parse them.
243 if Weather.is_type1 xml
244 then if Weather.teams_are_normal xml
245 then go Weather.pickle_message
246 else do
247 let msg = "Teams in reverse order in weatherxml.dtd" ++
248 " (" ++ path ++ ")"
249 return $ ImportUnsupported msg
250 else do
251 let msg = "Unsupported weatherxml.dtd type (" ++ path ++ ")"
252 return $ ImportUnsupported msg
253
254 | dtd `elem` GameInfo.dtds = do
255 let either_m = GameInfo.parse_xml dtd xml
256 case either_m of
257 -- This might give us a slightly better error
258 -- message than the default 'errmsg'.
259 Left err -> return $ ImportFailed (format_parse_error err)
260 Right m -> migrate_and_import m
261
262 | dtd `elem` SportInfo.dtds = do
263 let either_m = SportInfo.parse_xml dtd xml
264 case either_m of
265 -- This might give us a slightly better error
266 -- message than the default 'errmsg'.
267 Left err -> return $ ImportFailed (format_parse_error err)
268 Right m -> migrate_and_import m
269
270 | otherwise = do
271 let infomsg =
272 "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
273 return $ ImportUnsupported infomsg
274
275
276
277 -- | Entry point of the program. It twiddles some knobs for
278 -- configuration options and then calls 'import_file' on each XML
279 -- file given on the command-line.
280 --
281 -- Any file successfully processed is then optionally removed, and
282 -- we're done.
283 --
284 main :: IO ()
285 main = do
286 rc_cfg <- OC.from_rc
287 cmd_cfg <- get_args
288
289 -- Merge the config file options with the command-line ones,
290 -- prefering the command-line ones.
291 let opt_config = rc_cfg <> cmd_cfg
292
293 -- Update a default config with any options that have been set in
294 -- either the config file or on the command-line. We initialize
295 -- logging before the missing parameter checks below so that we can
296 -- log the errors.
297 let cfg = (def :: Configuration) `merge_optional` opt_config
298 init_logging (log_level cfg) (log_file cfg) (syslog cfg)
299
300 -- Check the optional config for missing required options.
301 when (null $ OC.xml_files opt_config) $ do
302 report_error "No XML files given."
303 exitWith (ExitFailure exit_no_xml_files)
304
305 -- We don't do this in parallel (for now?) to keep the error
306 -- messages nice and linear.
307 results <- mapM (import_file cfg) (OC.xml_files opt_config)
308
309 -- Zip the results with the files list to find out which ones can be
310 -- deleted.
311 let result_pairs = zip (OC.xml_files opt_config) results
312 let victims = [ p | (p, True) <- result_pairs ]
313 let processed_count = length victims
314 report_info $ "Processed " ++ (show processed_count) ++ " document(s) total."
315 when (remove cfg) $ mapM_ (kill True) victims
316
317 where
318 -- | Wrap these two actions into one function so that we don't
319 -- report that the file was removed if the exception handler is
320 -- run.
321 remove_and_report path = do
322 removeFile path
323 report_info $ "Removed processed file " ++ path ++ "."
324
325 -- | Try to remove @path@ and potentially try again.
326 kill try_again path =
327 (remove_and_report path) `catchIOError` exception_handler
328 where
329 -- | A wrapper around threadDelay which takes seconds instead of
330 -- microseconds as its argument.
331 thread_sleep :: Int -> IO ()
332 thread_sleep seconds = do
333 let microseconds = seconds * (10 ^ (6 :: Int))
334 threadDelay microseconds
335
336 -- | If we can't remove the file, report that, and try once
337 -- more after waiting a few seconds.
338 exception_handler :: IOError -> IO ()
339 exception_handler e = do
340 report_error (show e)
341 report_error $ "Failed to remove imported file " ++ path ++ "."
342 if try_again then do
343 report_info "Waiting 5 seconds to attempt removal again..."
344 thread_sleep 5
345 kill False path
346 else
347 report_info $ "Giving up on " ++ path ++ "."