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 | Open_domain of string * inspection_data callback
51 | Open_images of (string * string option) list * inspection_data callback
52 | Read_directory of source * string * direntry list callback
53 | Run_command of string * unit callback
55 let rec string_of_command = function
56 | Exit_thread -> "Exit_thread"
57 | Checksum_file (src, pathname, csumtype, _) ->
58 sprintf "Checksum_file (%s, %s, %s)"
59 (string_of_source src) pathname csumtype
60 | Connect (Some name, _) -> sprintf "Connect %s" name
61 | Connect (None, _) -> "Connect NULL"
62 | Disk_usage (src, remotedir, _) ->
63 sprintf "Disk_usage (%s, %s)" (string_of_source src) remotedir
64 | Download_dir_find0 (src, remotedir, localfile, _) ->
65 sprintf "Download_dir_find0 (%s, %s, %s)"
66 (string_of_source src) remotedir localfile
67 | Download_dir_tarball (src, remotedir, format, localfile, _) ->
68 sprintf "Download_dir_tarball (%s, %s, %s, %s)"
69 (string_of_source src) remotedir
70 (string_of_download_dir_tarball_format format) localfile
71 | Download_file (src, remotefile, localfile, check, _) ->
72 sprintf "Download_file (%s, %s, %s, %b)"
73 (string_of_source src) remotefile localfile check
74 | File_information (src, pathname, _) ->
75 sprintf "File_information (%s, %s)" (string_of_source src) pathname
76 | Open_domain (name, _) -> sprintf "Open_domain %s" name
77 | Open_images (images, _) ->
78 sprintf "Open_images %s" (string_of_images images)
79 | Read_directory (src, dir, _) ->
80 sprintf "Read_directory (%s, %s)" (string_of_source src) dir
81 | Run_command (cmd, _) ->
82 sprintf "Run_command %s" cmd
84 and string_of_images images =
89 | fn, Some format -> sprintf "%s (%s)" fn format)
92 and string_of_source = function
93 | OS { insp_root = root } ->
96 sprintf "Volume %s" dev
98 and string_of_download_dir_tarball_format = function
103 let no_callback _ = ()
105 let failure_hook = ref (fun _ -> ())
106 let busy_hook = ref (fun _ -> ())
107 let idle_hook = ref (fun _ -> ())
108 let status_hook = ref (fun _ -> ())
109 let progress_hook = ref (fun _ -> ())
111 let set_failure_hook cb = failure_hook := cb
112 let set_busy_hook cb = busy_hook := cb
113 let set_idle_hook cb = idle_hook := cb
114 let set_status_hook cb = status_hook := cb
115 let set_progress_hook cb = progress_hook := cb
117 (* Execute a function, while holding a mutex. If the function
118 * fails, ensure we release the mutex before rethrowing the
123 let r = try Left (f ()) with exn -> Right exn in
127 | Right exn -> raise exn
129 (* The queue of commands, and a lock and condition to protect it. *)
131 let q_discard = ref false
132 let q_lock = M.create ()
133 let q_cond = Cond.create ()
135 (* Send a command message to the slave thread. *)
136 let send_to_slave ?fail cmd =
137 debug "sending message %s to slave thread ..." (string_of_command cmd);
140 Q.push (fail, cmd) q;
144 let discard_command_queue () =
148 (* Discard the currently running command. *)
152 let checksum_file ?fail src pathname csumtype cb =
153 send_to_slave ?fail (Checksum_file (src, pathname, csumtype, cb))
154 let connect ?fail uri cb = send_to_slave ?fail (Connect (uri, cb))
155 let disk_usage ?fail src remotedir cb =
156 send_to_slave ?fail (Disk_usage (src, remotedir, cb))
157 let download_dir_find0 ?fail src remotedir localfile cb =
158 send_to_slave ?fail (Download_dir_find0 (src, remotedir, localfile, cb))
159 let download_dir_tarball ?fail src remotedir format localfile cb =
161 (Download_dir_tarball (src, remotedir, format, localfile, cb))
162 let download_file ?fail src remotefile localfile cb =
163 send_to_slave ?fail (Download_file (src, remotefile, localfile, false, cb))
164 let download_file_if_not_exist ?fail src remotefile localfile cb =
165 send_to_slave ?fail (Download_file (src, remotefile, localfile, true, cb))
166 let file_information ?fail src pathname cb =
167 send_to_slave ?fail (File_information (src, pathname, cb))
168 let open_domain ?fail name cb = send_to_slave ?fail (Open_domain (name, cb))
169 let open_images ?fail images cb = send_to_slave ?fail (Open_images (images, cb))
170 let read_directory ?fail src path cb =
171 send_to_slave ?fail (Read_directory (src, path, cb))
172 let run_command ?fail cmd cb =
173 send_to_slave ?fail (Run_command (cmd, cb))
175 (*----- Slave thread starts here -----*)
177 (* Set this to true to exit the thread. *)
180 (* Handles. These are not protected by locks because only the slave
181 * thread has access to them.
186 (* Run the callback unless someone set the q_discard flag while
187 * we were running the command.
189 let callback_if_not_discarded (cb : 'a callback) (arg : 'a) =
190 let discard = with_lock q_lock (fun () -> !q_discard) in
192 GtkThread.async cb arg
194 (* Update the status bar. *)
196 let f str = GtkThread.async !status_hook str in
200 debug "top of slave loop";
202 (* Get the next command. *)
206 while Q.is_empty q do Cond.wait q_cond q_lock done;
211 debug "slave processing command %s ..." (string_of_command cmd);
214 GtkThread.async !busy_hook ();
217 (* If the user provided an override ?fail parameter to the
218 * original call, call that, else call the global hook.
221 | Some cb -> GtkThread.async cb exn
222 | None -> GtkThread.async !failure_hook exn
225 (* If there are no more commands in the queue, run the idle hook. *)
226 let empty = with_lock q_lock (fun () -> Q.is_empty q) in
227 if empty then GtkThread.async !idle_hook ();
229 if !quit then Thread.exit ();
232 and execute_command = function
237 | Checksum_file (src, pathname, csumtype, cb) ->
238 status "Calculating %s checksum of %s ..." csumtype pathname;
242 with_mount_ro g src (
244 g#checksum csumtype pathname
247 status "Finished calculating %s checksum of %s" csumtype pathname;
248 callback_if_not_discarded cb r
250 | Connect (name, cb) ->
252 match name with None -> "default hypervisor" | Some uri -> uri in
253 status "Connecting to %s ..." printable_name;
256 conn := Some (C.connect_readonly ?name ());
258 let conn = get_conn () in
259 let doms = D.get_domains conn [D.ListAll] in
260 let doms = List.map (
262 { dom_id = D.get_id d;
263 dom_name = D.get_name d;
264 dom_state = (D.get_info d).D.state }
266 let cmp { dom_name = n1 } { dom_name = n2 } = UTF8.compare n1 n2 in
267 let doms = List.sort ~cmp doms in
269 status "Connected to %s" printable_name;
270 callback_if_not_discarded cb doms
272 | Disk_usage (src, remotedir, cb) ->
273 status "Calculating disk usage of %s ..." remotedir;
277 with_mount_ro g src (
282 status "Finished calculating disk usage of %s" remotedir;
283 callback_if_not_discarded cb r
285 | Download_dir_find0 (src, remotedir, localfile, cb) ->
286 status "Downloading %s filenames to %s ..." remotedir localfile;
289 with_mount_ro g src (
291 g#find0 remotedir localfile
294 status "Finished downloading %s" localfile;
295 callback_if_not_discarded cb ()
297 | Download_dir_tarball (src, remotedir, format, localfile, cb) ->
298 status "Downloading %s to %s ..." remotedir localfile;
301 let f = match format with
306 with_mount_ro g src (
308 f remotedir localfile
311 status "Finished downloading %s" localfile;
312 callback_if_not_discarded cb ()
314 | Download_file (src, remotefile, localfile, check, cb) ->
315 if not check || not (local_file_exists localfile) then (
316 status "Downloading %s to %s ..." remotefile localfile;
319 with_mount_ro g src (
321 g#download remotefile localfile
324 status "Finished downloading %s" localfile
326 callback_if_not_discarded cb ()
328 | File_information (src, pathname, cb) ->
329 status "Calculating file information for %s ..." pathname;
333 with_mount_ro g src (
338 status "Finished calculating file information for %s" pathname;
339 callback_if_not_discarded cb r
341 | Open_domain (name, cb) ->
342 status "Opening %s ..." name;
344 let conn = get_conn () in
345 let dom = D.lookup_by_name conn name in
346 let xml = D.get_xml_desc dom in
347 let images = get_disk_images_from_xml xml in
348 open_disk_images images cb
350 | Open_images (images, cb) ->
351 status "Opening disk images ...";
353 open_disk_images images cb
355 | Read_directory (src, dir, cb) ->
356 status "Reading directory %s ..." dir;
359 let names, stats, links =
360 with_mount_ro g src (
362 let names = g#ls dir in (* sorted and without . and .. *)
363 let stats = lstatlist g dir names in
364 let links = readlinks g dir names (Array.of_list stats) in
365 Array.to_list names, stats, links
368 let n = List.length names in
369 n = List.length stats && n = List.length links
371 let entries = List.combine (List.combine names stats) links in
372 let entries = List.map (
373 fun ((name, stat), link) ->
374 { dent_name = name; dent_stat = stat; dent_link = link }
377 status "Finished reading directory %s" dir;
378 callback_if_not_discarded cb entries
380 | Run_command (cmd, cb) ->
381 status "Running %s ..." cmd;
383 if Sys.command cmd <> 0 then
384 failwith "External command failed: %s" cmd;
386 status "Finished %s ..." cmd;
388 callback_if_not_discarded cb ()
390 (* Expect to be connected, and return the current libvirt connection. *)
394 | None -> failwith "not connected to libvirt"
399 | None -> failwith "no domain or disk image is open"
401 (* Close all libvirt and libguestfs handles. *)
403 (match !conn with Some conn -> C.close conn | None -> ());
408 (match !g with Some g -> g#close () | None -> ());
411 and get_disk_images_from_xml xml =
412 let xml = Xml.parse_string xml in
414 (* Return the device nodes. *)
417 | Xml.Element ("domain", _, children) ->
421 | Xml.Element ("devices", _, devices) -> Some devices
426 failwith "get_xml_desc didn't return <domain/>" in
428 (* Look for <source attr_name=attr_val/> and return attr_val. *)
429 let rec source_of attr_name = function
431 | Xml.Element ("source", attrs, _) :: rest ->
432 (try Some (List.assoc attr_name attrs)
433 with Not_found -> source_of attr_name rest)
434 | _ :: rest -> source_of attr_name rest
437 (* Look for <driver type=attr_val/> and return attr_val. *)
438 let rec format_of = function
440 | Xml.Element ("driver", attrs, _) :: rest ->
441 (try Some (List.assoc "type" attrs)
442 with Not_found -> format_of rest)
443 | _ :: rest -> format_of rest
446 (* Look for <disk> nodes and return the sources (block devices) of those. *)
450 | Xml.Element ("disk", attrs, disks) ->
453 let typ = List.assoc "type" attrs in
454 if typ = "file" then source_of "file" disks
455 else if typ = "block" then source_of "dev" disks
462 let format = format_of disks in
463 Some (filename, format)
469 (* The common code for Open_domain and Open_images which opens the
470 * libguestfs handle, adds the disks, and launches the appliance.
472 and open_disk_images images cb =
473 debug "opening disk image %s" (string_of_images images);
476 let g' = new G.guestfs () in
480 g#set_trace (trace ());
482 (* Uncomment the next line to pass the verbose flag from the command
483 * line through to libguestfs. This is not generally necessary since
484 * we are not so interested in debugging libguestfs problems at this
485 * level, and the user can always set LIBGUESTFS_DEBUG=1 if they need
488 (* g#set_verbose (verbose ());*)
490 (* Attach progress bar callback. *)
492 g#set_event_callback (
493 fun g event handle buf array ->
494 if event == G.EVENT_PROGRESS && Array.length array == 4 then (
495 let proc_nr = array.(0)
496 and serial = array.(1)
497 and position = array.(2)
498 and total = array.(3) in
499 debug "progress callback proc_nr=%Ld serial=%Ld posn=%Ld total=%Ld"
500 proc_nr serial position total;
501 GtkThread.async !progress_hook (position, total)
503 ) [ G.EVENT_PROGRESS ]
509 g#add_drive_opts ~readonly:true filename
510 | filename, Some format ->
511 g#add_drive_opts ~readonly:true ~format filename
516 status "Listing filesystems ...";
518 (* Get list of filesystems. *)
519 let fses = g#list_filesystems () in
521 status "Looking for operating systems ...";
523 (* Perform inspection. This can fail, ignore errors. *)
525 try Array.to_list (g#inspect_os ())
528 debug "inspection failed (error ignored): %s" msg;
531 let oses = List.map (
533 let typ = g#inspect_get_type root in
534 let windows_systemroot =
535 if typ <> "windows" then None
537 try Some (g#inspect_get_windows_systemroot root)
538 with G.Error _ -> None
541 (* Create most of the OS object that we're going to return. We
542 * have to pass this to with_mount_ro below which is why we need
543 * to partially create it here.
547 insp_arch = g#inspect_get_arch root;
548 insp_distro = g#inspect_get_distro root;
549 insp_filesystems = g#inspect_get_filesystems root;
550 insp_hostname = g#inspect_get_hostname root;
551 insp_major_version = g#inspect_get_major_version root;
552 insp_minor_version = g#inspect_get_minor_version root;
553 insp_mountpoints = g#inspect_get_mountpoints root;
554 insp_package_format = g#inspect_get_package_format root;
555 insp_package_management = g#inspect_get_package_management root;
556 insp_product_name = g#inspect_get_product_name root;
558 insp_windows_systemroot = windows_systemroot;
559 insp_winreg_DEFAULT = None; (* incomplete, see below *)
560 insp_winreg_SAM = None;
561 insp_winreg_SECURITY = None;
562 insp_winreg_SOFTWARE = None;
563 insp_winreg_SYSTEM = None;
566 (* We need to mount the root in order to look for Registry hives. *)
567 let winreg_DEFAULT, winreg_SAM, winreg_SECURITY, winreg_SOFTWARE,
569 match windows_systemroot with
570 | None -> None, None, None, None, None
572 with_mount_ro g (OS os) (
574 let check_for_hive filename =
576 sprintf "%s/system32/config/%s" sysroot filename in
577 try Some (g#case_sensitive_path path)
578 with G.Error _ -> None
580 check_for_hive "default",
581 check_for_hive "sam",
582 check_for_hive "security",
583 check_for_hive "software",
584 check_for_hive "system"
587 (* Fill in the remaining struct fields. *)
589 insp_winreg_DEFAULT = winreg_DEFAULT;
590 insp_winreg_SAM = winreg_SAM;
591 insp_winreg_SECURITY = winreg_SECURITY;
592 insp_winreg_SOFTWARE = winreg_SOFTWARE;
593 insp_winreg_SYSTEM = winreg_SYSTEM
599 insp_all_filesystems = fses;
603 status "Finished opening disk";
604 callback_if_not_discarded cb data
606 (* Start up one slave thread. *)
607 let slave_thread = Thread.create loop ()
609 (* Note the following function is called from the main thread. *)
611 discard_command_queue ();
612 ignore (send_to_slave Exit_thread);
613 Thread.join slave_thread