]> matita.cs.unibo.it Git - helm.git/blob - helm/uwobo/uwobo.ml
d680f9e2825d6ff6f80ff10efb90188a2e2c53a6
[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
39   (* First of all we load the configuration *)
40 let _ =
41  let configuration_file = "/projects/helm/etc/uwobo.conf.xml" in
42   Helm_registry.load_from configuration_file
43 ;;
44
45   (* other settings *)
46 let daemon_name = "UWOBO OCaml" ;;
47 let default_media_type = "text/html" ;;
48 let default_encoding = "utf8" ;;
49
50 let get_media_type props =
51  try
52   List.assoc "media-type" props
53  with
54   Not_found -> default_media_type
55 ;;
56
57 let get_encoding props =
58  try
59   List.assoc "encoding" props
60  with
61   Not_found -> default_encoding
62 ;;
63
64 let port = Helm_registry.get_int "uwobo.port";;
65
66 let logfilename_of_port port =
67  let basename = Helm_registry.get "uwobo.log_basename" in
68  let extension = Helm_registry.get "uwobo.log_extension" in
69   basename ^ "_" ^ string_of_int port ^ extension
70 ;;
71
72 let logfile = logfilename_of_port port;;
73 let logfile_perm = 0o640 ;;
74
75 let respond_html body outchan =
76   Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
77 ;;
78
79   (** perform an 'action' that can be applied to a list of keys or, if no keys
80   was given, to all keys *)
81 let act_on_keys
82   keys_param styles logger per_key_action all_keys_action all_keys logmsg
83 =
84   let keys =
85     try
86       Pcre.split ~pat:"," keys_param
87     with Http_types.Param_not_found _ -> []
88   in
89   match keys with
90   | [] -> (* no key provided, act on all stylesheets *)
91       logger#log (sprintf "%s all stylesheets (keys = %s) ..."
92         logmsg (String.concat ", " all_keys));
93       (try all_keys_action () with e -> logger#log (Printexc.to_string e));
94       logger#log (sprintf "Done! (all stylesheets)")
95   | keys ->
96       List.iter
97         (fun key -> (* act on a single stylesheet *)
98           logger#log (sprintf "%s stylesheet %s" logmsg key);
99           (try per_key_action key with e -> logger#log (Printexc.to_string e));
100           logger#log (sprintf "Done! (stylesheet %s)" key))
101         keys
102 ;;
103
104   (** parse parameters for '/apply' action *)
105 let parse_apply_params =
106   let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
107   let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
108   let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
109   List.fold_left
110     (fun (old_params, old_properties) (name, value) ->
111       match name with
112       | name when is_global_param name ->
113           let name = Pcre.replace ~pat:"^param\\." name in
114           ((fun x -> (old_params x) @ [name, value]), old_properties)
115       | name when is_local_param name ->
116           let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
117           let (key, name) = (pieces.(1), pieces.(2)) in
118           ((function
119             | x when x = key -> [name, value] @ (old_params x)
120             | x -> old_params x),
121            old_properties)
122       | name when is_property name ->
123           let name = Pcre.replace ~pat:"^prop\\." name in
124           (old_params, ((name, value) :: old_properties))
125       | _ -> (old_params, old_properties))
126     ((fun _ -> []), []) (* no parameters, no properties *)
127 ;;
128
129   (** Parse libxslt's message modes for error and debugging messages. Default is
130   to ignore mesages of both kind *)
131 let parse_libxslt_msgs_mode (req: Http_types.request) =
132   ((try
133     (match req#param "errormode" with
134     | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
135     | s when String.lowercase s = "comment" -> LibXsltMsgComment
136     | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
137     | err ->
138         raise (Uwobo_failure
139           (sprintf
140             "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
141             err "errormode" "ignore" "comment")))
142   with Http_types.Param_not_found _ -> LibXsltMsgIgnore),
143   (try
144     (match req#param "debugmode" with
145     | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
146     | s when String.lowercase s = "comment" -> LibXsltMsgComment
147     | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
148     | err ->
149         raise (Uwobo_failure
150           (sprintf
151             "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
152             err "debugmode" "ignore" "comment")))
153   with Http_types.Param_not_found _ -> LibXsltMsgIgnore))
154 ;;
155
156   (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
157   on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
158   received from ~res_pipe *)
159 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
160 (*   debug_print (sprintf "Sending command '%s' to grandparent ..." cmd); *)
161   output_string cmd_pipe (cmd ^ "\n");  (* send command to grandfather *)
162   flush cmd_pipe;
163   let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
164   let (read_fds, _, _) =  (* wait for an answer *)
165     Unix.select [res_pipe_fd] [] [] 60.0
166   in
167   (match read_fds with
168   | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
169       Http_daemon.send_basic_headers ~code:200 outchan;
170       Http_daemon.send_header "Content-Type" "text/html" outchan;
171       Http_daemon.send_CRLF outchan;
172       (try
173         while true do
174           output_string outchan ((input_line res_pipe) ^ "\n")
175         done
176       with End_of_file -> flush outchan)
177   | _ ->  (* no answer received from grandfather *)
178       return_error "Timeout!" outchan)
179 ;;
180
181 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE, kill_cmd_RE) =
182   (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ",
183    Pcre.regexp "^kill")
184 ;;
185
186   (** raised by child processes when HTTP daemon process have to be restarted *)
187 exception Restart_HTTP_daemon ;;
188
189   (** log a list of libxslt's messages using a processing logger *)
190 let log_libxslt_msgs logger libxslt_logger =
191   List.iter
192     (function
193       | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
194       | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
195     libxslt_logger#msgs
196 ;;
197
198   (* LibXSLT logger *)
199 let veillogger = new Uwobo_common.libXsltLogger ;;
200
201   (* start_new_session cmd_pipe_exit res_pipe_entrance outchan port logfile
202   @param cmd_pipe Pipe to be closed before forking
203   @param res_pipe Pipe to be closed before forking
204   @param outchan  To be closed before forking
205   @param port The port to be used
206   @param logfile The logfile to redirect the stdout and sterr to
207   *)
208   (* It can raise Failure "Connection refused" *)
209   (* It can raise Failure "Port already in use" *)
210 let start_new_session cmd_pipe res_pipe outchan port logfile =
211  (* Let's check that the port is free *)
212  (try
213    ignore
214     (Http_client.http_get
215       ("http://127.0.0.1:" ^ string_of_int port ^ "/help")) ;
216    raise (Failure "Port already in use")
217   with
218    Unix.Unix_error (Unix.ECONNREFUSED, _, _) -> ()
219  ) ;
220  match Unix.fork () with
221     0 ->
222       Unix.handle_unix_error
223        (function () ->
224          (* 1. We close all the open pipes to avoid duplicating them *)
225          Unix.close (Unix.descr_of_out_channel cmd_pipe) ;
226          Unix.close (Unix.descr_of_in_channel res_pipe) ;
227          Unix.close (Unix.descr_of_out_channel outchan) ;
228          (* 2. We redirect stdout and stderr to the logfile *)
229          Unix.close Unix.stdout ;
230          assert
231           (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
232             0o664 = Unix.stdout) ;
233          Unix.close Unix.stderr ;
234          assert
235           (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
236             0o664 = Unix.stderr) ;
237          prerr_endline "***** Starting a new session" ;
238
239          (* 3. We set up a new environment *)
240          let environment =
241           (* Here I am loosing the current value of port_env_var; *)
242           (* this should not matter                               *)
243           Unix.putenv "UWOBO__PORT" (string_of_int port) ;
244           Unix.environment ()
245          in
246          (* 4. We exec a new copy of uwobo *)
247          Unix.execve Sys.executable_name [||] environment ; 
248          (* It should never reach this point *)
249          assert false
250        ) ()
251   | child when child > 0 ->
252      (* let's check if the new UWOBO started correctly *)
253      Unix.sleep 5 ;
254      (* It can raise Failure "Connection refused" *)
255      (try
256        ignore
257          (Http_client.http_get
258            ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
259      with Unix.Unix_error (Unix.ECONNREFUSED, _, _) ->
260        raise (Failure "Connection refused"))
261   | _ -> failwith "Can't fork :-("
262 ;;
263
264   (* request handler action
265   @param syslogger Uwobo_logger.sysLogger instance used for logginf
266   @param styles Uwobo_styles.styles instance which keeps the stylesheets list
267   @param cmd_pipe output _channel_ used to _write_ update messages
268   @param res_pipe input _channel_ used to _read_ grandparent results
269   @param req http request instance
270   @param outchan output channel connected to http client
271   *)
272 let callback
273   ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
274   =
275   try
276     syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
277     syslogger#log `Debug (sprintf "Received request: %s" req#path);
278     (match req#path with
279     | "/add" ->
280         (let bindings = req#paramAll "bind" in
281         if bindings = [] then
282           return_error "No [key,stylesheet] binding provided" outchan
283         else begin
284           let cmd = sprintf "add %s" (String.concat ";" bindings) in
285           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
286         end)
287     | "/kill" ->
288         let logger = new Uwobo_logger.processingLogger () in
289          logger#log "Exiting" ;
290          respond_html logger#asHtml outchan ;
291          let cmd = "kill" in
292           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
293     | "/newsession" ->
294         let logger = new Uwobo_logger.processingLogger () in
295         let port = int_of_string (req#param "port") in
296         let logfile = logfilename_of_port port in
297         (try
298           start_new_session cmd_pipe res_pipe outchan port logfile ;
299           logger#log (sprintf "New session started: port = %d" port) ;
300           respond_html logger#asHtml outchan
301          with
302             Failure "int_of_string" ->
303              logger#log (sprintf "Invalid port number") ;
304              respond_html logger#asHtml outchan
305           | Failure "Port already in use" ->
306              Uwobo_common.return_error "port already in use" outchan
307           | Failure "Connection refused" ->
308              let log = ref [] in
309               (try
310                 let ch = open_in logfile in
311                  while true do log := (input_line ch ^ "\n") :: !log ; done
312                with
313                   Sys_error _
314                 | End_of_file -> ()
315               ) ;
316               let rec get_last_lines acc =
317                function
318                   (n,he::tl) when n > 0 ->
319                     get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
320                 | _ -> acc
321               in
322                (* we just show the last 10 lines of the log file *)
323                let msg =
324                 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
325                  get_last_lines "" (10,!log)
326                in
327                 Uwobo_common.return_error "daemon not initialized"
328                  ~body:msg outchan)
329     | "/remove" ->
330           let cmd = sprintf "remove %s" (req#param "keys") in
331           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
332     | "/reload" ->
333           let cmd = sprintf "reload %s" (req#param "keys") in
334           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
335     | "/list" ->
336         (let logger = new Uwobo_logger.processingLogger () in
337         (match styles#list with
338         | [] -> logger#log "No stylesheets loaded (yet)!"
339         | l ->
340             logger#log "Stylesheets list:";
341             List.iter (fun s -> logger#log s) l);
342         respond_html logger#asHtml outchan)
343     | "/apply" ->
344         let logger = new Uwobo_logger.processingLogger () in
345         veillogger#clearMsgs;
346         let xmluri = req#param "xmluri" in
347         let keys = Pcre.split ~pat:"," (req#param "keys") in
348         (* notation: "local" parameters are those defined on a per-stylesheet
349         pasis (i.e. param.key.param=value), "global" parameters are those
350         defined for all stylesheets (i.e. param.param=value) *)
351         let (params, props) = parse_apply_params req#params in
352         let (libxslt_errormode, libxslt_debugmode) =
353           parse_libxslt_msgs_mode req
354         in
355         syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
356         let domImpl = Gdome.domImplementation () in
357         let input = domImpl#createDocumentFromURI ~uri:xmluri () in
358         syslogger#log `Debug "Applying stylesheet chain ...";
359         (try
360           let (write_result, media_type, encoding) = (* out_channel -> unit *)
361             Uwobo_engine.apply
362               ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
363               ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
364               input
365           in
366           let content_type = (* value of Content-Type HTTP response header *)
367             sprintf "%s; charset=%s"
368               (match media_type with None -> get_media_type props | Some t -> t)
369               (match encoding with None -> get_encoding props | Some e -> e)
370           in
371           syslogger#log `Debug
372             (sprintf "sending output to client (Content-Type: %s)...."
373               content_type);
374           Http_daemon.send_basic_headers ~code:200 outchan;
375           Http_daemon.send_header "Content-Type" content_type outchan;
376           Http_daemon.send_CRLF outchan;
377           write_result outchan
378         with Uwobo_failure errmsg ->
379           return_error
380             ("Stylesheet chain application failed: " ^ errmsg)
381             ~body: ("<h2>LibXSLT's messages:</h2>" ^
382               String.concat "<br />\n"
383                 (List.map string_of_xslt_msg veillogger#msgs))
384             outchan)
385     | "/help" -> respond_html usage_string outchan
386     | invalid_request ->
387         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
388     syslogger#log `Debug (sprintf "%s done!" req#path);
389   with
390   | Http_types.Param_not_found attr_name ->
391       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
392   | exc ->
393       return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
394 ;;
395
396   (* UWOBO's startup *)
397 let main () =
398     (* (1) system logger *)
399   let logger_outchan =
400    debug_print (sprintf "Logging to file %s" logfile);
401    open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
402   in
403   let syslogger =
404     new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
405   in
406   syslogger#enable;
407     (* (2) stylesheets list *)
408   let styles = new Uwobo_styles.styles in
409     (* (3) clean up actions *)
410   let last_process = ref true in
411   let http_child = ref None in
412   let die_nice () = (** at_exit callback *)
413     if !last_process then begin
414       (match !http_child with
415       | None -> ()
416       | Some pid -> Unix.kill pid Sys.sigterm);
417       syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
418       syslogger#disable;
419       close_out logger_outchan
420     end
421   in
422   at_exit die_nice;
423   ignore (Sys.signal Sys.sigterm
424     (Sys.Signal_handle (fun _ -> raise Sys.Break)));
425   syslogger#log `Notice
426     (sprintf "%s started and listening on port %d" daemon_name port);
427   syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
428   Unix.putenv "http_proxy" "";  (* reset http_proxy to avoid libxslt problems *)
429   while true do
430     let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
431     let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
432     match Unix.fork () with
433     | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
434         http_child := Some child;
435         let stop_http_daemon () =  (* kill child *)
436           debug_print (sprintf "UWOBOmaster: killing pid %d" child);
437           Unix.kill child Sys.sigterm;  (* kill child ... *)
438           ignore (Unix.waitpid [] child);  (* ... and its zombie *)
439         in
440         Unix.close cmd_pipe_entrance;
441         Unix.close res_pipe_exit;
442         let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
443         let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
444         (try
445           while true do
446             (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
447             child process has been killed *)
448             debug_print "UWOBOmaster: waiting for commands ...";
449             let cmd = input_line cmd_pipe in
450             debug_print (sprintf "UWOBOmaster: received %s command" cmd);
451             (match cmd with  (* command from grandchild *)
452             | "test" ->
453                 stop_http_daemon ();
454                 output_string res_pipe "UWOBOmaster: Hello, world!\n";
455                 flush res_pipe;
456                 raise Restart_HTTP_daemon
457             | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
458                 exit 0
459             | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
460                 let bindings =
461                   Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
462                 in
463                 stop_http_daemon ();
464                 let logger = new Uwobo_logger.processingLogger () in
465                 List.iter
466                   (fun binding -> (* add a <key, stylesheet> binding *)
467                     let pieces = Pcre.split ~pat:"," binding in
468                     match pieces with
469                     | [key; style] ->
470                         logger#log (sprintf "adding binding <%s,%s>" key style);
471                         veillogger#clearMsgs;
472                         (try
473                           veillogger#clearMsgs;
474                           styles#add key style;
475                           log_libxslt_msgs logger veillogger;
476                         with e ->
477                           logger#log (Printexc.to_string e))
478                     | _ -> logger#log (sprintf "invalid binding %s" binding))
479                   bindings;
480                 output_string res_pipe logger#asHtml;
481                 flush res_pipe;
482                 raise Restart_HTTP_daemon
483             | line when Pcre.pmatch ~rex:remove_cmd_RE line ->  (* /remove *)
484                 stop_http_daemon ();
485                 let arg = Pcre.replace ~rex:remove_cmd_RE line in
486                 let logger = new Uwobo_logger.processingLogger () in
487                 veillogger#clearMsgs;
488                 act_on_keys
489                   arg styles logger
490                   styles#remove (fun () -> styles#removeAll) styles#keys
491                   "removing";
492                 log_libxslt_msgs logger veillogger;
493                 output_string res_pipe (logger#asHtml);
494                 raise Restart_HTTP_daemon
495             | line when Pcre.pmatch ~rex:reload_cmd_RE line ->  (* /reload *)
496                 stop_http_daemon ();
497                 let arg = Pcre.replace ~rex:reload_cmd_RE line in
498                 let logger = new Uwobo_logger.processingLogger () in
499                 veillogger#clearMsgs;
500                 act_on_keys
501                   arg styles logger
502                   styles#reload (fun () -> styles#reloadAll) styles#keys
503                   "reloading";
504                 output_string res_pipe (logger#asHtml);
505                 raise Restart_HTTP_daemon
506             | cmd ->  (* invalid interprocess command received *)
507                 syslogger#log `Warning
508                   (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
509           done
510         with Restart_HTTP_daemon ->
511           close_in cmd_pipe;  (* these calls close also fds *)
512           close_out res_pipe;)
513     | 0 ->  (* (5) child: serve http requests *)
514         Unix.close cmd_pipe_exit;
515         Unix.close res_pipe_entrance;
516         last_process := false;
517         let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
518         let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
519         debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
520           (* next invocation doesn't return, process will keep on serving HTTP
521           requests until it will get killed by father *)
522         Http_daemon.start'~port ~mode:`Fork
523           (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
524     | _ (* < 0 *) ->  (* fork failed :-((( *)
525         failwith "Can't fork :-("
526   done
527 ;;
528
529   (* daemon initialization *)
530 try
531   Sys.catch_break true;
532   main ()
533 with Sys.Break -> ()  (* 'die_nice' registered with at_exit *)
534 ;;
535