]> matita.cs.unibo.it Git - helm.git/blob - helm/uwobo/uwobo.ml
- catch libxslt error and debugging messages and return them to the user
[helm.git] / helm / uwobo / uwobo.ml
1 (*
2  * Copyright (C) 2003:
3  *    Stefano Zacchiroli <zack@cs.unibo.it>
4  *    for the HELM Team http://helm.cs.unibo.it/
5  *
6  *  This file is part of HELM, an Hypertextual, Electronic
7  *  Library of Mathematics, developed at the Computer Science
8  *  Department, University of Bologna, Italy.
9  *
10  *  HELM is free software; you can redistribute it and/or
11  *  modify it under the terms of the GNU General Public License
12  *  as published by the Free Software Foundation; either version 2
13  *  of the License, or (at your option) any later version.
14  *
15  *  HELM is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with HELM; if not, write to the Free Software
22  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23  *  MA  02111-1307, USA.
24  *
25  *  For details, see the HELM World-Wide-Web page,
26  *  http://helm.cs.unibo.it/
27  *)
28
29 open Printf;;
30 open Uwobo_common;;
31
32  (* debugging settings *)
33 let debug = false;;
34 let debug_level = `Notice;;
35 let debug_print s = if debug then prerr_endline s;;
36 Http_common.debug := false;;
37 let logfile = Some "uwobo.log";;  (* relative to execution dir *)
38 let logfile_perm = 0o640;;
39
40   (* other settings *)
41 let daemon_name = "UWOBO OCaml";;
42 let default_port = 58080;;
43 let port_env_var = "UWOBO_PORT";;
44 let default_media_type = "text/html";;
45 let default_encoding = "utf8";;
46 let port =
47   try
48     int_of_string (Sys.getenv port_env_var)
49   with
50   | Not_found -> default_port
51   | Failure "int_of_string" ->
52       prerr_endline "Warning: invalid port, reverting to default";
53       default_port
54 ;;
55
56 let respond_html body outchan =
57   Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
58 ;;
59
60   (** perform an 'action' that can be applied to a list of keys or, if no keys
61   was given, to all keys *)
62 let act_on_keys keys_param styles logger per_key_action all_keys_action logmsg
63 =
64   let keys =
65     try
66       Pcre.split ~pat:"," keys_param
67     with Http_types.Param_not_found _ -> []
68   in
69   match keys with
70   | [] -> (* no key provided, act on all stylesheets *)
71       logger#log (sprintf "%s all stylesheets ..." logmsg);
72       (try all_keys_action () with e -> logger#log (Printexc.to_string e))
73   | keys ->
74       List.iter
75         (fun key -> (* act on a single stylesheet *)
76           logger#log (sprintf "%s stylesheet %s" logmsg key);
77           (try per_key_action key with e -> logger#log (Printexc.to_string e)))
78         keys
79 ;;
80
81   (** parse parameters for '/apply' action *)
82 let parse_apply_params =
83   let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
84   let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
85   let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
86   List.fold_left
87     (fun (old_params, old_properties) (name, value) ->
88       match name with
89       | name when is_global_param name ->
90           let name = Pcre.replace ~pat:"^param\\." name in
91           ((fun x -> (old_params x) @ [name, value]), old_properties)
92       | name when is_local_param name ->
93           let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
94           let (key, name) = (pieces.(1), pieces.(2)) in
95           ((function
96             | x when x = key -> [name, value] @ (old_params x)
97             | x -> old_params x),
98            old_properties)
99       | name when is_property name ->
100           let name = Pcre.replace ~pat:"^prop\\." name in
101           (old_params, ((name, value) :: old_properties))
102       | _ -> (old_params, old_properties))
103     ((fun _ -> []), []) (* no parameters, no properties *)
104 ;;
105
106   (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
107   on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
108   received from ~res_pipe *)
109 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
110 (*   debug_print (sprintf "Sending command '%s' to grandparent ..." cmd); *)
111   output_string cmd_pipe (cmd ^ "\n");  (* send command to grandfather *)
112   flush cmd_pipe;
113   let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
114   let (read_fds, _, _) =  (* wait for an answer *)
115     Unix.select [res_pipe_fd] [] [] 60.0
116   in
117   (match read_fds with
118   | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
119       Http_daemon.send_basic_headers ~code:200 outchan;
120       Http_daemon.send_header "Content-Type" "text/html" outchan;
121       Http_daemon.send_CRLF outchan;
122       (try
123         while true do
124           output_string outchan ((input_line res_pipe) ^ "\n")
125         done
126       with End_of_file -> flush outchan)
127   | _ ->  (* no answer received from grandfather *)
128       return_error "Timeout!" outchan)
129 ;;
130
131 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE) =
132   (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ")
133 ;;
134
135 exception Restart_HTTP_daemon;;
136
137   (** log a list of libxslt's messages using a processing logger *)
138 let log_libxslt_msgs logger =
139   List.iter
140     (function
141       | Uwobo_styles.LibXsltErrorMsg msg ->
142           logger#logBold ("LibXSLT ERROR: " ^ msg)
143       | Uwobo_styles.LibXsltDebugMsg msg ->
144           logger#logEmph ("LibXSLT DEBUG " ^ msg))
145 ;;
146
147   (* request handler action
148   @param syslogger Uwobo_logger.sysLogger instance used for logginf
149   @param styles Uwobo_styles.styles instance which keeps the stylesheets list
150   @param cmd_pipe output _channel_ used to _write_ update messages
151   @param res_pipe input _channel_ used to _read_ grandparent results
152   @param req http request instance
153   @param outchan output channel connected to http client
154   *)
155 let callback
156   ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
157   =
158   try
159     syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
160     syslogger#log `Debug (sprintf "Received request: %s" req#path);
161     (match req#path with
162     | "/add" ->
163         (let bindings = req#paramAll "bind" in
164         if bindings = [] then
165           return_error "No [key,stylesheet] binding provided" outchan
166         else begin
167           let cmd = sprintf "add %s" (String.concat ";" bindings) in
168           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
169         end)
170     | "/remove" ->
171           let cmd = sprintf "remove %s" (req#param "keys") in
172           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
173     | "/reload" ->
174           let cmd = sprintf "reload %s" (req#param "keys") in
175           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
176     | "/list" ->
177         (let log = new Uwobo_logger.processingLogger () in
178         (match styles#list with
179         | [] -> log#log "No stylesheets loaded (yet)!"
180         | l ->
181             log#log "Stylesheets list:";
182             List.iter (fun s -> log#log s) l);
183         respond_html log#asHtml outchan)
184     | "/apply" ->
185         let logger = new Uwobo_logger.processingLogger () in
186         let xmluri = req#param "xmluri" in
187         let keys = Pcre.split ~pat:"," (req#param "keys") in
188         (* notation: "local" parameters are those defined on a per-stylesheet
189         pasis (i.e. param.key.param=value), "global" parameters are those
190         defined for all stylesheets (i.e. param.param=value) *)
191         let (params, props) = parse_apply_params req#params in
192         syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
193         let domImpl = Gdome.domImplementation () in
194         let input = domImpl#createDocumentFromURI ~uri:xmluri () in
195         syslogger#log `Debug "Applying stylesheet chain ...";
196         (try
197           let (write_result, media_type, encoding) = (* out_channel -> unit *)
198             let res = Uwobo_engine.apply
199               ~logger:syslogger ~styles ~keys ~input ~params ~props in
200             res
201           in
202           let content_type = (* value of Content-Type HTTP response header *)
203             sprintf "%s; charset=%s"
204               (match media_type with None -> default_media_type | Some t -> t)
205               (match encoding with None -> default_encoding | Some e -> e)
206           in
207           syslogger#log `Debug
208             (sprintf "sending output to client (Content-Type: %s)...."
209               content_type);
210           Http_daemon.send_basic_headers ~code:200 outchan;
211           Http_daemon.send_header "Content-Type" content_type outchan;
212           Http_daemon.send_CRLF outchan;
213           write_result outchan
214         with Uwobo_failure errmsg ->
215           return_error
216             (sprintf "Stylesheet chain application failed: %s" errmsg)
217             outchan)
218     | "/help" -> respond_html usage_string outchan
219     | invalid_request ->
220         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
221     syslogger#log `Debug (sprintf "%s done!" req#path);
222   with
223   | Http_types.Param_not_found attr_name ->
224       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
225   | exc ->
226       return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
227 ;;
228
229   (* UWOBO's startup *)
230 let main () =
231     (* (1) system logger *)
232   let logger_outchan =
233     match logfile with
234     | None -> stderr
235     | Some f ->
236         open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm f
237   in
238   let syslogger =
239     new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
240   in
241   syslogger#enable;
242     (* (2) stylesheets list *)
243   let styles = new Uwobo_styles.styles in
244     (* (3) clean up actions *)
245   let last_process = ref true in
246   let http_child = ref None in
247   let die_nice () = (** at_exit callback *)
248     if !last_process then begin
249       (match !http_child with
250       | None -> ()
251       | Some pid -> Unix.kill pid Sys.sigterm);
252       syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
253       syslogger#disable;
254       close_out logger_outchan
255     end
256   in
257   at_exit die_nice;
258   ignore (Sys.signal Sys.sigterm
259     (Sys.Signal_handle (fun _ -> raise Sys.Break)));
260   syslogger#log `Notice
261     (sprintf "%s started and listening on port %d" daemon_name port);
262   syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
263   Unix.putenv "http_proxy" "";  (* reset http_proxy to avoid libxslt problems *)
264   while true do
265     let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
266     let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
267     match Unix.fork () with
268     | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
269         http_child := Some child;
270         let stop_http_daemon () =  (* kill child *)
271           debug_print (sprintf "UWOBOmaster: killing pid %d" child);
272           Unix.kill child Sys.sigterm;  (* kill child ... *)
273           ignore (Unix.waitpid [] child);  (* ... and its zombie *)
274         in
275         Unix.close cmd_pipe_entrance;
276         Unix.close res_pipe_exit;
277         let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
278         let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
279         (try
280           while true do
281             (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
282             child process has been killed *)
283             debug_print "UWOBOmaster: waiting for commands ...";
284             let cmd = input_line cmd_pipe in
285             debug_print (sprintf "UWOBOmaster: received %s command" cmd);
286             (match cmd with  (* command from grandchild *)
287             | "test" ->
288                 stop_http_daemon ();
289                 output_string res_pipe "UWOBOmaster: Hello, world!\n";
290                 flush res_pipe;
291                 raise Restart_HTTP_daemon
292             | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
293                 let bindings =
294                   Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
295                 in
296                 stop_http_daemon ();
297                 let log = new Uwobo_logger.processingLogger () in
298                 List.iter
299                   (fun binding -> (* add a <key, stylesheet> binding *)
300                     let pieces = Pcre.split ~pat:"," binding in
301                     match pieces with
302                     | [key; style] ->
303                         log#log (sprintf "adding binding <%s,%s>" key style);
304                         (try
305                           log_libxslt_msgs log (styles#add key style)
306                         with e ->
307                           log#log (Printexc.to_string e))
308                     | _ -> log#log (sprintf "invalid binding %s" binding))
309                   bindings;
310                 output_string res_pipe log#asHtml;
311                 flush res_pipe;
312                 raise Restart_HTTP_daemon
313             | line when Pcre.pmatch ~rex:remove_cmd_RE line ->  (* /remove *)
314                 stop_http_daemon ();
315                 let arg = Pcre.replace ~rex:remove_cmd_RE line in
316                 let logger = new Uwobo_logger.processingLogger () in
317                 act_on_keys
318                   arg styles logger
319                   (fun key -> log_libxslt_msgs logger (styles#remove key))
320                   (fun () -> log_libxslt_msgs logger styles#removeAll)
321                   "removing";
322                 output_string res_pipe (logger#asHtml);
323                 raise Restart_HTTP_daemon
324             | line when Pcre.pmatch ~rex:reload_cmd_RE line ->  (* /reload *)
325                 stop_http_daemon ();
326                 let arg = Pcre.replace ~rex:reload_cmd_RE line in
327                 let logger = new Uwobo_logger.processingLogger () in
328                 act_on_keys
329                   arg styles logger
330                   (fun key -> log_libxslt_msgs logger (styles#reload key))
331                   (fun () -> log_libxslt_msgs logger styles#reloadAll)
332                   "reloading";
333                 output_string res_pipe (logger#asHtml);
334                 raise Restart_HTTP_daemon
335             | cmd ->  (* invalid interprocess command received *)
336                 syslogger#log `Warning
337                   (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
338           done
339         with Restart_HTTP_daemon ->
340           close_in cmd_pipe;  (* these calls close also fds *)
341           close_out res_pipe;)
342     | 0 ->  (* (5) child: serve http requests *)
343         Unix.close cmd_pipe_exit;
344         Unix.close res_pipe_entrance;
345         last_process := false;
346         let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
347         let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
348         debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
349           (* next invocation doesn't return, process will keep on serving HTTP
350           requests until it will get killed by father *)
351         Http_daemon.start'~port ~mode:`Fork
352           (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
353     | _ (* < 0 *) ->  (* fork failed :-((( *)
354         failwith "Can't fork :-("
355   done
356 ;;
357
358   (* daemon initialization *)
359 try
360   Sys.catch_break true;
361   main ()
362 with Sys.Break -> ()  (* 'die_nice' registered with at_exit *)
363 ;;
364