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