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