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