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