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