]> gitweb.michael.orlitzky.com - dead/htsn-import.git/blob - src/Main.hs
Add GameInfo DTDs and an explanation to the man page.
[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 )
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 | dtd == Injuries.dtd = do
169 let m = unpickleDoc Injuries.pickle_message xml
170 maybe (return $ ImportFailed errmsg) migrate_and_import m
171
172 | dtd == InjuriesDetail.dtd = do
173 let m = unpickleDoc InjuriesDetail.pickle_message xml
174 maybe (return $ ImportFailed errmsg) migrate_and_import m
175
176
177 | dtd == News.dtd = do
178 let m = unpickleDoc News.pickle_message xml
179 maybe (return $ ImportFailed errmsg) migrate_and_import m
180
181 | dtd == Odds.dtd = do
182 let m = unpickleDoc Odds.pickle_message xml
183 maybe (return $ ImportFailed errmsg) migrate_and_import m
184
185 | dtd == Scores.dtd = do
186 let m = unpickleDoc Scores.pickle_message xml
187 maybe (return $ ImportFailed errmsg) migrate_and_import m
188
189 | dtd == Weather.dtd = do
190 let m = unpickleDoc Weather.pickle_message xml
191 maybe (return $ ImportFailed errmsg) migrate_and_import m
192
193 | dtd `elem` GameInfo.dtds = do
194 let either_m = GameInfo.parse_xml dtd xml
195 case either_m of
196 -- This might give us a slightly better error
197 -- message than the default 'errmsg'.
198 Left err -> return $ ImportFailed err
199 Right m -> migrate_and_import m
200
201 | dtd `elem` SportInfo.dtds = undefined
202
203 | otherwise = do
204 let infomsg =
205 "Unrecognized DTD in " ++ path ++ ": " ++ dtd ++ "."
206 return $ ImportUnsupported infomsg
207
208 where
209 errmsg = "Could not unpickle " ++ dtd ++ "."
210
211
212 -- | Entry point of the program. It twiddles some knobs for
213 -- configuration options and then calls 'import_file' on each XML
214 -- file given on the command-line.
215 --
216 -- Any file successfully processed is then optionally removed, and
217 -- we're done.
218 --
219 main :: IO ()
220 main = do
221 rc_cfg <- OC.from_rc
222 cmd_cfg <- get_args
223
224 -- Merge the config file options with the command-line ones,
225 -- prefering the command-line ones.
226 let opt_config = rc_cfg <> cmd_cfg
227
228 -- Update a default config with any options that have been set in
229 -- either the config file or on the command-line. We initialize
230 -- logging before the missing parameter checks below so that we can
231 -- log the errors.
232 let cfg = (def :: Configuration) `merge_optional` opt_config
233 init_logging (log_level cfg) (log_file cfg) (syslog cfg)
234
235 -- Check the optional config for missing required options.
236 when (null $ OC.xml_files opt_config) $ do
237 report_error "No XML files given."
238 exitWith (ExitFailure exit_no_xml_files)
239
240 -- We don't do this in parallel (for now?) to keep the error
241 -- messages nice and linear.
242 results <- mapM (import_file cfg) (OC.xml_files opt_config)
243
244 -- Zip the results with the files list to find out which ones can be
245 -- deleted.
246 let result_pairs = zip (OC.xml_files opt_config) results
247 let victims = [ p | (p, True) <- result_pairs ]
248 let processed_count = length victims
249 report_info $ "Processed " ++ (show processed_count) ++ " document(s) total."
250 when (remove cfg) $ mapM_ (kill True) victims
251
252 where
253 -- | Wrap these two actions into one function so that we don't
254 -- report that the file was removed if the exception handler is
255 -- run.
256 remove_and_report path = do
257 removeFile path
258 report_info $ "Removed processed file " ++ path ++ "."
259
260 -- | Try to remove @path@ and potentially try again.
261 kill try_again path =
262 (remove_and_report path) `catchIOError` exception_handler
263 where
264 -- | A wrapper around threadDelay which takes seconds instead of
265 -- microseconds as its argument.
266 thread_sleep :: Int -> IO ()
267 thread_sleep seconds = do
268 let microseconds = seconds * (10 ^ (6 :: Int))
269 threadDelay microseconds
270
271 -- | If we can't remove the file, report that, and try once
272 -- more after waiting a few seconds.
273 exception_handler :: IOError -> IO ()
274 exception_handler e = do
275 report_error (show e)
276 report_error $ "Failed to remove imported file " ++ path ++ "."
277 if try_again then do
278 report_info "Waiting 5 seconds to attempt removal again..."
279 thread_sleep 5
280 kill False path
281 else
282 report_info $ "Giving up on " ++ path ++ "."