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