Unicode support for the console.
[virt-p2v.git] / virt-p2v.ml
1 (* -*- tuareg -*- *)
2 (* virt-p2v is a script which performs a physical to
3  * virtual conversion of local disks.
4  *
5  * Copyright (C) 2007-2008 Red Hat Inc.
6  * Written by Richard W.M. Jones <rjones@redhat.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *)
22
23 type partition =
24   | Part of string * string             (* eg. "hda", "1" *)
25   | LV of string * string               (* eg. "VolGroup00", "LogVol00" *)
26 type transfer =
27   | P2V                                 (* physical to virtual *)
28   | V2V                                 (* virtual to virtual *)
29   (*| V2P*)                             (* virtual to physical - not impl *)
30 type network =
31   | Auto of partition                   (* Automatic network configuration. *)
32   | Shell                               (* Start a shell. *)
33   | QEMUUserNet                         (* Assume we're running under qemu. *)
34   | Static of string * string * string * string * string
35       (* interface, address, netmask, gateway, nameserver *)
36   | NoNetwork
37 type ssh_config = {
38   ssh_host : string;                    (* Remote host for SSH. *)
39   ssh_port : string;                    (* Remote port. *)
40   ssh_directory : string;               (* Remote directory. *)
41   ssh_username : string;                (* Remote username. *)
42   ssh_compression : bool;               (* If true, use SSH compression. *)
43   ssh_check : bool;                     (* If true, check SSH is working. *)
44 }
45 type hypervisor =
46   | Xen
47   | QEMU
48   | KVM
49 type architecture =
50   | I386 | X86_64 | IA64 | PPC | PPC64 | SPARC | SPARC64
51   | OtherArch of string
52   | UnknownArch
53 type wordsize =
54   | W32 | W64 | WUnknown
55 type target_config = {
56   tgt_hypervisor : hypervisor option;   (* Remote hypervisor. *)
57   tgt_architecture : architecture;      (* Remote architecture. *)
58   tgt_memory : int;                     (* Memory (megabytes). *)
59   tgt_vcpus : int;                      (* Number of virtual CPUs. *)
60   tgt_mac_address : string;             (* MAC address. *)
61   tgt_libvirtd : bool;                  (* True if libvirtd on remote. *)
62 }
63
64 (*----------------------------------------------------------------------*)
65 (* TO MAKE A CUSTOM VIRT-P2V SCRIPT, adjust the defaults in this section.
66  *
67  * If left as they are, then this will create a generic virt-p2v script
68  * which asks the user for each question.  If you set the defaults here
69  * then you will get a custom virt-p2v which is partially or even fully
70  * automated and won't ask the user any questions.
71  *
72  * Note that 'None' means 'no default' (ie. ask the user) whereas
73  * 'Some foo' means use 'foo' as the answer.
74  *
75  * These are documented in the virt-p2v(1) manual page.
76  *
77  * After changing them, run './virt-p2v --test' to check syntax.
78  *)
79
80 (* If greeting is true, wait for keypress after boot and during
81  * final verification.  Set to 'false' for less interactions.
82  *)
83 let config_greeting = ref true
84
85 (* General type of transfer. *)
86 let config_transfer_type = ref None
87
88 (* Network configuration. *)
89 let config_network = ref None
90
91 (* SSH configuration. *)
92 let config_ssh = ref None
93
94 (* What to transfer. *)
95 let config_devices_to_send = ref None
96 let config_root_filesystem = ref None
97
98 (* Configuration of the target. *)
99 let config_target = ref None
100
101 (* The name of the program as displayed in various places. *)
102 let program_name = "virt-p2v"
103
104 (* If you want to test the dialog stages, set this to true. *)
105 let test_dialog_stages = false
106
107 (* END OF CUSTOM virt-p2v SCRIPT SECTION.                               *)
108 (*----------------------------------------------------------------------*)
109
110 open Unix
111 open Printf
112 open ExtList
113 open ExtString
114
115 (*----------------------------------------------------------------------*)
116 (* Gettext support.
117  *
118  * Use s_ "string" to mark a translatable string, and f_ "string %s"
119  * to mark a format string (eg. for printf).  There are other
120  * functions: see ocaml-gettext manual and GNU gettext info.
121  *
122  * Try not to mark strings which always go to the log file (eg.
123  * eprintf messages).
124  *)
125
126 module P2VGettext = Gettext.Program (
127   struct
128     let textdomain   = "virt-p2v"
129     let codeset      = None
130     let dir          = None
131     let dependencies = []
132   end
133 ) (GettextStub.Native)
134 open P2VGettext
135
136 (*----------------------------------------------------------------------*)
137 (* General helper functions. *)
138
139 let sort_uniq ?(cmp = compare) xs =     (* sort and uniq a list *)
140   let xs = List.sort ~cmp xs in
141   let rec loop = function
142     | [] -> [] | [x] -> [x]
143     | x1 :: x2 :: xs when x1 = x2 -> loop (x1 :: xs)
144     | x :: xs -> x :: loop xs
145   in
146   loop xs
147
148 let input_all_lines chan =
149   let lines = ref [] in
150   try
151     while true do lines := input_line chan :: !lines done; []
152   with
153     End_of_file -> List.rev !lines
154
155 let dev_of_partition = function
156   | Part (dev, partnum) -> sprintf "/dev/%s%s" dev partnum
157   | LV (vg, lv) -> sprintf "/dev/%s/%s" vg lv
158
159 let string_of_architecture = function
160   | I386 -> "i386"
161   | X86_64 -> "x86_64"
162   | IA64 -> "ia64"
163   | PPC -> "ppc"
164   | PPC64 -> "ppc64"
165   | SPARC -> "sparc"
166   | SPARC64 -> "sparc64"
167   | OtherArch arch -> arch
168   | UnknownArch -> ""
169
170 let architecture_of_string = function
171   | str when
172       String.length str = 4 &&
173       (str.[0] = 'i' || str.[0] = 'I') &&
174       (str.[1] >= '3' && str.[1] <= '6') &&
175       str.[2] = '8' && str.[3] = '6' -> I386
176   | "x86_64" | "X86_64" | "x86-64" | "X86-64" -> X86_64
177   | "ia64" | "IA64" -> IA64
178   | "ppc" | "PPC" | "ppc32" | "PPC32" -> PPC
179   | "ppc64" | "PPC64" -> PPC64
180   | "sparc" | "SPARC" | "sparc32" | "SPARC32" -> SPARC
181   | "sparc64" | "SPARC64" -> SPARC64
182   | "" -> UnknownArch
183   | str -> OtherArch str
184
185 let wordsize_of_architecture = function
186   | I386 -> W32
187   | X86_64 -> W64
188   | IA64 -> W64
189   | PPC -> W32
190   | PPC64 -> W64
191   | SPARC -> W32
192   | SPARC64 -> W64
193   | OtherArch arch -> WUnknown
194   | UnknownArch -> WUnknown
195
196 type nature = LinuxSwap
197             | LinuxRoot of architecture * linux_distro
198             | WindowsRoot               (* Windows C: *)
199             | LinuxBoot                 (* Linux /boot *)
200             | NotRoot                   (* mountable, but not / or /boot *)
201             | UnknownNature
202 and linux_distro = RHEL of int * int
203                  | Fedora of int
204                  | Debian of int * int
205                  | OtherLinux
206
207 let rec string_of_nature = function
208   | LinuxSwap -> s_ "Linux swap"
209   | LinuxRoot (architecture, distro) ->
210       string_of_linux_distro distro ^ " " ^ string_of_architecture architecture
211   | WindowsRoot -> s_ "Windows root"
212   | LinuxBoot -> s_ "Linux /boot"
213   | NotRoot -> s_ "Mountable non-root"
214   | UnknownNature -> s_ "Unknown partition type"
215 and string_of_linux_distro = function
216   | RHEL (a,b) -> sprintf "RHEL %d.%d" a b
217   | Fedora v -> sprintf "Fedora %d" v
218   | Debian (a,b) -> sprintf "Debian %d.%d" a b
219   | OtherLinux -> "Linux"
220
221 (* XML helper functions. *)
222 let rec children_with_name name xml =
223   let children = Xml.children xml in
224   List.filter (
225     function
226     | Xml.Element (n, _, _) when n = name -> true
227     | _ -> false
228   ) children
229 and xml_has_pcdata_child name pcdata xml =
230   xml_has_child_matching (
231     function
232     | Xml.Element (n, _, [Xml.PCData pcd])
233         when n = name && pcd = pcdata -> true
234     | _ -> false
235   ) xml
236 and xml_has_attrib_child name attrib xml =
237   xml_has_child_matching (
238     function
239     | Xml.Element (n, attribs, _)
240         when n = name && List.mem attrib attribs -> true
241     | _ -> false
242   ) xml
243 and xml_has_child_matching f xml =
244   let children = Xml.children xml in
245   List.exists f children
246 and find_child_with_name name xml =
247   let children = children_with_name name xml in
248   match children with
249   | [] -> raise Not_found
250   | h :: _ -> h
251 and find_pcdata_child name xml =
252   let children = children_with_name name xml in
253   let rec loop = function
254     | [] -> raise Not_found
255     | Xml.Element (_, _, [Xml.PCData pcd]) :: _ -> pcd
256     | _ :: tl -> loop tl
257   in
258   loop children
259
260 type ('a, 'b) either = Either of 'a | Or of 'b
261
262 (* We go into and out of newt mode at various stages, but we might
263  * also need to put up a message at any time.  This keeps track of
264  * whether we are in newt mode or not.
265  *
266  * General tip: Try to do any complex operations like setting up the
267  * network or probing disks outside newt mode, and try not to throw
268  * exceptions in newt mode.
269  *)
270 let in_newt = ref false
271 let with_newt f =
272   if !in_newt then f ()
273   else (
274     in_newt := true;
275     let r =
276       try Either (Newt.init_and_finish f)
277       with exn -> Or exn in
278     in_newt := false;
279     match r with Either r -> r | Or exn -> raise exn
280   )
281
282 (* Clear the screen, open a new centered window, make sure the background
283  * and help messages are consistent.
284  *)
285 let open_centered_window ?stage width height title =
286   if not !in_newt then failwith (s_ "open_centered_window: not in newt mode");
287   Newt.cls ();
288   Newt.centered_window width height title;
289   let root_text =
290     program_name ^ (match stage with
291                     | None -> ""
292                     | Some stage -> " - " ^ stage) in
293   Newt.draw_root_text 0 0 root_text;
294   Newt.push_help_line
295     (s_ "F12 for next screen | [ALT] [F2] root / no password for shell")
296
297 let ok_button = "  OK  "
298
299 (* Some general dialog boxes. *)
300 let message_box title text =
301   with_newt (
302     fun () ->
303       open_centered_window 40 20 title;
304
305       let textbox = Newt.textbox 1 1 36 14 [Newt.WRAP; Newt.SCROLL] in
306       Newt.textbox_set_text textbox text;
307       let ok = Newt.button 28 16 ok_button in
308       let form = Newt.form None None [] in
309       Newt.form_add_components form [textbox; ok];
310
311       Newt.component_takes_focus ok true;
312
313       ignore (Newt.run_form form);
314       Newt.pop_window ()
315   )
316
317 (* Fail and exit with error. *)
318 let failwith text =
319   prerr_endline text;
320   let text = "\n"
321     ^ text
322     ^ s_ "\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
323   message_box (s_ "Error") text;
324   exit 1
325
326 (* Display a dialog with checkboxes, return the multiple selected items. *)
327 let select_multiple ?stage ?(force_one = false) width title items =
328   with_newt (
329     fun () ->
330       open_centered_window ?stage width 20 title;
331
332       let entries =
333         List.mapi (
334           fun i (label, handle, selected) ->
335             let cb =
336               Newt.checkbox 1 (i+1) label
337                 (if selected then '*' else ' ') None in
338             (handle, cb)
339         ) items in
340
341       let ok = Newt.button 48 16 ok_button in
342
343       let vb =
344         if List.length entries > 10 then
345           Some (Newt.vertical_scrollbar 58 1 10
346                   Newt_int.NEWT_COLORSET_WINDOW
347                   Newt_int.NEWT_COLORSET_ACTCHECKBOX)
348         else
349           None in
350       let form = Newt.form vb None [] in
351       Newt.form_add_components form (List.map snd entries);
352       Newt.form_add_component form ok;
353
354       let selected =
355         let rec loop () =
356           ignore (Newt.run_form form);
357           let selected = List.filter_map (
358             fun (handle, cb) ->
359               if Newt.checkbox_get_value cb = '*' then Some handle else None
360           ) entries in
361           if force_one && selected = [] then loop ()
362           else selected
363         in
364         loop () in
365
366       Newt.pop_window ();
367
368       selected
369   )
370
371 (* Display a dialog with radio buttons, return the single selected item. *)
372 let select_single ?stage width title items =
373   if items = [] then failwith "select_single: no items";
374
375   with_newt (
376     fun () ->
377       open_centered_window ?stage width 20 title;
378
379       let prev = ref None in
380       let entries =
381         List.mapi (
382           fun i (label, handle) ->
383             let rb = Newt.radio_button 1 (i+1) label (!prev = None) !prev in
384             prev := Some rb;
385             (handle, rb)
386         ) items in
387
388       let ok = Newt.button (width-12) 16 ok_button in
389
390       let vb =
391         if List.length entries > 10 then
392           Some (Newt.vertical_scrollbar 58 1 10
393                   Newt_int.NEWT_COLORSET_WINDOW
394                   Newt_int.NEWT_COLORSET_ACTCHECKBOX)
395         else
396           None in
397       let form = Newt.form vb None [] in
398       Newt.form_add_components form (List.map snd entries);
399       Newt.form_add_component form ok;
400
401       let (selected, _) =
402         let rec loop () =
403           ignore (Newt.run_form form);
404           let r = Option.get !prev in
405           let r = Newt.radio_get_current r in
406           (* Now we compare 'r' to all the 'rb's in the list
407            * to see which one is selected.
408            *)
409           try
410             List.find (fun (_, rb) -> Newt.component_equals r rb) entries
411           with
412             Not_found -> loop ()
413         in
414         loop () in
415
416       Newt.pop_window ();
417
418       selected
419   )
420
421 (* Shell-safe quoting function.  In fact there's one in stdlib so use it. *)
422 let quote = Filename.quote
423
424 (* Run a shell command and check it returns 0. *)
425 let sh cmd =
426   eprintf "sh: %s\n%!" cmd;
427   if Sys.command cmd <> 0 then
428     failwith (sprintf (f_ "Command failed:\n\n%s") cmd)
429
430 let shfailok cmd =
431   eprintf "shfailok: %s\n%!" cmd;
432   ignore (Sys.command cmd)
433
434 let shwithstatus cmd =
435   eprintf "shwithstatus: %s\n%!" cmd;
436   Sys.command cmd
437
438 (* Same as `cmd` in shell.  Any error message will be in the logfile. *)
439 let shget cmd =
440   eprintf "shget: %s\n%!" cmd;
441   let chan = open_process_in cmd in
442   let lines = input_all_lines chan in
443   match close_process_in chan with
444   | WEXITED 0 -> Some lines             (* command succeeded *)
445   | WEXITED _ -> None                   (* command failed *)
446   | WSIGNALED i ->
447       failwith (sprintf (f_ "shget: command killed by signal %d") i)
448   | WSTOPPED i ->
449       failwith (sprintf (f_ "shget: command stopped by signal %d") i)
450
451 (* Start an interactive shell.  Need to juggle file descriptors a bit
452  * because bash write PS1 to stderr (currently directed to the logfile).
453  *)
454 let shell () =
455   match fork () with
456   | 0 ->                                (* child, runs bash *)
457       close stderr;
458       dup2 stdout stderr;
459       (* Sys.command runs 'sh -c' which blows away PS1, so set it late. *)
460       ignore (
461         Sys.command "PS1='\\u@\\h:\\w\\$ ' /bin/bash --norc --noprofile -i"
462       )
463   | _ ->                                (* parent, waits *)
464       eprintf "waiting for subshell to exit\n%!";
465       ignore (wait ())
466
467 (* Some true if is dir/file, Some false if not, None if not found. *)
468 let is_dir path =
469   try Some ((stat path).st_kind = S_DIR)
470   with Unix_error (ENOENT, "stat", _) -> None
471 let is_file path =
472   try Some ((stat path).st_kind = S_REG)
473   with Unix_error (ENOENT, "stat", _) -> None
474
475 (*----------------------------------------------------------------------*)
476 (* P2V-specific helper functions. *)
477
478 (* Generate a predictable safe name containing only letters, numbers
479  * and underscores.  If passed a string with no letters or numbers,
480  * generates "_1", "_2", etc.
481  *)
482 let safe_name =
483   let next_anon =
484     let i = ref 0 in
485     fun () -> incr i; "_" ^ string_of_int !i
486   in
487   fun name ->
488     let is_safe = function 'a'..'z'|'A'..'Z'|'0'..'9' -> true | _ -> false in
489     let name = String.copy name in
490     let have_safe = ref false in
491     for i = 0 to String.length name - 1 do
492       if not (is_safe name.[i]) then name.[i] <- '_' else have_safe := true
493     done;
494     if !have_safe then name else next_anon ()
495
496 type block_device = string * int64      (* "hda" & size in bytes *)
497
498 (* Parse the output of 'lvs' to get list of LV names, sizes,
499  * corresponding PVs, etc.  Returns a list of (lvname, PVs, lvsize).
500  *)
501 let get_lvs =
502   let devname = Pcre.regexp "^/dev/(.+)\\(.+\\)$" in
503
504   fun () ->
505     match
506     shget "lvs --noheadings -o vg_name,lv_name,devices,lv_size"
507     with
508     | None -> []
509     | Some lines ->
510         let lines = List.map Pcre.split lines in
511         List.map (
512           function
513           | [vg; lv; pvs; lvsize]
514           | [_; vg; lv; pvs; lvsize] ->
515               let pvs = String.nsplit pvs "," in
516               let pvs = List.filter_map (
517                 fun pv ->
518                   try
519                     let subs = Pcre.exec ~rex:devname pv in
520                     Some (Pcre.get_substring subs 1)
521                   with
522                     Not_found ->
523                       eprintf "lvs: unexpected device name: %s\n%!" pv;
524                       None
525               ) pvs in
526               LV (vg, lv), pvs, lvsize
527           | line ->
528               failwith ("lvs: " ^ s_ "unexpected output: " ^
529                           String.concat "," line)
530         ) lines
531
532 (* Get the partitions on a block device.
533  * eg. "sda" -> [Part ("sda","1"); Part ("sda", "2")]
534  *)
535 let get_partitions dev =
536   let rex = Pcre.regexp ("^" ^ dev ^ "(.+)$") in
537   let devdir = "/sys/block/" ^ dev in
538   let parts = Sys.readdir devdir in
539   let parts = Array.to_list parts in
540   let parts = List.filter (
541     fun name -> Some true = is_dir (devdir ^ "/" ^ name)
542   ) parts in
543   let parts = List.filter_map (
544     fun part ->
545       try
546         let subs = Pcre.exec ~rex part in
547         Some (Part (dev, Pcre.get_substring subs 1))
548       with
549         Not_found -> None
550   ) parts in
551   parts
552
553 (* Generate snapshot device name from device name. *)
554 let snapshot_name dev =
555   "snap" ^ (safe_name dev)
556
557 (* Perform a device-mapper snapshot with ramdisk overlay. *)
558 let snapshot =
559   let next_free_ram_disk =
560     let i = ref 0 in
561     fun () -> incr i; "/dev/ram" ^ string_of_int !i
562   in
563   fun origin_dev snapshot_dev ->
564     let ramdisk = next_free_ram_disk () in
565     let sectors =
566       let cmd = "blockdev --getsz " ^ quote ("/dev/" ^ origin_dev) in
567       let lines = shget cmd in
568       match lines with
569       | Some (sectors::_) -> Int64.of_string sectors
570       | Some [] | None ->
571           failwith (sprintf (f_ "Disk snapshot failed: unable to read the size in sectors of block device %s") origin_dev) in
572
573     (* Create the snapshot origin device.  Called, eg. snap_sda1_org *)
574     sh (sprintf "dmsetup create %s_org --table='0 %Ld snapshot-origin /dev/%s'"
575           snapshot_dev sectors origin_dev);
576     (* Create the snapshot. *)
577     sh (sprintf "dmsetup create %s --table='0 %Ld snapshot /dev/mapper/%s_org %s n 64'"
578           snapshot_dev sectors snapshot_dev ramdisk)
579
580 (* Try to perform automatic network configuration, assuming a Fedora or
581  * RHEL-like root filesystem mounted on /mnt/root.
582  *)
583 let auto_network () =
584   (* Fedora gives an error if this file doesn't exist. *)
585   sh "touch /etc/resolv.conf";
586
587   (* NB. Lazy unmount is required because dhclient keeps its current
588    * directory open on /etc/sysconfig/network-scripts/
589    * (Fixed in dhcp >= 4.0.0 but be generous anyway).
590    *)
591   sh "mount -o bind /mnt/root/etc /etc";
592   let status = shwithstatus "/etc/init.d/network start" in
593   sh "umount -l /etc";
594
595   (* Try to ping the default gateway to see if this worked. *)
596   shfailok "ping -c3 `/sbin/ip route list match 0.0.0.0 | head -1 | awk '{print $3}'`";
597
598   if !config_greeting then (
599     print_endline (s_ "\n\nDid automatic network configuration work?\nHint: If not sure, there is a shell on console [ALT] [F2]");
600     printf "    (y/n) %!";
601     let line = read_line () in
602     String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
603   )
604   else
605     (* Non-interactive: return the status of /etc/init.d/network start. *)
606     status = 0
607
608 (* Configure the network statically. *)
609 let static_network (interface, address, netmask, gateway, nameserver) =
610   let do_cmd_or_exit cmd = if shwithstatus cmd <> 0 then raise Exit in
611   try
612     do_cmd_or_exit (sprintf "ifconfig %s %s netmask %s"
613                       (quote interface) (quote address) (quote netmask));
614     do_cmd_or_exit (sprintf "route add default gw %s %s"
615                       (quote gateway) (quote interface));
616     if nameserver <> "" then
617       do_cmd_or_exit (sprintf "echo nameserver %s > /etc/resolv.conf"
618                         (quote nameserver));
619     true                                (* succeeded *)
620   with
621     Exit -> false                       (* failed *)
622
623 (* http://fabrice.bellard.free.fr/qemu/qemu-doc.html#SEC30 *)
624 let qemu_network () =
625   sh "ifconfig eth0 10.0.2.10 netmask 255.255.255.0";
626   sh "route add default gw 10.0.2.2 eth0";
627   sh "echo nameserver 10.0.2.3 > /etc/resolv.conf"
628
629 (* Map local device names to remote devices names.  At the moment we
630  * just change sd* to hd* (as device names appear under fullvirt).  In
631  * future, lots of complex possibilities.
632  *)
633 let remote_of_origin_dev =
634   let devsd = Pcre.regexp "^sd([[:alpha:]]+[[:digit:]]*)$" in
635   let devsd_subst = Pcre.subst "hd$1" in
636   fun dev ->
637     Pcre.replace ~rex:devsd ~itempl:devsd_subst dev
638
639 (* Make an SSH connection to the remote machine, execute command.
640  * The connection remains open until you call ssh_disconnect, it
641  * times out or there is some error.
642  *
643  * NB. The command is NOT quoted.
644  *
645  * Returns a pair (file descriptor, channel), both referring to the
646  * same thing.  Use whichever is more convenient.
647  *)
648 let ssh_connect config cmd =
649   let cmd = sprintf "ssh%s -l %s -p %s %s %s"
650     (if config.ssh_compression then " -C" else "")
651     (quote config.ssh_username) (quote config.ssh_port) (quote config.ssh_host)
652     cmd in
653   eprintf "ssh_connect: %s\n%!" cmd;
654   let chan = open_process_out cmd in
655   descr_of_out_channel chan, chan
656
657 let ssh_disconnect (_, chan) =
658   eprintf "ssh_disconnect\n%!";
659   match close_process_out chan with
660   | WEXITED 0 -> ()             (* OK *)
661   | WEXITED i -> failwith (sprintf (f_ "ssh: exited with error code %d") i)
662   | WSIGNALED i -> failwith (sprintf (f_ "ssh: killed by signal %d") i)
663   | WSTOPPED i -> failwith (sprintf (f_ "ssh: stopped by signal %d") i)
664
665 (* Use these functions to upload a file. *)
666 let ssh_start_upload config filename =
667   let cmd =
668     sprintf "cat \\> %s/%s" (quote config.ssh_directory) (quote filename) in
669   ssh_connect config cmd
670
671 let ssh_finish_upload = ssh_disconnect
672
673 (* Test SSH connection. *)
674 let test_ssh config =
675   print_endline
676     (s_ "Testing SSH connection by listing files in remote directory ...\n");
677
678   let cmd = sprintf "/bin/ls %s" (quote config.ssh_directory) in
679   let conn = ssh_connect config cmd in
680   ssh_disconnect conn;
681
682   if !config_greeting then (
683     print_endline (s_ "\n\nDid SSH work?\nHint: If not sure, there is a shell on console [ALT] [F2]\n");
684     printf "    (y/n) %!";
685     let line = read_line () in
686     String.length line > 0 && (line.[0] = 'y' || line.[0] = 'Y')
687   )
688   else
689     true
690
691 (* Rewrite /mnt/root/etc/fstab. *)
692 let rewrite_fstab devices_to_send =
693   let filename = "/mnt/root/etc/fstab" in
694   if is_file filename = Some true then (
695     sh ("cp " ^ quote filename ^ " " ^ quote (filename ^ ".p2vsaved"));
696
697     let chan = open_in filename in
698     let lines = input_all_lines chan in
699     close_in chan;
700     let lines = List.map Pcre.split lines in
701     let lines = List.map (
702       function
703       | dev :: rest when String.starts_with dev "/dev/" ->
704           let dev = String.sub dev 5 (String.length dev - 5) in
705           let dev = remote_of_origin_dev dev in
706           let dev = "/dev/" ^ dev in
707           dev :: rest
708       | line -> line
709     ) lines in
710
711     let chan = open_out filename in
712     List.iter (
713       function
714       | [dev; mountpoint; fstype; options; freq; passno] ->
715           fprintf chan "%-23s %-23s %-7s %-15s %s %s\n"
716             dev mountpoint fstype options freq passno
717       | line ->
718           output_string chan (String.concat " " line);
719           output_char chan '\n'
720     ) lines;
721     close_out chan
722   )
723
724 (* Generate a random MAC address in the Xen-reserved space. *)
725 let random_mac_address () =
726   let random =
727     List.map (sprintf "%02x") (
728       List.map (fun _ -> Random.int 256) [0;0;0]
729     ) in
730   String.concat ":" ("00"::"16"::"3e"::random)
731
732 (* Generate a random UUID. *)
733 let random_uuid =
734   let hex = "0123456789abcdef" in
735   fun () ->
736   let str = String.create 32 in
737   for i = 0 to 31 do str.[i] <- hex.[Random.int 16] done;
738   str
739
740 (*----------------------------------------------------------------------*)
741 (* Main entry point. *)
742
743 (* The general plan for the main function is to operate in stages:
744  *
745  *      Start-up
746  *         |
747  *         V
748  *      Information gathering about the system
749  *         |     (eg. block devices, number of CPUs, etc.)
750  *         V
751  *      Greeting and type of transfer question
752  *         |
753  *         V
754  *      Set up the network
755  *         |     (after this point we have a working network)
756  *         V
757  *      Set up SSH
758  *         |     (after this point we have a working SSH connection)
759  *         V
760  *      Questions about what to transfer (block devs, root fs) <--.
761  *         |                                                      |
762  *         V                                                      |
763  *      Questions about hypervisor configuration                  |
764  *         |                                                      |
765  *         V                                                      |
766  *      Verify information -------- user wants to change info ----/
767  *         |
768  *         V
769  *      Perform transfer
770  *
771  * Prior versions of virt-p2v (the ones which used 'dialog') had support
772  * for a back button so they could go back through dialogs.  I removed
773  * this because it was hard to support and not particularly useful.
774  *)
775
776 let rec main ttyname =
777   Random.self_init ();
778
779   (* Running from an init script.  We don't have much of a
780    * login environment, so set one up.
781    *)
782   putenv "PATH"
783     (String.concat ":"
784        ["/usr/sbin"; "/sbin"; "/usr/local/bin"; "/usr/kerberos/bin";
785         "/usr/bin"; "/bin"]);
786   putenv "HOME" "/root";
787   putenv "LOGNAME" "root";
788
789   (* We can safely write in /tmp (it's a synthetic live CD directory). *)
790   chdir "/tmp";
791
792   (* Set up logging to /tmp/virt-p2v.log. *)
793   let fd = openfile "virt-p2v.log" [ O_WRONLY; O_APPEND; O_CREAT ] 0o644 in
794   dup2 fd stderr;
795   close fd;
796
797   (* Log the start up time. *)
798   eprintf "\n\n**************************************************\n\n";
799   let tm = localtime (time ()) in
800   eprintf "%s starting up at %04d-%02d-%02d %02d:%02d:%02d\n\n%!"
801     program_name
802     (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec;
803
804   (* Connect stdin/stdout to the tty. *)
805   (match ttyname with
806    | None -> ()
807    | Some ttyname ->
808        let fd = openfile ("/dev/" ^ ttyname) [ O_RDWR ] 0 in
809        dup2 fd stdin;
810        dup2 fd stdout;
811        close fd
812   );
813
814   (* Choose language early, so messages are translated. *)
815   if !config_greeting then (
816     with_newt (
817       fun () ->
818         (* Note these strings are NOT translated! *)
819         let items = [
820           "English", "en_US.UTF-8";
821           "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E (Japanese)", "ja_JP.UTF-8"
822         ] in
823
824         let lang = select_single ~stage:(s_ "Select language") 40
825           (s_ "Select language")
826           items in
827
828         putenv "LANGUAGE" lang;
829         ignore (GettextStubCompat.setlocale GettextStubCompat.LC_ALL lang)
830     )
831   );
832
833   let () = printf (f_ "%s starting up ...\n%!") program_name in
834
835   (* Disable screen blanking on tty. *)
836   sh "setterm -blank 0";
837
838   (* Check that the environment is a sane-looking live CD.  If not, bail. *)
839   if not test_dialog_stages && is_dir "/mnt/root" <> Some true then
840     failwith
841       (s_ "You should only run this script from the live CD or a USB key.");
842
843   (* Start of the information gathering phase. *)
844   print_endline
845     (s_ "Detecting hard drives (this may take some time) ...");
846
847   (* Search for all non-removable block devices.  Do this early and bail
848    * if we can't find anything.  This is a list of strings, like "hda".
849    *)
850   let all_block_devices : block_device list =
851     let rex = Pcre.regexp "^[hs]d" in
852     let devices = Array.to_list (Sys.readdir "/sys/block") in
853     let devices = List.sort devices in
854     let devices = List.filter (fun d -> Pcre.pmatch ~rex d) devices in
855     eprintf "all_block_devices: block devices: %s\n%!"
856       (String.concat "; " devices);
857     (* Run blockdev --getsize64 on each, and reject any where this fails
858      * (probably removable devices).
859      *)
860     let devices = List.filter_map (
861       fun d ->
862         let cmd = "blockdev --getsize64 " ^ quote ("/dev/" ^ d) in
863         let lines = shget cmd in
864         match lines with
865         | Some (blksize::_) -> Some (d, Int64.of_string blksize)
866         | Some [] | None -> None
867     ) devices in
868     eprintf "all_block_devices: non-removable block devices: %s\n%!"
869       (String.concat "; "
870          (List.map (fun (d, b) -> sprintf "%s [%Ld]" d b) devices));
871     if devices = [] then
872       failwith
873         (s_ "No non-removable block devices (hard disks, etc.) could be found on this machine.");
874     devices in
875
876   (* Search for partitions and LVs (anything that could contain a
877    * filesystem directly).  We refer to these generically as
878    * "partitions".
879    *)
880   let all_partitions : partition list =
881     (* LVs & PVs. *)
882     let lvs, pvs =
883       let lvs = get_lvs () in
884       let pvs = List.map (fun (_, pvs, _) -> pvs) lvs in
885       let pvs = List.concat pvs in
886       let pvs = sort_uniq pvs in
887       eprintf "all_partitions: PVs: %s\n%!" (String.concat "; " pvs);
888       let lvs = List.map (fun (lvname, _, _) -> lvname) lvs in
889       eprintf "all_partitions: LVs: %s\n%!"
890         (String.concat "; " (List.map dev_of_partition lvs));
891       lvs, pvs in
892
893     (* Partitions (eg. "sda1", "sda2"). *)
894     let parts =
895       let parts = List.map fst all_block_devices in
896       let parts = List.map get_partitions parts in
897       let parts = List.concat parts in
898       eprintf "all_partitions: all partitions: %s\n%!"
899         (String.concat "; " (List.map dev_of_partition parts));
900
901       (* Remove any partitions which are PVs. *)
902       let parts = List.filter (
903         function
904         | Part (dev, partnum) -> not (List.mem (dev ^ partnum) pvs)
905         | LV _ -> assert false
906       ) parts in
907       parts in
908     eprintf "all_partitions: partitions after removing PVs: %s\n%!"
909       (String.concat "; " (List.map dev_of_partition parts));
910
911     (* Concatenate LVs & Parts *)
912     lvs @ parts in
913
914   (* Try to determine the nature of each partition.
915    * Root? Swap? Architecture? etc.
916    *)
917   let all_partitions : (partition * nature) list =
918     (* Output of 'file' command for Linux swap file. *)
919     let swap = Pcre.regexp "Linux.*swap.*file" in
920     (* Contents of /etc/redhat-release. *)
921     let rhel = Pcre.regexp "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)(?:\\.(\\d+))?" in
922     let fedora = Pcre.regexp "Fedora.*release (\\d+)" in
923     (* Contents of /etc/debian_version. *)
924     let debian = Pcre.regexp "^(\\d+)\\.(\\d+)" in
925     (* Output of 'file' on certain executables. *)
926     let i386 = Pcre.regexp ", Intel 80386," in
927     let x86_64 = Pcre.regexp ", x86-64," in
928     let itanic = Pcre.regexp ", IA-64," in
929
930     (* Examine the filesystem mounted on 'mnt' to determine the
931      * operating system, and, if Linux, the distro.
932      *)
933     let detect_os mnt =
934       if is_dir (mnt ^ "/Windows") = Some true &&
935         is_file (mnt ^ "/autoexec.bat") = Some true then
936           WindowsRoot
937       else if is_dir (mnt ^ "/etc") = Some true &&
938         is_dir (mnt ^ "/sbin") = Some true &&
939         is_dir (mnt ^ "/var") = Some true then (
940           if is_file (mnt ^ "/etc/redhat-release") = Some true then (
941             let chan = open_in (mnt ^ "/etc/redhat-release") in
942             let lines = input_all_lines chan in
943             close_in chan;
944
945             match lines with
946             | [] -> (* empty /etc/redhat-release ...? *)
947                 LinuxRoot (UnknownArch, OtherLinux)
948             | line::_ -> (* try to detect OS from /etc/redhat-release *)
949                 try
950                   let subs = Pcre.exec ~rex:rhel line in
951                   let major = int_of_string (Pcre.get_substring subs 1) in
952                   let minor =
953                     try int_of_string (Pcre.get_substring subs 2)
954                     with Not_found -> 0 in
955                   LinuxRoot (UnknownArch, RHEL (major, minor))
956                 with
957                   Not_found | Failure "int_of_string" ->
958                     try
959                       let subs = Pcre.exec ~rex:fedora line in
960                       let version = int_of_string (Pcre.get_substring subs 1) in
961                       LinuxRoot (UnknownArch, Fedora version)
962                     with
963                       Not_found | Failure "int_of_string" ->
964                         LinuxRoot (UnknownArch, OtherLinux)
965           )
966           else if is_file (mnt ^ "/etc/debian_version") = Some true then (
967             let chan = open_in (mnt ^ "/etc/debian_version") in
968             let lines = input_all_lines chan in
969             close_in chan;
970
971             match lines with
972             | [] -> (* empty /etc/debian_version ...? *)
973                 LinuxRoot (UnknownArch, OtherLinux)
974             | line::_ -> (* try to detect version from /etc/debian_version *)
975                 try
976                   let subs = Pcre.exec ~rex:debian line in
977                   let major = int_of_string (Pcre.get_substring subs 1) in
978                   let minor = int_of_string (Pcre.get_substring subs 2) in
979                   LinuxRoot (UnknownArch, Debian (major, minor))
980                 with
981                   Not_found | Failure "int_of_string" ->
982                     LinuxRoot (UnknownArch, OtherLinux)
983           )
984           else
985             LinuxRoot (UnknownArch, OtherLinux)
986         ) else if is_dir (mnt ^ "/grub") = Some true &&
987           is_file (mnt ^ "/grub/stage1") = Some true then (
988             LinuxBoot
989         ) else
990           NotRoot (* mountable, but not a root filesystem *)
991     in
992
993     (* Examine the Linux root filesystem mounted on 'mnt' to
994      * determine the architecture. We do this by looking at some
995      * well-known binaries that we expect to be there.
996      *)
997     let detect_architecture mnt =
998       let cmd = "file -bL " ^ quote (mnt ^ "/sbin/init") in
999       match shget cmd with
1000       | Some (str::_) when Pcre.pmatch ~rex:i386 str -> I386
1001       | Some (str::_) when Pcre.pmatch ~rex:x86_64 str -> X86_64
1002       | Some (str::_) when Pcre.pmatch ~rex:itanic str -> IA64
1003       | _ -> UnknownArch
1004     in
1005
1006     List.map (
1007       fun part ->
1008         let dev = dev_of_partition part in (* Get /dev device. *)
1009
1010         let nature =
1011           (* Use 'file' command to detect if it is swap. *)
1012           let cmd = "file -sbL " ^ quote dev in
1013           match shget cmd with
1014           | Some (str::_) when Pcre.pmatch ~rex:swap str -> LinuxSwap
1015           | _ ->
1016               (* Blindly try to mount the device. *)
1017               let cmd = "mount -o ro " ^ quote dev ^ " /mnt/root" in
1018               match shwithstatus cmd with
1019               | 0 ->
1020                   let os = detect_os "/mnt/root" in
1021                   let nature =
1022                     match os with
1023                     | LinuxRoot (UnknownArch, distro) ->
1024                         let architecture = detect_architecture "/mnt/root" in
1025                         LinuxRoot (architecture, distro)
1026                     | os -> os in
1027                   sh "umount /mnt/root";
1028                   nature
1029
1030               | _ -> UnknownNature (* not mountable *)
1031
1032         in
1033
1034         eprintf "partition detection: %s is %s\n%!"
1035           dev (string_of_nature nature);
1036
1037         (part, nature)
1038     ) all_partitions
1039   in
1040
1041   print_endline (s_ "Finished detecting hard drives.");
1042
1043   (* Autodetect system memory. *)
1044   let system_memory =
1045     (* Try to parse dmesg first to find the 'Memory:' report when
1046      * the kernel booted.  If available, this can give us an
1047      * indication of usable RAM on this system.
1048      *)
1049     let dmesg = shget "dmesg" in
1050     try
1051       let dmesg =
1052         match dmesg with Some lines -> lines | None -> raise Not_found in
1053       let line =
1054         List.find (fun line -> String.starts_with line "Memory: ") dmesg in
1055       let subs = Pcre.exec ~pat:"k/([[:digit:]]+)k available" line in
1056       let mem = Pcre.get_substring subs 1 in
1057       int_of_string mem / 1024
1058     with
1059       Not_found | Failure "int_of_string" ->
1060         (* 'dmesg' can't be parsed.  The backup plan is to look
1061          * at /proc/meminfo.
1062          *)
1063         let mem = shget "head -1 /proc/meminfo | awk '{print $2/1024}'" in
1064         match mem with
1065         | Some (mem::_) -> int_of_float (float_of_string mem)
1066
1067         (* For some reason even /proc/meminfo didn't work.  Just
1068          * assume 256 MB instead.
1069          *)
1070         | _ -> 256 in
1071
1072   (* Autodetect system # pCPUs. *)
1073   let system_nr_cpus =
1074     let cpus =
1075       shget "grep ^processor /proc/cpuinfo | tail -1 | awk '{print $3+1}'" in
1076     match cpus with
1077     | Some (cpus::_) -> int_of_string cpus
1078     | _ -> 1 in
1079
1080   (* Greeting, type of transfer, network question stages.
1081    * These are all done in newt mode.
1082    *)
1083   let config_transfer_type, config_network =
1084     with_newt (
1085       fun () ->
1086         (* Greeting. *)
1087         if !config_greeting then
1088           message_box program_name (sprintf (f_ "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);
1089
1090         (* Type of transfer. *)
1091         let config_transfer_type =
1092           match !config_transfer_type with
1093           | Some t -> t
1094           | None ->
1095               let items = [
1096                 s_ "Physical to Virtual (P2V)", P2V;
1097                 s_ "Virtual to Virtual (V2V)", V2V;
1098               ] in
1099
1100               select_single ~stage:(s_ "Transfer type") 40
1101                 (s_ "Transfer type")
1102                 items in
1103
1104         (* Network configuration. *)
1105         let config_network =
1106           match !config_network with
1107           | Some n -> n
1108           | None ->
1109               open_centered_window ~stage:(s_ "Network")
1110                 60 20 (s_ "Configure network");
1111
1112               let autolist = Newt.listbox 4 2 4 [Newt.SCROLL] in
1113               Newt.listbox_set_width autolist 52;
1114
1115               (* Populate the "Automatic" listbox with RHEL/Fedora
1116                * root partitions found which allow us to do
1117                * automatic configuration in a known way.
1118                *)
1119               let rec loop = function
1120                 | [] -> ()
1121                 | (partition, LinuxRoot (_, ((RHEL _|Fedora _) as distro)))
1122                   :: parts ->
1123                     let label =
1124                       sprintf "%s (%s)"
1125                         (dev_of_partition partition)
1126                         (string_of_linux_distro distro) in
1127                     ignore (Newt.listbox_append_entry autolist label partition);
1128                     loop parts
1129                 | _ :: parts -> loop parts
1130               in
1131               loop all_partitions;
1132
1133               (* If there is no suitable root partition (the listbox
1134                * is empty) then disable the auto option and the listbox.
1135                *)
1136               let no_auto = Newt.listbox_item_count autolist = 0 in
1137
1138               let auto =
1139                 Newt.radio_button 1 1
1140                   (s_ "Automatic from:") (not no_auto) None in
1141               let shell =
1142                 Newt.radio_button 1 6
1143                   (s_ "Start a shell") no_auto (Some auto) in
1144
1145               if no_auto then (
1146                 Newt.component_takes_focus auto false;
1147                 Newt.component_takes_focus
1148                   (Newt.component_of_listbox autolist) false
1149               );
1150
1151               let qemu =
1152                 Newt.radio_button 1 7
1153                   (s_ "QEMU user network") false (Some shell) in
1154               let nonet =
1155                 Newt.radio_button 1 8
1156                   (s_ "Don't configure the network") false (Some qemu) in
1157               let static =
1158                 Newt.radio_button 1 9
1159                   (s_ "Static configuration:") false (Some nonet) in
1160
1161               let label1 = Newt.label 4 10 (s_ "Interface") in
1162               let entry1 = Newt.entry 16 10 (Some "eth0") 8 [] in
1163               let label2 = Newt.label 4 11 (s_ "IP") in
1164               let entry2 = Newt.entry 16 11 None 16 [] in
1165               let label3 = Newt.label 4 12 (s_ "Netmask") in
1166               let entry3 = Newt.entry 16 12 (Some "255.255.255.0") 16 [] in
1167               let label4 = Newt.label 4 13 (s_ "Gateway") in
1168               let entry4 = Newt.entry 16 13 None 16 [] in
1169               let label5 = Newt.label 4 14 (s_ "Nameserver") in
1170               let entry5 = Newt.entry 16 14 None 16 [] in
1171
1172               let enable_static () =
1173                 Newt.component_takes_focus entry1 true;
1174                 Newt.component_takes_focus entry2 true;
1175                 Newt.component_takes_focus entry3 true;
1176                 Newt.component_takes_focus entry4 true;
1177                 Newt.component_takes_focus entry5 true
1178               in
1179
1180               let disable_static () =
1181                 Newt.component_takes_focus entry1 false;
1182                 Newt.component_takes_focus entry2 false;
1183                 Newt.component_takes_focus entry3 false;
1184                 Newt.component_takes_focus entry4 false;
1185                 Newt.component_takes_focus entry5 false
1186               in
1187
1188               let enable_autolist () =
1189                 Newt.component_takes_focus
1190                   (Newt.component_of_listbox autolist) true
1191               in
1192               let disable_autolist () =
1193                 Newt.component_takes_focus
1194                   (Newt.component_of_listbox autolist) false
1195               in
1196
1197               disable_static ();
1198               Newt.component_add_callback auto
1199                 (fun () ->disable_static (); enable_autolist ());
1200               Newt.component_add_callback shell
1201                 (fun () -> disable_static (); disable_autolist ());
1202               Newt.component_add_callback qemu
1203                 (fun () -> disable_static (); disable_autolist ());
1204               Newt.component_add_callback nonet
1205                 (fun () -> disable_static (); disable_autolist ());
1206               Newt.component_add_callback static
1207                 (fun () -> enable_static (); disable_autolist ());
1208
1209               let ok = Newt.button 48 16 ok_button in
1210
1211               let form = Newt.form None None [] in
1212               Newt.form_add_components form [auto;
1213                                              Newt.component_of_listbox autolist;
1214                                              shell;qemu;nonet;static;
1215                                              label1;label2;label3;label4;label5;
1216                                              entry1;entry2;entry3;entry4;entry5;
1217                                              ok];
1218
1219               let n =
1220                 let rec loop () =
1221                   ignore (Newt.run_form form);
1222
1223                   let r = Newt.radio_get_current auto in
1224                   if Newt.component_equals r auto then (
1225                     match Newt.listbox_get_current autolist with
1226                     | None -> loop ()
1227                     | Some part -> Auto part
1228                   )
1229                   else if Newt.component_equals r shell then Shell
1230                   else if Newt.component_equals r qemu then QEMUUserNet
1231                   else if Newt.component_equals r nonet then NoNetwork
1232                   else if Newt.component_equals r static then (
1233                     let interface = Newt.entry_get_value entry1 in
1234                     let address = Newt.entry_get_value entry2 in
1235                     let netmask = Newt.entry_get_value entry3 in
1236                     let gateway = Newt.entry_get_value entry4 in
1237                     let nameserver = Newt.entry_get_value entry5 in
1238                     if interface = "" || address = "" ||
1239                       netmask = "" || gateway = "" then
1240                         loop ()
1241                     else
1242                       Static (interface, address, netmask, gateway, nameserver)
1243                   )
1244                   else loop ()
1245                 in
1246                 loop () in
1247               Newt.pop_window ();
1248
1249               n in
1250
1251         config_transfer_type, config_network
1252     ) in
1253
1254   (* Try to bring up the network. *)
1255   (match config_network with
1256    | Shell ->
1257        print_endline (s_ "Network configuration.\n\nPlease configure the network from this shell.\n\nWhen you have finished, exit the shell with ^D or exit.\n");
1258        shell ()
1259
1260    | Static (interface, address, netmask, gateway, nameserver) ->
1261        print_endline (s_ "Trying static network configuration.\n");
1262        if not (static_network
1263                  (interface, address, netmask, gateway, nameserver)) then (
1264          print_endline (s_ "\nAuto-configuration failed.  Starting a shell.\n\nPlease configure the network from this shell.\n\nWhen you have finished, exit the shell with ^D or exit.\n");
1265          shell ()
1266        )
1267
1268    | Auto rootfs ->
1269        print_endline
1270          (s_ "Trying network auto-configuration from root filesystem ...\n");
1271
1272        (* Mount the root filesystem read-only under /mnt/root. *)
1273        sh ("mount -o ro " ^ quote (dev_of_partition rootfs) ^ " /mnt/root");
1274
1275        if not (auto_network ()) then (
1276          print_endline (s_ "\nAuto-configuration failed.  Starting a shell.\n\nPlease configure the network from this shell.\n\nWhen you have finished, exit the shell with ^D or exit.\n");
1277          shell ()
1278        );
1279
1280        (* NB. Lazy unmount is required because dhclient keeps its current
1281         * directory open on /etc/sysconfig/network-scripts/
1282         *)
1283        sh ("umount -l /mnt/root");
1284
1285    | QEMUUserNet ->
1286        print_endline (s_ "Trying QEMU network configuration.\n");
1287        qemu_network ()
1288
1289    | NoNetwork -> (* this is easy ... *) ()
1290   );
1291
1292   (* SSH configuration phase. *)
1293   let config_ssh =
1294     with_newt (
1295       fun () ->
1296         match !config_ssh with
1297         | Some c -> c
1298         | None ->
1299             (* Query the user for SSH configuration. *)
1300             open_centered_window ~stage:(s_ "SSH configuration")
1301               60 20 (s_ "SSH configuration");
1302
1303             let label1 = Newt.label 1 1 (s_ "Remote host") in
1304             let host = Newt.entry 20 1 None 36 [] in
1305             let label2 = Newt.label 1 2 (s_ "Remote port") in
1306             let port = Newt.entry 20 2 (Some "22") 6 [] in
1307             let label3 = Newt.label 1 3 (s_ "Remote directory") in
1308             let dir = Newt.entry 20 3 (Some "/var/lib/xen/images") 36 [] in
1309             let label4 = Newt.label 1 4 (s_ "SSH username") in
1310             let user = Newt.entry 20 4 (Some "root") 16 [] in
1311             (*
1312               There's no sensible way to support this for SSH:
1313             let label5 = Newt.label 1 5 (s_ "SSH password") in
1314             let pass = Newt.entry 20 5 None 16 [Newt.PASSWORD] in
1315             *)
1316
1317             let compr =
1318               Newt.checkbox 16 7 (s_ "Use SSH compression (not good for LANs)")
1319                 ' ' None in
1320
1321             let check =
1322               Newt.checkbox 16 9 (s_ "Test SSH connection") '*' None in
1323
1324             let ok = Newt.button 48 16 ok_button in
1325
1326             let form = Newt.form None None [] in
1327             Newt.form_add_components form [label1;label2;label3;label4;
1328                                            host;port;dir;user;
1329                                            compr;check;
1330                                            ok];
1331
1332             let c =
1333               let rec loop () =
1334                 ignore (Newt.run_form form);
1335                 let host = Newt.entry_get_value host in
1336                 let port = Newt.entry_get_value port in
1337                 let dir = Newt.entry_get_value dir in
1338                 let user = Newt.entry_get_value user in
1339                 let compr = Newt.checkbox_get_value compr = '*' in
1340                 let check = Newt.checkbox_get_value check = '*' in
1341                 if host <> "" && port <> "" && user <> "" then
1342                     { ssh_host = host; ssh_port = port; ssh_directory = dir;
1343                       ssh_username = user;
1344                       ssh_compression = compr;
1345                       ssh_check = check; }
1346                 else
1347                   loop ()
1348               in
1349               loop () in
1350
1351             Newt.pop_window ();
1352             c
1353     ) in
1354
1355   (* If asked, check the SSH connection. *)
1356   if config_ssh.ssh_check then
1357     if not (test_ssh config_ssh) then
1358       failwith (s_ "SSH configuration failed");
1359
1360   (* Devices and root partition and target configuration selection stage. *)
1361   let config_devices_to_send, config_root_filesystem, config_target =
1362     with_newt (
1363       fun () ->
1364         let config_devices_to_send =
1365           match !config_devices_to_send with
1366           | Some ds -> ds
1367           | None ->
1368               let items = List.map (
1369                   fun (dev, size) ->
1370                     let label =
1371                       sprintf "/dev/%s (%.3f GB)" dev
1372                       ((Int64.to_float size) /. (1024.*.1024.*.1024.)) in
1373                     (label, dev, true)
1374               ) all_block_devices in
1375
1376               select_multiple ~stage:(s_ "Block devices")
1377                 ~force_one:true 60
1378                 (s_ "Select block devices to send")
1379                 items in
1380
1381         let config_root_filesystem =
1382           match !config_root_filesystem with
1383           | Some fs -> fs
1384           | None ->
1385               let items = List.map (
1386                 fun (part, nature) ->
1387                   let label =
1388                     sprintf "%s %s" (dev_of_partition part)
1389                       (string_of_nature nature) in
1390                   (label, part)
1391               ) all_partitions in
1392
1393               select_single ~stage:(s_ "Root filesystem") 60
1394                 (s_ "Select root filesystem")
1395                 items in
1396
1397         let config_target =
1398           match !config_target with
1399           | Some t -> t
1400           | None ->
1401               open_centered_window ~stage:(s_ "Target system") 40 20
1402                 (s_ "Configure target system");
1403
1404               let hvlabel = Newt.label 1 1 (s_ "Hypervisor:") in
1405               let hvlistbox = Newt.listbox 16 1 4 [Newt.SCROLL] in
1406               Newt.listbox_append_entry hvlistbox "Xen" (Some Xen);
1407               Newt.listbox_append_entry hvlistbox "QEMU" (Some QEMU);
1408               Newt.listbox_append_entry hvlistbox "KVM" (Some KVM);
1409               Newt.listbox_append_entry hvlistbox "Other" None;
1410
1411               let archlabel = Newt.label 1 5 (s_ "Architecture:") in
1412               let archlistbox = Newt.listbox 16 5 4 [Newt.SCROLL] in
1413               Newt.listbox_append_entry archlistbox "i386" I386;
1414               Newt.listbox_append_entry archlistbox
1415                     "x86-64 (64-bit x86)" X86_64;
1416               Newt.listbox_append_entry archlistbox "IA64 (Itanium)" IA64;
1417               Newt.listbox_append_entry archlistbox "PowerPC 32-bit" PPC;
1418               Newt.listbox_append_entry archlistbox "PowerPC 64-bit" PPC64;
1419               Newt.listbox_append_entry archlistbox "SPARC 32-bit" SPARC;
1420               Newt.listbox_append_entry archlistbox "SPARC 64-bit" SPARC64;
1421               Newt.listbox_append_entry archlistbox "Unknown/other" UnknownArch;
1422
1423               (* Get the architecture of the selected root filesystem.
1424                * If not known, default to UnknownArch.
1425                *)
1426               Newt.listbox_set_current_by_key archlistbox UnknownArch;
1427               (try
1428                  match List.assoc config_root_filesystem all_partitions with
1429                  | LinuxRoot (arch, _) ->
1430                      Newt.listbox_set_current_by_key archlistbox arch
1431                  | _ -> ()
1432                 with
1433                   Not_found -> ());
1434
1435               let memlabel = Newt.label 1 9 (s_ "Memory (MB):") in
1436               let mementry = Newt.entry 16 9
1437                 (Some (string_of_int system_memory)) 8 [] in
1438               let cpulabel = Newt.label 1 10 (s_ "CPUs:") in
1439               let cpuentry = Newt.entry 16 10
1440                 (Some (string_of_int system_nr_cpus)) 4 [] in
1441               let maclabel = Newt.label 1 11 (s_ "MAC addr:") in
1442               let macentry = Newt.entry 16 11 None 20 [] in
1443               let maclabel2 =
1444                 Newt.label 1 12 (s_ "(leave MAC blank for random)") in
1445
1446               let libvirtd =
1447                 Newt.checkbox 12 14 (s_ "Use remote libvirtd") '*' None in
1448
1449               let ok = Newt.button 28 16 ok_button in
1450
1451               let form = Newt.form None None [] in
1452               Newt.form_add_components form
1453                 [hvlabel; Newt.component_of_listbox hvlistbox;
1454                  archlabel; Newt.component_of_listbox archlistbox;
1455                  memlabel; mementry;
1456                  cpulabel; cpuentry;
1457                  maclabel; macentry; maclabel2;
1458                  libvirtd;
1459                  ok];
1460
1461               let c =
1462                 let rec loop () =
1463                   ignore (Newt.run_form form);
1464                   try
1465                     let hv = Newt.listbox_get_current hvlistbox in
1466                     let arch = Newt.listbox_get_current archlistbox in
1467                     let mem = int_of_string (Newt.entry_get_value mementry) in
1468                     let cpus = int_of_string (Newt.entry_get_value cpuentry) in
1469                     let mac = Newt.entry_get_value macentry in
1470                     let libvirtd = Newt.checkbox_get_value libvirtd = '*' in
1471                     if hv <> None && arch <> None && mem >= 0 && cpus >= 0
1472                     then
1473                       { tgt_hypervisor = Option.get hv;
1474                         tgt_architecture = Option.get arch;
1475                         tgt_memory = mem; tgt_vcpus = cpus;
1476                         tgt_mac_address =
1477                           if mac <> "" then mac else random_mac_address ();
1478                         tgt_libvirtd = libvirtd }
1479                     else
1480                       loop ()
1481                   with
1482                     Not_found | Failure "int_of_string" -> loop ()
1483                 in
1484                 loop () in
1485
1486               Newt.pop_window ();
1487
1488               c in
1489
1490         config_devices_to_send, config_root_filesystem, config_target
1491     ) in
1492
1493   (* If architecture is set to UnknownArch, then assume the same
1494    * architecture as the live CD.
1495    *)
1496   let config_target =
1497     match config_target.tgt_architecture with
1498     | UnknownArch ->
1499         let arch = shget "uname -m" in
1500         let arch =
1501           match arch with
1502           | Some (arch :: _) -> architecture_of_string arch
1503           | _ -> I386 (* probably wrong XXX *) in
1504         { config_target with tgt_architecture = arch }
1505     | _ -> config_target in
1506
1507   (* Try to get the capabilities from the remote machine.  If we fail
1508    * it doesn't matter too much.
1509    *)
1510   let caps_os_type, caps_emulator, caps_loader, caps_machine =
1511     try
1512       if not config_target.tgt_libvirtd then raise Not_found;
1513
1514       let proto, path =
1515         match config_target.tgt_hypervisor with
1516         | Some Xen -> "xen", "/"
1517         | Some (QEMU|KVM) -> "qemu", "/system"
1518         | None -> raise Not_found in
1519       let name =
1520         sprintf "%s+ssh://%s@%s:%s%s"
1521           proto config_ssh.ssh_username
1522           config_ssh.ssh_host config_ssh.ssh_port path in
1523       eprintf "capabilities URI = %S\n%!" name;
1524
1525       print_endline (s_ "Try to fetch remote hypervisor capabilities ...\n");
1526
1527       let conn = Libvirt.Connect.connect_readonly ~name () in
1528       let caps = Libvirt.Connect.get_capabilities conn in
1529       Libvirt.Connect.close conn;
1530
1531       (* Turn it into XML data. *)
1532       let caps = Xml.parse_string caps in
1533       eprintf "capabilities:\n%s\n%!" (Xml.to_string_fmt caps);
1534
1535       (* We're looking for a guest with <os_type>hvm</os_type>
1536        * and <arch name="target-arch">...  Later when we can
1537        * install PV drivers automatically, we will want to look
1538        * for paravirt guest types too.
1539        *)
1540       let guests = children_with_name "guest" caps in
1541       let guests =
1542         List.filter (xml_has_pcdata_child "os_type" "hvm") guests in
1543       let arch_str = string_of_architecture config_target.tgt_architecture in
1544       let guests =
1545         List.filter (
1546           xml_has_child_matching (
1547             function
1548             | Xml.Element (n, attribs, _)
1549                 when n = "arch"
1550                   && List.exists (
1551                     fun (n, a) ->
1552                       n = "name" &&
1553                       (* deal with i386 vs i686 pestilence *)
1554                       architecture_of_string a = config_target.tgt_architecture
1555                   ) attribs
1556                   -> true
1557             | _ -> false
1558           )
1559         ) guests in
1560
1561       (* In theory at this point we only have a single guest type
1562        * remaining.  It might be that we have _zero_ available
1563        * guest types, which indicates probably an unsupported
1564        * capability of the remote hypervisor (or just that one of
1565        * many parsing or heuristics failed).  It might be that
1566        * we have > 1 available guest types, which indicates some
1567        * feature we don't know about.
1568        *)
1569       let len = List.length guests in
1570       if len = 0 then (
1571         message_box (s_ "Warning")
1572           (sprintf (f_ "Remote hypervisor claims not to support fully virtualized %s guests.\n\nContinuing anyway.\n\n%!") arch_str);
1573         raise Not_found
1574       );
1575
1576       if len > 1 then (
1577         message_box (s_ "Note")
1578           (sprintf (f_ "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)
1579       );
1580
1581       let guest = List.hd guests in
1582
1583       let os_type =
1584         try Some (find_pcdata_child "os_type" guest)
1585         with Not_found -> None in
1586       let arch_section = find_child_with_name "arch" guest in
1587       let emulator =
1588         try Some (find_pcdata_child "emulator" arch_section)
1589         with Not_found -> None in
1590       let loader =
1591         try Some (find_pcdata_child "loader" arch_section)
1592         with Not_found -> None in
1593       let machine =
1594         try Some (find_pcdata_child "machine" arch_section)
1595         with Not_found -> None in
1596
1597       os_type, emulator, loader, machine
1598     with
1599     | Not_found -> None, None, None, None
1600     | Xml.Error err ->
1601         eprintf "XML error: %s\n%!" (Xml.error err);
1602         None, None, None, None
1603     | Xml.Not_element _ | Xml.Not_pcdata _ | Xml.No_attribute _ ->
1604         (* If these occur, need to add some more debugging. *)
1605         eprintf "XML error when parsing capabilities\n%!";
1606         None, None, None, None
1607     | Libvirt.Virterror err ->
1608         eprintf "libvirt error: %s\n%!" (Libvirt.Virterror.to_string err);
1609         None, None, None, None
1610     | Invalid_argument str ->
1611         eprintf "libvirt error: %s\n%!" str;
1612         None, None, None, None in
1613
1614   (* In test mode, exit here before we do Bad Things to the developer's
1615    * hard disk.
1616    *)
1617   if test_dialog_stages then exit 1;
1618
1619   print_endline (s_ "Performing LVM snapshots ...\n");
1620
1621   (* Switch LVM config. *)
1622   sh "vgchange -a n";
1623   putenv "LVM_SYSTEM_DIR" "/etc/lvm.new"; (* see lvm(8) *)
1624   sh "rm -f /etc/lvm/cache/.cache";
1625   sh "rm -f /etc/lvm.new/cache/.cache";
1626
1627   (* Snapshot the block devices to send. *)
1628   let config_devices_to_send =
1629     List.map (
1630       fun origin_dev ->
1631         let snapshot_dev = snapshot_name origin_dev in
1632         snapshot origin_dev snapshot_dev;
1633         (origin_dev, snapshot_dev)
1634     ) config_devices_to_send in
1635
1636   (* Run kpartx on the snapshots. *)
1637   List.iter (
1638     fun (origin, snapshot) ->
1639       shfailok ("kpartx -a " ^ quote ("/dev/mapper/" ^ snapshot))
1640   ) config_devices_to_send;
1641
1642   (* Rescan for LVs. *)
1643   sh "vgscan";
1644   sh "vgchange -a y";
1645
1646   (* Mount the root filesystem under /mnt/root. *)
1647   (match config_root_filesystem with
1648    | Part (dev, partnum) ->
1649        let dev = dev ^ partnum in
1650        let snapshot_dev = snapshot_name dev in
1651        sh ("mount " ^ quote ("/dev/mapper/" ^ snapshot_dev) ^ " /mnt/root")
1652
1653    | LV (vg, lv) ->
1654        (* The LV will be backed by a snapshot device, so just mount
1655         * directly.
1656         *)
1657        sh ("mount " ^ quote ("/dev/" ^ vg ^ "/" ^ lv) ^ " /mnt/root")
1658   );
1659
1660   (* Work out what devices will be called at the remote end. *)
1661   let config_devices_to_send = List.map (
1662     fun (origin_dev, snapshot_dev) ->
1663       let remote_dev = remote_of_origin_dev origin_dev in
1664       (origin_dev, snapshot_dev, remote_dev)
1665   ) config_devices_to_send in
1666
1667   (* Modify files on the root filesystem. *)
1668   rewrite_fstab config_devices_to_send;
1669   (* XXX Other files to rewrite? *)
1670
1671   (* Unmount the root filesystem and sync disks. *)
1672   sh "umount /mnt/root";
1673   sh "sync";                            (* Ugh, should be in stdlib. *)
1674
1675   (* XXX This is using the hostname derived from network configuration
1676    * above.  We might want to ask the user to choose.
1677    *)
1678   let hostname = safe_name (gethostname ()) in
1679   let basename =
1680     let date = sprintf "%04d%02d%02d%02d%02d"
1681       (tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min in
1682     "p2v-" ^ hostname ^ "-" ^ date in
1683
1684   (* Work out what the image filenames will be at the remote end. *)
1685   let config_devices_to_send = List.map (
1686     fun (origin_dev, snapshot_dev, remote_dev) ->
1687       let remote_name = basename ^ "-" ^ remote_dev ^ ".img" in
1688       (origin_dev, snapshot_dev, remote_dev, remote_name)
1689   ) config_devices_to_send in
1690
1691   (* Write a configuration file.  Not sure if this is any better than
1692    * just 'sprintf-ing' bits of XML text together, but at least we will
1693    * always get well-formed XML.
1694    *
1695    * XXX There is a case for using virt-install to generate this XML.
1696    * When we start to incorporate libvirt access & storage API this
1697    * needs to be rethought.
1698    *)
1699   let conf_filename = basename ^ ".conf" in
1700
1701   let xml =
1702     (* Shortcut to make "<name>value</name>". *)
1703     let leaf name value = Xml.Element (name, [], [Xml.PCData value]) in
1704     (* ... and the _other_ sort of leaf (god I hate XML). *)
1705     let tleaf name attribs = Xml.Element (name, attribs, []) in
1706
1707     let arch_str =
1708       string_of_architecture config_target.tgt_architecture in
1709     let arch_wordsize =
1710       wordsize_of_architecture config_target.tgt_architecture in
1711
1712     (* Standard stuff for every domain. *)
1713     let name = leaf "name" hostname in
1714     let uuid = leaf "uuid" (random_uuid ()) in
1715     let maxmem, memory =
1716       let m = string_of_int (config_target.tgt_memory * 1024) in
1717       leaf "maxmem" m, leaf "memory" m in
1718     let vcpu = leaf "vcpu" (string_of_int config_target.tgt_vcpus) in
1719
1720     (* Top-level stuff which differs for each HV type (isn't this supposed
1721      * to be portable ...)
1722      *)
1723     let extras =
1724       (* Use capabilities for os_type, etc. else use some good guesses. *)
1725       let os_type = Option.default "hvm" caps_os_type in
1726       let machine = Option.default "pc" caps_machine in
1727       let loader = Option.default "/usr/lib/xen/boot/hvmloader" caps_loader in
1728
1729       match config_target.tgt_hypervisor with
1730       | Some Xen ->
1731           [Xml.Element ("os", [],
1732                         [leaf "type" os_type;
1733                          leaf "loader" loader;
1734                          tleaf "boot" ["dev", "hd"]]);
1735            Xml.Element ("features", [],
1736                         [tleaf "pae" [];
1737                          tleaf "acpi" [];
1738                          tleaf "apic" []]);
1739            tleaf "clock" ["sync", "localtime"]]
1740       | Some KVM ->
1741           [Xml.Element ("os", [], [leaf "type" os_type]);
1742            tleaf "clock" ["sync", "localtime"]]
1743       | Some QEMU ->
1744           [Xml.Element ("os", [],
1745                         [Xml.Element ("type",
1746                                       ["arch", arch_str;
1747                                        "machine", machine],
1748                                       [Xml.PCData os_type]);
1749                          tleaf "boot" ["dev", "hd"]])]
1750       | None ->
1751           [] in
1752
1753     (* <devices> section. *)
1754     let devices =
1755       let emulator =
1756         match caps_emulator with
1757         (* Use the emulator from the libvirt capabilities. *)
1758         | Some s -> [leaf "emulator" s]
1759         | None ->
1760             (* If we don't have libvirt capabilities, best guess. *)
1761             match config_target.tgt_hypervisor with
1762             | Some Xen ->
1763                 [leaf "emulator"
1764                    (if arch_wordsize = W64 then "/usr/lib64/xen/bin/qemu-dm"
1765                     else "/usr/lib/xen/bin/qemu-dm")]
1766             | Some QEMU ->
1767                 [leaf "emulator" "/usr/bin/qemu"]
1768             | Some KVM ->
1769                 [leaf "emulator" "/usr/bin/qemu-kvm"]
1770             | None ->
1771                 [] in
1772       let interface =
1773         Xml.Element ("interface", ["type", "user"],
1774                      [tleaf "mac" ["address",
1775                                    config_target.tgt_mac_address]]) in
1776       (* XXX should have an option for Xen bridging:
1777         Xml.Element (
1778         "interface", ["type","bridge"],
1779         [tleaf "source" ["bridge","xenbr0"];
1780         tleaf "mac" ["address",mac_address];
1781         tleaf "script" ["path","vif-bridge"]])*)
1782       let graphics = tleaf "graphics" ["type", "vnc"] in
1783
1784       let disks = List.map (
1785         fun (_, _, remote_dev, remote_name) ->
1786           Xml.Element (
1787             "disk", ["type", "file";
1788                      "device", "disk"],
1789             [tleaf "source" ["file",
1790                              config_ssh.ssh_directory ^ "/" ^ remote_name];
1791              tleaf "target" ["dev", remote_dev]]
1792           )
1793       ) config_devices_to_send in
1794
1795       Xml.Element (
1796         "devices", [],
1797         emulator @ interface :: graphics :: disks
1798       ) in
1799
1800     (* Put it all together in <domain type='foo'>. *)
1801     Xml.Element (
1802       "domain",
1803       (match config_target.tgt_hypervisor with
1804        | Some Xen -> ["type", "xen"]
1805        | Some QEMU -> ["type", "qemu"]
1806        | Some KVM -> ["type", "kvm"]
1807        | None -> []),
1808       name :: uuid :: memory :: maxmem :: vcpu :: extras @ [devices]
1809     ) in
1810
1811   (* Convert XML configuration file to a string, then send it to the
1812    * remote server.
1813    *)
1814   let () =
1815     let xml = Xml.to_string_fmt xml in
1816
1817     let conn_arg =
1818       match config_target.tgt_hypervisor with
1819       | Some Xen | None -> ""
1820       | Some QEMU | Some KVM -> " -c qemu:///system" in
1821     let xml = sprintf (f_ "\
1822 <!--
1823   This is an automatically generated libvirt configuration file.
1824   It was written by the %s program.
1825
1826   Please check the values in this configuration file carefully,
1827   particularly maxmem, memory, vcpu and any paths.
1828
1829   To start the domain, do:
1830     virsh%s define %s
1831     virsh%s start %s
1832 -->\n\n") program_name conn_arg conf_filename conn_arg hostname
1833       ^ xml
1834       ^ "\n" in
1835
1836     let xml_len = String.length xml in
1837     eprintf "length of configuration file is %d bytes\n%!" xml_len;
1838
1839     print_endline (s_ "\nWriting configuration file ...\n");
1840
1841     let (sock,_) as conn = ssh_start_upload config_ssh conf_filename in
1842     (* In OCaml this actually loops calling write(2) *)
1843     ignore (write sock xml 0 xml_len);
1844     ssh_finish_upload conn in
1845
1846   (* Send the device snapshots to the remote host. *)
1847   (* XXX This code should be made more robust against both network
1848    * errors and local I/O errors.  Also should allow the user several
1849    * attempts to connect, or let them go back to the dialog stage.
1850    *)
1851   List.iter (
1852     fun (origin_dev, snapshot_dev, remote_dev, remote_name) ->
1853       eprintf "sending %s as %s\n%!" origin_dev remote_name;
1854
1855       let size =
1856         try List.assoc origin_dev all_block_devices
1857         with Not_found -> assert false (* internal error *) in
1858
1859       let () =
1860         printf (f_ "\nSending /dev/%s (%.3f GB) to remote machine\n\n%!")
1861           origin_dev ((Int64.to_float size) /. (1024.*.1024.*.1024.)) in
1862
1863       (* Open the snapshot device. *)
1864       let fd = openfile ("/dev/mapper/" ^ snapshot_dev) [O_RDONLY] 0 in
1865
1866       (* Now connect. *)
1867       let (sock,_) as conn = ssh_start_upload config_ssh remote_name in
1868
1869       (* Copy the data. *)
1870       let spinners = "|/-\\" (* "Oo" *) in
1871       let bufsize = 1024 * 1024 in
1872       let buffer = String.create bufsize in
1873       let start = gettimeofday () in
1874
1875       let rec copy bytes_sent last_printed_at spinner =
1876         let n = read fd buffer 0 bufsize in
1877         if n > 0 then (
1878           let n' = write sock buffer 0 n in
1879           if n <> n' then assert false; (* never, according to the manual *)
1880
1881           let bytes_sent = Int64.add bytes_sent (Int64.of_int n) in
1882           let last_printed_at, spinner =
1883             let now = gettimeofday () in
1884             (* Print progress every few seconds. *)
1885             if now -. last_printed_at > 2. then (
1886               let elapsed = Int64.to_float bytes_sent /. Int64.to_float size in
1887               let secs_elapsed = now -. start in
1888               printf "%.0f%% %c %.1f Mbps"
1889                 (100. *. elapsed) spinners.[spinner]
1890                 (Int64.to_float bytes_sent/.secs_elapsed/.1_000_000. *. 8.);
1891               (* After 60 seconds has elapsed, start printing estimates. *)
1892               if secs_elapsed >= 60. then (
1893                 let remaining = 1. -. elapsed in
1894                 let secs_remaining = (remaining /. elapsed) *. secs_elapsed in
1895                 if secs_remaining > 120. then
1896                   printf (f_ " (about %.0f minutes remaining)")
1897                     (secs_remaining/.60.)
1898                 else
1899                   printf (f_ " (about %.0f seconds remaining)")
1900                     secs_remaining
1901               );
1902               printf "          \r%!";
1903               let spinner = (spinner + 1) mod String.length spinners in
1904               now, spinner
1905             )
1906             else last_printed_at, spinner in
1907
1908           copy bytes_sent last_printed_at spinner
1909         )
1910       in
1911       copy 0L start 0;
1912       printf "\n\n%!"; (* because of the messages printed above *)
1913
1914       (* Disconnect. *)
1915       ssh_finish_upload conn
1916   ) config_devices_to_send;
1917
1918   (*printf "\n\nPress any key ...\n%!"; ignore (read_line ());*)
1919
1920   (* Clean up and reboot. *)
1921   ignore (
1922     message_box (sprintf (f_ "%s has finished") program_name)
1923       (sprintf (f_ "\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.")
1924          config_ssh.ssh_directory conf_filename)
1925   );
1926
1927   shfailok "eject";
1928   shfailok "reboot";
1929
1930   exit 0
1931
1932 (*----------------------------------------------------------------------*)
1933
1934 let usage () =
1935   let () = eprintf (f_ "usage: virt-p2v [--test] [ttyname]\n%!") in
1936   exit 2
1937
1938 (* Make sure that exceptions from 'main' get printed out on stdout
1939  * as well as stderr, since stderr is probably redirected to the
1940  * logfile, and so not visible to the user.
1941  *)
1942 let handle_exn f arg =
1943   try f arg
1944   with exn ->
1945     print_endline (Printexc.to_string exn);
1946     raise exn
1947
1948 (* Test harness for the Makefile.  The Makefile invokes this script as
1949  * 'virt-p2v --test' just to check it compiles.  When it is running
1950  * from the actual live CD, there is a single parameter which is the
1951  * tty name (so usually 'virt-p2v tty1').
1952  *)
1953 let () =
1954   match Array.to_list Sys.argv with
1955   | [ _; ("--help"|"-help"|"-?"|"-h") ] -> usage ();
1956   | [ _; "--test" ] -> ()               (* Makefile test - do nothing. *)
1957   | [ _; ttyname ] ->                   (* Run main with ttyname. *)
1958       handle_exn main (Some ttyname)
1959   | [ _ ] ->                            (* Interactive - no ttyname. *)
1960       handle_exn main None
1961   | _ -> usage ()
1962
1963 (* This file must end with a newline *)