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