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