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