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