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