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