libvirt capabilities parsed and incorporated into the generated config file.
[virt-p2v.git] / virt-p2v
1 #!/usr/bin/ocamlrun /usr/bin/ocaml
2 (* -*- tuareg -*- *)
3 (* virt-p2v is a script which performs a physical to
4  * virtual conversion of local disks.
5  *
6  * Copyright (C) 2007-2008 Red Hat Inc.
7  * Written by Richard W.M. Jones <rjones@redhat.com>
8  *
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.
13  *
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.
18  *
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
22  *)
23
24 type partition =
25   | Part of string * string             (* eg. "hda", "1" *)
26   | LV of string * string               (* eg. "VolGroup00", "LogVol00" *)
27 type transfer =
28   | P2V                                 (* physical to virtual *)
29   | V2V                                 (* virtual to virtual *)
30   (*| V2P*)                             (* virtual to physical - not impl *)
31 type network =
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 *)
37   | NoNetwork
38 type ssh_config = {
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. *)
45 }
46 type hypervisor =
47   | Xen
48   | QEMU
49   | KVM
50 type architecture =
51   | I386 | X86_64 | IA64 | PPC | PPC64 | SPARC | SPARC64
52   | OtherArch of string
53   | UnknownArch
54 type wordsize =
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. *)
63 }
64
65 (*----------------------------------------------------------------------*)
66 (* TO MAKE A CUSTOM VIRT-P2V SCRIPT, adjust the defaults in this section.
67  *
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.
72  *
73  * Note that 'None' means 'no default' (ie. ask the user) whereas
74  * 'Some foo' means use 'foo' as the answer.
75  *
76  * These are documented in the virt-p2v(1) manual page.
77  *
78  * After changing them, run './virt-p2v --test' to check syntax.
79  *)
80
81 (* If greeting is true, wait for keypress after boot and during
82  * final verification.  Set to 'false' for less interactions.
83  *)
84 let config_greeting = ref true
85
86 (* General type of transfer. *)
87 let config_transfer_type = ref None
88
89 (* Network configuration. *)
90 let config_network = ref None
91
92 (* SSH configuration. *)
93 let config_ssh = ref None
94
95 (* What to transfer. *)
96 let config_devices_to_send = ref None
97 let config_root_filesystem = ref None
98
99 (* Configuration of the target. *)
100 let config_target = ref None
101
102 (* The name of the program as displayed in various places. *)
103 let program_name = "virt-p2v"
104
105 (* If you want to test the dialog stages, set this to true. *)
106 let test_dialog_stages = false
107
108 (* END OF CUSTOM virt-p2v SCRIPT SECTION.                               *)
109 (*----------------------------------------------------------------------*)
110
111 (* Load external libraries. *)
112 ;;
113 #load "unix.cma";;
114 #directory "+extlib";;
115 #load "extLib.cma";;
116 #directory "+pcre";;
117 #load "pcre.cma";;
118 #directory "+newt";;
119 #load "mlnewt.cma";;
120 #directory "+xml-light";;
121 #load "xml-light.cma";;
122 #directory "+libvirt";;
123 #load "mllibvirt.cma";;
124
125 open Unix
126 open Printf
127 open ExtList
128 open ExtString
129
130 (*----------------------------------------------------------------------*)
131 (* General helper functions. *)
132
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
139   in
140   loop xs
141
142 let input_all_lines chan =
143   let lines = ref [] in
144   try
145     while true do lines := input_line chan :: !lines done; []
146   with
147     End_of_file -> List.rev !lines
148
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
152
153 let string_of_architecture = function
154   | I386 -> "i386"
155   | X86_64 -> "x86_64"
156   | IA64 -> "ia64"
157   | PPC -> "ppc"
158   | PPC64 -> "ppc64"
159   | SPARC -> "sparc"
160   | SPARC64 -> "sparc64"
161   | OtherArch arch -> arch
162   | UnknownArch -> ""
163
164 let architecture_of_string = function
165   | str when
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
176   | "" -> UnknownArch
177   | str -> OtherArch str
178
179 let wordsize_of_architecture = function
180   | I386 -> W32
181   | X86_64 -> W64
182   | IA64 -> W64
183   | PPC -> W32
184   | PPC64 -> W64
185   | SPARC -> W32
186   | SPARC64 -> W64
187   | OtherArch arch -> WUnknown
188   | UnknownArch -> WUnknown
189
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 *)
195             | UnknownNature
196 and linux_distro = RHEL of int * int
197                  | Fedora of int
198                  | Debian of int * int
199                  | OtherLinux
200
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"
214
215 (* XML helper functions. *)
216 let rec children_with_name name xml =
217   let children = Xml.children xml in
218   List.filter (
219     function
220     | Xml.Element (n, _, _) when n = name -> true
221     | _ -> false
222   ) children
223 and xml_has_pcdata_child name pcdata xml =
224   xml_has_child_matching (
225     function
226     | Xml.Element (n, _, [Xml.PCData pcd])
227         when n = name && pcd = pcdata -> true
228     | _ -> false
229   ) xml
230 and xml_has_attrib_child name attrib xml =
231   xml_has_child_matching (
232     function
233     | Xml.Element (n, attribs, _)
234         when n = name && List.mem attrib attribs -> true
235     | _ -> false
236   ) xml
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
242   match children with
243   | [] -> raise Not_found
244   | h :: _ -> h
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
250     | _ :: tl -> loop tl
251   in
252   loop children
253
254 type ('a, 'b) either = Either of 'a | Or of 'b
255
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.
259  *
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.
263  *)
264 let in_newt = ref false
265 let with_newt f =
266   if !in_newt then f ()
267   else (
268     in_newt := true;
269     let r =
270       try Either (Newt.init_and_finish f)
271       with exn -> Or exn in
272     in_newt := false;
273     match r with Either r -> r | Or exn -> raise exn
274   )
275
276 (* Clear the screen, open a new centered window, make sure the background
277  * and help messages are consistent.
278  *)
279 let open_centered_window ?stage width height title =
280   if not !in_newt then failwith "open_centered_window: not in newt mode";
281   Newt.cls ();
282   Newt.centered_window width height title;
283   let root_text =
284     program_name ^ (match stage with
285                     | None -> ""
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"
289
290 (* Some general dialog boxes. *)
291 let message_box title text =
292   with_newt (
293     fun () ->
294       open_centered_window 40 20 title;
295
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];
301
302       Newt.component_takes_focus ok true;
303
304       ignore (Newt.run_form form);
305       Newt.pop_window ()
306   )
307
308 (* Fail and exit with error. *)
309 let failwith text =
310   prerr_endline text;
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;
313   exit 1
314
315 (* Display a dialog with checkboxes, return the multiple selected items. *)
316 let select_multiple ?stage ?(force_one = false) width title items =
317   with_newt (
318     fun () ->
319       open_centered_window ?stage width 20 title;
320
321       let entries =
322         List.mapi (
323           fun i (label, handle, selected) ->
324             let cb =
325               Newt.checkbox 1 (i+1) label
326                 (if selected then '*' else ' ') None in
327             (handle, cb)
328         ) items in
329
330       let ok = Newt.button 48 16 "  OK  " in
331
332       let vb =
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)
337         else
338           None in
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;
342
343       let selected =
344         let rec loop () =
345           ignore (Newt.run_form form);
346           let selected = List.filter_map (
347             fun (handle, cb) ->
348               if Newt.checkbox_get_value cb = '*' then Some handle else None
349           ) entries in
350           if force_one && selected = [] then loop ()
351           else selected
352         in
353         loop () in
354
355       Newt.pop_window ();
356
357       selected
358   )
359
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";
363
364   with_newt (
365     fun () ->
366       open_centered_window ?stage width 20 title;
367
368       let prev = ref None in
369       let entries =
370         List.mapi (
371           fun i (label, handle) ->
372             let rb = Newt.radio_button 1 (i+1) label (!prev = None) !prev in
373             prev := Some rb;
374             (handle, rb)
375         ) items in
376
377       let ok = Newt.button (width-12) 16 "  OK  " in
378
379       let vb =
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)
384         else
385           None in
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;
389
390       let (selected, _) =
391         let rec loop () =
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.
397            *)
398           try
399             List.find (fun (_, rb) -> Newt.component_equals r rb) entries
400           with
401             Not_found -> loop ()
402         in
403         loop () in
404
405       Newt.pop_window ();
406
407       selected
408   )
409
410 (* Shell-safe quoting function.  In fact there's one in stdlib so use it. *)
411 let quote = Filename.quote
412
413 (* Run a shell command and check it returns 0. *)
414 let sh cmd =
415   eprintf "sh: %s\n%!" cmd;
416   if Sys.command cmd <> 0 then failwith (sprintf "Command failed:\n\n%s" cmd)
417
418 let shfailok cmd =
419   eprintf "shfailok: %s\n%!" cmd;
420   ignore (Sys.command cmd)
421
422 let shwithstatus cmd =
423   eprintf "shwithstatus: %s\n%!" cmd;
424   Sys.command cmd
425
426 (* Same as `cmd` in shell.  Any error message will be in the logfile. *)
427 let shget cmd =
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)
436
437 (* Start an interactive shell.  Need to juggle file descriptors a bit
438  * because bash write PS1 to stderr (currently directed to the logfile).
439  *)
440 let shell () =
441   match fork () with
442   | 0 ->                                (* child, runs bash *)
443       close stderr;
444       dup2 stdout stderr;
445       (* Sys.command runs 'sh -c' which blows away PS1, so set it late. *)
446       ignore (
447         Sys.command "PS1='\\u@\\h:\\w\\$ ' /bin/bash --norc --noprofile -i"
448       )
449   | _ ->                                (* parent, waits *)
450       eprintf "waiting for subshell to exit\n%!";
451       ignore (wait ())
452
453 (* Some true if is dir/file, Some false if not, None if not found. *)
454 let is_dir path =
455   try Some ((stat path).st_kind = S_DIR)
456   with Unix_error (ENOENT, "stat", _) -> None
457 let is_file path =
458   try Some ((stat path).st_kind = S_REG)
459   with Unix_error (ENOENT, "stat", _) -> None
460
461 (*----------------------------------------------------------------------*)
462 (* P2V-specific helper functions. *)
463
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.
467  *)
468 let safe_name =
469   let next_anon =
470     let i = ref 0 in
471     fun () -> incr i; "_" ^ string_of_int !i
472   in
473   fun name ->
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
479     done;
480     if !have_safe then name else next_anon ()
481
482 type block_device = string * int64      (* "hda" & size in bytes *)
483
484 (* Parse the output of 'lvs' to get list of LV names, sizes,
485  * corresponding PVs, etc.  Returns a list of (lvname, PVs, lvsize).
486  *)
487 let get_lvs =
488   let devname = Pcre.regexp "^/dev/(.+)\\(.+\\)$" in
489
490   fun () ->
491     match
492     shget "lvs --noheadings -o vg_name,lv_name,devices,lv_size"
493     with
494     | None -> []
495     | Some lines ->
496         let lines = List.map Pcre.split lines in
497         List.map (
498           function
499           | [vg; lv; pvs; lvsize]
500           | [_; vg; lv; pvs; lvsize] ->
501               let pvs = String.nsplit pvs "," in
502               let pvs = List.filter_map (
503                 fun pv ->
504                   try
505                     let subs = Pcre.exec ~rex:devname pv in
506                     Some (Pcre.get_substring subs 1)
507                   with
508                     Not_found ->
509                       eprintf "lvs: unexpected device name: %s\n%!" pv;
510                       None
511               ) pvs in
512               LV (vg, lv), pvs, lvsize
513           | line ->
514               failwith ("lvs: unexpected output: " ^ String.concat "," line)
515         ) lines
516
517 (* Get the partitions on a block device.
518  * eg. "sda" -> [Part ("sda","1"); Part ("sda", "2")]
519  *)
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)
527   ) parts in
528   let parts = List.filter_map (
529     fun part ->
530       try
531         let subs = Pcre.exec ~rex part in
532         Some (Part (dev, Pcre.get_substring subs 1))
533       with
534         Not_found -> None
535   ) parts in
536   parts
537
538 (* Generate snapshot device name from device name. *)
539 let snapshot_name dev =
540   "snap" ^ (safe_name dev)
541
542 (* Perform a device-mapper snapshot with ramdisk overlay. *)
543 let snapshot =
544   let next_free_ram_disk =
545     let i = ref 0 in
546     fun () -> incr i; "/dev/ram" ^ string_of_int !i
547   in
548   fun origin_dev snapshot_dev ->
549     let ramdisk = next_free_ram_disk () in
550     let sectors =
551       let cmd = "blockdev --getsz " ^ quote ("/dev/" ^ origin_dev) in
552       let lines = shget cmd in
553       match lines with
554       | Some (sectors::_) -> Int64.of_string sectors
555       | Some [] | None ->
556           failwith (sprintf "Snapshot failed - unable to read the size in sectors of block device %s" origin_dev) in
557
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)
564
565 (* Try to perform automatic network configuration, assuming a Fedora or
566  * RHEL-like root filesystem mounted on /mnt/root.
567  *)
568 let auto_network () =
569   (* Fedora gives an error if this file doesn't exist. *)
570   sh "touch /etc/resolv.conf";
571
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).
575    *)
576   sh "mount -o bind /mnt/root/etc /etc";
577   let status = shwithstatus "/etc/init.d/network start" in
578   sh "umount -l /etc";
579
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}'`";
582
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";
586     printf "    (y/n) %!";
587     let line = read_line () in
588     String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
589   )
590   else
591     (* Non-interactive: return the status of /etc/init.d/network start. *)
592     status = 0
593
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
597   try
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"
604                         (quote nameserver));
605     true                                (* succeeded *)
606   with
607     Exit -> false                       (* failed *)
608
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"
614
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.
618  *)
619 let remote_of_origin_dev =
620   let devsd = Pcre.regexp "^sd([[:alpha:]]+[[:digit:]]*)$" in
621   let devsd_subst = Pcre.subst "hd$1" in
622   fun dev ->
623     Pcre.replace ~rex:devsd ~itempl:devsd_subst dev
624
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.
628  *
629  * NB. The command is NOT quoted.
630  *
631  * Returns a pair (file descriptor, channel), both referring to the
632  * same thing.  Use whichever is more convenient.
633  *)
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)
638     cmd in
639   eprintf "ssh_connect: %s\n%!" cmd;
640   let chan = open_process_out cmd in
641   descr_of_out_channel chan, chan
642
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)
650
651 (* Use these functions to upload a file. *)
652 let ssh_start_upload config filename =
653   let cmd =
654     sprintf "cat \\> %s/%s" (quote config.ssh_directory) (quote filename) in
655   ssh_connect config cmd
656
657 let ssh_finish_upload = ssh_disconnect
658
659 (* Test SSH connection. *)
660 let test_ssh config =
661   printf "Testing SSH connection by listing files in remote directory ...\n\n%!";
662
663   let cmd = sprintf "/bin/ls %s" (quote config.ssh_directory) in
664   let conn = ssh_connect config cmd in
665   ssh_disconnect conn;
666
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";
670     printf "    (y/n) %!";
671     let line = read_line () in
672     String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
673   )
674   else
675     true
676
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"));
682
683     let chan = open_in filename in
684     let lines = input_all_lines chan in
685     close_in chan;
686     let lines = List.map Pcre.split lines in
687     let lines = List.map (
688       function
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
693           dev :: rest
694       | line -> line
695     ) lines in
696
697     let chan = open_out filename in
698     List.iter (
699       function
700       | [dev; mountpoint; fstype; options; freq; passno] ->
701           fprintf chan "%-23s %-23s %-7s %-15s %s %s\n"
702             dev mountpoint fstype options freq passno
703       | line ->
704           output_string chan (String.concat " " line);
705           output_char chan '\n'
706     ) lines;
707     close_out chan
708   )
709
710 (* Generate a random MAC address in the Xen-reserved space. *)
711 let random_mac_address () =
712   let random =
713     List.map (sprintf "%02x") (
714       List.map (fun _ -> Random.int 256) [0;0;0]
715     ) in
716   String.concat ":" ("00"::"16"::"3e"::random)
717
718 (* Generate a random UUID. *)
719 let random_uuid =
720   let hex = "0123456789abcdef" in
721   fun () ->
722   let str = String.create 32 in
723   for i = 0 to 31 do str.[i] <- hex.[Random.int 16] done;
724   str
725
726 (*----------------------------------------------------------------------*)
727 (* Main entry point. *)
728
729 (* The general plan for the main function is to operate in stages:
730  *
731  *      Start-up
732  *         |
733  *         V
734  *      Information gathering about the system
735  *         |     (eg. block devices, number of CPUs, etc.)
736  *         V
737  *      Greeting and type of transfer question
738  *         |
739  *         V
740  *      Set up the network
741  *         |     (after this point we have a working network)
742  *         V
743  *      Set up SSH
744  *         |     (after this point we have a working SSH connection)
745  *         V
746  *      Questions about what to transfer (block devs, root fs) <--.
747  *         |                                                      |
748  *         V                                                      |
749  *      Questions about hypervisor configuration                  |
750  *         |                                                      |
751  *         V                                                      |
752  *      Verify information -------- user wants to change info ----/
753  *         |
754  *         V
755  *      Perform transfer
756  *
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.
760  *)
761
762 let rec main ttyname =
763   Random.self_init ();
764
765   (* Running from an init script.  We don't have much of a
766    * login environment, so set one up.
767    *)
768   putenv "PATH"
769     (String.concat ":"
770        ["/usr/sbin"; "/sbin"; "/usr/local/bin"; "/usr/kerberos/bin";
771         "/usr/bin"; "/bin"]);
772   putenv "HOME" "/root";
773   putenv "LOGNAME" "root";
774
775   (* We can safely write in /tmp (it's a synthetic live CD directory). *)
776   chdir "/tmp";
777
778   (* Set up logging to /tmp/virt-p2v.log. *)
779   let fd = openfile "virt-p2v.log" [ O_WRONLY; O_APPEND; O_CREAT ] 0o644 in
780   dup2 fd stderr;
781   close fd;
782
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%!"
787     program_name
788     (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec;
789
790   (* Connect stdin/stdout to the tty. *)
791   (match ttyname with
792    | None -> ()
793    | Some ttyname ->
794        let fd = openfile ("/dev/" ^ ttyname) [ O_RDWR ] 0 in
795        dup2 fd stdin;
796        dup2 fd stdout;
797        close fd);
798   printf "%s starting up ...\n%!" program_name;
799
800   (* Disable screen blanking on tty. *)
801   sh "setterm -blank 0";
802
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
805     failwith
806       "You should only run this script from the live CD or a USB key.";
807
808   (* Start of the information gathering phase. *)
809   printf "Detecting hard drives (this may take some time) ...\n%!";
810
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".
813    *)
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).
823      *)
824     let devices = List.filter_map (
825       fun d ->
826         let cmd = "blockdev --getsize64 " ^ quote ("/dev/" ^ d) in
827         let lines = shget cmd in
828         match lines with
829         | Some (blksize::_) -> Some (d, Int64.of_string blksize)
830         | Some [] | None -> None
831     ) devices in
832     eprintf "all_block_devices: non-removable block devices: %s\n%!"
833       (String.concat "; "
834          (List.map (fun (d, b) -> sprintf "%s [%Ld]" d b) devices));
835     if devices = [] then
836       failwith "No non-removable block devices (hard disks, etc.) could be found on this machine.";
837     devices in
838
839   (* Search for partitions and LVs (anything that could contain a
840    * filesystem directly).  We refer to these generically as
841    * "partitions".
842    *)
843   let all_partitions : partition list =
844     (* LVs & PVs. *)
845     let lvs, pvs =
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));
854       lvs, pvs in
855
856     (* Partitions (eg. "sda1", "sda2"). *)
857     let parts =
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));
863
864       (* Remove any partitions which are PVs. *)
865       let parts = List.filter (
866         function
867         | Part (dev, partnum) -> not (List.mem (dev ^ partnum) pvs)
868         | LV _ -> assert false
869       ) parts in
870       parts in
871     eprintf "all_partitions: partitions after removing PVs: %s\n%!"
872       (String.concat "; " (List.map dev_of_partition parts));
873
874     (* Concatenate LVs & Parts *)
875     lvs @ parts in
876
877   (* Try to determine the nature of each partition.
878    * Root? Swap? Architecture? etc.
879    *)
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
892
893     (* Examine the filesystem mounted on 'mnt' to determine the
894      * operating system, and, if Linux, the distro.
895      *)
896     let detect_os mnt =
897       if is_dir (mnt ^ "/Windows") = Some true &&
898         is_file (mnt ^ "/autoexec.bat") = Some true then
899           WindowsRoot
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
906             close_in chan;
907
908             match lines with
909             | [] -> (* empty /etc/redhat-release ...? *)
910                 LinuxRoot (UnknownArch, OtherLinux)
911             | line::_ -> (* try to detect OS from /etc/redhat-release *)
912                 try
913                   let subs = Pcre.exec ~rex:rhel line in
914                   let major = int_of_string (Pcre.get_substring subs 1) in
915                   let minor =
916                     try int_of_string (Pcre.get_substring subs 2)
917                     with Not_found -> 0 in
918                   LinuxRoot (UnknownArch, RHEL (major, minor))
919                 with
920                   Not_found | Failure "int_of_string" ->
921                     try
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)
925                     with
926                       Not_found | Failure "int_of_string" ->
927                         LinuxRoot (UnknownArch, OtherLinux)
928           )
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
932             close_in chan;
933
934             match lines with
935             | [] -> (* empty /etc/debian_version ...? *)
936                 LinuxRoot (UnknownArch, OtherLinux)
937             | line::_ -> (* try to detect version from /etc/debian_version *)
938                 try
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))
943                 with
944                   Not_found | Failure "int_of_string" ->
945                     LinuxRoot (UnknownArch, OtherLinux)
946           )
947           else
948             LinuxRoot (UnknownArch, OtherLinux)
949         ) else if is_dir (mnt ^ "/grub") = Some true &&
950           is_file (mnt ^ "/grub/stage1") = Some true then (
951             LinuxBoot
952         ) else
953           NotRoot (* mountable, but not a root filesystem *)
954     in
955
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.
959      *)
960     let detect_architecture mnt =
961       let cmd = "file -bL " ^ quote (mnt ^ "/sbin/init") in
962       match shget cmd with
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
966       | _ -> UnknownArch
967     in
968
969     List.map (
970       fun part ->
971         let dev = dev_of_partition part in (* Get /dev device. *)
972
973         let nature =
974           (* Use 'file' command to detect if it is swap. *)
975           let cmd = "file -sbL " ^ quote dev in
976           match shget cmd with
977           | Some (str::_) when Pcre.pmatch ~rex:swap str -> LinuxSwap
978           | _ ->
979               (* Blindly try to mount the device. *)
980               let cmd = "mount -o ro " ^ quote dev ^ " /mnt/root" in
981               match shwithstatus cmd with
982               | 0 ->
983                   let os = detect_os "/mnt/root" in
984                   let nature =
985                     match os with
986                     | LinuxRoot (UnknownArch, distro) ->
987                         let architecture = detect_architecture "/mnt/root" in
988                         LinuxRoot (architecture, distro)
989                     | os -> os in
990                   sh "umount /mnt/root";
991                   nature
992
993               | _ -> UnknownNature (* not mountable *)
994
995         in
996
997         eprintf "partition detection: %s is %s\n%!"
998           dev (string_of_nature nature);
999
1000         (part, nature)
1001     ) all_partitions
1002   in
1003
1004   printf "Finished detecting hard drives.\n%!";
1005
1006   (* Autodetect system memory. *)
1007   let 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.
1011      *)
1012     let dmesg = shget "dmesg" in
1013     try
1014       let dmesg =
1015         match dmesg with Some lines -> lines | None -> raise Not_found in
1016       let line =
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
1021     with
1022       Not_found | Failure "int_of_string" ->
1023         (* 'dmesg' can't be parsed.  The backup plan is to look
1024          * at /proc/meminfo.
1025          *)
1026         let mem = shget "head -1 /proc/meminfo | awk '{print $2/1024}'" in
1027         match mem with
1028         | Some (mem::_) -> int_of_float (float_of_string mem)
1029
1030         (* For some reason even /proc/meminfo didn't work.  Just
1031          * assume 256 MB instead.
1032          *)
1033         | _ -> 256 in
1034
1035   (* Autodetect system # pCPUs. *)
1036   let system_nr_cpus =
1037     let cpus =
1038       shget "grep ^processor /proc/cpuinfo | tail -1 | awk '{print $3+1}'" in
1039     match cpus with
1040     | Some (cpus::_) -> int_of_string cpus
1041     | _ -> 1 in
1042
1043   (* Greeting, type of transfer, network question stages.
1044    * These are all done in newt mode.
1045    *)
1046   let config_transfer_type, config_network =
1047     with_newt (
1048       fun () ->
1049         (* Greeting. *)
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);
1052
1053         (* Type of transfer. *)
1054         let config_transfer_type =
1055           match !config_transfer_type with
1056           | Some t -> t
1057           | None ->
1058               let items = [
1059                 "Physical to Virtual (P2V)", P2V;
1060                 "Virtual to Virtual (V2V)", V2V;
1061               ] in
1062
1063               select_single ~stage:"Transfer type" 40
1064                 "Transfer type"
1065                 items in
1066
1067         (* Network configuration. *)
1068         let config_network =
1069           match !config_network with
1070           | Some n -> n
1071           | None ->
1072               open_centered_window ~stage:"Network"
1073                 60 20 "Configure network";
1074
1075               let autolist = Newt.listbox 4 2 4 [Newt.SCROLL] in
1076               Newt.listbox_set_width autolist 52;
1077
1078               (* Populate the "Automatic" listbox with RHEL/Fedora
1079                * root partitions found which allow us to do
1080                * automatic configuration in a known way.
1081                *)
1082               let rec loop = function
1083                 | [] -> ()
1084                 | (partition, LinuxRoot (_, ((RHEL _|Fedora _) as distro)))
1085                   :: parts ->
1086                     let label =
1087                       sprintf "%s (%s)"
1088                         (dev_of_partition partition)
1089                         (string_of_linux_distro distro) in
1090                     ignore (Newt.listbox_append_entry autolist label partition);
1091                     loop parts
1092                 | _ :: parts -> loop parts
1093               in
1094               loop all_partitions;
1095
1096               (* If there is no suitable root partition (the listbox
1097                * is empty) then disable the auto option and the listbox.
1098                *)
1099               let no_auto = Newt.listbox_item_count autolist = 0 in
1100
1101               let auto =
1102                 Newt.radio_button 1 1
1103                   "Automatic from:" (not no_auto) None in
1104               let shell =
1105                 Newt.radio_button 1 6
1106                   "Start a shell" no_auto (Some auto) in
1107
1108               if no_auto then (
1109                 Newt.component_takes_focus auto false;
1110                 Newt.component_takes_focus
1111                   (Newt.component_of_listbox autolist) false
1112               );
1113
1114               let qemu =
1115                 Newt.radio_button 1 7
1116                   "QEMU user network" false (Some shell) in
1117               let nonet =
1118                 Newt.radio_button 1 8
1119                   "No network or network already configured" false
1120                   (Some qemu) in
1121               let static =
1122                 Newt.radio_button 1 9
1123                   "Static configuration:" false (Some nonet) in
1124
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
1135
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
1142               in
1143
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
1150               in
1151
1152               let enable_autolist () =
1153                 Newt.component_takes_focus
1154                   (Newt.component_of_listbox autolist) true
1155               in
1156               let disable_autolist () =
1157                 Newt.component_takes_focus
1158                   (Newt.component_of_listbox autolist) false
1159               in
1160
1161               disable_static ();
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 ());
1172
1173               let ok = Newt.button 48 16 "  OK  " in
1174
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;
1181                                              ok];
1182
1183               let n =
1184                 let rec loop () =
1185                   ignore (Newt.run_form form);
1186
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
1190                     | None -> loop ()
1191                     | Some part -> Auto part
1192                   )
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
1204                         loop ()
1205                     else
1206                       Static (interface, address, netmask, gateway, nameserver)
1207                   )
1208                   else loop ()
1209                 in
1210                 loop () in
1211               Newt.pop_window ();
1212
1213               n in
1214
1215         config_transfer_type, config_network
1216     ) in
1217
1218   (* Try to bring up the network. *)
1219   (match config_network with
1220    | Shell ->
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%!";
1224        shell ()
1225
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";
1233          shell ()
1234        )
1235
1236    | Auto rootfs ->
1237        printf
1238          "Trying network auto-configuration from root filesystem ...\n\n%!";
1239
1240        (* Mount the root filesystem read-only under /mnt/root. *)
1241        sh ("mount -o ro " ^ quote (dev_of_partition rootfs) ^ " /mnt/root");
1242
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";
1247          shell ()
1248        );
1249
1250        (* NB. Lazy unmount is required because dhclient keeps its current
1251         * directory open on /etc/sysconfig/network-scripts/
1252         *)
1253        sh ("umount -l /mnt/root");
1254
1255    | QEMUUserNet ->
1256        printf "Trying QEMU network configuration.\n\n%!";
1257        qemu_network ()
1258
1259    | NoNetwork -> (* this is easy ... *) ()
1260   );
1261
1262   (* SSH configuration phase. *)
1263   let config_ssh =
1264     with_newt (
1265       fun () ->
1266         match !config_ssh with
1267         | Some c -> c
1268         | None ->
1269             (* Query the user for SSH configuration. *)
1270             open_centered_window ~stage:"SSH configuration"
1271               60 20 "SSH configuration";
1272
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
1281             (*
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
1285             *)
1286
1287             let compr =
1288               Newt.checkbox 16 7 "Use SSH compression (not good for LANs)"
1289                 ' ' None in
1290
1291             let check = Newt.checkbox 16 9 "Test SSH connection" '*' None in
1292
1293             let ok = Newt.button 48 16 "  OK  " in
1294
1295             let form = Newt.form None None [] in
1296             Newt.form_add_components form [label1;label2;label3;label4;
1297                                            host;port;dir;user;
1298                                            compr;check;
1299                                            ok];
1300
1301             let c =
1302               let rec loop () =
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; }
1315                 else
1316                   loop ()
1317               in
1318               loop () in
1319
1320             Newt.pop_window ();
1321             c
1322     ) in
1323
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";
1328
1329   (* Devices and root partition and target configuration selection stage. *)
1330   let config_devices_to_send, config_root_filesystem, config_target =
1331     with_newt (
1332       fun () ->
1333         let config_devices_to_send =
1334           match !config_devices_to_send with
1335           | Some ds -> ds
1336           | None ->
1337               let items = List.map (
1338                   fun (dev, size) ->
1339                     let label =
1340                       sprintf "/dev/%s (%.3f GB)" dev
1341                       ((Int64.to_float size) /. (1024.*.1024.*.1024.)) in
1342                     (label, dev, true)
1343               ) all_block_devices in
1344
1345               select_multiple ~stage:"Block devices" ~force_one:true 60
1346                 "Select block devices to send"
1347                 items in
1348
1349         let config_root_filesystem =
1350           match !config_root_filesystem with
1351           | Some fs -> fs
1352           | None ->
1353               let items = List.map (
1354                 fun (part, nature) ->
1355                   let label =
1356                     sprintf "%s %s" (dev_of_partition part)
1357                       (string_of_nature nature) in
1358                   (label, part)
1359               ) all_partitions in
1360
1361               select_single ~stage:"Root filesystem" 60
1362                 "Select root filesystem"
1363                 items in
1364
1365         let config_target =
1366           match !config_target with
1367           | Some t -> t
1368           | None ->
1369               open_centered_window ~stage:"Target system" 40 20
1370                 "Configure target system";
1371
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;
1378
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;
1390
1391               (* Get the architecture of the selected root filesystem.
1392                * If not known, default to UnknownArch.
1393                *)
1394               Newt.listbox_set_current_by_key archlistbox UnknownArch;
1395               (try
1396                  match List.assoc config_root_filesystem all_partitions with
1397                  | LinuxRoot (arch, _) ->
1398                      Newt.listbox_set_current_by_key archlistbox arch
1399                  | _ -> ()
1400                 with
1401                   Not_found -> ());
1402
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
1412
1413               let libvirtd =
1414                 Newt.checkbox 12 14 "Use remote libvirtd" '*' None in
1415
1416               let ok = Newt.button 28 16 "  OK  " in
1417
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;
1422                  memlabel; mementry;
1423                  cpulabel; cpuentry;
1424                  maclabel; macentry; maclabel2;
1425                  libvirtd;
1426                  ok];
1427
1428               let c =
1429                 let rec loop () =
1430                   ignore (Newt.run_form form);
1431                   try
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
1439                     then
1440                       { tgt_hypervisor = Option.get hv;
1441                         tgt_architecture = Option.get arch;
1442                         tgt_memory = mem; tgt_vcpus = cpus;
1443                         tgt_mac_address =
1444                           if mac <> "" then mac else random_mac_address ();
1445                         tgt_libvirtd = libvirtd }
1446                     else
1447                       loop ()
1448                   with
1449                     Not_found | Failure "int_of_string" -> loop ()
1450                 in
1451                 loop () in
1452
1453               Newt.pop_window ();
1454
1455               c in
1456
1457         config_devices_to_send, config_root_filesystem, config_target
1458     ) in
1459
1460   (* If architecture is set to UnknownArch, then assume the same
1461    * architecture as the live CD.
1462    *)
1463   let config_target =
1464     match config_target.tgt_architecture with
1465     | UnknownArch ->
1466         let arch = shget "uname -m" in
1467         let arch =
1468           match arch with
1469           | Some (arch :: _) -> architecture_of_string arch
1470           | _ -> I386 (* probably wrong XXX *) in
1471         { config_target with tgt_architecture = arch }
1472     | _ -> config_target in
1473
1474   (* Try to get the capabilities from the remote machine.  If we fail
1475    * it doesn't matter too much.
1476    *)
1477   let caps_os_type, caps_emulator, caps_loader, caps_machine =
1478     try
1479       if not config_target.tgt_libvirtd then raise Not_found;
1480
1481       let proto, path =
1482         match config_target.tgt_hypervisor with
1483         | Some Xen -> "xen", "/"
1484         | Some (QEMU|KVM) -> "qemu", "/system"
1485         | None -> raise Not_found in
1486       let name =
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;
1491
1492       printf "Try to fetch remote hypervisor capabilities ...\n\n%!";
1493
1494       let conn = Libvirt.Connect.connect_readonly ~name () in
1495       let caps = Libvirt.Connect.get_capabilities conn in
1496       Libvirt.Connect.close conn;
1497
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);
1501
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.
1506        *)
1507       let guests = children_with_name "guest" caps in
1508       let guests =
1509         List.filter (xml_has_pcdata_child "os_type" "hvm") guests in
1510       let arch_str = string_of_architecture config_target.tgt_architecture in
1511       let guests =
1512         List.filter (
1513           xml_has_child_matching (
1514             function
1515             | Xml.Element (n, attribs, _)
1516                 when n = "arch"
1517                   && List.exists (
1518                     fun (n, a) ->
1519                       n = "name" &&
1520                       (* deal with i386 vs i686 pestilence *)
1521                       architecture_of_string a = config_target.tgt_architecture
1522                   ) attribs
1523                   -> true
1524             | _ -> false
1525           )
1526         ) guests in
1527
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.
1535        *)
1536       let len = List.length guests in
1537       if len = 0 then (
1538         message_box "Warning"
1539           (sprintf "Remote hypervisor claims not to support fully virtualized %s guests.\n\nContinuing anyway.\n\n%!" arch_str);
1540         raise Not_found
1541       );
1542
1543       if len > 1 then (
1544         message_box "Note"
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)
1546       );
1547
1548       let guest = List.hd guests in
1549
1550       let os_type =
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
1554       let emulator =
1555         try Some (find_pcdata_child "emulator" arch_section)
1556         with Not_found -> None in
1557       let loader =
1558         try Some (find_pcdata_child "loader" arch_section)
1559         with Not_found -> None in
1560       let machine =
1561         try Some (find_pcdata_child "machine" arch_section)
1562         with Not_found -> None in
1563
1564       os_type, emulator, loader, machine
1565     with
1566     | Not_found -> None, None, None, None
1567     | Xml.Error err ->
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
1580
1581   (* In test mode, exit here before we do Bad Things to the developer's
1582    * hard disk.
1583    *)
1584   if test_dialog_stages then exit 1;
1585
1586   (* Switch LVM config. *)
1587   sh "vgchange -a n";
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";
1591
1592   (* Snapshot the block devices to send. *)
1593   let config_devices_to_send =
1594     List.map (
1595       fun origin_dev ->
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
1600
1601   (* Run kpartx on the snapshots. *)
1602   List.iter (
1603     fun (origin, snapshot) ->
1604       shfailok ("kpartx -a " ^ quote ("/dev/mapper/" ^ snapshot))
1605   ) config_devices_to_send;
1606
1607   (* Rescan for LVs. *)
1608   sh "vgscan";
1609   sh "vgchange -a y";
1610
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")
1617
1618    | LV (vg, lv) ->
1619        (* The LV will be backed by a snapshot device, so just mount
1620         * directly.
1621         *)
1622        sh ("mount " ^ quote ("/dev/" ^ vg ^ "/" ^ lv) ^ " /mnt/root")
1623   );
1624
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
1631
1632   (* Modify files on the root filesystem. *)
1633   rewrite_fstab config_devices_to_send;
1634   (* XXX Other files to rewrite? *)
1635
1636   (* Unmount the root filesystem and sync disks. *)
1637   sh "umount /mnt/root";
1638   sh "sync";                            (* Ugh, should be in stdlib. *)
1639
1640   (* XXX This is using the hostname derived from network configuration
1641    * above.  We might want to ask the user to choose.
1642    *)
1643   let hostname = safe_name (gethostname ()) in
1644   let basename =
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
1648
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
1655
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.
1659    *
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.
1663    *)
1664   let conf_filename = basename ^ ".conf" in
1665
1666   let xml =
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
1671
1672     let arch_str =
1673       string_of_architecture config_target.tgt_architecture in
1674     let arch_wordsize =
1675       wordsize_of_architecture config_target.tgt_architecture in
1676
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
1684
1685     (* Top-level stuff which differs for each HV type (isn't this supposed
1686      * to be portable ...)
1687      *)
1688     let extras =
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
1693
1694       match config_target.tgt_hypervisor with
1695       | Some Xen ->
1696           [Xml.Element ("os", [],
1697                         [leaf "type" os_type;
1698                          leaf "loader" loader;
1699                          tleaf "boot" ["dev", "hd"]]);
1700            Xml.Element ("features", [],
1701                         [tleaf "pae" [];
1702                          tleaf "acpi" [];
1703                          tleaf "apic" []]);
1704            tleaf "clock" ["sync", "localtime"]]
1705       | Some KVM ->
1706           [Xml.Element ("os", [], [leaf "type" os_type]);
1707            tleaf "clock" ["sync", "localtime"]]
1708       | Some QEMU ->
1709           [Xml.Element ("os", [],
1710                         [Xml.Element ("type",
1711                                       ["arch", arch_str;
1712                                        "machine", machine],
1713                                       [Xml.PCData os_type]);
1714                          tleaf "boot" ["dev", "hd"]])]
1715       | None ->
1716           [] in
1717
1718     (* <devices> section. *)
1719     let devices =
1720       let emulator =
1721         match caps_emulator with
1722         (* Use the emulator from the libvirt capabilities. *)
1723         | Some s -> [leaf "emulator" s]
1724         | None ->
1725             (* If we don't have libvirt capabilities, best guess. *)
1726             match config_target.tgt_hypervisor with
1727             | Some Xen ->
1728                 [leaf "emulator"
1729                    (if arch_wordsize = W64 then "/usr/lib64/xen/bin/qemu-dm"
1730                     else "/usr/lib/xen/bin/qemu-dm")]
1731             | Some QEMU ->
1732                 [leaf "emulator" "/usr/bin/qemu"]
1733             | Some KVM ->
1734                 [leaf "emulator" "/usr/bin/qemu-kvm"]
1735             | None ->
1736                 [] in
1737       let interface =
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:
1742         Xml.Element (
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
1748
1749       let disks = List.map (
1750         fun (_, _, remote_dev, remote_name) ->
1751           Xml.Element (
1752             "disk", ["type", "file";
1753                      "device", "disk"],
1754             [tleaf "source" ["file",
1755                              config_ssh.ssh_directory ^ "/" ^ remote_name];
1756              tleaf "target" ["dev", remote_dev]]
1757           )
1758       ) config_devices_to_send in
1759
1760       Xml.Element (
1761         "devices", [],
1762         emulator @ interface :: graphics :: disks
1763       ) in
1764
1765     (* Put it all together in <domain type='foo'>. *)
1766     Xml.Element (
1767       "domain",
1768       (match config_target.tgt_hypervisor with
1769        | Some Xen -> ["type", "xen"]
1770        | Some QEMU -> ["type", "qemu"]
1771        | Some KVM -> ["type", "kvm"]
1772        | None -> []),
1773       name :: uuid :: memory :: maxmem :: vcpu :: extras @ [devices]
1774     ) in
1775
1776   (* Convert XML configuration file to a string, then send it to the
1777    * remote server.
1778    *)
1779   let () =
1780     let xml = Xml.to_string_fmt xml in
1781
1782     let conn_arg =
1783       match config_target.tgt_hypervisor with
1784       | Some Xen | None -> ""
1785       | Some QEMU | Some KVM -> " -c qemu:///system" in
1786     let xml = sprintf "\
1787 <!--
1788   This is an automatically generated libvirt configuration file.
1789   It was written by the %s program.
1790
1791   Please check the values in this configuration file carefully,
1792   particularly maxmem, memory, vcpu and any paths.
1793
1794   To start the domain, do:
1795     virsh%s define %s
1796     virsh%s start %s
1797 -->\n\n" program_name conn_arg conf_filename conn_arg hostname
1798       ^ xml
1799       ^ "\n" in
1800
1801     let xml_len = String.length xml in
1802     eprintf "length of configuration file is %d bytes\n%!" xml_len;
1803
1804     printf "\nWriting configuration file ...\n\n%!";
1805
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
1810
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.
1815    *)
1816   List.iter (
1817     fun (origin_dev, snapshot_dev, remote_dev, remote_name) ->
1818       eprintf "sending %s as %s\n%!" origin_dev remote_name;
1819
1820       let size =
1821         try List.assoc origin_dev all_block_devices
1822         with Not_found -> assert false (* internal error *) in
1823
1824       printf "\nSending /dev/%s (%.3f GB) to remote machine\n\n%!" origin_dev
1825         ((Int64.to_float size) /. (1024.*.1024.*.1024.));
1826
1827       (* Open the snapshot device. *)
1828       let fd = openfile ("/dev/mapper/" ^ snapshot_dev) [O_RDONLY] 0 in
1829
1830       (* Now connect. *)
1831       let (sock,_) as conn = ssh_start_upload config_ssh remote_name in
1832
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
1838
1839       let rec copy bytes_sent last_printed_at spinner =
1840         let n = read fd buffer 0 bufsize in
1841         if n > 0 then (
1842           let n' = write sock buffer 0 n in
1843           if n <> n' then assert false; (* never, according to the manual *)
1844
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.)
1861                 else
1862                   printf " (about %.0f seconds remaining)"
1863                     secs_remaining
1864               );
1865               printf "          \r%!";
1866               let spinner = (spinner + 1) mod String.length spinners in
1867               now, spinner
1868             )
1869             else last_printed_at, spinner in
1870
1871           copy bytes_sent last_printed_at spinner
1872         )
1873       in
1874       copy 0L start 0;
1875       printf "\n\n%!"; (* because of the messages printed above *)
1876
1877       (* Disconnect. *)
1878       ssh_finish_upload conn
1879   ) config_devices_to_send;
1880
1881   (*printf "\n\nPress any key ...\n%!"; ignore (read_line ());*)
1882
1883   (* Clean up and reboot. *)
1884   ignore (
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)
1888   );
1889
1890   shfailok "eject";
1891   shfailok "reboot";
1892
1893   exit 0
1894
1895 (*----------------------------------------------------------------------*)
1896
1897 let usage () =
1898   eprintf "usage: virt-p2v [--test] [ttyname]\n%!";
1899   exit 2
1900
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.
1904  *)
1905 let handle_exn f arg =
1906   try f arg
1907   with exn ->
1908     print_endline (Printexc.to_string exn);
1909     raise exn
1910
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').
1915  *)
1916 let () =
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
1924   | _ -> usage ()
1925
1926 (* This file must end with a newline *)