2 * Copyright (C) 2010 Red Hat Inc.
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.
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.
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.
23 module C = Libvirt.Connect
24 module Cond = Condition
25 module D = Libvirt.Domain
29 type 'a callback = 'a -> unit
34 | Connect of string option * domain list callback
35 | Disk_usage of source * string * int64 callback
36 | Download_dir_find0 of source * string * string * unit callback
37 | Download_dir_tarball of source * string * download_dir_tarball_format * string * unit callback
38 | Download_file of source * string * string * unit callback
39 | Open_domain of string * inspection_data callback
40 | Open_images of (string * string option) list * inspection_data callback
41 | Read_directory of source * string * direntry list callback
49 and inspection_data = {
50 insp_all_filesystems : (string * string) list;
51 insp_oses : inspection_os list;
58 insp_filesystems : string array;
59 insp_hostname : string;
60 insp_major_version : int;
61 insp_minor_version : int;
62 insp_mountpoints : (string * string) list;
63 insp_package_format : string;
64 insp_package_management : string;
65 insp_product_name : string;
67 insp_windows_systemroot : string option;
70 and source = OS of inspection_os | Volume of string
74 dent_stat : Guestfs.stat;
78 and download_dir_tarball_format = Tar | TGZ | TXZ
80 let rec string_of_command = function
81 | Exit_thread -> "Exit_thread"
82 | Connect (Some name, _) -> sprintf "Connect %s" name
83 | Connect (None, _) -> "Connect NULL"
84 | Disk_usage (src, remotedir, _) ->
85 sprintf "Disk_usage (%s, %s)" (string_of_source src) remotedir
86 | Download_dir_find0 (src, remotedir, localfile, _) ->
87 sprintf "Download_dir_find0 (%s, %s, %s)"
88 (string_of_source src) remotedir localfile
89 | Download_dir_tarball (src, remotedir, format, localfile, _) ->
90 sprintf "Download_dir_tarball (%s, %s, %s, %s)"
91 (string_of_source src) remotedir
92 (string_of_download_dir_tarball_format format) localfile
93 | Download_file (src, remotefile, localfile, _) ->
94 sprintf "Download_file (%s, %s, %s)"
95 (string_of_source src) remotefile localfile
96 | Open_domain (name, _) -> sprintf "Open_domain %s" name
97 | Open_images (images, _) ->
98 sprintf "Open_images %s" (string_of_images images)
99 | Read_directory (src, dir, _) ->
100 sprintf "Read_directory (%s, %s)" (string_of_source src) dir
102 and string_of_images images =
107 | fn, Some format -> sprintf "%s (%s)" fn format)
110 and string_of_source = function
111 | OS { insp_root = root } ->
114 sprintf "Volume %s" dev
116 and string_of_download_dir_tarball_format = function
121 let no_callback _ = ()
123 let failure_hook = ref (fun _ -> ())
124 let busy_hook = ref (fun _ -> ())
125 let idle_hook = ref (fun _ -> ())
126 let status_hook = ref (fun _ -> ())
127 let progress_hook = ref (fun _ -> ())
129 let set_failure_hook cb = failure_hook := cb
130 let set_busy_hook cb = busy_hook := cb
131 let set_idle_hook cb = idle_hook := cb
132 let set_status_hook cb = status_hook := cb
133 let set_progress_hook cb = progress_hook := cb
135 (* Execute a function, while holding a mutex. If the function
136 * fails, ensure we release the mutex before rethrowing the
141 let r = try Left (f ()) with exn -> Right exn in
145 | Right exn -> raise exn
147 (* The queue of commands, and a lock and condition to protect it. *)
149 let q_discard = ref false
150 let q_lock = M.create ()
151 let q_cond = Cond.create ()
153 (* Send a command message to the slave thread. *)
154 let send_to_slave ?fail cmd =
155 debug "sending message %s to slave thread ..." (string_of_command cmd);
158 Q.push (fail, cmd) q;
162 let discard_command_queue () =
166 (* Discard the currently running command. *)
170 let connect ?fail uri cb = send_to_slave ?fail (Connect (uri, cb))
171 let disk_usage ?fail src remotedir cb =
172 send_to_slave ?fail (Disk_usage (src, remotedir, cb))
173 let download_dir_find0 ?fail src remotedir localfile cb =
174 send_to_slave ?fail (Download_dir_find0 (src, remotedir, localfile, cb))
175 let download_dir_tarball ?fail src remotedir format localfile cb =
177 (Download_dir_tarball (src, remotedir, format, localfile, cb))
178 let download_file ?fail src remotefile localfile cb =
179 send_to_slave ?fail (Download_file (src, remotefile, localfile, cb))
180 let open_domain ?fail name cb = send_to_slave ?fail (Open_domain (name, cb))
181 let open_images ?fail images cb = send_to_slave ?fail (Open_images (images, cb))
182 let read_directory ?fail src path cb =
183 send_to_slave ?fail (Read_directory (src, path, cb))
185 (*----- Slave thread starts here -----*)
187 (* Set this to true to exit the thread. *)
190 (* Handles. These are not protected by locks because only the slave
191 * thread has access to them.
196 (* Run the callback unless someone set the q_discard flag while
197 * we were running the command.
199 let callback_if_not_discarded (cb : 'a callback) (arg : 'a) =
200 let discard = with_lock q_lock (fun () -> !q_discard) in
202 GtkThread.async cb arg
204 (* Call 'f ()' with source mounted read-only. Ensure that everything
205 * is unmounted even if an exception is thrown.
207 let with_mount_ro g src (f : unit -> 'a) : 'a =
208 Std.finally (fun () -> g#umount_all ()) (
210 (* Do the mount - could be OS or single volume. *)
212 | Volume dev -> g#mount_ro dev "/";
213 | OS { insp_mountpoints = mps } ->
214 (* Sort the mountpoint keys by length, shortest first. *)
215 let cmp (a,_) (b,_) = compare (String.length a) (String.length b) in
216 let mps = List.sort ~cmp mps in
217 (* Mount the filesystems. *)
219 fun (mp, dev) -> g#mount_ro dev mp
225 (* Update the status bar. *)
227 let f str = GtkThread.async !status_hook str in
231 debug "top of slave loop";
233 (* Get the next command. *)
237 while Q.is_empty q do Cond.wait q_cond q_lock done;
242 debug "slave processing command %s ..." (string_of_command cmd);
245 GtkThread.async !busy_hook ();
248 (* If the user provided an override ?fail parameter to the
249 * original call, call that, else call the global hook.
252 | Some cb -> GtkThread.async cb exn
253 | None -> GtkThread.async !failure_hook exn
256 (* If there are no more commands in the queue, run the idle hook. *)
257 let empty = with_lock q_lock (fun () -> Q.is_empty q) in
258 if empty then GtkThread.async !idle_hook ();
260 if !quit then Thread.exit ();
263 and execute_command = function
268 | Connect (name, cb) ->
270 match name with None -> "default hypervisor" | Some uri -> uri in
271 status "Connecting to %s ..." printable_name;
274 conn := Some (C.connect_readonly ?name ());
276 let conn = get_conn () in
277 let doms = D.get_domains conn [D.ListAll] in
278 let doms = List.map (
280 { dom_id = D.get_id d;
281 dom_name = D.get_name d;
282 dom_state = (D.get_info d).D.state }
284 let cmp { dom_name = n1 } { dom_name = n2 } = compare n1 n2 in
285 let doms = List.sort ~cmp doms in
287 status "Connected to %s" printable_name;
288 callback_if_not_discarded cb doms
290 | Disk_usage (src, remotedir, cb) ->
291 status "Calculating disk usage of %s ..." remotedir;
295 with_mount_ro g src (
300 status "Finished calculating disk usage of %s" remotedir;
301 callback_if_not_discarded cb r
303 | Download_dir_find0 (src, remotedir, localfile, cb) ->
304 status "Downloading %s filenames to %s ..." remotedir localfile;
307 with_mount_ro g src (
309 g#find0 remotedir localfile
312 status "Finished downloading %s" localfile;
313 callback_if_not_discarded cb ()
315 | Download_dir_tarball (src, remotedir, format, localfile, cb) ->
316 status "Downloading %s to %s ..." remotedir localfile;
319 let f = match format with
324 with_mount_ro g src (
326 f remotedir localfile
329 status "Finished downloading %s" localfile;
330 callback_if_not_discarded cb ()
332 | Download_file (src, remotefile, localfile, cb) ->
333 status "Downloading %s to %s ..." remotefile localfile;
336 with_mount_ro g src (
338 g#download remotefile localfile
341 status "Finished downloading %s" localfile;
342 callback_if_not_discarded cb ()
344 | Open_domain (name, cb) ->
345 status "Opening %s ..." name;
347 let conn = get_conn () in
348 let dom = D.lookup_by_name conn name in
349 let xml = D.get_xml_desc dom in
350 let images = get_disk_images_from_xml xml in
351 open_disk_images images cb
353 | Open_images (images, cb) ->
354 status "Opening disk images ...";
356 open_disk_images images cb
358 | Read_directory (src, dir, cb) ->
359 status "Reading directory %s ..." dir;
362 let names, stats, links =
363 with_mount_ro g src (
365 let names = g#ls dir in (* sorted and without . and .. *)
366 let names = Array.to_list names in
367 let stats = lstatlist_wrapper g dir names in
368 let links = readlinklist_wrapper g dir names in
372 let n = List.length names in
373 n = List.length stats && n = List.length links
375 let entries = List.combine (List.combine names stats) links in
376 let entries = List.map (
377 fun ((name, stat), link) ->
378 { dent_name = name; dent_stat = stat; dent_link = link }
381 status "Finished reading directory %s" dir;
382 callback_if_not_discarded cb entries
384 (* Expect to be connected, and return the current libvirt connection. *)
388 | None -> failwith "not connected to libvirt"
393 | None -> failwith "no domain or disk image is open"
395 (* Close all libvirt and libguestfs handles. *)
397 (match !conn with Some conn -> C.close conn | None -> ());
402 (match !g with Some g -> g#close () | None -> ());
405 and get_disk_images_from_xml xml =
406 let xml = Xml.parse_string xml in
408 (* Return the device nodes. *)
411 | Xml.Element ("domain", _, children) ->
415 | Xml.Element ("devices", _, devices) -> Some devices
420 failwith "get_xml_desc didn't return <domain/>" in
422 (* Look for <source attr_name=attr_val/> and return attr_val. *)
423 let rec source_of attr_name = function
425 | Xml.Element ("source", attrs, _) :: rest ->
426 (try Some (List.assoc attr_name attrs)
427 with Not_found -> source_of attr_name rest)
428 | _ :: rest -> source_of attr_name rest
431 (* Look for <driver type=attr_val/> and return attr_val. *)
432 let rec format_of = function
434 | Xml.Element ("driver", attrs, _) :: rest ->
435 (try Some (List.assoc "type" attrs)
436 with Not_found -> format_of rest)
437 | _ :: rest -> format_of rest
440 (* Look for <disk> nodes and return the sources (block devices) of those. *)
444 | Xml.Element ("disk", attrs, disks) ->
447 let typ = List.assoc "type" attrs in
448 if typ = "file" then source_of "file" disks
449 else if typ = "block" then source_of "dev" disks
456 let format = format_of disks in
457 Some (filename, format)
463 (* The common code for Open_domain and Open_images which opens the
464 * libguestfs handle, adds the disks, and launches the appliance.
466 and open_disk_images images cb =
467 debug "opening disk image %s" (string_of_images images);
470 let g' = new Guestfs.guestfs () in
474 g#set_trace (trace ());
476 (* Uncomment the next line to pass the verbose flag from the command
477 * line through to libguestfs. This is not generally necessary since
478 * we are not so interested in debugging libguestfs problems at this
479 * level, and the user can always set LIBGUESTFS_DEBUG=1 if they need
482 (* g#set_verbose (verbose ());*)
484 (* Attach progress bar callback. *)
485 g#set_progress_callback (
486 fun proc_nr serial position total ->
487 debug "progress callback proc_nr=%d serial=%d posn=%Ld total=%Ld"
488 proc_nr serial position total;
489 GtkThread.async !progress_hook (position, total)
495 g#add_drive_opts ~readonly:true filename
496 | filename, Some format ->
497 g#add_drive_opts ~readonly:true ~format filename
502 status "Listing filesystems ...";
504 (* Get list of filesystems. *)
505 let fses = g#list_filesystems () in
507 status "Looking for operating systems ...";
509 (* Perform inspection. This can fail, ignore errors. *)
511 try Array.to_list (g#inspect_os ())
514 debug "inspection failed (error ignored): %s" msg;
517 let oses = List.map (
520 insp_arch = g#inspect_get_arch root;
521 insp_distro = g#inspect_get_distro root;
522 insp_filesystems = g#inspect_get_filesystems root;
523 insp_hostname = g#inspect_get_hostname root;
524 insp_major_version = g#inspect_get_major_version root;
525 insp_minor_version = g#inspect_get_minor_version root;
526 insp_mountpoints = g#inspect_get_mountpoints root;
527 insp_package_format = g#inspect_get_package_format root;
528 insp_package_management = g#inspect_get_package_management root;
529 insp_product_name = g#inspect_get_product_name root;
530 insp_type = g#inspect_get_type root;
531 insp_windows_systemroot =
532 try Some (g#inspect_get_windows_systemroot root)
533 with Guestfs.Error _ -> None
537 insp_all_filesystems = fses;
541 status "Finished opening disk";
542 callback_if_not_discarded cb data
544 (* guestfs_lstatlist has a "hidden" limit of the protocol message size.
545 * Call this function, but split the list of names into chunks.
547 and lstatlist_wrapper g dir = function
550 let names', names = List.take 1000 names, List.drop 1000 names in
551 let xs = g#lstatlist dir (Array.of_list names') in
552 let xs = Array.to_list xs in
553 xs @ lstatlist_wrapper g dir names
555 (* Same as above for guestfs_readlinklist. *)
556 and readlinklist_wrapper g dir = function
559 let names', names = List.take 1000 names, List.drop 1000 names in
560 let xs = g#readlinklist dir (Array.of_list names') in
561 let xs = Array.to_list xs in
562 xs @ readlinklist_wrapper g dir names
564 (* Start up one slave thread. *)
565 let slave_thread = Thread.create loop ()
567 (* Note the following function is called from the main thread. *)
569 discard_command_queue ();
570 ignore (send_to_slave Exit_thread);
571 Thread.join slave_thread