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