2 * Copyright (C) 2010-2011 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.
29 module C = Libvirt.Connect
30 module Cond = Condition
31 module D = Libvirt.Domain
35 module UTF8 = CamomileLibraryDefault.Camomile.UTF8
38 type 'a callback = 'a -> unit
43 | Checksum_file of source * string * string * string callback
44 | Connect of string option * domain list callback
45 | Disk_usage of source * string * int64 callback
46 | Download_dir_find0 of source * string * string * unit callback
47 | Download_dir_tarball of source * string * download_dir_tarball_format * string * unit callback
48 | Download_file of source * string * string * bool * unit callback
49 | File_information of source * string * string callback
50 | List_applications of inspection_os * G.application array callback
51 | Open_domain of string * inspection_data callback
52 | Open_images of (string * string option) list * inspection_data callback
53 | Read_directory of source * string * direntry list callback
54 | Run_command of string * unit callback
56 let rec string_of_command = function
57 | Exit_thread -> "Exit_thread"
58 | Checksum_file (src, pathname, csumtype, _) ->
59 sprintf "Checksum_file (%s, %s, %s)"
60 (string_of_source src) pathname csumtype
61 | Connect (Some name, _) -> sprintf "Connect %s" name
62 | Connect (None, _) -> "Connect NULL"
63 | Disk_usage (src, remotedir, _) ->
64 sprintf "Disk_usage (%s, %s)" (string_of_source src) remotedir
65 | Download_dir_find0 (src, remotedir, localfile, _) ->
66 sprintf "Download_dir_find0 (%s, %s, %s)"
67 (string_of_source src) remotedir localfile
68 | Download_dir_tarball (src, remotedir, format, localfile, _) ->
69 sprintf "Download_dir_tarball (%s, %s, %s, %s)"
70 (string_of_source src) remotedir
71 (string_of_download_dir_tarball_format format) localfile
72 | Download_file (src, remotefile, localfile, check, _) ->
73 sprintf "Download_file (%s, %s, %s, %b)"
74 (string_of_source src) remotefile localfile check
75 | File_information (src, pathname, _) ->
76 sprintf "File_information (%s, %s)" (string_of_source src) pathname
77 | List_applications (os, _) ->
78 sprintf "List_applications %s" os.insp_root
79 | Open_domain (name, _) -> sprintf "Open_domain %s" name
80 | Open_images (images, _) ->
81 sprintf "Open_images %s" (string_of_images images)
82 | Read_directory (src, dir, _) ->
83 sprintf "Read_directory (%s, %s)" (string_of_source src) dir
84 | Run_command (cmd, _) ->
85 sprintf "Run_command %s" cmd
87 and string_of_images images =
92 | fn, Some format -> sprintf "%s (%s)" fn format)
95 and string_of_source = function
96 | OS { insp_root = root } ->
99 sprintf "Volume %s" dev
101 and string_of_download_dir_tarball_format = function
106 let no_callback _ = ()
108 let failure_hook = ref (fun _ -> ())
109 let busy_hook = ref (fun _ -> ())
110 let idle_hook = ref (fun _ -> ())
111 let status_hook = ref (fun _ -> ())
112 let progress_hook = ref (fun _ -> ())
114 let set_failure_hook cb = failure_hook := cb
115 let set_busy_hook cb = busy_hook := cb
116 let set_idle_hook cb = idle_hook := cb
117 let set_status_hook cb = status_hook := cb
118 let set_progress_hook cb = progress_hook := cb
120 (* Execute a function, while holding a mutex. If the function
121 * fails, ensure we release the mutex before rethrowing the
126 let r = try Left (f ()) with exn -> Right exn in
130 | Right exn -> raise exn
132 (* The queue of commands, and a lock and condition to protect it. *)
134 let q_discard = ref false
135 let q_lock = M.create ()
136 let q_cond = Cond.create ()
138 (* Send a command message to the slave thread. *)
139 let send_to_slave ?fail cmd =
140 debug "sending message %s to slave thread ..." (string_of_command cmd);
143 Q.push (fail, cmd) q;
147 let discard_command_queue () =
151 (* Discard the currently running command. *)
155 let checksum_file ?fail src pathname csumtype cb =
156 send_to_slave ?fail (Checksum_file (src, pathname, csumtype, cb))
157 let connect ?fail uri cb = send_to_slave ?fail (Connect (uri, cb))
158 let disk_usage ?fail src remotedir cb =
159 send_to_slave ?fail (Disk_usage (src, remotedir, cb))
160 let download_dir_find0 ?fail src remotedir localfile cb =
161 send_to_slave ?fail (Download_dir_find0 (src, remotedir, localfile, cb))
162 let download_dir_tarball ?fail src remotedir format localfile cb =
164 (Download_dir_tarball (src, remotedir, format, localfile, cb))
165 let download_file ?fail src remotefile localfile cb =
166 send_to_slave ?fail (Download_file (src, remotefile, localfile, false, cb))
167 let download_file_if_not_exist ?fail src remotefile localfile cb =
168 send_to_slave ?fail (Download_file (src, remotefile, localfile, true, cb))
169 let file_information ?fail src pathname cb =
170 send_to_slave ?fail (File_information (src, pathname, cb))
171 let list_applications ?fail os cb =
172 send_to_slave ?fail (List_applications (os, cb))
173 let open_domain ?fail name cb = send_to_slave ?fail (Open_domain (name, cb))
174 let open_images ?fail images cb = send_to_slave ?fail (Open_images (images, cb))
175 let read_directory ?fail src path cb =
176 send_to_slave ?fail (Read_directory (src, path, cb))
177 let run_command ?fail cmd cb =
178 send_to_slave ?fail (Run_command (cmd, cb))
180 (*----- Slave thread starts here -----*)
182 (* Set this to true to exit the thread. *)
185 (* Handles. These are not protected by locks because only the slave
186 * thread has access to them.
191 (* Run the callback unless someone set the q_discard flag while
192 * we were running the command.
194 let callback_if_not_discarded (cb : 'a callback) (arg : 'a) =
195 let discard = with_lock q_lock (fun () -> !q_discard) in
197 GtkThread.async cb arg
199 (* Update the status bar. *)
201 let f str = GtkThread.async !status_hook str in
205 debug "top of slave loop";
207 (* Get the next command. *)
211 while Q.is_empty q do Cond.wait q_cond q_lock done;
216 debug "slave processing command %s ..." (string_of_command cmd);
219 GtkThread.async !busy_hook ();
222 (* If the user provided an override ?fail parameter to the
223 * original call, call that, else call the global hook.
226 | Some cb -> GtkThread.async cb exn
227 | None -> GtkThread.async !failure_hook exn
230 (* If there are no more commands in the queue, run the idle hook. *)
231 let empty = with_lock q_lock (fun () -> Q.is_empty q) in
232 if empty then GtkThread.async !idle_hook ();
234 if !quit then Thread.exit ();
237 and execute_command = function
242 | Checksum_file (src, pathname, csumtype, cb) ->
243 status "Calculating %s checksum of %s ..." csumtype pathname;
247 with_mount_ro g src (
249 g#checksum csumtype pathname
252 status "Finished calculating %s checksum of %s" csumtype pathname;
253 callback_if_not_discarded cb r
255 | Connect (name, cb) ->
257 match name with None -> "default hypervisor" | Some uri -> uri in
258 status "Connecting to %s ..." printable_name;
261 conn := Some (C.connect_readonly ?name ());
263 let conn = get_conn () in
264 let doms = D.get_domains conn [D.ListAll] in
265 let doms = List.map (
267 { dom_id = D.get_id d;
268 dom_name = D.get_name d;
269 dom_state = (D.get_info d).D.state }
271 let cmp { dom_name = n1 } { dom_name = n2 } = UTF8.compare n1 n2 in
272 let doms = List.sort ~cmp doms in
274 status "Connected to %s" printable_name;
275 callback_if_not_discarded cb doms
277 | Disk_usage (src, remotedir, cb) ->
278 status "Calculating disk usage of %s ..." remotedir;
282 with_mount_ro g src (
287 status "Finished calculating disk usage of %s" remotedir;
288 callback_if_not_discarded cb r
290 | Download_dir_find0 (src, remotedir, localfile, cb) ->
291 status "Downloading %s filenames to %s ..." remotedir localfile;
294 with_mount_ro g src (
296 g#find0 remotedir localfile
299 status "Finished downloading %s" localfile;
300 callback_if_not_discarded cb ()
302 | Download_dir_tarball (src, remotedir, format, localfile, cb) ->
303 status "Downloading %s to %s ..." remotedir localfile;
306 let f = match format with
311 with_mount_ro g src (
313 f remotedir localfile
316 status "Finished downloading %s" localfile;
317 callback_if_not_discarded cb ()
319 | Download_file (src, remotefile, localfile, check, cb) ->
320 if not check || not (local_file_exists localfile) then (
321 status "Downloading %s to %s ..." remotefile localfile;
324 with_mount_ro g src (
326 g#download remotefile localfile
329 status "Finished downloading %s" localfile
331 callback_if_not_discarded cb ()
333 | File_information (src, pathname, cb) ->
334 status "Calculating file information for %s ..." pathname;
338 with_mount_ro g src (
343 status "Finished calculating file information for %s" pathname;
344 callback_if_not_discarded cb r
346 | List_applications (os, cb) ->
347 status "Listing applications ...";
351 with_mount_ro g (OS os) (
353 g#inspect_list_applications os.insp_root
356 status "Finished listing applications";
357 callback_if_not_discarded cb r
359 | Open_domain (name, cb) ->
360 status "Opening %s ..." name;
362 let conn = get_conn () in
363 let dom = D.lookup_by_name conn name in
364 let xml = D.get_xml_desc dom in
365 let images = get_disk_images_from_xml xml in
366 open_disk_images images cb
368 | Open_images (images, cb) ->
369 status "Opening disk images ...";
371 open_disk_images images cb
373 | Read_directory (src, dir, cb) ->
374 status "Reading directory %s ..." dir;
377 let names, stats, links =
378 with_mount_ro g src (
380 let names = g#ls dir in (* sorted and without . and .. *)
381 let stats = lstatlist g dir names in
382 let links = readlinks g dir names (Array.of_list stats) in
383 Array.to_list names, stats, links
386 let n = List.length names in
387 n = List.length stats && n = List.length links
389 let entries = List.combine (List.combine names stats) links in
390 let entries = List.map (
391 fun ((name, stat), link) ->
392 { dent_name = name; dent_stat = stat; dent_link = link }
395 status "Finished reading directory %s" dir;
396 callback_if_not_discarded cb entries
398 | Run_command (cmd, cb) ->
399 status "Running %s ..." cmd;
401 if Sys.command cmd <> 0 then
402 failwith "External command failed: %s" cmd;
404 status "Finished %s ..." cmd;
406 callback_if_not_discarded cb ()
408 (* Expect to be connected, and return the current libvirt connection. *)
412 | None -> failwith "not connected to libvirt"
417 | None -> failwith "no domain or disk image is open"
419 (* Close all libvirt and libguestfs handles. *)
421 (match !conn with Some conn -> C.close conn | None -> ());
426 (match !g with Some g -> g#close () | None -> ());
429 and get_disk_images_from_xml xml =
430 let xml = Xml.parse_string xml in
432 (* Return the device nodes. *)
435 | Xml.Element ("domain", _, children) ->
439 | Xml.Element ("devices", _, devices) -> Some devices
444 failwith "get_xml_desc didn't return <domain/>" in
446 (* Look for <source attr_name=attr_val/> and return attr_val. *)
447 let rec source_of attr_name = function
449 | Xml.Element ("source", attrs, _) :: rest ->
450 (try Some (List.assoc attr_name attrs)
451 with Not_found -> source_of attr_name rest)
452 | _ :: rest -> source_of attr_name rest
455 (* Look for <driver type=attr_val/> and return attr_val. *)
456 let rec format_of = function
458 | Xml.Element ("driver", attrs, _) :: rest ->
459 (try Some (List.assoc "type" attrs)
460 with Not_found -> format_of rest)
461 | _ :: rest -> format_of rest
464 (* Look for <disk> nodes and return the sources (block devices) of those. *)
468 | Xml.Element ("disk", attrs, disks) ->
471 let typ = List.assoc "type" attrs in
472 if typ = "file" then source_of "file" disks
473 else if typ = "block" then source_of "dev" disks
480 let format = format_of disks in
481 Some (filename, format)
487 (* The common code for Open_domain and Open_images which opens the
488 * libguestfs handle, adds the disks, and launches the appliance.
490 and open_disk_images images cb =
491 debug "opening disk image %s" (string_of_images images);
494 let g' = new G.guestfs () in
498 g#set_trace (trace ());
500 (* Uncomment the next line to pass the verbose flag from the command
501 * line through to libguestfs. This is not generally necessary since
502 * we are not so interested in debugging libguestfs problems at this
503 * level, and the user can always set LIBGUESTFS_DEBUG=1 if they need
506 (* g#set_verbose (verbose ());*)
508 (* Attach progress bar callback. *)
510 g#set_event_callback (
511 fun g event handle buf array ->
512 if event == G.EVENT_PROGRESS && Array.length array >= 4 then (
513 let proc_nr = array.(0)
514 and serial = array.(1)
515 and position = array.(2)
516 and total = array.(3) in
517 debug "progress callback proc_nr=%Ld serial=%Ld posn=%Ld total=%Ld"
518 proc_nr serial position total;
519 GtkThread.async !progress_hook (position, total)
521 ) [ G.EVENT_PROGRESS ]
527 g#add_drive_opts ~readonly:true filename
528 | filename, Some format ->
529 g#add_drive_opts ~readonly:true ~format filename
534 status "Listing filesystems ...";
536 (* Get list of filesystems. *)
537 let fses = g#list_filesystems () in
539 status "Looking for operating systems ...";
541 (* Perform inspection. This can fail, ignore errors. *)
543 try Array.to_list (g#inspect_os ())
546 debug "inspection failed (error ignored): %s" msg;
549 let oses = List.map (
551 let typ = g#inspect_get_type root in
552 let windows_current_control_set =
553 if typ <> "windows" then None
555 try Some (g#inspect_get_windows_current_control_set root)
556 with G.Error _ -> None
558 let windows_systemroot =
559 if typ <> "windows" then None
561 try Some (g#inspect_get_windows_systemroot root)
562 with G.Error _ -> None
565 (* Create most of the OS object that we're going to return. We
566 * have to pass this to with_mount_ro below which is why we need
567 * to partially create it here.
571 insp_arch = g#inspect_get_arch root;
572 insp_distro = g#inspect_get_distro root;
573 insp_drive_mappings = g#inspect_get_drive_mappings root;
574 insp_filesystems = g#inspect_get_filesystems root;
575 insp_hostname = g#inspect_get_hostname root;
576 insp_major_version = g#inspect_get_major_version root;
577 insp_minor_version = g#inspect_get_minor_version root;
578 insp_mountpoints = g#inspect_get_mountpoints root;
579 insp_package_format = g#inspect_get_package_format root;
580 insp_package_management = g#inspect_get_package_management root;
581 insp_product_name = g#inspect_get_product_name root;
582 insp_product_variant = g#inspect_get_product_variant root;
584 insp_windows_current_control_set = windows_current_control_set;
585 insp_windows_systemroot = windows_systemroot;
586 insp_winreg_DEFAULT = None; (* incomplete, see below *)
587 insp_winreg_SAM = None;
588 insp_winreg_SECURITY = None;
589 insp_winreg_SOFTWARE = None;
590 insp_winreg_SYSTEM = None;
593 (* We need to mount the root in order to look for Registry hives. *)
594 let winreg_DEFAULT, winreg_SAM, winreg_SECURITY, winreg_SOFTWARE,
596 match windows_systemroot with
597 | None -> None, None, None, None, None
599 with_mount_ro g (OS os) (
601 let check_for_hive filename =
603 sprintf "%s/system32/config/%s" sysroot filename in
604 try Some (g#case_sensitive_path path)
605 with G.Error _ -> None
607 check_for_hive "default",
608 check_for_hive "sam",
609 check_for_hive "security",
610 check_for_hive "software",
611 check_for_hive "system"
614 (* Fill in the remaining struct fields. *)
616 insp_winreg_DEFAULT = winreg_DEFAULT;
617 insp_winreg_SAM = winreg_SAM;
618 insp_winreg_SECURITY = winreg_SECURITY;
619 insp_winreg_SOFTWARE = winreg_SOFTWARE;
620 insp_winreg_SYSTEM = winreg_SYSTEM
626 insp_all_filesystems = fses;
630 status "Finished opening disk";
631 callback_if_not_discarded cb data
633 (* Start up one slave thread. *)
634 let slave_thread = Thread.create loop ()
636 (* Note the following function is called from the main thread. *)
638 discard_command_queue ();
639 ignore (send_to_slave Exit_thread);
640 Thread.join slave_thread