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