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