1 #!/usr/bin/ocamlrun /usr/bin/ocaml
3 (* virt-p2v is a script which performs a physical to
4 * virtual conversion of local disks.
6 * Copyright (C) 2007-2008 Red Hat Inc.
7 * Written by Richard W.M. Jones <rjones@redhat.com>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 | Part of string * string (* eg. "hda", "1" *)
26 | LV of string * string (* eg. "VolGroup00", "LogVol00" *)
28 | P2V (* physical to virtual *)
29 | V2V (* virtual to virtual *)
30 (*| V2P*) (* virtual to physical - not impl *)
32 | Auto of partition (* Automatic network configuration. *)
33 | Shell (* Start a shell. *)
34 | QEMUUserNet (* Assume we're running under qemu. *)
35 | Static of string * string * string * string * string
36 (* interface, address, netmask, gateway, nameserver *)
39 ssh_host : string; (* Remote host for SSH. *)
40 ssh_port : string; (* Remote port. *)
41 ssh_directory : string; (* Remote directory. *)
42 ssh_username : string; (* Remote username. *)
43 ssh_compression : bool; (* If true, use SSH compression. *)
44 ssh_check : bool; (* If true, check SSH is working. *)
51 | I386 | X86_64 | IA64 | PPC | PPC64 | SPARC | SPARC64
55 | W32 | W64 | WUnknown
56 type target_config = {
57 tgt_hypervisor : hypervisor option; (* Remote hypervisor. *)
58 tgt_architecture : architecture; (* Remote architecture. *)
59 tgt_memory : int; (* Memory (megabytes). *)
60 tgt_vcpus : int; (* Number of virtual CPUs. *)
61 tgt_mac_address : string; (* MAC address. *)
62 tgt_libvirtd : bool; (* True if libvirtd on remote. *)
65 (*----------------------------------------------------------------------*)
66 (* TO MAKE A CUSTOM VIRT-P2V SCRIPT, adjust the defaults in this section.
68 * If left as they are, then this will create a generic virt-p2v script
69 * which asks the user for each question. If you set the defaults here
70 * then you will get a custom virt-p2v which is partially or even fully
71 * automated and won't ask the user any questions.
73 * Note that 'None' means 'no default' (ie. ask the user) whereas
74 * 'Some foo' means use 'foo' as the answer.
76 * These are documented in the virt-p2v(1) manual page.
78 * After changing them, run './virt-p2v --test' to check syntax.
81 (* If greeting is true, wait for keypress after boot and during
82 * final verification. Set to 'false' for less interactions.
84 let config_greeting = ref true
86 (* General type of transfer. *)
87 let config_transfer_type = ref None
89 (* Network configuration. *)
90 let config_network = ref None
92 (* SSH configuration. *)
93 let config_ssh = ref None
95 (* What to transfer. *)
96 let config_devices_to_send = ref None
97 let config_root_filesystem = ref None
99 (* Configuration of the target. *)
100 let config_target = ref None
102 (* The name of the program as displayed in various places. *)
103 let program_name = "virt-p2v"
105 (* If you want to test the dialog stages, set this to true. *)
106 let test_dialog_stages = false
108 (* END OF CUSTOM virt-p2v SCRIPT SECTION. *)
109 (*----------------------------------------------------------------------*)
111 (* Load external libraries. *)
114 #directory "+extlib";;
120 #directory "+xml-light";;
121 #load "xml-light.cma";;
122 #directory "+libvirt";;
123 #load "mllibvirt.cma";;
130 (*----------------------------------------------------------------------*)
131 (* General helper functions. *)
133 let sort_uniq ?(cmp = compare) xs = (* sort and uniq a list *)
134 let xs = List.sort ~cmp xs in
135 let rec loop = function
136 | [] -> [] | [x] -> [x]
137 | x1 :: x2 :: xs when x1 = x2 -> loop (x1 :: xs)
138 | x :: xs -> x :: loop xs
142 let input_all_lines chan =
143 let lines = ref [] in
145 while true do lines := input_line chan :: !lines done; []
147 End_of_file -> List.rev !lines
149 let dev_of_partition = function
150 | Part (dev, partnum) -> sprintf "/dev/%s%s" dev partnum
151 | LV (vg, lv) -> sprintf "/dev/%s/%s" vg lv
153 let string_of_architecture = function
160 | SPARC64 -> "sparc64"
161 | OtherArch arch -> arch
164 let architecture_of_string = function
166 String.length str = 4 &&
167 (str.[0] = 'i' || str.[0] = 'I') &&
168 (str.[1] >= '3' && str.[1] <= '6') &&
169 str.[2] = '8' && str.[3] = '6' -> I386
170 | "x86_64" | "X86_64" | "x86-64" | "X86-64" -> X86_64
171 | "ia64" | "IA64" -> IA64
172 | "ppc" | "PPC" | "ppc32" | "PPC32" -> PPC
173 | "ppc64" | "PPC64" -> PPC64
174 | "sparc" | "SPARC" | "sparc32" | "SPARC32" -> SPARC
175 | "sparc64" | "SPARC64" -> SPARC64
177 | str -> OtherArch str
179 let wordsize_of_architecture = function
187 | OtherArch arch -> WUnknown
188 | UnknownArch -> WUnknown
190 type nature = LinuxSwap
191 | LinuxRoot of architecture * linux_distro
192 | WindowsRoot (* Windows C: *)
193 | LinuxBoot (* Linux /boot *)
194 | NotRoot (* mountable, but not / or /boot *)
196 and linux_distro = RHEL of int * int
198 | Debian of int * int
201 let rec string_of_nature = function
202 | LinuxSwap -> "Linux swap"
203 | LinuxRoot (architecture, distro) ->
204 string_of_linux_distro distro ^ " " ^ string_of_architecture architecture
205 | WindowsRoot -> "Windows root"
206 | LinuxBoot -> "Linux /boot"
207 | NotRoot -> "Mountable non-root"
208 | UnknownNature -> "Unknown"
209 and string_of_linux_distro = function
210 | RHEL (a,b) -> sprintf "RHEL %d.%d" a b
211 | Fedora v -> sprintf "Fedora %d" v
212 | Debian (a,b) -> sprintf "Debian %d.%d" a b
213 | OtherLinux -> "Linux"
215 (* XML helper functions. *)
216 let rec children_with_name name xml =
217 let children = Xml.children xml in
220 | Xml.Element (n, _, _) when n = name -> true
223 and xml_has_pcdata_child name pcdata xml =
224 xml_has_child_matching (
226 | Xml.Element (n, _, [Xml.PCData pcd])
227 when n = name && pcd = pcdata -> true
230 and xml_has_attrib_child name attrib xml =
231 xml_has_child_matching (
233 | Xml.Element (n, attribs, _)
234 when n = name && List.mem attrib attribs -> true
237 and xml_has_child_matching f xml =
238 let children = Xml.children xml in
239 List.exists f children
240 and find_child_with_name name xml =
241 let children = children_with_name name xml in
243 | [] -> raise Not_found
245 and find_pcdata_child name xml =
246 let children = children_with_name name xml in
247 let rec loop = function
248 | [] -> raise Not_found
249 | Xml.Element (_, _, [Xml.PCData pcd]) :: _ -> pcd
254 type ('a, 'b) either = Either of 'a | Or of 'b
256 (* We go into and out of newt mode at various stages, but we might
257 * also need to put up a message at any time. This keeps track of
258 * whether we are in newt mode or not.
260 * General tip: Try to do any complex operations like setting up the
261 * network or probing disks outside newt mode, and try not to throw
262 * exceptions in newt mode.
264 let in_newt = ref false
266 if !in_newt then f ()
270 try Either (Newt.init_and_finish f)
271 with exn -> Or exn in
273 match r with Either r -> r | Or exn -> raise exn
276 (* Clear the screen, open a new centered window, make sure the background
277 * and help messages are consistent.
279 let open_centered_window ?stage width height title =
280 if not !in_newt then failwith "open_centered_window: not in newt mode";
282 Newt.centered_window width height title;
284 program_name ^ (match stage with
286 | Some stage -> " - " ^ stage) in
287 Newt.draw_root_text 0 0 root_text;
288 Newt.push_help_line "F12 for next screen | [ALT] [F2] root / no password for shell"
290 (* Some general dialog boxes. *)
291 let message_box title text =
294 open_centered_window 40 20 title;
296 let textbox = Newt.textbox 1 1 36 14 [Newt.WRAP; Newt.SCROLL] in
297 Newt.textbox_set_text textbox text;
298 let ok = Newt.button 28 16 " OK " in
299 let form = Newt.form None None [] in
300 Newt.form_add_components form [textbox; ok];
302 Newt.component_takes_focus ok true;
304 ignore (Newt.run_form form);
308 (* Fail and exit with error. *)
311 let text = "\n" ^ text ^ "\n\nIf you want to report this error, there is a shell on [ALT] [F2], log in as root with no password.\n\nPlease provide the contents of /tmp/virt-p2v.log and output of the 'dmesg' command." in
312 message_box "Error" text;
315 (* Display a dialog with checkboxes, return the multiple selected items. *)
316 let select_multiple ?stage ?(force_one = false) width title items =
319 open_centered_window ?stage width 20 title;
323 fun i (label, handle, selected) ->
325 Newt.checkbox 1 (i+1) label
326 (if selected then '*' else ' ') None in
330 let ok = Newt.button 48 16 " OK " in
333 if List.length entries > 10 then
334 Some (Newt.vertical_scrollbar 58 1 10
335 Newt_int.NEWT_COLORSET_WINDOW
336 Newt_int.NEWT_COLORSET_ACTCHECKBOX)
339 let form = Newt.form vb None [] in
340 Newt.form_add_components form (List.map snd entries);
341 Newt.form_add_component form ok;
345 ignore (Newt.run_form form);
346 let selected = List.filter_map (
348 if Newt.checkbox_get_value cb = '*' then Some handle else None
350 if force_one && selected = [] then loop ()
360 (* Display a dialog with radio buttons, return the single selected item. *)
361 let select_single ?stage width title items =
362 if items = [] then failwith "select_single: no items";
366 open_centered_window ?stage width 20 title;
368 let prev = ref None in
371 fun i (label, handle) ->
372 let rb = Newt.radio_button 1 (i+1) label (!prev = None) !prev in
377 let ok = Newt.button (width-12) 16 " OK " in
380 if List.length entries > 10 then
381 Some (Newt.vertical_scrollbar 58 1 10
382 Newt_int.NEWT_COLORSET_WINDOW
383 Newt_int.NEWT_COLORSET_ACTCHECKBOX)
386 let form = Newt.form vb None [] in
387 Newt.form_add_components form (List.map snd entries);
388 Newt.form_add_component form ok;
392 ignore (Newt.run_form form);
393 let r = Option.get !prev in
394 let r = Newt.radio_get_current r in
395 (* Now we compare 'r' to all the 'rb's in the list
396 * to see which one is selected.
399 List.find (fun (_, rb) -> Newt.component_equals r rb) entries
410 (* Shell-safe quoting function. In fact there's one in stdlib so use it. *)
411 let quote = Filename.quote
413 (* Run a shell command and check it returns 0. *)
415 eprintf "sh: %s\n%!" cmd;
416 if Sys.command cmd <> 0 then failwith (sprintf "Command failed:\n\n%s" cmd)
419 eprintf "shfailok: %s\n%!" cmd;
420 ignore (Sys.command cmd)
422 let shwithstatus cmd =
423 eprintf "shwithstatus: %s\n%!" cmd;
426 (* Same as `cmd` in shell. Any error message will be in the logfile. *)
428 eprintf "shget: %s\n%!" cmd;
429 let chan = open_process_in cmd in
430 let lines = input_all_lines chan in
431 match close_process_in chan with
432 | WEXITED 0 -> Some lines (* command succeeded *)
433 | WEXITED _ -> None (* command failed *)
434 | WSIGNALED i -> failwith (sprintf "shget: command killed by signal %d" i)
435 | WSTOPPED i -> failwith (sprintf "shget: command stopped by signal %d" i)
437 (* Start an interactive shell. Need to juggle file descriptors a bit
438 * because bash write PS1 to stderr (currently directed to the logfile).
442 | 0 -> (* child, runs bash *)
445 (* Sys.command runs 'sh -c' which blows away PS1, so set it late. *)
447 Sys.command "PS1='\\u@\\h:\\w\\$ ' /bin/bash --norc --noprofile -i"
449 | _ -> (* parent, waits *)
450 eprintf "waiting for subshell to exit\n%!";
453 (* Some true if is dir/file, Some false if not, None if not found. *)
455 try Some ((stat path).st_kind = S_DIR)
456 with Unix_error (ENOENT, "stat", _) -> None
458 try Some ((stat path).st_kind = S_REG)
459 with Unix_error (ENOENT, "stat", _) -> None
461 (*----------------------------------------------------------------------*)
462 (* P2V-specific helper functions. *)
464 (* Generate a predictable safe name containing only letters, numbers
465 * and underscores. If passed a string with no letters or numbers,
466 * generates "_1", "_2", etc.
471 fun () -> incr i; "_" ^ string_of_int !i
474 let is_safe = function 'a'..'z'|'A'..'Z'|'0'..'9' -> true | _ -> false in
475 let name = String.copy name in
476 let have_safe = ref false in
477 for i = 0 to String.length name - 1 do
478 if not (is_safe name.[i]) then name.[i] <- '_' else have_safe := true
480 if !have_safe then name else next_anon ()
482 type block_device = string * int64 (* "hda" & size in bytes *)
484 (* Parse the output of 'lvs' to get list of LV names, sizes,
485 * corresponding PVs, etc. Returns a list of (lvname, PVs, lvsize).
488 let devname = Pcre.regexp "^/dev/(.+)\\(.+\\)$" in
492 shget "lvs --noheadings -o vg_name,lv_name,devices,lv_size"
496 let lines = List.map Pcre.split lines in
499 | [vg; lv; pvs; lvsize]
500 | [_; vg; lv; pvs; lvsize] ->
501 let pvs = String.nsplit pvs "," in
502 let pvs = List.filter_map (
505 let subs = Pcre.exec ~rex:devname pv in
506 Some (Pcre.get_substring subs 1)
509 eprintf "lvs: unexpected device name: %s\n%!" pv;
512 LV (vg, lv), pvs, lvsize
514 failwith ("lvs: unexpected output: " ^ String.concat "," line)
517 (* Get the partitions on a block device.
518 * eg. "sda" -> [Part ("sda","1"); Part ("sda", "2")]
520 let get_partitions dev =
521 let rex = Pcre.regexp ("^" ^ dev ^ "(.+)$") in
522 let devdir = "/sys/block/" ^ dev in
523 let parts = Sys.readdir devdir in
524 let parts = Array.to_list parts in
525 let parts = List.filter (
526 fun name -> Some true = is_dir (devdir ^ "/" ^ name)
528 let parts = List.filter_map (
531 let subs = Pcre.exec ~rex part in
532 Some (Part (dev, Pcre.get_substring subs 1))
538 (* Generate snapshot device name from device name. *)
539 let snapshot_name dev =
540 "snap" ^ (safe_name dev)
542 (* Perform a device-mapper snapshot with ramdisk overlay. *)
544 let next_free_ram_disk =
546 fun () -> incr i; "/dev/ram" ^ string_of_int !i
548 fun origin_dev snapshot_dev ->
549 let ramdisk = next_free_ram_disk () in
551 let cmd = "blockdev --getsz " ^ quote ("/dev/" ^ origin_dev) in
552 let lines = shget cmd in
554 | Some (sectors::_) -> Int64.of_string sectors
556 failwith (sprintf "Snapshot failed - unable to read the size in sectors of block device %s" origin_dev) in
558 (* Create the snapshot origin device. Called, eg. snap_sda1_org *)
559 sh (sprintf "dmsetup create %s_org --table='0 %Ld snapshot-origin /dev/%s'"
560 snapshot_dev sectors origin_dev);
561 (* Create the snapshot. *)
562 sh (sprintf "dmsetup create %s --table='0 %Ld snapshot /dev/mapper/%s_org %s n 64'"
563 snapshot_dev sectors snapshot_dev ramdisk)
565 (* Try to perform automatic network configuration, assuming a Fedora or
566 * RHEL-like root filesystem mounted on /mnt/root.
568 let auto_network () =
569 (* Fedora gives an error if this file doesn't exist. *)
570 sh "touch /etc/resolv.conf";
572 (* NB. Lazy unmount is required because dhclient keeps its current
573 * directory open on /etc/sysconfig/network-scripts/
574 * (Fixed in dhcp >= 4.0.0 but be generous anyway).
576 sh "mount -o bind /mnt/root/etc /etc";
577 let status = shwithstatus "/etc/init.d/network start" in
580 (* Try to ping the default gateway to see if this worked. *)
581 shfailok "ping -c3 `/sbin/ip route list match 0.0.0.0 | head -1 | awk '{print $3}'`";
583 if !config_greeting then (
584 printf "\n\nDid automatic network configuration work?\n";
585 printf "Hint: If not sure, there is a shell on console [ALT] [F2]\n";
587 let line = read_line () in
588 String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
591 (* Non-interactive: return the status of /etc/init.d/network start. *)
594 (* Configure the network statically. *)
595 let static_network (interface, address, netmask, gateway, nameserver) =
596 let do_cmd_or_exit cmd = if shwithstatus cmd <> 0 then raise Exit in
598 do_cmd_or_exit (sprintf "ifconfig %s %s netmask %s"
599 (quote interface) (quote address) (quote netmask));
600 do_cmd_or_exit (sprintf "route add default gw %s %s"
601 (quote gateway) (quote interface));
602 if nameserver <> "" then
603 do_cmd_or_exit (sprintf "echo nameserver %s > /etc/resolv.conf"
607 Exit -> false (* failed *)
609 (* http://fabrice.bellard.free.fr/qemu/qemu-doc.html#SEC30 *)
610 let qemu_network () =
611 sh "ifconfig eth0 10.0.2.10 netmask 255.255.255.0";
612 sh "route add default gw 10.0.2.2 eth0";
613 sh "echo nameserver 10.0.2.3 > /etc/resolv.conf"
615 (* Map local device names to remote devices names. At the moment we
616 * just change sd* to hd* (as device names appear under fullvirt). In
617 * future, lots of complex possibilities.
619 let remote_of_origin_dev =
620 let devsd = Pcre.regexp "^sd([[:alpha:]]+[[:digit:]]*)$" in
621 let devsd_subst = Pcre.subst "hd$1" in
623 Pcre.replace ~rex:devsd ~itempl:devsd_subst dev
625 (* Make an SSH connection to the remote machine, execute command.
626 * The connection remains open until you call ssh_disconnect, it
627 * times out or there is some error.
629 * NB. The command is NOT quoted.
631 * Returns a pair (file descriptor, channel), both referring to the
632 * same thing. Use whichever is more convenient.
634 let ssh_connect config cmd =
635 let cmd = sprintf "ssh%s -l %s -p %s %s %s"
636 (if config.ssh_compression then " -C" else "")
637 (quote config.ssh_username) (quote config.ssh_port) (quote config.ssh_host)
639 eprintf "ssh_connect: %s\n%!" cmd;
640 let chan = open_process_out cmd in
641 descr_of_out_channel chan, chan
643 let ssh_disconnect (_, chan) =
644 eprintf "ssh_disconnect\n%!";
645 match close_process_out chan with
646 | WEXITED 0 -> () (* OK *)
647 | WEXITED i -> failwith (sprintf "ssh: exited with error code %d" i)
648 | WSIGNALED i -> failwith (sprintf "ssh: killed by signal %d" i)
649 | WSTOPPED i -> failwith (sprintf "ssh: stopped by signal %d" i)
651 (* Use these functions to upload a file. *)
652 let ssh_start_upload config filename =
654 sprintf "cat \\> %s/%s" (quote config.ssh_directory) (quote filename) in
655 ssh_connect config cmd
657 let ssh_finish_upload = ssh_disconnect
659 (* Test SSH connection. *)
660 let test_ssh config =
661 printf "Testing SSH connection by listing files in remote directory ...\n\n%!";
663 let cmd = sprintf "/bin/ls %s" (quote config.ssh_directory) in
664 let conn = ssh_connect config cmd in
667 if !config_greeting then (
668 printf "\n\nDid SSH work?\n";
669 printf "Hint: If not sure, there is a shell on console [ALT] [F2]\n";
671 let line = read_line () in
672 String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
677 (* Rewrite /mnt/root/etc/fstab. *)
678 let rewrite_fstab devices_to_send =
679 let filename = "/mnt/root/etc/fstab" in
680 if is_file filename = Some true then (
681 sh ("cp " ^ quote filename ^ " " ^ quote (filename ^ ".p2vsaved"));
683 let chan = open_in filename in
684 let lines = input_all_lines chan in
686 let lines = List.map Pcre.split lines in
687 let lines = List.map (
689 | dev :: rest when String.starts_with dev "/dev/" ->
690 let dev = String.sub dev 5 (String.length dev - 5) in
691 let dev = remote_of_origin_dev dev in
692 let dev = "/dev/" ^ dev in
697 let chan = open_out filename in
700 | [dev; mountpoint; fstype; options; freq; passno] ->
701 fprintf chan "%-23s %-23s %-7s %-15s %s %s\n"
702 dev mountpoint fstype options freq passno
704 output_string chan (String.concat " " line);
705 output_char chan '\n'
710 (* Generate a random MAC address in the Xen-reserved space. *)
711 let random_mac_address () =
713 List.map (sprintf "%02x") (
714 List.map (fun _ -> Random.int 256) [0;0;0]
716 String.concat ":" ("00"::"16"::"3e"::random)
718 (* Generate a random UUID. *)
720 let hex = "0123456789abcdef" in
722 let str = String.create 32 in
723 for i = 0 to 31 do str.[i] <- hex.[Random.int 16] done;
726 (*----------------------------------------------------------------------*)
727 (* Main entry point. *)
729 (* The general plan for the main function is to operate in stages:
734 * Information gathering about the system
735 * | (eg. block devices, number of CPUs, etc.)
737 * Greeting and type of transfer question
741 * | (after this point we have a working network)
744 * | (after this point we have a working SSH connection)
746 * Questions about what to transfer (block devs, root fs) <--.
749 * Questions about hypervisor configuration |
752 * Verify information -------- user wants to change info ----/
757 * Prior versions of virt-p2v (the ones which used 'dialog') had support
758 * for a back button so they could go back through dialogs. I removed
759 * this because it was hard to support and not particularly useful.
762 let rec main ttyname =
765 (* Running from an init script. We don't have much of a
766 * login environment, so set one up.
770 ["/usr/sbin"; "/sbin"; "/usr/local/bin"; "/usr/kerberos/bin";
771 "/usr/bin"; "/bin"]);
772 putenv "HOME" "/root";
773 putenv "LOGNAME" "root";
775 (* We can safely write in /tmp (it's a synthetic live CD directory). *)
778 (* Set up logging to /tmp/virt-p2v.log. *)
779 let fd = openfile "virt-p2v.log" [ O_WRONLY; O_APPEND; O_CREAT ] 0o644 in
783 (* Log the start up time. *)
784 eprintf "\n\n**************************************************\n\n";
785 let tm = localtime (time ()) in
786 eprintf "%s starting up at %04d-%02d-%02d %02d:%02d:%02d\n\n%!"
788 (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec;
790 (* Connect stdin/stdout to the tty. *)
794 let fd = openfile ("/dev/" ^ ttyname) [ O_RDWR ] 0 in
798 printf "%s starting up ...\n%!" program_name;
800 (* Disable screen blanking on tty. *)
801 sh "setterm -blank 0";
803 (* Check that the environment is a sane-looking live CD. If not, bail. *)
804 if not test_dialog_stages && is_dir "/mnt/root" <> Some true then
806 "You should only run this script from the live CD or a USB key.";
808 (* Start of the information gathering phase. *)
809 printf "Detecting hard drives (this may take some time) ...\n%!";
811 (* Search for all non-removable block devices. Do this early and bail
812 * if we can't find anything. This is a list of strings, like "hda".
814 let all_block_devices : block_device list =
815 let rex = Pcre.regexp "^[hs]d" in
816 let devices = Array.to_list (Sys.readdir "/sys/block") in
817 let devices = List.sort devices in
818 let devices = List.filter (fun d -> Pcre.pmatch ~rex d) devices in
819 eprintf "all_block_devices: block devices: %s\n%!"
820 (String.concat "; " devices);
821 (* Run blockdev --getsize64 on each, and reject any where this fails
822 * (probably removable devices).
824 let devices = List.filter_map (
826 let cmd = "blockdev --getsize64 " ^ quote ("/dev/" ^ d) in
827 let lines = shget cmd in
829 | Some (blksize::_) -> Some (d, Int64.of_string blksize)
830 | Some [] | None -> None
832 eprintf "all_block_devices: non-removable block devices: %s\n%!"
834 (List.map (fun (d, b) -> sprintf "%s [%Ld]" d b) devices));
836 failwith "No non-removable block devices (hard disks, etc.) could be found on this machine.";
839 (* Search for partitions and LVs (anything that could contain a
840 * filesystem directly). We refer to these generically as
843 let all_partitions : partition list =
846 let lvs = get_lvs () in
847 let pvs = List.map (fun (_, pvs, _) -> pvs) lvs in
848 let pvs = List.concat pvs in
849 let pvs = sort_uniq pvs in
850 eprintf "all_partitions: PVs: %s\n%!" (String.concat "; " pvs);
851 let lvs = List.map (fun (lvname, _, _) -> lvname) lvs in
852 eprintf "all_partitions: LVs: %s\n%!"
853 (String.concat "; " (List.map dev_of_partition lvs));
856 (* Partitions (eg. "sda1", "sda2"). *)
858 let parts = List.map fst all_block_devices in
859 let parts = List.map get_partitions parts in
860 let parts = List.concat parts in
861 eprintf "all_partitions: all partitions: %s\n%!"
862 (String.concat "; " (List.map dev_of_partition parts));
864 (* Remove any partitions which are PVs. *)
865 let parts = List.filter (
867 | Part (dev, partnum) -> not (List.mem (dev ^ partnum) pvs)
868 | LV _ -> assert false
871 eprintf "all_partitions: partitions after removing PVs: %s\n%!"
872 (String.concat "; " (List.map dev_of_partition parts));
874 (* Concatenate LVs & Parts *)
877 (* Try to determine the nature of each partition.
878 * Root? Swap? Architecture? etc.
880 let all_partitions : (partition * nature) list =
881 (* Output of 'file' command for Linux swap file. *)
882 let swap = Pcre.regexp "Linux.*swap.*file" in
883 (* Contents of /etc/redhat-release. *)
884 let rhel = Pcre.regexp "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)(?:\\.(\\d+))?" in
885 let fedora = Pcre.regexp "Fedora.*release (\\d+)" in
886 (* Contents of /etc/debian_version. *)
887 let debian = Pcre.regexp "^(\\d+)\\.(\\d+)" in
888 (* Output of 'file' on certain executables. *)
889 let i386 = Pcre.regexp ", Intel 80386," in
890 let x86_64 = Pcre.regexp ", x86-64," in
891 let itanic = Pcre.regexp ", IA-64," in
893 (* Examine the filesystem mounted on 'mnt' to determine the
894 * operating system, and, if Linux, the distro.
897 if is_dir (mnt ^ "/Windows") = Some true &&
898 is_file (mnt ^ "/autoexec.bat") = Some true then
900 else if is_dir (mnt ^ "/etc") = Some true &&
901 is_dir (mnt ^ "/sbin") = Some true &&
902 is_dir (mnt ^ "/var") = Some true then (
903 if is_file (mnt ^ "/etc/redhat-release") = Some true then (
904 let chan = open_in (mnt ^ "/etc/redhat-release") in
905 let lines = input_all_lines chan in
909 | [] -> (* empty /etc/redhat-release ...? *)
910 LinuxRoot (UnknownArch, OtherLinux)
911 | line::_ -> (* try to detect OS from /etc/redhat-release *)
913 let subs = Pcre.exec ~rex:rhel line in
914 let major = int_of_string (Pcre.get_substring subs 1) in
916 try int_of_string (Pcre.get_substring subs 2)
917 with Not_found -> 0 in
918 LinuxRoot (UnknownArch, RHEL (major, minor))
920 Not_found | Failure "int_of_string" ->
922 let subs = Pcre.exec ~rex:fedora line in
923 let version = int_of_string (Pcre.get_substring subs 1) in
924 LinuxRoot (UnknownArch, Fedora version)
926 Not_found | Failure "int_of_string" ->
927 LinuxRoot (UnknownArch, OtherLinux)
929 else if is_file (mnt ^ "/etc/debian_version") = Some true then (
930 let chan = open_in (mnt ^ "/etc/debian_version") in
931 let lines = input_all_lines chan in
935 | [] -> (* empty /etc/debian_version ...? *)
936 LinuxRoot (UnknownArch, OtherLinux)
937 | line::_ -> (* try to detect version from /etc/debian_version *)
939 let subs = Pcre.exec ~rex:debian line in
940 let major = int_of_string (Pcre.get_substring subs 1) in
941 let minor = int_of_string (Pcre.get_substring subs 2) in
942 LinuxRoot (UnknownArch, Debian (major, minor))
944 Not_found | Failure "int_of_string" ->
945 LinuxRoot (UnknownArch, OtherLinux)
948 LinuxRoot (UnknownArch, OtherLinux)
949 ) else if is_dir (mnt ^ "/grub") = Some true &&
950 is_file (mnt ^ "/grub/stage1") = Some true then (
953 NotRoot (* mountable, but not a root filesystem *)
956 (* Examine the Linux root filesystem mounted on 'mnt' to
957 * determine the architecture. We do this by looking at some
958 * well-known binaries that we expect to be there.
960 let detect_architecture mnt =
961 let cmd = "file -bL " ^ quote (mnt ^ "/sbin/init") in
963 | Some (str::_) when Pcre.pmatch ~rex:i386 str -> I386
964 | Some (str::_) when Pcre.pmatch ~rex:x86_64 str -> X86_64
965 | Some (str::_) when Pcre.pmatch ~rex:itanic str -> IA64
971 let dev = dev_of_partition part in (* Get /dev device. *)
974 (* Use 'file' command to detect if it is swap. *)
975 let cmd = "file -sbL " ^ quote dev in
977 | Some (str::_) when Pcre.pmatch ~rex:swap str -> LinuxSwap
979 (* Blindly try to mount the device. *)
980 let cmd = "mount -o ro " ^ quote dev ^ " /mnt/root" in
981 match shwithstatus cmd with
983 let os = detect_os "/mnt/root" in
986 | LinuxRoot (UnknownArch, distro) ->
987 let architecture = detect_architecture "/mnt/root" in
988 LinuxRoot (architecture, distro)
990 sh "umount /mnt/root";
993 | _ -> UnknownNature (* not mountable *)
997 eprintf "partition detection: %s is %s\n%!"
998 dev (string_of_nature nature);
1004 printf "Finished detecting hard drives.\n%!";
1006 (* Autodetect system memory. *)
1008 (* Try to parse dmesg first to find the 'Memory:' report when
1009 * the kernel booted. If available, this can give us an
1010 * indication of usable RAM on this system.
1012 let dmesg = shget "dmesg" in
1015 match dmesg with Some lines -> lines | None -> raise Not_found in
1017 List.find (fun line -> String.starts_with line "Memory: ") dmesg in
1018 let subs = Pcre.exec ~pat:"k/([[:digit:]]+)k available" line in
1019 let mem = Pcre.get_substring subs 1 in
1020 int_of_string mem / 1024
1022 Not_found | Failure "int_of_string" ->
1023 (* 'dmesg' can't be parsed. The backup plan is to look
1026 let mem = shget "head -1 /proc/meminfo | awk '{print $2/1024}'" in
1028 | Some (mem::_) -> int_of_float (float_of_string mem)
1030 (* For some reason even /proc/meminfo didn't work. Just
1031 * assume 256 MB instead.
1035 (* Autodetect system # pCPUs. *)
1036 let system_nr_cpus =
1038 shget "grep ^processor /proc/cpuinfo | tail -1 | awk '{print $3+1}'" in
1040 | Some (cpus::_) -> int_of_string cpus
1043 (* Greeting, type of transfer, network question stages.
1044 * These are all done in newt mode.
1046 let config_transfer_type, config_network =
1050 if !config_greeting then
1051 message_box program_name (sprintf "Welcome to %s, a live CD for migrating a physical machine to a virtualized host.\n\nTo continue press the Return key.\n\nTo get a shell you can use [ALT] [F2] and log in as root with no password.\n\nExtra information is logged in /tmp/virt-p2v.log but this file disappears when the machine reboots." program_name);
1053 (* Type of transfer. *)
1054 let config_transfer_type =
1055 match !config_transfer_type with
1059 "Physical to Virtual (P2V)", P2V;
1060 "Virtual to Virtual (V2V)", V2V;
1063 select_single ~stage:"Transfer type" 40
1067 (* Network configuration. *)
1068 let config_network =
1069 match !config_network with
1072 open_centered_window ~stage:"Network"
1073 60 20 "Configure network";
1075 let autolist = Newt.listbox 4 2 4 [Newt.SCROLL] in
1076 Newt.listbox_set_width autolist 52;
1078 (* Populate the "Automatic" listbox with RHEL/Fedora
1079 * root partitions found which allow us to do
1080 * automatic configuration in a known way.
1082 let rec loop = function
1084 | (partition, LinuxRoot (_, ((RHEL _|Fedora _) as distro)))
1088 (dev_of_partition partition)
1089 (string_of_linux_distro distro) in
1090 ignore (Newt.listbox_append_entry autolist label partition);
1092 | _ :: parts -> loop parts
1094 loop all_partitions;
1096 (* If there is no suitable root partition (the listbox
1097 * is empty) then disable the auto option and the listbox.
1099 let no_auto = Newt.listbox_item_count autolist = 0 in
1102 Newt.radio_button 1 1
1103 "Automatic from:" (not no_auto) None in
1105 Newt.radio_button 1 6
1106 "Start a shell" no_auto (Some auto) in
1109 Newt.component_takes_focus auto false;
1110 Newt.component_takes_focus
1111 (Newt.component_of_listbox autolist) false
1115 Newt.radio_button 1 7
1116 "QEMU user network" false (Some shell) in
1118 Newt.radio_button 1 8
1119 "No network or network already configured" false
1122 Newt.radio_button 1 9
1123 "Static configuration:" false (Some nonet) in
1125 let label1 = Newt.label 4 10 "Interface" in
1126 let entry1 = Newt.entry 16 10 (Some "eth0") 8 [] in
1127 let label2 = Newt.label 4 11 "Address" in
1128 let entry2 = Newt.entry 16 11 None 16 [] in
1129 let label3 = Newt.label 4 12 "Netmask" in
1130 let entry3 = Newt.entry 16 12 (Some "255.255.255.0") 16 [] in
1131 let label4 = Newt.label 4 13 "Gateway" in
1132 let entry4 = Newt.entry 16 13 None 16 [] in
1133 let label5 = Newt.label 4 14 "Nameserver" in
1134 let entry5 = Newt.entry 16 14 None 16 [] in
1136 let enable_static () =
1137 Newt.component_takes_focus entry1 true;
1138 Newt.component_takes_focus entry2 true;
1139 Newt.component_takes_focus entry3 true;
1140 Newt.component_takes_focus entry4 true;
1141 Newt.component_takes_focus entry5 true
1144 let disable_static () =
1145 Newt.component_takes_focus entry1 false;
1146 Newt.component_takes_focus entry2 false;
1147 Newt.component_takes_focus entry3 false;
1148 Newt.component_takes_focus entry4 false;
1149 Newt.component_takes_focus entry5 false
1152 let enable_autolist () =
1153 Newt.component_takes_focus
1154 (Newt.component_of_listbox autolist) true
1156 let disable_autolist () =
1157 Newt.component_takes_focus
1158 (Newt.component_of_listbox autolist) false
1162 Newt.component_add_callback auto
1163 (fun () ->disable_static (); enable_autolist ());
1164 Newt.component_add_callback shell
1165 (fun () -> disable_static (); disable_autolist ());
1166 Newt.component_add_callback qemu
1167 (fun () -> disable_static (); disable_autolist ());
1168 Newt.component_add_callback nonet
1169 (fun () -> disable_static (); disable_autolist ());
1170 Newt.component_add_callback static
1171 (fun () -> enable_static (); disable_autolist ());
1173 let ok = Newt.button 48 16 " OK " in
1175 let form = Newt.form None None [] in
1176 Newt.form_add_components form [auto;
1177 Newt.component_of_listbox autolist;
1178 shell;qemu;nonet;static;
1179 label1;label2;label3;label4;label5;
1180 entry1;entry2;entry3;entry4;entry5;
1185 ignore (Newt.run_form form);
1187 let r = Newt.radio_get_current auto in
1188 if Newt.component_equals r auto then (
1189 match Newt.listbox_get_current autolist with
1191 | Some part -> Auto part
1193 else if Newt.component_equals r shell then Shell
1194 else if Newt.component_equals r qemu then QEMUUserNet
1195 else if Newt.component_equals r nonet then NoNetwork
1196 else if Newt.component_equals r static then (
1197 let interface = Newt.entry_get_value entry1 in
1198 let address = Newt.entry_get_value entry2 in
1199 let netmask = Newt.entry_get_value entry3 in
1200 let gateway = Newt.entry_get_value entry4 in
1201 let nameserver = Newt.entry_get_value entry5 in
1202 if interface = "" || address = "" ||
1203 netmask = "" || gateway = "" then
1206 Static (interface, address, netmask, gateway, nameserver)
1215 config_transfer_type, config_network
1218 (* Try to bring up the network. *)
1219 (match config_network with
1221 printf "Network configuration.\n\n";
1222 printf "Please configure the network from this shell.\n\n";
1223 printf "When you have finished, exit the shell with ^D or exit.\n\n%!";
1226 | Static (interface, address, netmask, gateway, nameserver) ->
1227 printf "Trying static network configuration.\n\n%!";
1228 if not (static_network
1229 (interface, address, netmask, gateway, nameserver)) then (
1230 printf "\nAuto-configuration failed. Starting a shell.\n\n";
1231 printf "Please configure the network from this shell.\n\n";
1232 printf "When you have finished, exit the shell with ^D or exit.\n\n";
1238 "Trying network auto-configuration from root filesystem ...\n\n%!";
1240 (* Mount the root filesystem read-only under /mnt/root. *)
1241 sh ("mount -o ro " ^ quote (dev_of_partition rootfs) ^ " /mnt/root");
1243 if not (auto_network ()) then (
1244 printf "\nAuto-configuration failed. Starting a shell.\n\n";
1245 printf "Please configure the network from this shell.\n\n";
1246 printf "When you have finished, exit the shell with ^D or exit.\n\n";
1250 (* NB. Lazy unmount is required because dhclient keeps its current
1251 * directory open on /etc/sysconfig/network-scripts/
1253 sh ("umount -l /mnt/root");
1256 printf "Trying QEMU network configuration.\n\n%!";
1259 | NoNetwork -> (* this is easy ... *) ()
1262 (* SSH configuration phase. *)
1266 match !config_ssh with
1269 (* Query the user for SSH configuration. *)
1270 open_centered_window ~stage:"SSH configuration"
1271 60 20 "SSH configuration";
1273 let label1 = Newt.label 1 1 "Remote host" in
1274 let host = Newt.entry 20 1 None 36 [] in
1275 let label2 = Newt.label 1 2 "Remote port" in
1276 let port = Newt.entry 20 2 (Some "22") 6 [] in
1277 let label3 = Newt.label 1 3 "Remote directory" in
1278 let dir = Newt.entry 20 3 (Some "/var/lib/xen/images") 36 [] in
1279 let label4 = Newt.label 1 4 "SSH username" in
1280 let user = Newt.entry 20 4 (Some "root") 16 [] in
1282 There's no sensible way to support this for SSH:
1283 let label5 = Newt.label 1 5 "SSH password" in
1284 let pass = Newt.entry 20 5 None 16 [Newt.PASSWORD] in
1288 Newt.checkbox 16 7 "Use SSH compression (not good for LANs)"
1291 let check = Newt.checkbox 16 9 "Test SSH connection" '*' None in
1293 let ok = Newt.button 48 16 " OK " in
1295 let form = Newt.form None None [] in
1296 Newt.form_add_components form [label1;label2;label3;label4;
1303 ignore (Newt.run_form form);
1304 let host = Newt.entry_get_value host in
1305 let port = Newt.entry_get_value port in
1306 let dir = Newt.entry_get_value dir in
1307 let user = Newt.entry_get_value user in
1308 let compr = Newt.checkbox_get_value compr = '*' in
1309 let check = Newt.checkbox_get_value check = '*' in
1310 if host <> "" && port <> "" && user <> "" then
1311 { ssh_host = host; ssh_port = port; ssh_directory = dir;
1312 ssh_username = user;
1313 ssh_compression = compr;
1314 ssh_check = check; }
1324 (* If asked, check the SSH connection. *)
1325 if config_ssh.ssh_check then
1326 if not (test_ssh config_ssh) then
1327 failwith "SSH configuration failed";
1329 (* Devices and root partition and target configuration selection stage. *)
1330 let config_devices_to_send, config_root_filesystem, config_target =
1333 let config_devices_to_send =
1334 match !config_devices_to_send with
1337 let items = List.map (
1340 sprintf "/dev/%s (%.3f GB)" dev
1341 ((Int64.to_float size) /. (1024.*.1024.*.1024.)) in
1343 ) all_block_devices in
1345 select_multiple ~stage:"Block devices" ~force_one:true 60
1346 "Select block devices to send"
1349 let config_root_filesystem =
1350 match !config_root_filesystem with
1353 let items = List.map (
1354 fun (part, nature) ->
1356 sprintf "%s %s" (dev_of_partition part)
1357 (string_of_nature nature) in
1361 select_single ~stage:"Root filesystem" 60
1362 "Select root filesystem"
1366 match !config_target with
1369 open_centered_window ~stage:"Target system" 40 20
1370 "Configure target system";
1372 let hvlabel = Newt.label 1 1 "Hypervisor:" in
1373 let hvlistbox = Newt.listbox 16 1 4 [Newt.SCROLL] in
1374 Newt.listbox_append_entry hvlistbox "Xen" (Some Xen);
1375 Newt.listbox_append_entry hvlistbox "QEMU" (Some QEMU);
1376 Newt.listbox_append_entry hvlistbox "KVM" (Some KVM);
1377 Newt.listbox_append_entry hvlistbox "Other" None;
1379 let archlabel = Newt.label 1 5 "Architecture:" in
1380 let archlistbox = Newt.listbox 16 5 4 [Newt.SCROLL] in
1381 Newt.listbox_append_entry archlistbox "i386" I386;
1382 Newt.listbox_append_entry archlistbox
1383 "x86-64 (64-bit x86)" X86_64;
1384 Newt.listbox_append_entry archlistbox "IA64 (Itanium)" IA64;
1385 Newt.listbox_append_entry archlistbox "PowerPC 32-bit" PPC;
1386 Newt.listbox_append_entry archlistbox "PowerPC 64-bit" PPC64;
1387 Newt.listbox_append_entry archlistbox "SPARC 32-bit" SPARC;
1388 Newt.listbox_append_entry archlistbox "SPARC 64-bit" SPARC64;
1389 Newt.listbox_append_entry archlistbox "Unknown/other" UnknownArch;
1391 (* Get the architecture of the selected root filesystem.
1392 * If not known, default to UnknownArch.
1394 Newt.listbox_set_current_by_key archlistbox UnknownArch;
1396 match List.assoc config_root_filesystem all_partitions with
1397 | LinuxRoot (arch, _) ->
1398 Newt.listbox_set_current_by_key archlistbox arch
1403 let memlabel = Newt.label 1 9 "Memory (MB):" in
1404 let mementry = Newt.entry 16 9
1405 (Some (string_of_int system_memory)) 8 [] in
1406 let cpulabel = Newt.label 1 10 "CPUs:" in
1407 let cpuentry = Newt.entry 16 10
1408 (Some (string_of_int system_nr_cpus)) 4 [] in
1409 let maclabel = Newt.label 1 11 "MAC addr:" in
1410 let macentry = Newt.entry 16 11 None 20 [] in
1411 let maclabel2 = Newt.label 1 12 "(leave MAC blank for random)" in
1414 Newt.checkbox 12 14 "Use remote libvirtd" '*' None in
1416 let ok = Newt.button 28 16 " OK " in
1418 let form = Newt.form None None [] in
1419 Newt.form_add_components form
1420 [hvlabel; Newt.component_of_listbox hvlistbox;
1421 archlabel; Newt.component_of_listbox archlistbox;
1424 maclabel; macentry; maclabel2;
1430 ignore (Newt.run_form form);
1432 let hv = Newt.listbox_get_current hvlistbox in
1433 let arch = Newt.listbox_get_current archlistbox in
1434 let mem = int_of_string (Newt.entry_get_value mementry) in
1435 let cpus = int_of_string (Newt.entry_get_value cpuentry) in
1436 let mac = Newt.entry_get_value macentry in
1437 let libvirtd = Newt.checkbox_get_value libvirtd = '*' in
1438 if hv <> None && arch <> None && mem >= 0 && cpus >= 0
1440 { tgt_hypervisor = Option.get hv;
1441 tgt_architecture = Option.get arch;
1442 tgt_memory = mem; tgt_vcpus = cpus;
1444 if mac <> "" then mac else random_mac_address ();
1445 tgt_libvirtd = libvirtd }
1449 Not_found | Failure "int_of_string" -> loop ()
1457 config_devices_to_send, config_root_filesystem, config_target
1460 (* If architecture is set to UnknownArch, then assume the same
1461 * architecture as the live CD.
1464 match config_target.tgt_architecture with
1466 let arch = shget "uname -m" in
1469 | Some (arch :: _) -> architecture_of_string arch
1470 | _ -> I386 (* probably wrong XXX *) in
1471 { config_target with tgt_architecture = arch }
1472 | _ -> config_target in
1474 (* Try to get the capabilities from the remote machine. If we fail
1475 * it doesn't matter too much.
1477 let caps_os_type, caps_emulator, caps_loader, caps_machine =
1479 if not config_target.tgt_libvirtd then raise Not_found;
1482 match config_target.tgt_hypervisor with
1483 | Some Xen -> "xen", "/"
1484 | Some (QEMU|KVM) -> "qemu", "/system"
1485 | None -> raise Not_found in
1487 sprintf "%s+ssh://%s@%s:%s%s"
1488 proto config_ssh.ssh_username
1489 config_ssh.ssh_host config_ssh.ssh_port path in
1490 eprintf "capabilities URI = %S\n%!" name;
1492 printf "Try to fetch remote hypervisor capabilities ...\n\n%!";
1494 let conn = Libvirt.Connect.connect_readonly ~name () in
1495 let caps = Libvirt.Connect.get_capabilities conn in
1496 Libvirt.Connect.close conn;
1498 (* Turn it into XML data. *)
1499 let caps = Xml.parse_string caps in
1500 eprintf "capabilities:\n%s\n%!" (Xml.to_string_fmt caps);
1502 (* We're looking for a guest with <os_type>hvm</os_type>
1503 * and <arch name="target-arch">... Later when we can
1504 * install PV drivers automatically, we will want to look
1505 * for paravirt guest types too.
1507 let guests = children_with_name "guest" caps in
1509 List.filter (xml_has_pcdata_child "os_type" "hvm") guests in
1510 let arch_str = string_of_architecture config_target.tgt_architecture in
1513 xml_has_child_matching (
1515 | Xml.Element (n, attribs, _)
1520 (* deal with i386 vs i686 pestilence *)
1521 architecture_of_string a = config_target.tgt_architecture
1528 (* In theory at this point we only have a single guest type
1529 * remaining. It might be that we have _zero_ available
1530 * guest types, which indicates probably an unsupported
1531 * capability of the remote hypervisor (or just that one of
1532 * many parsing or heuristics failed). It might be that
1533 * we have > 1 available guest types, which indicates some
1534 * feature we don't know about.
1536 let len = List.length guests in
1538 message_box "Warning"
1539 (sprintf "Remote hypervisor claims not to support fully virtualized %s guests.\n\nContinuing anyway.\n\n%!" arch_str);
1545 (sprintf "Remote hypervisor supports multiple types of fully virtualized %s guests.\n\nPlease help further development of libvirt and virt-p2v by sending the file /tmp/virt-p2v.log back to the developers. See the main virt-p2v website for contact details." arch_str)
1548 let guest = List.hd guests in
1551 try Some (find_pcdata_child "os_type" guest)
1552 with Not_found -> None in
1553 let arch_section = find_child_with_name "arch" guest in
1555 try Some (find_pcdata_child "emulator" arch_section)
1556 with Not_found -> None in
1558 try Some (find_pcdata_child "loader" arch_section)
1559 with Not_found -> None in
1561 try Some (find_pcdata_child "machine" arch_section)
1562 with Not_found -> None in
1564 os_type, emulator, loader, machine
1566 | Not_found -> None, None, None, None
1568 eprintf "XML error: %s\n%!" (Xml.error err);
1569 None, None, None, None
1570 | Xml.Not_element _ | Xml.Not_pcdata _ | Xml.No_attribute _ ->
1571 (* If these occur, need to add some more debugging. *)
1572 eprintf "XML error when parsing capabilities\n%!";
1573 None, None, None, None
1574 | Libvirt.Virterror err ->
1575 eprintf "libvirt error: %s\n%!" (Libvirt.Virterror.to_string err);
1576 None, None, None, None
1577 | Invalid_argument str ->
1578 eprintf "libvirt error: %s\n%!" str;
1579 None, None, None, None in
1581 (* In test mode, exit here before we do Bad Things to the developer's
1584 if test_dialog_stages then exit 1;
1586 (* Switch LVM config. *)
1588 putenv "LVM_SYSTEM_DIR" "/etc/lvm.new"; (* see lvm(8) *)
1589 sh "rm -f /etc/lvm/cache/.cache";
1590 sh "rm -f /etc/lvm.new/cache/.cache";
1592 (* Snapshot the block devices to send. *)
1593 let config_devices_to_send =
1596 let snapshot_dev = snapshot_name origin_dev in
1597 snapshot origin_dev snapshot_dev;
1598 (origin_dev, snapshot_dev)
1599 ) config_devices_to_send in
1601 (* Run kpartx on the snapshots. *)
1603 fun (origin, snapshot) ->
1604 shfailok ("kpartx -a " ^ quote ("/dev/mapper/" ^ snapshot))
1605 ) config_devices_to_send;
1607 (* Rescan for LVs. *)
1611 (* Mount the root filesystem under /mnt/root. *)
1612 (match config_root_filesystem with
1613 | Part (dev, partnum) ->
1614 let dev = dev ^ partnum in
1615 let snapshot_dev = snapshot_name dev in
1616 sh ("mount " ^ quote ("/dev/mapper/" ^ snapshot_dev) ^ " /mnt/root")
1619 (* The LV will be backed by a snapshot device, so just mount
1622 sh ("mount " ^ quote ("/dev/" ^ vg ^ "/" ^ lv) ^ " /mnt/root")
1625 (* Work out what devices will be called at the remote end. *)
1626 let config_devices_to_send = List.map (
1627 fun (origin_dev, snapshot_dev) ->
1628 let remote_dev = remote_of_origin_dev origin_dev in
1629 (origin_dev, snapshot_dev, remote_dev)
1630 ) config_devices_to_send in
1632 (* Modify files on the root filesystem. *)
1633 rewrite_fstab config_devices_to_send;
1634 (* XXX Other files to rewrite? *)
1636 (* Unmount the root filesystem and sync disks. *)
1637 sh "umount /mnt/root";
1638 sh "sync"; (* Ugh, should be in stdlib. *)
1640 (* XXX This is using the hostname derived from network configuration
1641 * above. We might want to ask the user to choose.
1643 let hostname = safe_name (gethostname ()) in
1645 let date = sprintf "%04d%02d%02d%02d%02d"
1646 (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min in
1647 "p2v-" ^ hostname ^ "-" ^ date in
1649 (* Work out what the image filenames will be at the remote end. *)
1650 let config_devices_to_send = List.map (
1651 fun (origin_dev, snapshot_dev, remote_dev) ->
1652 let remote_name = basename ^ "-" ^ remote_dev ^ ".img" in
1653 (origin_dev, snapshot_dev, remote_dev, remote_name)
1654 ) config_devices_to_send in
1656 (* Write a configuration file. Not sure if this is any better than
1657 * just 'sprintf-ing' bits of XML text together, but at least we will
1658 * always get well-formed XML.
1660 * XXX There is a case for using virt-install to generate this XML.
1661 * When we start to incorporate libvirt access & storage API this
1662 * needs to be rethought.
1664 let conf_filename = basename ^ ".conf" in
1667 (* Shortcut to make "<name>value</name>". *)
1668 let leaf name value = Xml.Element (name, [], [Xml.PCData value]) in
1669 (* ... and the _other_ sort of leaf (god I hate XML). *)
1670 let tleaf name attribs = Xml.Element (name, attribs, []) in
1673 string_of_architecture config_target.tgt_architecture in
1675 wordsize_of_architecture config_target.tgt_architecture in
1677 (* Standard stuff for every domain. *)
1678 let name = leaf "name" hostname in
1679 let uuid = leaf "uuid" (random_uuid ()) in
1680 let maxmem, memory =
1681 let m = string_of_int (config_target.tgt_memory * 1024) in
1682 leaf "maxmem" m, leaf "memory" m in
1683 let vcpu = leaf "vcpu" (string_of_int config_target.tgt_vcpus) in
1685 (* Top-level stuff which differs for each HV type (isn't this supposed
1686 * to be portable ...)
1689 (* Use capabilities for os_type, etc. else use some good guesses. *)
1690 let os_type = Option.default "hvm" caps_os_type in
1691 let machine = Option.default "pc" caps_machine in
1692 let loader = Option.default "/usr/lib/xen/boot/hvmloader" caps_loader in
1694 match config_target.tgt_hypervisor with
1696 [Xml.Element ("os", [],
1697 [leaf "type" os_type;
1698 leaf "loader" loader;
1699 tleaf "boot" ["dev", "hd"]]);
1700 Xml.Element ("features", [],
1704 tleaf "clock" ["sync", "localtime"]]
1706 [Xml.Element ("os", [], [leaf "type" os_type]);
1707 tleaf "clock" ["sync", "localtime"]]
1709 [Xml.Element ("os", [],
1710 [Xml.Element ("type",
1712 "machine", machine],
1713 [Xml.PCData os_type]);
1714 tleaf "boot" ["dev", "hd"]])]
1718 (* <devices> section. *)
1721 match caps_emulator with
1722 (* Use the emulator from the libvirt capabilities. *)
1723 | Some s -> [leaf "emulator" s]
1725 (* If we don't have libvirt capabilities, best guess. *)
1726 match config_target.tgt_hypervisor with
1729 (if arch_wordsize = W64 then "/usr/lib64/xen/bin/qemu-dm"
1730 else "/usr/lib/xen/bin/qemu-dm")]
1732 [leaf "emulator" "/usr/bin/qemu"]
1734 [leaf "emulator" "/usr/bin/qemu-kvm"]
1738 Xml.Element ("interface", ["type", "user"],
1739 [tleaf "mac" ["address",
1740 config_target.tgt_mac_address]]) in
1741 (* XXX should have an option for Xen bridging:
1743 "interface", ["type","bridge"],
1744 [tleaf "source" ["bridge","xenbr0"];
1745 tleaf "mac" ["address",mac_address];
1746 tleaf "script" ["path","vif-bridge"]])*)
1747 let graphics = tleaf "graphics" ["type", "vnc"] in
1749 let disks = List.map (
1750 fun (_, _, remote_dev, remote_name) ->
1752 "disk", ["type", "file";
1754 [tleaf "source" ["file",
1755 config_ssh.ssh_directory ^ "/" ^ remote_name];
1756 tleaf "target" ["dev", remote_dev]]
1758 ) config_devices_to_send in
1762 emulator @ interface :: graphics :: disks
1765 (* Put it all together in <domain type='foo'>. *)
1768 (match config_target.tgt_hypervisor with
1769 | Some Xen -> ["type", "xen"]
1770 | Some QEMU -> ["type", "qemu"]
1771 | Some KVM -> ["type", "kvm"]
1773 name :: uuid :: memory :: maxmem :: vcpu :: extras @ [devices]
1776 (* Convert XML configuration file to a string, then send it to the
1780 let xml = Xml.to_string_fmt xml in
1783 match config_target.tgt_hypervisor with
1784 | Some Xen | None -> ""
1785 | Some QEMU | Some KVM -> " -c qemu:///system" in
1786 let xml = sprintf "\
1788 This is an automatically generated libvirt configuration file.
1789 It was written by the %s program.
1791 Please check the values in this configuration file carefully,
1792 particularly maxmem, memory, vcpu and any paths.
1794 To start the domain, do:
1797 -->\n\n" program_name conn_arg conf_filename conn_arg hostname
1801 let xml_len = String.length xml in
1802 eprintf "length of configuration file is %d bytes\n%!" xml_len;
1804 printf "\nWriting configuration file ...\n\n%!";
1806 let (sock,_) as conn = ssh_start_upload config_ssh conf_filename in
1807 (* In OCaml this actually loops calling write(2) *)
1808 ignore (write sock xml 0 xml_len);
1809 ssh_finish_upload conn in
1811 (* Send the device snapshots to the remote host. *)
1812 (* XXX This code should be made more robust against both network
1813 * errors and local I/O errors. Also should allow the user several
1814 * attempts to connect, or let them go back to the dialog stage.
1817 fun (origin_dev, snapshot_dev, remote_dev, remote_name) ->
1818 eprintf "sending %s as %s\n%!" origin_dev remote_name;
1821 try List.assoc origin_dev all_block_devices
1822 with Not_found -> assert false (* internal error *) in
1824 printf "\nSending /dev/%s (%.3f GB) to remote machine\n\n%!" origin_dev
1825 ((Int64.to_float size) /. (1024.*.1024.*.1024.));
1827 (* Open the snapshot device. *)
1828 let fd = openfile ("/dev/mapper/" ^ snapshot_dev) [O_RDONLY] 0 in
1831 let (sock,_) as conn = ssh_start_upload config_ssh remote_name in
1833 (* Copy the data. *)
1834 let spinners = "|/-\\" (* "Oo" *) in
1835 let bufsize = 1024 * 1024 in
1836 let buffer = String.create bufsize in
1837 let start = gettimeofday () in
1839 let rec copy bytes_sent last_printed_at spinner =
1840 let n = read fd buffer 0 bufsize in
1842 let n' = write sock buffer 0 n in
1843 if n <> n' then assert false; (* never, according to the manual *)
1845 let bytes_sent = Int64.add bytes_sent (Int64.of_int n) in
1846 let last_printed_at, spinner =
1847 let now = gettimeofday () in
1848 (* Print progress every few seconds. *)
1849 if now -. last_printed_at > 2. then (
1850 let elapsed = Int64.to_float bytes_sent /. Int64.to_float size in
1851 let secs_elapsed = now -. start in
1852 printf "%.0f%% %c %.1f Mbps"
1853 (100. *. elapsed) spinners.[spinner]
1854 (Int64.to_float bytes_sent/.secs_elapsed/.1_000_000. *. 8.);
1855 (* After 60 seconds has elapsed, start printing estimates. *)
1856 if secs_elapsed >= 60. then (
1857 let remaining = 1. -. elapsed in
1858 let secs_remaining = (remaining /. elapsed) *. secs_elapsed in
1859 if secs_remaining > 120. then
1860 printf " (about %.0f minutes remaining)" (secs_remaining/.60.)
1862 printf " (about %.0f seconds remaining)"
1866 let spinner = (spinner + 1) mod String.length spinners in
1869 else last_printed_at, spinner in
1871 copy bytes_sent last_printed_at spinner
1875 printf "\n\n%!"; (* because of the messages printed above *)
1878 ssh_finish_upload conn
1879 ) config_devices_to_send;
1881 (*printf "\n\nPress any key ...\n%!"; ignore (read_line ());*)
1883 (* Clean up and reboot. *)
1885 message_box (sprintf "%s completed" program_name)
1886 (sprintf "\nThe physical to virtual migration is complete.\n\nPlease verify the disk image(s) and configuration file on the remote host, and then start up the virtual machine by doing:\n\ncd %s\nvirsh define %s\n\nWhen you press [OK] this machine will reboot."
1887 config_ssh.ssh_directory conf_filename)
1895 (*----------------------------------------------------------------------*)
1898 eprintf "usage: virt-p2v [--test] [ttyname]\n%!";
1901 (* Make sure that exceptions from 'main' get printed out on stdout
1902 * as well as stderr, since stderr is probably redirected to the
1903 * logfile, and so not visible to the user.
1905 let handle_exn f arg =
1908 print_endline (Printexc.to_string exn);
1911 (* Test harness for the Makefile. The Makefile invokes this script as
1912 * 'virt-p2v --test' just to check it compiles. When it is running
1913 * from the actual live CD, there is a single parameter which is the
1914 * tty name (so usually 'virt-p2v tty1').
1917 match Array.to_list Sys.argv with
1918 | [ _; ("--help"|"-help"|"-?"|"-h") ] -> usage ();
1919 | [ _; "--test" ] -> () (* Makefile test - do nothing. *)
1920 | [ _; ttyname ] -> (* Run main with ttyname. *)
1921 handle_exn main (Some ttyname)
1922 | [ _ ] -> (* Interactive - no ttyname. *)
1923 handle_exn main None
1926 (* This file must end with a newline *)