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