Daily checkin of rewritten code.
[guestfs-browser.git] / slave.ml
1 (* Guestfs Browser.
2  * Copyright (C) 2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *)
18
19 open ExtList
20 open Printf
21 open Utils
22
23 module C = Libvirt.Connect
24 module Cond = Condition
25 module D = Libvirt.Domain
26 module M = Mutex
27 module Q = Queue
28
29 type 'a callback = 'a -> unit
30
31 (* The commands. *)
32 type command =
33   | Exit_thread
34   | Connect of string option * domain list callback
35   | Open_domain of string * inspection_data callback
36   | Open_images of (string * string option) list * inspection_data callback
37   | Read_directory of source * string * direntry list callback
38
39 and domain = {
40   dom_id : int;
41   dom_name : string;
42   dom_state : D.state;
43 }
44
45 and inspection_data = {
46   insp_all_filesystems : (string * string) list;
47   insp_oses : inspection_os list;
48 }
49
50 and inspection_os = {
51   insp_root : string;
52   insp_arch : string;
53   insp_distro : string;
54   insp_filesystems : string array;
55   insp_hostname : string;
56   insp_major_version : int;
57   insp_minor_version : int;
58   insp_mountpoints : (string * string) list;
59   insp_package_format : string;
60   insp_package_management : string;
61   insp_product_name : string;
62   insp_type : string;
63   insp_windows_systemroot : string option;
64 }
65
66 and source = OS of inspection_os | Volume of string
67
68 and direntry = {
69   dent_name : string;
70   dent_stat : Guestfs.stat;
71   dent_link : string;
72 }
73
74 let rec string_of_command = function
75   | Exit_thread -> "Exit_thread"
76   | Connect (Some name, _) -> sprintf "Connect %s" name
77   | Connect (None, _) -> "Connect NULL"
78   | Open_domain (name, _) -> sprintf "Open_domain %s" name
79   | Open_images (images, _) ->
80       sprintf "Open_images %s" (string_of_images images)
81   | Read_directory (OS { insp_root = root }, dir, _) ->
82       sprintf "Read_directory (OS %s, %s)" root dir
83   | Read_directory (Volume dev, dir, _) ->
84       sprintf "Read_directory (Volume %s, %s)" dev dir
85
86 and string_of_images images =
87   "[" ^
88     String.concat "; "
89     (List.map (function
90                | fn, None -> fn
91                | fn, Some format -> sprintf "%s (%s)" fn format)
92        images) ^ "]"
93
94 let no_callback _ = ()
95
96 let failure_hook = ref (fun _ -> ())
97 let busy_hook = ref (fun _ -> ())
98 let idle_hook = ref (fun _ -> ())
99
100 let set_failure_hook cb = failure_hook := cb
101 let set_busy_hook cb = busy_hook := cb
102 let set_idle_hook cb = idle_hook := cb
103
104 (* Execute a function, while holding a mutex.  If the function
105  * fails, ensure we release the mutex before rethrowing the
106  * exception.
107  *)
108 let with_lock m f =
109   M.lock m;
110   let r = try Left (f ()) with exn -> Right exn in
111   M.unlock m;
112   match r with
113   | Left r -> r
114   | Right exn -> raise exn
115
116 (* The queue of commands, and a lock and condition to protect it. *)
117 let q = Q.create ()
118 let q_discard = ref false
119 let q_lock = M.create ()
120 let q_cond = Cond.create ()
121
122 (* Send a command message to the slave thread. *)
123 let send_to_slave ?fail cmd =
124   debug "sending message %s to slave thread ..." (string_of_command cmd);
125   with_lock q_lock (
126     fun () ->
127       Q.push (fail, cmd) q;
128       Cond.signal q_cond
129   )
130
131 let discard_command_queue () =
132   with_lock q_lock (
133     fun () ->
134       Q.clear q;
135       (* Discard the currently running command. *)
136       q_discard := true
137   )
138
139 let connect ?fail uri cb = send_to_slave ?fail (Connect (uri, cb))
140 let open_domain ?fail name cb = send_to_slave ?fail (Open_domain (name, cb))
141 let open_images ?fail images cb = send_to_slave ?fail (Open_images (images, cb))
142 let read_directory ?fail src path cb =
143   send_to_slave ?fail (Read_directory (src, path, cb))
144
145 (*----- Slave thread starts here -----*)
146
147 (* Set this to true to exit the thread. *)
148 let quit = ref false
149
150 (* Handles.  These are not protected by locks because only the slave
151  * thread has access to them.
152  *)
153 let conn = ref None
154 let g = ref None
155
156 (* Run the callback unless someone set the q_discard flag while
157  * we were running the command.
158  *)
159 let callback_if_not_discarded (cb : 'a callback) (arg : 'a) =
160   let discard = with_lock q_lock (fun () -> !q_discard) in
161   if not discard then
162     GtkThread.async cb arg
163
164 (* Call 'f ()' with source mounted read-only.  Ensure that everything
165  * is unmounted even if an exception is thrown.
166  *)
167 let with_mount_ro g src (f : unit -> 'a) : 'a =
168   Std.finally (fun () -> g#umount_all ()) (
169     fun () ->
170       (* Do the mount - could be OS or single volume. *)
171       (match src with
172       | Volume dev -> g#mount_ro dev "/";
173       | OS { insp_mountpoints = mps } ->
174           (* Sort the mountpoint keys by length, shortest first. *)
175           let cmp (a,_) (b,_) = compare (String.length a) (String.length b) in
176           let mps = List.sort ~cmp mps in
177           (* Mount the filesystems. *)
178           List.iter (
179             fun (mp, dev) -> g#mount_ro dev mp
180           ) mps
181       );
182       f ()
183   ) ()
184
185 let rec loop () =
186   debug "top of slave loop";
187
188   (* Get the next command. *)
189   let fail, cmd =
190     with_lock q_lock (
191       fun () ->
192         while Q.is_empty q do Cond.wait q_cond q_lock done;
193         q_discard := false;
194         Q.pop q
195     ) in
196
197   debug "slave processing command %s ..." (string_of_command cmd);
198
199   (try
200      GtkThread.async !busy_hook ();
201      execute_command cmd
202    with exn ->
203      (* If the user provided an override ?fail parameter to the
204       * original call, call that, else call the global hook.
205       *)
206      match fail with
207      | Some cb -> GtkThread.async cb exn
208      | None -> GtkThread.async !failure_hook exn
209   );
210
211   (* If there are no more commands in the queue, run the idle hook. *)
212   let empty = with_lock q_lock (fun () -> Q.is_empty q) in
213   if empty then GtkThread.async !idle_hook ();
214
215   if !quit then Thread.exit ();
216   loop ()
217
218 and execute_command = function
219   | Exit_thread ->
220       quit := true;
221       close_all ()
222
223   | Connect (name, cb) ->
224       close_all ();
225       conn := Some (C.connect_readonly ?name ());
226
227       let conn = get_conn () in
228       let doms = D.get_domains conn [D.ListAll] in
229       let doms = List.map (
230         fun d ->
231           { dom_id = D.get_id d;
232             dom_name = D.get_name d;
233             dom_state = (D.get_info d).D.state }
234       ) doms in
235       let cmp { dom_name = n1 } { dom_name = n2 } = compare n1 n2 in
236       let doms = List.sort ~cmp doms in
237       callback_if_not_discarded cb doms
238
239   | Open_domain (name, cb) ->
240       let conn = get_conn () in
241       let dom = D.lookup_by_name conn name in
242       let xml = D.get_xml_desc dom in
243       let images = get_disk_images_from_xml xml in
244       open_disk_images images cb
245
246   | Open_images (images, cb) ->
247       open_disk_images images cb
248
249   | Read_directory (src, dir, cb) ->
250       let g = get_g () in
251       let names, stats, links =
252         with_mount_ro g src (
253           fun () ->
254             let names = g#ls dir in (* sorted and without . and .. *)
255             let names = Array.to_list names in
256             let stats = lstatlist_wrapper g dir names in
257             let links = readlinklist_wrapper g dir names in
258             names, stats, links
259         ) in
260       assert (
261         let n = List.length names in
262         n = List.length stats && n = List.length links
263       );
264       let entries = List.combine (List.combine names stats) links in
265       let entries = List.map (
266         fun ((name, stat), link) ->
267           { dent_name = name; dent_stat = stat; dent_link = link }
268       ) entries in
269       callback_if_not_discarded cb entries
270
271 (* Expect to be connected, and return the current libvirt connection. *)
272 and get_conn () =
273   match !conn with
274   | Some conn -> conn
275   | None -> failwith "not connected to libvirt"
276
277 and get_g () =
278   match !g with
279   | Some g -> g
280   | None -> failwith "no domain or disk image is open"
281
282 (* Close all libvirt and libguestfs handles. *)
283 and close_all () =
284   (match !conn with Some conn -> C.close conn | None -> ());
285   conn := None;
286   close_g ()
287
288 and close_g () =
289   (match !g with Some g -> g#close () | None -> ());
290   g := None
291
292 and get_disk_images_from_xml xml =
293   let xml = Xml.parse_string xml in
294
295   (* Return the device nodes. *)
296   let devices =
297     match xml with
298     | Xml.Element ("domain", _, children) ->
299         let devices =
300           List.filter_map (
301             function
302             | Xml.Element ("devices", _, devices) -> Some devices
303             | _ -> None
304           ) children in
305         List.concat devices
306     | _ ->
307         failwith "get_xml_desc didn't return <domain/>" in
308
309   (* Look for <source attr_name=attr_val/> and return attr_val. *)
310   let rec source_of attr_name = function
311     | [] -> None
312     | Xml.Element ("source", attrs, _) :: rest ->
313         (try Some (List.assoc attr_name attrs)
314          with Not_found -> source_of attr_name rest)
315     | _ :: rest -> source_of attr_name rest
316   in
317
318   (* Look for <driver type=attr_val/> and return attr_val. *)
319   let rec format_of = function
320     | [] -> None
321     | Xml.Element ("driver", attrs, _) :: rest ->
322         (try Some (List.assoc "type" attrs)
323          with Not_found -> format_of rest)
324     | _ :: rest -> format_of rest
325   in
326
327   (* Look for <disk> nodes and return the sources (block devices) of those. *)
328   let blkdevs =
329     List.filter_map (
330       function
331       | Xml.Element ("disk", attrs, disks) ->
332           let filename =
333             try
334               let typ = List.assoc "type" attrs in
335               if typ = "file" then source_of "file" disks
336               else if typ = "block" then source_of "dev" disks
337               else None
338             with
339               Not_found -> None in
340           (match filename with
341            | None -> None
342            | Some filename ->
343                let format = format_of disks in
344                Some (filename, format)
345           );
346       | _ -> None
347     ) devices in
348   blkdevs
349
350 (* The common code for Open_domain and Open_images which opens the
351  * libguestfs handle, adds the disks, and launches the appliance.
352  *)
353 and open_disk_images images cb =
354   debug "opening disk image %s" (string_of_images images);
355
356   close_g ();
357   let g' = new Guestfs.guestfs () in
358   g := Some g';
359   let g = g' in
360
361   (* Uncomment the next line to pass the verbose flag from the command
362    * line through to libguestfs.  This is not generally necessary since
363    * we are not so interested in debugging libguestfs problems at this
364    * level, and the user can always set LIBGUESTFS_DEBUG=1 if they need
365    * to.
366    *)
367   (* g#set_verbose (verbose ());*)
368
369   List.iter (
370     function
371     | filename, None ->
372         g#add_drive_opts ~readonly:true filename
373     | filename, Some format ->
374         g#add_drive_opts ~readonly:true ~format filename
375   ) images;
376
377   g#launch ();
378
379   (* Get list of filesystems. *)
380   let fses = g#list_filesystems () in
381
382   (* Perform inspection.  This can fail, ignore errors. *)
383   let roots =
384     try Array.to_list (g#inspect_os ())
385     with
386       Guestfs.Error msg ->
387         debug "inspection failed (error ignored): %s" msg;
388         [] in
389
390   let oses = List.map (
391     fun root -> {
392       insp_root = root;
393       insp_arch = g#inspect_get_arch root;
394       insp_distro = g#inspect_get_distro root;
395       insp_filesystems = g#inspect_get_filesystems root;
396       insp_hostname = g#inspect_get_hostname root;
397       insp_major_version = g#inspect_get_major_version root;
398       insp_minor_version = g#inspect_get_minor_version root;
399       insp_mountpoints = g#inspect_get_mountpoints root;
400       insp_package_format = g#inspect_get_package_format root;
401       insp_package_management = g#inspect_get_package_management root;
402       insp_product_name = g#inspect_get_product_name root;
403       insp_type = g#inspect_get_type root;
404       insp_windows_systemroot =
405         try Some (g#inspect_get_windows_systemroot root)
406         with Guestfs.Error _ -> None
407     }
408   ) roots in
409   let data = {
410     insp_all_filesystems = fses;
411     insp_oses = oses;
412   } in
413   callback_if_not_discarded cb data
414
415 (* guestfs_lstatlist has a "hidden" limit of the protocol message size.
416  * Call this function, but split the list of names into chunks.
417  *)
418 and lstatlist_wrapper g dir = function
419   | [] -> []
420   | names ->
421       let names', names = List.take 1000 names, List.drop 1000 names in
422       let xs = g#lstatlist dir (Array.of_list names') in
423       let xs = Array.to_list xs in
424       xs @ lstatlist_wrapper g dir names
425
426 (* Same as above for guestfs_readlinklist. *)
427 and readlinklist_wrapper g dir = function
428   | [] -> []
429   | names ->
430       let names', names = List.take 1000 names, List.drop 1000 names in
431       let xs = g#readlinklist dir (Array.of_list names') in
432       let xs = Array.to_list xs in
433       xs @ readlinklist_wrapper g dir names
434
435 (* Start up one slave thread. *)
436 let slave_thread = Thread.create loop ()
437
438 (* Note the following function is called from the main thread. *)
439 let exit_thread () =
440   discard_command_queue ();
441   ignore (send_to_slave Exit_thread);
442   Thread.join slave_thread