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