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
54 type target_config = {
55 tgt_hypervisor : hypervisor option; (* Remote hypervisor. *)
56 tgt_architecture : architecture; (* Remote architecture. *)
57 tgt_memory : int; (* Memory (megabytes). *)
58 tgt_vcpus : int; (* Number of virtual CPUs. *)
59 tgt_mac_address : string; (* MAC address. *)
60 tgt_libvirtd : bool; (* True if libvirtd on remote. *)
63 (*----------------------------------------------------------------------*)
64 (* TO MAKE A CUSTOM VIRT-P2V SCRIPT, adjust the defaults in this section.
66 * If left as they are, then this will create a generic virt-p2v script
67 * which asks the user for each question. If you set the defaults here
68 * then you will get a custom virt-p2v which is partially or even fully
69 * automated and won't ask the user any questions.
71 * Note that 'None' means 'no default' (ie. ask the user) whereas
72 * 'Some foo' means use 'foo' as the answer.
74 * These are documented in the virt-p2v(1) manual page.
76 * After changing them, run './virt-p2v --test' to check syntax.
79 (* If greeting is true, wait for keypress after boot and during
80 * final verification. Set to 'false' for less interactions.
82 let config_greeting = ref true
84 (* General type of transfer. *)
85 let config_transfer_type = ref None
87 (* Network configuration. *)
88 let config_network = ref None
90 (* SSH configuration. *)
91 let config_ssh = ref None
93 (* What to transfer. *)
94 let config_devices_to_send = ref None
95 let config_root_filesystem = ref None
97 (* Configuration of the target. *)
98 let config_target = ref None
100 (* The name of the program as displayed in various places. *)
101 let program_name = "virt-p2v"
103 (* If you want to test the dialog stages, set this to true. *)
104 let test_dialog_stages = false
106 (* END OF CUSTOM virt-p2v SCRIPT SECTION. *)
107 (*----------------------------------------------------------------------*)
109 (* Load external libraries. *)
112 #directory "+extlib";;
118 #directory "+xml-light";;
119 #load "xml-light.cma";;
126 (*----------------------------------------------------------------------*)
127 (* General helper functions. *)
129 let sort_uniq ?(cmp = compare) xs = (* sort and uniq a list *)
130 let xs = List.sort ~cmp xs in
131 let rec loop = function
132 | [] -> [] | [x] -> [x]
133 | x1 :: x2 :: xs when x1 = x2 -> loop (x1 :: xs)
134 | x :: xs -> x :: loop xs
138 let input_all_lines chan =
139 let lines = ref [] in
141 while true do lines := input_line chan :: !lines done; []
143 End_of_file -> List.rev !lines
145 let dev_of_partition = function
146 | Part (dev, partnum) -> sprintf "/dev/%s%s" dev partnum
147 | LV (vg, lv) -> sprintf "/dev/%s/%s" vg lv
149 let string_of_architecture = function
156 | SPARC64 -> "sparc64"
157 | OtherArch arch -> arch
160 type nature = LinuxSwap
161 | LinuxRoot of architecture * linux_distro
162 | WindowsRoot (* Windows C: *)
163 | LinuxBoot (* Linux /boot *)
164 | NotRoot (* mountable, but not / or /boot *)
166 and linux_distro = RHEL of int * int
168 | Debian of int * int
171 let rec string_of_nature = function
172 | LinuxSwap -> "Linux swap"
173 | LinuxRoot (architecture, distro) ->
174 string_of_linux_distro distro ^ " " ^ string_of_architecture architecture
175 | WindowsRoot -> "Windows root"
176 | LinuxBoot -> "Linux /boot"
177 | NotRoot -> "Mountable non-root"
178 | UnknownNature -> "Unknown"
179 and string_of_linux_distro = function
180 | RHEL (a,b) -> sprintf "RHEL %d.%d" a b
181 | Fedora v -> sprintf "Fedora %d" v
182 | Debian (a,b) -> sprintf "Debian %d.%d" a b
183 | OtherLinux -> "Linux"
185 type ('a, 'b) either = Either of 'a | Or of 'b
187 (* We go into and out of newt mode at various stages, but we might
188 * also need to put up a message at any time. This keeps track of
189 * whether we are in newt mode or not.
191 * General tip: Try to do any complex operations like setting up the
192 * network or probing disks outside newt mode, and try not to throw
193 * exceptions in newt mode.
195 let in_newt = ref false
197 if !in_newt then f ()
201 try Either (Newt.init_and_finish f)
202 with exn -> Or exn in
204 match r with Either r -> r | Or exn -> raise exn
207 (* Clear the screen, open a new centered window, make sure the background
208 * and help messages are consistent.
210 let open_centered_window ?stage width height title =
211 if not !in_newt then failwith "open_centered_window: not in newt mode";
213 Newt.centered_window width height title;
215 program_name ^ (match stage with
217 | Some stage -> " - " ^ stage) in
218 Newt.draw_root_text 0 0 root_text;
219 Newt.push_help_line "F12 for next screen | [ALT] [F2] root / no password for shell"
221 (* Some general dialog boxes. *)
222 let message_box title text =
225 open_centered_window 40 20 title;
227 let textbox = Newt.textbox 1 1 36 14 [Newt.WRAP; Newt.SCROLL] in
228 Newt.textbox_set_text textbox text;
229 let ok = Newt.button 28 16 " OK " in
230 let form = Newt.form None None [] in
231 Newt.form_add_components form [textbox; ok];
233 Newt.component_takes_focus ok true;
235 ignore (Newt.run_form form);
239 (* Fail and exit with error. *)
242 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
243 message_box "Error" text;
246 (* Display a dialog with checkboxes, return the multiple selected items. *)
247 let select_multiple ?stage ?(force_one = false) width title items =
250 open_centered_window ?stage width 20 title;
254 fun i (label, handle, selected) ->
256 Newt.checkbox 1 (i+1) label
257 (if selected then '*' else ' ') None in
261 let ok = Newt.button 48 16 " OK " in
264 if List.length entries > 10 then
265 Some (Newt.vertical_scrollbar 58 1 10
266 Newt_int.NEWT_COLORSET_WINDOW
267 Newt_int.NEWT_COLORSET_ACTCHECKBOX)
270 let form = Newt.form vb None [] in
271 Newt.form_add_components form (List.map snd entries);
272 Newt.form_add_component form ok;
276 ignore (Newt.run_form form);
277 let selected = List.filter_map (
279 if Newt.checkbox_get_value cb = '*' then Some handle else None
281 if force_one && selected = [] then loop ()
291 (* Display a dialog with radio buttons, return the single selected item. *)
292 let select_single ?stage width title items =
293 if items = [] then failwith "select_single: no items";
297 open_centered_window ?stage width 20 title;
299 let prev = ref None in
302 fun i (label, handle) ->
303 let rb = Newt.radio_button 1 (i+1) label (!prev = None) !prev in
308 let ok = Newt.button 48 16 " OK " in
311 if List.length entries > 10 then
312 Some (Newt.vertical_scrollbar 58 1 10
313 Newt_int.NEWT_COLORSET_WINDOW
314 Newt_int.NEWT_COLORSET_ACTCHECKBOX)
317 let form = Newt.form vb None [] in
318 Newt.form_add_components form (List.map snd entries);
319 Newt.form_add_component form ok;
323 ignore (Newt.run_form form);
324 let r = Option.get !prev in
325 let r = Newt.radio_get_current r in
326 (* Now we compare 'r' to all the 'rb's in the list
327 * to see which one is selected.
330 List.find (fun (_, rb) -> Newt.component_equals r rb) entries
341 (* Shell-safe quoting function. In fact there's one in stdlib so use it. *)
342 let quote = Filename.quote
344 (* Run a shell command and check it returns 0. *)
346 eprintf "sh: %s\n%!" cmd;
347 if Sys.command cmd <> 0 then failwith (sprintf "Command failed:\n\n%s" cmd)
350 eprintf "shfailok: %s\n%!" cmd;
351 ignore (Sys.command cmd)
353 let shwithstatus cmd =
354 eprintf "shwithstatus: %s\n%!" cmd;
357 (* Same as `cmd` in shell. Any error message will be in the logfile. *)
359 eprintf "shget: %s\n%!" cmd;
360 let chan = open_process_in cmd in
361 let lines = input_all_lines chan in
362 match close_process_in chan with
363 | WEXITED 0 -> Some lines (* command succeeded *)
364 | WEXITED _ -> None (* command failed *)
365 | WSIGNALED i -> failwith (sprintf "shget: command killed by signal %d" i)
366 | WSTOPPED i -> failwith (sprintf "shget: command stopped by signal %d" i)
368 (* Start an interactive shell. Need to juggle file descriptors a bit
369 * because bash write PS1 to stderr (currently directed to the logfile).
373 | 0 -> (* child, runs bash *)
376 (* Sys.command runs 'sh -c' which blows away PS1, so set it late. *)
378 Sys.command "PS1='\\u@\\h:\\w\\$ ' /bin/bash --norc --noprofile -i"
380 | _ -> (* parent, waits *)
381 eprintf "waiting for subshell to exit\n%!";
384 (* Some true if is dir/file, Some false if not, None if not found. *)
386 try Some ((stat path).st_kind = S_DIR)
387 with Unix_error (ENOENT, "stat", _) -> None
389 try Some ((stat path).st_kind = S_REG)
390 with Unix_error (ENOENT, "stat", _) -> None
392 (*----------------------------------------------------------------------*)
393 (* P2V-specific helper functions. *)
395 (* Generate a predictable safe name containing only letters, numbers
396 * and underscores. If passed a string with no letters or numbers,
397 * generates "_1", "_2", etc.
402 fun () -> incr i; "_" ^ string_of_int !i
405 let is_safe = function 'a'..'z'|'A'..'Z'|'0'..'9' -> true | _ -> false in
406 let name = String.copy name in
407 let have_safe = ref false in
408 for i = 0 to String.length name - 1 do
409 if not (is_safe name.[i]) then name.[i] <- '_' else have_safe := true
411 if !have_safe then name else next_anon ()
413 type block_device = string * int64 (* "hda" & size in bytes *)
415 (* Parse the output of 'lvs' to get list of LV names, sizes,
416 * corresponding PVs, etc. Returns a list of (lvname, PVs, lvsize).
419 let devname = Pcre.regexp "^/dev/(.+)\\(.+\\)$" in
423 shget "lvs --noheadings -o vg_name,lv_name,devices,lv_size"
427 let lines = List.map Pcre.split lines in
430 | [vg; lv; pvs; lvsize]
431 | [_; vg; lv; pvs; lvsize] ->
432 let pvs = String.nsplit pvs "," in
433 let pvs = List.filter_map (
436 let subs = Pcre.exec ~rex:devname pv in
437 Some (Pcre.get_substring subs 1)
440 eprintf "lvs: unexpected device name: %s\n%!" pv;
443 LV (vg, lv), pvs, lvsize
445 failwith ("lvs: unexpected output: " ^ String.concat "," line)
448 (* Get the partitions on a block device.
449 * eg. "sda" -> [Part ("sda","1"); Part ("sda", "2")]
451 let get_partitions dev =
452 let rex = Pcre.regexp ("^" ^ dev ^ "(.+)$") in
453 let devdir = "/sys/block/" ^ dev in
454 let parts = Sys.readdir devdir in
455 let parts = Array.to_list parts in
456 let parts = List.filter (
457 fun name -> Some true = is_dir (devdir ^ "/" ^ name)
459 let parts = List.filter_map (
462 let subs = Pcre.exec ~rex part in
463 Some (Part (dev, Pcre.get_substring subs 1))
469 (* Generate snapshot device name from device name. *)
470 let snapshot_name dev =
471 "snap" ^ (safe_name dev)
473 (* Perform a device-mapper snapshot with ramdisk overlay. *)
475 let next_free_ram_disk =
477 fun () -> incr i; "/dev/ram" ^ string_of_int !i
479 fun origin_dev snapshot_dev ->
480 let ramdisk = next_free_ram_disk () in
482 let cmd = "blockdev --getsz " ^ quote ("/dev/" ^ origin_dev) in
483 let lines = shget cmd in
485 | Some (sectors::_) -> Int64.of_string sectors
487 failwith (sprintf "Snapshot failed - unable to read the size in sectors of block device %s" origin_dev) in
489 (* Create the snapshot origin device. Called, eg. snap_sda1_org *)
490 sh (sprintf "dmsetup create %s_org --table='0 %Ld snapshot-origin /dev/%s'"
491 snapshot_dev sectors origin_dev);
492 (* Create the snapshot. *)
493 sh (sprintf "dmsetup create %s --table='0 %Ld snapshot /dev/mapper/%s_org %s n 64'"
494 snapshot_dev sectors snapshot_dev ramdisk)
496 (* Try to perform automatic network configuration, assuming a Fedora or
497 * RHEL-like root filesystem mounted on /mnt/root.
499 let auto_network () =
500 (* Fedora gives an error if this file doesn't exist. *)
501 sh "touch /etc/resolv.conf";
503 (* NB. Lazy unmount is required because dhclient keeps its current
504 * directory open on /etc/sysconfig/network-scripts/
506 sh "mount -o bind /mnt/root/etc /etc";
507 let status = shwithstatus "/etc/init.d/network start" in
510 (* Try to ping the default gateway to see if this worked. *)
511 shfailok "ping -c3 `/sbin/ip route list match 0.0.0.0 | head -1 | awk '{print $3}'`";
513 if !config_greeting then (
514 printf "\n\nDid automatic network configuration work?\n";
515 printf "Hint: If not sure, there is a shell on console [ALT] [F2]\n";
517 let line = read_line () in
518 String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
521 (* Non-interactive: return the status of /etc/init.d/network start. *)
524 (* Configure the network statically. *)
525 let static_network (interface, address, netmask, gateway, nameserver) =
526 let do_cmd_or_exit cmd = if shwithstatus cmd <> 0 then raise Exit in
528 do_cmd_or_exit (sprintf "ifconfig %s %s netmask %s"
529 (quote interface) (quote address) (quote netmask));
530 do_cmd_or_exit (sprintf "route add default gw %s %s"
531 (quote gateway) (quote interface));
532 if nameserver <> "" then
533 do_cmd_or_exit (sprintf "echo nameserver %s > /etc/resolv.conf"
537 Exit -> false (* failed *)
539 (* http://fabrice.bellard.free.fr/qemu/qemu-doc.html#SEC30 *)
540 let qemu_network () =
541 sh "ifconfig eth0 10.0.2.10 netmask 255.255.255.0";
542 sh "route add default gw 10.0.2.2 eth0";
543 sh "echo nameserver 10.0.2.3 > /etc/resolv.conf"
545 (* Map local device names to remote devices names. At the moment we
546 * just change sd* to hd* (as device names appear under fullvirt). In
547 * future, lots of complex possibilities.
549 let remote_of_origin_dev =
550 let devsd = Pcre.regexp "^sd([[:alpha:]]+[[:digit:]]*)$" in
551 let devsd_subst = Pcre.subst "hd$1" in
553 Pcre.replace ~rex:devsd ~itempl:devsd_subst dev
555 (* Make an SSH connection to the remote machine, execute command.
556 * The connection remains open until you call ssh_disconnect, it
557 * times out or there is some error.
559 * NB. The command is NOT quoted.
561 * Returns a pair (file descriptor, channel), both referring to the
562 * same thing. Use whichever is more convenient.
564 let ssh_connect config cmd =
565 let cmd = sprintf "ssh%s -l %s -p %s %s %s"
566 (if config.ssh_compression then " -C" else "")
567 (quote config.ssh_username) (quote config.ssh_port) (quote config.ssh_host)
569 eprintf "ssh_connect: %s\n%!" cmd;
570 let chan = open_process_out cmd in
571 descr_of_out_channel chan, chan
573 let ssh_disconnect (_, chan) =
574 eprintf "ssh_disconnect\n%!";
575 match close_process_out chan with
576 | WEXITED 0 -> () (* OK *)
577 | WEXITED i -> failwith (sprintf "ssh: exited with error code %d" i)
578 | WSIGNALED i -> failwith (sprintf "ssh: killed by signal %d" i)
579 | WSTOPPED i -> failwith (sprintf "ssh: stopped by signal %d" i)
581 (* Test SSH connection. *)
582 let test_ssh config =
583 printf "Testing SSH connection by listing files in remote directory ...\n\n%!";
585 let cmd = sprintf "/bin/ls %s" (quote config.ssh_directory) in
586 let conn = ssh_connect config cmd in
589 if !config_greeting then (
590 printf "\n\nDid SSH work?\n";
591 printf "Hint: If not sure, there is a shell on console [ALT] [F2]\n";
593 let line = read_line () in
594 String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
599 (* Rewrite /mnt/root/etc/fstab. *)
600 let rewrite_fstab state devices_to_send =
601 let filename = "/mnt/root/etc/fstab" in
602 if is_file filename = Some true then (
603 sh ("cp " ^ quote filename ^ " " ^ quote (filename ^ ".p2vsaved"));
605 let chan = open_in filename in
606 let lines = input_all_lines chan in
608 let lines = List.map Pcre.split lines in
609 let lines = List.map (
611 | dev :: rest when String.starts_with dev "/dev/" ->
612 let dev = String.sub dev 5 (String.length dev - 5) in
613 let dev = remote_of_origin_dev dev in
614 let dev = "/dev/" ^ dev in
619 let chan = open_out filename in
622 | [dev; mountpoint; fstype; options; freq; passno] ->
623 fprintf chan "%-23s %-23s %-7s %-15s %s %s\n"
624 dev mountpoint fstype options freq passno
626 output_string chan (String.concat " " line);
627 output_char chan '\n'
632 (* Generate a random MAC address in the Xen-reserved space. *)
633 let random_mac_address () =
635 List.map (sprintf "%02x") (
636 List.map (fun _ -> Random.int 256) [0;0;0]
638 String.concat ":" ("00"::"16"::"3e"::random)
640 (* Generate a random UUID. *)
642 let hex = "0123456789abcdef" in
644 let str = String.create 32 in
645 for i = 0 to 31 do str.[i] <- hex.[Random.int 16] done;
648 (*----------------------------------------------------------------------*)
649 (* Main entry point. *)
651 (* The general plan for the main function is to operate in stages:
656 * Information gathering about the system
657 * | (eg. block devices, number of CPUs, etc.)
659 * Greeting and type of transfer question
663 * | (after this point we have a working network)
666 * | (after this point we have a working SSH connection)
668 * Questions about what to transfer (block devs, root fs) <--.
671 * Questions about hypervisor configuration |
674 * Verify information -------- user wants to change info ----/
679 * Prior versions of virt-p2v (the ones which used 'dialog') had support
680 * for a back button so they could go back through dialogs. I removed
681 * this because it was hard to support and not particularly useful.
684 let rec main ttyname =
687 (* Running from an init script. We don't have much of a
688 * login environment, so set one up.
692 ["/usr/sbin"; "/sbin"; "/usr/local/bin"; "/usr/kerberos/bin";
693 "/usr/bin"; "/bin"]);
694 putenv "HOME" "/root";
695 putenv "LOGNAME" "root";
697 (* We can safely write in /tmp (it's a synthetic live CD directory). *)
700 (* Set up logging to /tmp/virt-p2v.log. *)
701 let fd = openfile "virt-p2v.log" [ O_WRONLY; O_APPEND; O_CREAT ] 0o644 in
705 (* Log the start up time. *)
706 eprintf "\n\n**************************************************\n\n";
707 let tm = localtime (time ()) in
708 eprintf "%s starting up at %04d-%02d-%02d %02d:%02d:%02d\n\n%!"
710 (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec;
712 (* Connect stdin/stdout to the tty. *)
716 let fd = openfile ("/dev/" ^ ttyname) [ O_RDWR ] 0 in
720 printf "%s starting up ...\n%!" program_name;
722 (* Disable screen blanking on tty. *)
723 sh "setterm -blank 0";
725 (* Check that the environment is a sane-looking live CD. If not, bail. *)
726 if not test_dialog_stages && is_dir "/mnt/root" <> Some true then
728 "You should only run this script from the live CD or a USB key.";
730 (* Start of the information gathering phase. *)
731 printf "Detecting hard drives (this may take some time) ...\n%!";
733 (* Search for all non-removable block devices. Do this early and bail
734 * if we can't find anything. This is a list of strings, like "hda".
736 let all_block_devices : block_device list =
737 let rex = Pcre.regexp "^[hs]d" in
738 let devices = Array.to_list (Sys.readdir "/sys/block") in
739 let devices = List.sort devices in
740 let devices = List.filter (fun d -> Pcre.pmatch ~rex d) devices in
741 eprintf "all_block_devices: block devices: %s\n%!"
742 (String.concat "; " devices);
743 (* Run blockdev --getsize64 on each, and reject any where this fails
744 * (probably removable devices).
746 let devices = List.filter_map (
748 let cmd = "blockdev --getsize64 " ^ quote ("/dev/" ^ d) in
749 let lines = shget cmd in
751 | Some (blksize::_) -> Some (d, Int64.of_string blksize)
752 | Some [] | None -> None
754 eprintf "all_block_devices: non-removable block devices: %s\n%!"
756 (List.map (fun (d, b) -> sprintf "%s [%Ld]" d b) devices));
758 failwith "No non-removable block devices (hard disks, etc.) could be found on this machine.";
761 (* Search for partitions and LVs (anything that could contain a
762 * filesystem directly). We refer to these generically as
765 let all_partitions : partition list =
768 let lvs = get_lvs () in
769 let pvs = List.map (fun (_, pvs, _) -> pvs) lvs in
770 let pvs = List.concat pvs in
771 let pvs = sort_uniq pvs in
772 eprintf "all_partitions: PVs: %s\n%!" (String.concat "; " pvs);
773 let lvs = List.map (fun (lvname, _, _) -> lvname) lvs in
774 eprintf "all_partitions: LVs: %s\n%!"
775 (String.concat "; " (List.map dev_of_partition lvs));
778 (* Partitions (eg. "sda1", "sda2"). *)
780 let parts = List.map fst all_block_devices in
781 let parts = List.map get_partitions parts in
782 let parts = List.concat parts in
783 eprintf "all_partitions: all partitions: %s\n%!"
784 (String.concat "; " (List.map dev_of_partition parts));
786 (* Remove any partitions which are PVs. *)
787 let parts = List.filter (
789 | Part (dev, partnum) -> not (List.mem (dev ^ partnum) pvs)
790 | LV _ -> assert false
793 eprintf "all_partitions: partitions after removing PVs: %s\n%!"
794 (String.concat "; " (List.map dev_of_partition parts));
796 (* Concatenate LVs & Parts *)
799 (* Try to determine the nature of each partition.
800 * Root? Swap? Architecture? etc.
802 let all_partitions : (partition * nature) list =
803 (* Output of 'file' command for Linux swap file. *)
804 let swap = Pcre.regexp "Linux.*swap.*file" in
805 (* Contents of /etc/redhat-release. *)
806 let rhel = Pcre.regexp "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)(?:\\.(\\d+))?" in
807 let fedora = Pcre.regexp "Fedora.*release (\\d+)" in
808 (* Contents of /etc/debian_version. *)
809 let debian = Pcre.regexp "^(\\d+)\\.(\\d+)" in
810 (* Output of 'file' on certain executables. *)
811 let i386 = Pcre.regexp ", Intel 80386," in
812 let x86_64 = Pcre.regexp ", x86-64," in
813 let itanic = Pcre.regexp ", IA-64," in
815 (* Examine the filesystem mounted on 'mnt' to determine the
816 * operating system, and, if Linux, the distro.
819 if is_dir (mnt ^ "/Windows") = Some true &&
820 is_file (mnt ^ "/autoexec.bat") = Some true then
822 else if is_dir (mnt ^ "/etc") = Some true &&
823 is_dir (mnt ^ "/sbin") = Some true &&
824 is_dir (mnt ^ "/var") = Some true then (
825 if is_file (mnt ^ "/etc/redhat-release") = Some true then (
826 let chan = open_in (mnt ^ "/etc/redhat-release") in
827 let lines = input_all_lines chan in
831 | [] -> (* empty /etc/redhat-release ...? *)
832 LinuxRoot (UnknownArch, OtherLinux)
833 | line::_ -> (* try to detect OS from /etc/redhat-release *)
835 let subs = Pcre.exec ~rex:rhel line in
836 let major = int_of_string (Pcre.get_substring subs 1) in
838 try int_of_string (Pcre.get_substring subs 2)
839 with Not_found -> 0 in
840 LinuxRoot (UnknownArch, RHEL (major, minor))
842 Not_found | Failure "int_of_string" ->
844 let subs = Pcre.exec ~rex:fedora line in
845 let version = int_of_string (Pcre.get_substring subs 1) in
846 LinuxRoot (UnknownArch, Fedora version)
848 Not_found | Failure "int_of_string" ->
849 LinuxRoot (UnknownArch, OtherLinux)
851 else if is_file (mnt ^ "/etc/debian_version") = Some true then (
852 let chan = open_in (mnt ^ "/etc/debian_version") in
853 let lines = input_all_lines chan in
857 | [] -> (* empty /etc/debian_version ...? *)
858 LinuxRoot (UnknownArch, OtherLinux)
859 | line::_ -> (* try to detect version from /etc/debian_version *)
861 let subs = Pcre.exec ~rex:debian line in
862 let major = int_of_string (Pcre.get_substring subs 1) in
863 let minor = int_of_string (Pcre.get_substring subs 2) in
864 LinuxRoot (UnknownArch, Debian (major, minor))
866 Not_found | Failure "int_of_string" ->
867 LinuxRoot (UnknownArch, OtherLinux)
870 LinuxRoot (UnknownArch, OtherLinux)
871 ) else if is_dir (mnt ^ "/grub") = Some true &&
872 is_file (mnt ^ "/grub/stage1") = Some true then (
875 NotRoot (* mountable, but not a root filesystem *)
878 (* Examine the Linux root filesystem mounted on 'mnt' to
879 * determine the architecture. We do this by looking at some
880 * well-known binaries that we expect to be there.
882 let detect_architecture mnt =
883 let cmd = "file -bL " ^ quote (mnt ^ "/sbin/init") in
885 | Some (str::_) when Pcre.pmatch ~rex:i386 str -> I386
886 | Some (str::_) when Pcre.pmatch ~rex:x86_64 str -> X86_64
887 | Some (str::_) when Pcre.pmatch ~rex:itanic str -> IA64
893 let dev = dev_of_partition part in (* Get /dev device. *)
896 (* Use 'file' command to detect if it is swap. *)
897 let cmd = "file -sbL " ^ quote dev in
899 | Some (str::_) when Pcre.pmatch ~rex:swap str -> LinuxSwap
901 (* Blindly try to mount the device. *)
902 let cmd = "mount -o ro " ^ quote dev ^ " /mnt/root" in
903 match shwithstatus cmd with
905 let os = detect_os "/mnt/root" in
908 | LinuxRoot (UnknownArch, distro) ->
909 let architecture = detect_architecture "/mnt/root" in
910 LinuxRoot (architecture, distro)
912 sh "umount /mnt/root";
915 | _ -> UnknownNature (* not mountable *)
919 eprintf "partition detection: %s is %s\n%!"
920 dev (string_of_nature nature);
926 printf "Finished detecting hard drives.\n%!";
928 (* Autodetect system memory. *)
930 let mem = shget "head -1 /proc/meminfo | awk '{print $2/1024}'" in
932 | Some (mem::_) -> int_of_float (float_of_string mem)
935 (* Autodetect system # pCPUs. *)
938 shget "grep ^processor /proc/cpuinfo | tail -1 | awk '{print $3+1}'" in
940 | Some (cpus::_) -> int_of_string cpus
943 (* Greeting, type of transfer, network question stages.
944 * These are all done in newt mode.
946 let config_transfer_type, config_network =
950 if !config_greeting then
951 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);
953 (* Type of transfer. *)
954 let config_transfer_type =
955 match !config_transfer_type with
959 "Physical to Virtual (P2V)", P2V;
960 "Virtual to Virtual (V2V)", V2V;
963 select_single ~stage:"Transfer type" 40
967 (* Network configuration. *)
969 match !config_network with
972 open_centered_window ~stage:"Network"
973 60 20 "Configure network";
975 let autolist = Newt.listbox 4 2 4 [Newt.SCROLL] in
976 Newt.listbox_set_width autolist 52;
978 (* Populate the "Automatic" listbox with RHEL/Fedora
979 * root partitions found which allow us to do
980 * automatic configuration in a known way.
982 let rec loop = function
984 | (partition, LinuxRoot (_, ((RHEL _|Fedora _) as distro)))
988 (dev_of_partition partition)
989 (string_of_linux_distro distro) in
990 ignore (Newt.listbox_append_entry autolist label partition);
992 | _ :: parts -> loop parts
996 (* If there is no suitable root partition (the listbox
997 * is empty) then disable the auto option and the listbox.
999 let no_auto = Newt.listbox_item_count autolist = 0 in
1002 Newt.radio_button 1 1
1003 "Automatic from:" (not no_auto) None in
1005 Newt.radio_button 1 6
1006 "Start a shell" no_auto (Some auto) in
1009 Newt.component_takes_focus auto false;
1010 Newt.component_takes_focus
1011 (Newt.component_of_listbox autolist) false
1015 Newt.radio_button 1 7
1016 "QEMU user network" false (Some shell) in
1018 Newt.radio_button 1 8
1019 "No network or network already configured" false
1022 Newt.radio_button 1 9
1023 "Static configuration:" false (Some nonet) in
1025 let label1 = Newt.label 4 10 "Interface" in
1026 let entry1 = Newt.entry 16 10 (Some "eth0") 8 [] in
1027 let label2 = Newt.label 4 11 "Address" in
1028 let entry2 = Newt.entry 16 11 None 16 [] in
1029 let label3 = Newt.label 4 12 "Netmask" in
1030 let entry3 = Newt.entry 16 12 (Some "255.255.255.0") 16 [] in
1031 let label4 = Newt.label 4 13 "Gateway" in
1032 let entry4 = Newt.entry 16 13 None 16 [] in
1033 let label5 = Newt.label 4 14 "Nameserver" in
1034 let entry5 = Newt.entry 16 14 None 16 [] in
1036 let enable_static () =
1037 Newt.component_takes_focus entry1 true;
1038 Newt.component_takes_focus entry2 true;
1039 Newt.component_takes_focus entry3 true;
1040 Newt.component_takes_focus entry4 true;
1041 Newt.component_takes_focus entry5 true
1044 let disable_static () =
1045 Newt.component_takes_focus entry1 false;
1046 Newt.component_takes_focus entry2 false;
1047 Newt.component_takes_focus entry3 false;
1048 Newt.component_takes_focus entry4 false;
1049 Newt.component_takes_focus entry5 false
1052 let enable_autolist () =
1053 Newt.component_takes_focus
1054 (Newt.component_of_listbox autolist) true
1056 let disable_autolist () =
1057 Newt.component_takes_focus
1058 (Newt.component_of_listbox autolist) false
1062 Newt.component_add_callback auto
1063 (fun () ->disable_static (); enable_autolist ());
1064 Newt.component_add_callback shell
1065 (fun () -> disable_static (); disable_autolist ());
1066 Newt.component_add_callback qemu
1067 (fun () -> disable_static (); disable_autolist ());
1068 Newt.component_add_callback nonet
1069 (fun () -> disable_static (); disable_autolist ());
1070 Newt.component_add_callback static
1071 (fun () -> enable_static (); disable_autolist ());
1073 let ok = Newt.button 48 16 " OK " in
1075 let form = Newt.form None None [] in
1076 Newt.form_add_components form [auto;
1077 Newt.component_of_listbox autolist;
1078 shell;qemu;nonet;static;
1079 label1;label2;label3;label4;label5;
1080 entry1;entry2;entry3;entry4;entry5;
1085 ignore (Newt.run_form form);
1087 let r = Newt.radio_get_current auto in
1088 if Newt.component_equals r auto then (
1089 match Newt.listbox_get_current autolist with
1091 | Some part -> Auto part
1093 else if Newt.component_equals r shell then Shell
1094 else if Newt.component_equals r qemu then QEMUUserNet
1095 else if Newt.component_equals r nonet then NoNetwork
1096 else if Newt.component_equals r static then (
1097 let interface = Newt.entry_get_value entry1 in
1098 let address = Newt.entry_get_value entry2 in
1099 let netmask = Newt.entry_get_value entry3 in
1100 let gateway = Newt.entry_get_value entry4 in
1101 let nameserver = Newt.entry_get_value entry5 in
1102 if interface = "" || address = "" ||
1103 netmask = "" || gateway = "" then
1106 Static (interface, address, netmask, gateway, nameserver)
1115 config_transfer_type, config_network
1118 (* Try to bring up the network. *)
1119 (match config_network with
1121 printf "Network configuration.\n\n";
1122 printf "Please configure the network from this shell.\n\n";
1123 printf "When you have finished, exit the shell with ^D or exit.\n\n%!";
1126 | Static (interface, address, netmask, gateway, nameserver) ->
1127 printf "Trying static network configuration.\n\n%!";
1128 if not (static_network
1129 (interface, address, netmask, gateway, nameserver)) then (
1130 printf "\nAuto-configuration failed. Starting a shell.\n\n";
1131 printf "Please configure the network from this shell.\n\n";
1132 printf "When you have finished, exit the shell with ^D or exit.\n\n";
1138 "Trying network auto-configuration from root filesystem ...\n\n%!";
1140 (* Mount the root filesystem read-only under /mnt/root. *)
1141 sh ("mount -o ro " ^ quote (dev_of_partition rootfs) ^ " /mnt/root");
1143 if not (auto_network ()) then (
1144 printf "\nAuto-configuration failed. Starting a shell.\n\n";
1145 printf "Please configure the network from this shell.\n\n";
1146 printf "When you have finished, exit the shell with ^D or exit.\n\n";
1150 (* NB. Lazy unmount is required because dhclient keeps its current
1151 * directory open on /etc/sysconfig/network-scripts/
1153 sh ("umount -l /mnt/root");
1156 printf "Trying QEMU network configuration.\n\n%!";
1159 | NoNetwork -> (* this is easy ... *) ()
1162 (* SSH configuration phase. *)
1166 match !config_ssh with
1169 (* Query the user for SSH configuration. *)
1170 open_centered_window ~stage:"SSH configuration"
1171 60 20 "SSH configuration";
1173 let label1 = Newt.label 1 1 "Remote host" in
1174 let host = Newt.entry 20 1 None 36 [] in
1175 let label2 = Newt.label 1 2 "Remote port" in
1176 let port = Newt.entry 20 2 (Some "22") 6 [] in
1177 let label3 = Newt.label 1 3 "Remote directory" in
1178 let dir = Newt.entry 20 3 (Some "/var/lib/xen/images") 36 [] in
1179 let label4 = Newt.label 1 4 "SSH username" in
1180 let user = Newt.entry 20 4 (Some "root") 16 [] in
1182 There's no sensible way to support this for SSH:
1183 let label5 = Newt.label 1 5 "SSH password" in
1184 let pass = Newt.entry 20 5 None 16 [Newt.PASSWORD] in
1188 Newt.checkbox 16 7 "Use SSH compression (not good for LANs)"
1191 let check = Newt.checkbox 16 9 "Test SSH connection" '*' None in
1193 let ok = Newt.button 48 16 " OK " in
1195 let form = Newt.form None None [] in
1196 Newt.form_add_components form [label1;label2;label3;label4;
1203 ignore (Newt.run_form form);
1204 let host = Newt.entry_get_value host in
1205 let port = Newt.entry_get_value port in
1206 let dir = Newt.entry_get_value dir in
1207 let user = Newt.entry_get_value user in
1208 let compr = Newt.checkbox_get_value compr = '*' in
1209 let check = Newt.checkbox_get_value check = '*' in
1210 if host <> "" && port <> "" && user <> "" then
1211 { ssh_host = host; ssh_port = port; ssh_directory = dir;
1212 ssh_username = user;
1213 ssh_compression = compr;
1214 ssh_check = check; }
1224 (* If asked, check the SSH connection. *)
1225 if config_ssh.ssh_check then
1226 if not (test_ssh config_ssh) then
1227 failwith "SSH configuration failed";
1229 (* Devices and root partition and target configuration selection stage. *)
1230 let config_devices_to_send, config_root_filesystem, config_target =
1233 let config_devices_to_send =
1234 match !config_devices_to_send with
1237 let items = List.map (
1240 sprintf "/dev/%s (%.3f GB)" dev
1241 ((Int64.to_float size) /. (1024.*.1024.*.1024.)) in
1243 ) all_block_devices in
1245 select_multiple ~stage:"Block devices" ~force_one:true 60
1246 "Select block devices to send"
1249 let config_root_filesystem =
1250 match !config_root_filesystem with
1253 let items = List.map (
1254 fun (part, nature) ->
1256 sprintf "%s %s" (dev_of_partition part)
1257 (string_of_nature nature) in
1261 select_single ~stage:"Root filesystem" 60
1262 "Select root filesystem"
1266 match !config_target with
1269 open_centered_window ~stage:"Target system" 40 20
1270 "Configure target system";
1272 let hvlabel = Newt.label 1 1 "Hypervisor:" in
1273 let hvlistbox = Newt.listbox 16 1 4 [Newt.SCROLL] in
1274 Newt.listbox_append_entry hvlistbox "Xen" (Some Xen);
1275 Newt.listbox_append_entry hvlistbox "QEMU" (Some QEMU);
1276 Newt.listbox_append_entry hvlistbox "KVM" (Some KVM);
1277 Newt.listbox_append_entry hvlistbox "Other" None;
1279 let archlabel = Newt.label 1 5 "Architecture:" in
1280 let archlistbox = Newt.listbox 16 5 4 [Newt.SCROLL] in
1281 Newt.listbox_append_entry archlistbox "i386" I386;
1282 Newt.listbox_append_entry archlistbox
1283 "x86-64 (64-bit x86)" X86_64;
1284 Newt.listbox_append_entry archlistbox "IA64 (Itanium)" IA64;
1285 Newt.listbox_append_entry archlistbox "PowerPC 32-bit" PPC;
1286 Newt.listbox_append_entry archlistbox "PowerPC 64-bit" PPC64;
1287 Newt.listbox_append_entry archlistbox "SPARC 32-bit" SPARC;
1288 Newt.listbox_append_entry archlistbox "SPARC 64-bit" SPARC64;
1289 Newt.listbox_append_entry archlistbox "Unknown/other" UnknownArch;
1291 (* Get the architecture of the selected root filesystem. *)
1293 match List.assoc config_root_filesystem all_partitions with
1294 | LinuxRoot (arch, _) ->
1295 Newt.listbox_set_current_by_key archlistbox arch
1300 let memlabel = Newt.label 1 9 "Memory (MB):" in
1301 let mementry = Newt.entry 16 9
1302 (Some (string_of_int system_memory)) 8 [] in
1303 let cpulabel = Newt.label 1 10 "CPUs:" in
1304 let cpuentry = Newt.entry 16 10
1305 (Some (string_of_int system_nr_cpus)) 4 [] in
1306 let maclabel = Newt.label 1 11 "MAC addr:" in
1307 let macentry = Newt.entry 16 11 None 20 [] in
1308 let maclabel2 = Newt.label 1 12 "(leave MAC blank for random)" in
1311 Newt.checkbox 12 14 "Use remote libvirtd" '*' None in
1313 let ok = Newt.button 28 16 " OK " in
1315 let form = Newt.form None None [] in
1316 Newt.form_add_components form
1317 [hvlabel; Newt.component_of_listbox hvlistbox;
1318 archlabel; Newt.component_of_listbox archlistbox;
1321 maclabel; macentry; maclabel2;
1327 ignore (Newt.run_form form);
1329 let hv = Newt.listbox_get_current hvlistbox in
1330 let arch = Newt.listbox_get_current archlistbox in
1331 let mem = int_of_string (Newt.entry_get_value mementry) in
1332 let cpus = int_of_string (Newt.entry_get_value cpuentry) in
1333 let mac = Newt.entry_get_value macentry in
1334 let libvirtd = Newt.checkbox_get_value libvirtd = '*' in
1335 if hv <> None && arch <> None && mem >= 0 && cpus >= 0
1337 { tgt_hypervisor = Option.get hv;
1338 tgt_architecture = Option.get arch;
1339 tgt_memory = mem; tgt_vcpus = cpus;
1340 tgt_mac_address = mac;
1341 tgt_libvirtd = libvirtd }
1345 Not_found | Failure "int_of_string" -> loop ()
1353 config_devices_to_send, config_root_filesystem, config_target
1361 (* In test mode, exit here before we do bad things to the developer's
1364 if test_dialog_stages then exit 1;
1366 (* Switch LVM config. *)
1368 putenv "LVM_SYSTEM_DIR" "/etc/lvm.new"; (* see lvm(8) *)
1369 sh "rm -f /etc/lvm/cache/.cache";
1370 sh "rm -f /etc/lvm.new/cache/.cache";
1372 (* Snapshot the block devices to send. *)
1373 let devices_to_send = Option.get state.devices_to_send in
1374 let devices_to_send =
1377 let snapshot_dev = snapshot_name origin_dev in
1378 snapshot origin_dev snapshot_dev;
1379 (origin_dev, snapshot_dev)
1380 ) devices_to_send in
1382 (* Run kpartx on the snapshots. *)
1384 fun (origin, snapshot) ->
1385 shfailok ("kpartx -a " ^ quote ("/dev/mapper/" ^ snapshot))
1388 (* Rescan for LVs. *)
1392 (* Mount the root filesystem under /mnt/root. *)
1393 let root_filesystem = Option.get state.root_filesystem in
1394 (match root_filesystem with
1395 | Part (dev, partnum) ->
1396 let dev = dev ^ partnum in
1397 let snapshot_dev = snapshot_name dev in
1398 sh ("mount " ^ quote ("/dev/mapper/" ^ snapshot_dev) ^ " /mnt/root")
1401 (* The LV will be backed by a snapshot device, so just mount
1404 sh ("mount " ^ quote ("/dev/" ^ vg ^ "/" ^ lv) ^ " /mnt/root")
1407 (* Work out what devices will be called at the remote end. *)
1408 let devices_to_send = List.map (
1409 fun (origin_dev, snapshot_dev) ->
1410 let remote_dev = remote_of_origin_dev origin_dev in
1411 (origin_dev, snapshot_dev, remote_dev)
1412 ) devices_to_send in
1414 (* Modify files on the root filesystem. *)
1415 rewrite_fstab state devices_to_send;
1416 (* XXX Other files to rewrite? *)
1418 (* Unmount the root filesystem and sync disks. *)
1419 sh "umount /mnt/root";
1420 sh "sync"; (* Ugh, should be in stdlib. *)
1422 (* Get architecture of root filesystem, detected previously. *)
1423 let system_architecture =
1425 (match List.assoc root_filesystem all_partitions with
1426 | LinuxRoot (arch, _) -> arch
1427 | _ -> raise Not_found
1431 (* None was detected before, so assume same as live CD. *)
1432 let arch = shget "uname -m" in
1434 | Some (("i386"|"i486"|"i586"|"i686")::_) -> I386
1435 | Some ("x86_64"::_) -> X86_64
1436 | Some ("ia64"::_) -> IA64
1437 | _ -> I386 (* probably wrong XXX *) in
1439 let remote_host = Option.get state.remote_host in
1440 let remote_port = Option.get state.remote_port in
1441 let remote_directory = Option.get state.remote_directory in
1442 let remote_username = Option.get state.remote_username in
1444 (* XXX This is using the hostname derived from network configuration
1445 * above. We might want to ask the user to choose.
1447 let hostname = safe_name (gethostname ()) in
1449 let date = sprintf "%04d%02d%02d%02d%02d"
1450 (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min in
1451 "p2v-" ^ hostname ^ "-" ^ date in
1453 (* Work out what the image filenames will be at the remote end. *)
1454 let devices_to_send = List.map (
1455 fun (origin_dev, snapshot_dev, remote_dev) ->
1456 let remote_name = basename ^ "-" ^ remote_dev ^ ".img" in
1457 (origin_dev, snapshot_dev, remote_dev, remote_name)
1458 ) devices_to_send in
1460 (* Write a configuration file. Not sure if this is any better than
1461 * just 'sprintf-ing' bits of XML text together, but at least we will
1462 * always get well-formed XML.
1464 * XXX For some of the stuff here we really should do a
1465 * virConnectGetCapabilities call to the remote host first.
1467 * XXX There is a case for using virt-install to generate this XML.
1468 * When we start to incorporate libvirt access & storage API this
1469 * needs to be rethought.
1471 let conf_filename = basename ^ ".conf" in
1474 match state.architecture with
1475 | Some UnknownArch | None -> system_architecture
1476 | Some arch -> arch in
1478 match state.memory with
1479 | Some 0 | None -> system_memory
1480 | Some memory -> memory in
1482 match state.vcpus with
1483 | Some 0 | None -> system_nr_cpus
1486 match state.mac_address with
1487 | Some "" | None -> random_mac_address ()
1488 | Some mac -> mac in
1491 (* Shortcut to make "<name>value</name>". *)
1492 let leaf name value = Xml.Element (name, [], [Xml.PCData value]) in
1493 (* ... and the _other_ sort of leaf (god I hate XML). *)
1494 let tleaf name attribs = Xml.Element (name, attribs, []) in
1496 (* Standard stuff for every domain. *)
1497 let name = leaf "name" hostname in
1498 let uuid = leaf "uuid" (random_uuid ()) in
1499 let maxmem = leaf "maxmem" (string_of_int (memory * 1024)) in
1500 let memory = leaf "memory" (string_of_int (memory * 1024)) in
1501 let vcpu = leaf "vcpu" (string_of_int vcpus) in
1503 (* Top-level stuff which differs for each HV type (isn't this supposed
1504 * to be portable ...)
1507 match state.hypervisor with
1509 [Xml.Element ("os", [],
1511 leaf "loader" "/usr/lib/xen/boot/hvmloader";
1512 tleaf "boot" ["dev", "hd"]]);
1513 Xml.Element ("features", [],
1517 tleaf "clock" ["sync", "localtime"]]
1519 [Xml.Element ("os", [], [leaf "type" "hvm"]);
1520 tleaf "clock" ["sync", "localtime"]]
1522 [Xml.Element ("os", [],
1523 [Xml.Element ("type",
1525 string_of_architecture architecture;
1527 [Xml.PCData "hvm"]);
1528 tleaf "boot" ["dev", "hd"]])]
1532 (* <devices> section. *)
1535 match state.hypervisor with
1537 [leaf "emulator" "/usr/lib64/xen/bin/qemu-dm"] (* XXX lib64? *)
1539 [leaf "emulator" "/usr/bin/qemu"]
1541 [leaf "emulator" "/usr/bin/qemu-kvm"]
1545 Xml.Element ("interface", ["type", "user"],
1546 [tleaf "mac" ["address", mac_address]]) in
1547 (* XXX should have an option for Xen bridging:
1549 "interface", ["type","bridge"],
1550 [tleaf "source" ["bridge","xenbr0"];
1551 tleaf "mac" ["address",mac_address];
1552 tleaf "script" ["path","vif-bridge"]])*)
1553 let graphics = tleaf "graphics" ["type", "vnc"] in
1555 let disks = List.map (
1556 fun (_, _, remote_dev, remote_name) ->
1558 "disk", ["type", "file";
1560 [tleaf "source" ["file", remote_directory ^ "/" ^ remote_name];
1561 tleaf "target" ["dev", remote_dev]]
1563 ) devices_to_send in
1567 emulator @ interface :: graphics :: disks
1570 (* Put it all together in <domain type='foo'>. *)
1573 (match state.hypervisor with
1574 | Some Xen -> ["type", "xen"]
1575 | Some QEMU -> ["type", "qemu"]
1576 | Some KVM -> ["type", "kvm"]
1578 name :: uuid :: memory :: maxmem :: vcpu :: extras @ [devices]
1581 (* Convert XML configuration file to a string, then send it to the
1585 let xml = Xml.to_string_fmt xml in
1588 match state.hypervisor with
1589 | Some Xen | None -> ""
1590 | Some QEMU | Some KVM -> " -c qemu:///system" in
1591 let xml = sprintf "\
1593 This is a libvirt configuration file.
1595 To start the domain, do:
1598 -->\n\n" conn_arg conf_filename conn_arg hostname ^ xml in
1600 let xml_len = String.length xml in
1601 eprintf "length of configuration file is %d bytes\n%!" xml_len;
1603 let (sock,_) as conn = do_connect conf_filename (Int64.of_int xml_len) in
1604 (* In OCaml this actually loops calling write(2) *)
1605 ignore (write sock xml 0 xml_len);
1606 do_disconnect conn in
1608 (* Send the device snapshots to the remote host. *)
1609 (* XXX This code should be made more robust against both network
1610 * errors and local I/O errors. Also should allow the user several
1611 * attempts to connect, or let them go back to the dialog stage.
1614 fun (origin_dev, snapshot_dev, remote_dev, remote_name) ->
1615 eprintf "sending %s as %s\n%!" origin_dev remote_name;
1618 try List.assoc origin_dev all_block_devices
1619 with Not_found -> assert false (* internal error *) in
1621 printf "Sending /dev/%s (%.3f GB) to remote machine\n%!" origin_dev
1622 ((Int64.to_float size) /. (1024.*.1024.*.1024.));
1624 (* Open the snapshot device. *)
1625 let fd = openfile ("/dev/mapper/" ^ snapshot_dev) [O_RDONLY] 0 in
1628 let (sock,_) as conn = do_connect remote_name size in
1630 (* Copy the data. *)
1631 let spinners = "|/-\\" (* "Oo" *) in
1632 let bufsize = 1024 * 1024 in
1633 let buffer = String.create bufsize in
1634 let start = gettimeofday () in
1636 let rec copy bytes_sent last_printed_at spinner =
1637 let n = read fd buffer 0 bufsize in
1639 let n' = write sock buffer 0 n in
1640 if n <> n' then assert false; (* never, according to the manual *)
1642 let bytes_sent = Int64.add bytes_sent (Int64.of_int n) in
1643 let last_printed_at, spinner =
1644 let now = gettimeofday () in
1645 (* Print progress every few seconds. *)
1646 if now -. last_printed_at > 2. then (
1647 let elapsed = Int64.to_float bytes_sent /. Int64.to_float size in
1648 let secs_elapsed = now -. start in
1649 printf "%.0f%% %c %.1f Mbps"
1650 (100. *. elapsed) spinners.[spinner]
1651 (Int64.to_float bytes_sent/.secs_elapsed/.1_000_000. *. 8.);
1652 (* After 60 seconds has elapsed, start printing estimates. *)
1653 if secs_elapsed >= 60. then (
1654 let remaining = 1. -. elapsed in
1655 let secs_remaining = (remaining /. elapsed) *. secs_elapsed in
1656 if secs_remaining > 120. then
1657 printf " (about %.0f minutes remaining)" (secs_remaining/.60.)
1659 printf " (about %.0f seconds remaining)"
1663 let spinner = (spinner + 1) mod String.length spinners in
1666 else last_printed_at, spinner in
1668 copy bytes_sent last_printed_at spinner
1672 printf "\n\n%!"; (* because of the messages printed above *)
1678 (*printf "\n\nPress any key ...\n%!"; ignore (read_line ());*)
1680 (* Clean up and reboot. *)
1682 msgbox (sprintf "%s completed" program_name)
1683 (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."
1684 remote_directory conf_filename)
1693 (*----------------------------------------------------------------------*)
1696 eprintf "usage: virt-p2v [--test] [ttyname]\n%!";
1699 (* Make sure that exceptions from 'main' get printed out on stdout
1700 * as well as stderr, since stderr is probably redirected to the
1701 * logfile, and so not visible to the user.
1703 let handle_exn f arg =
1706 print_endline (Printexc.to_string exn);
1709 (* Test harness for the Makefile. The Makefile invokes this script as
1710 * 'virt-p2v --test' just to check it compiles. When it is running
1711 * from the actual live CD, there is a single parameter which is the
1712 * tty name (so usually 'virt-p2v tty1').
1715 match Array.to_list Sys.argv with
1716 | [ _; ("--help"|"-help"|"-?"|"-h") ] -> usage ();
1717 | [ _; "--test" ] -> () (* Makefile test - do nothing. *)
1718 | [ _; ttyname ] -> (* Run main with ttyname. *)
1719 handle_exn main (Some ttyname)
1720 | [ _ ] -> (* Interactive - no ttyname. *)
1721 handle_exn main None
1724 (* This file must end with a newline *)