1bd9632b4dcce53bf4399e5f11b739c46a82587b
[libguestfs.git] / resize / resize.ml
1 (* virt-resize
2  * Copyright (C) 2010-2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *)
18
19 open Printf
20
21 module G = Guestfs
22
23 open Utils
24
25 (* Minimum surplus before we create an extra partition. *)
26 let min_extra_partition = 10L *^ 1024L *^ 1024L
27
28 (* Command line argument parsing. *)
29 let prog = Filename.basename Sys.executable_name
30
31 let infile, outfile, copy_boot_loader, debug, deletes, dryrun,
32   expand, expand_content, extra_partition, format, ignores,
33   lv_expands, machine_readable, ntfsresize_force, output_format,
34   quiet, resizes, resizes_force, shrink =
35   let display_version () =
36     let g = new G.guestfs () in
37     let version = g#version () in
38     printf "virt-resize %Ld.%Ld.%Ld%s\n"
39       version.G.major version.G.minor version.G.release version.G.extra;
40     exit 0
41   in
42
43   let add xs s = xs := s :: !xs in
44
45   let copy_boot_loader = ref true in
46   let debug = ref false in
47   let deletes = ref [] in
48   let dryrun = ref false in
49   let expand = ref "" in
50   let set_expand s =
51     if s = "" then error "%s: empty --expand option" prog
52     else if !expand <> "" then error "--expand option given twice"
53     else expand := s
54   in
55   let expand_content = ref true in
56   let extra_partition = ref true in
57   let format = ref "" in
58   let ignores = ref [] in
59   let lv_expands = ref [] in
60   let machine_readable = ref false in
61   let ntfsresize_force = ref false in
62   let output_format = ref "" in
63   let quiet = ref false in
64   let resizes = ref [] in
65   let resizes_force = ref [] in
66   let shrink = ref "" in
67   let set_shrink s =
68     if s = "" then error "empty --shrink option"
69     else if !shrink <> "" then error "--shrink option given twice"
70     else shrink := s
71   in
72
73   let argspec = Arg.align [
74     "--no-copy-boot-loader", Arg.Clear copy_boot_loader, " Don't copy boot loader";
75     "-d",        Arg.Set debug,             " Enable debugging messages";
76     "--debug",   Arg.Set debug,             " -\"-";
77     "--delete",  Arg.String (add deletes),  "part Delete partition";
78     "--expand",  Arg.String set_expand,     "part Expand partition";
79     "--no-expand-content", Arg.Clear expand_content, " Don't expand content";
80     "--no-extra-partition", Arg.Clear extra_partition, " Don't create extra partition";
81     "--format",  Arg.Set_string format,     "format Format of input disk";
82     "--ignore",  Arg.String (add ignores),  "part Ignore partition";
83     "--lv-expand", Arg.String (add lv_expands), "lv Expand logical volume";
84     "--LV-expand", Arg.String (add lv_expands), "lv -\"-";
85     "--lvexpand", Arg.String (add lv_expands), "lv -\"-";
86     "--LVexpand", Arg.String (add lv_expands), "lv -\"-";
87     "--machine-readable", Arg.Set machine_readable, " Make output machine readable";
88     "-n",        Arg.Set dryrun,            " Don't perform changes";
89     "--dryrun",  Arg.Set dryrun,            " -\"-";
90     "--dry-run", Arg.Set dryrun,            " -\"-";
91     "--ntfsresize-force", Arg.Set ntfsresize_force, " Force ntfsresize";
92     "--output-format", Arg.Set_string format, "format Format of output disk";
93     "-q",        Arg.Set quiet,             " Don't print the summary";
94     "--quiet",   Arg.Set quiet,             " -\"-";
95     "--resize",  Arg.String (add resizes),  "part=size Resize partition";
96     "--resize-force", Arg.String (add resizes_force), "part=size Forcefully resize partition";
97     "--shrink",  Arg.String set_shrink,     "part Shrink partition";
98     "-V",        Arg.Unit display_version,  " Display version and exit";
99     "--version", Arg.Unit display_version,  " -\"-";
100   ] in
101   let disks = ref [] in
102   let anon_fun s = disks := s :: !disks in
103   let usage_msg =
104     sprintf "\
105 %s: resize a virtual machine disk
106
107 A short summary of the options is given below.  For detailed help please
108 read the man page virt-resize(1).
109 "
110       prog in
111   Arg.parse argspec anon_fun usage_msg;
112
113   let debug = !debug in
114   if debug then (
115     eprintf "command line:";
116     List.iter (eprintf " %s") (Array.to_list Sys.argv);
117     prerr_newline ()
118   );
119
120   (* Dereference the rest of the args. *)
121   let copy_boot_loader = !copy_boot_loader in
122   let deletes = List.rev !deletes in
123   let dryrun = !dryrun in
124   let expand = match !expand with "" -> None | str -> Some str in
125   let expand_content = !expand_content in
126   let extra_partition = !extra_partition in
127   let format = match !format with "" -> None | str -> Some str in
128   let ignores = List.rev !ignores in
129   let lv_expands = List.rev !lv_expands in
130   let machine_readable = !machine_readable in
131   let ntfsresize_force = !ntfsresize_force in
132   let output_format = match !output_format with "" -> None | str -> Some str in
133   let quiet = !quiet in
134   let resizes = List.rev !resizes in
135   let resizes_force = List.rev !resizes_force in
136   let shrink = match !shrink with "" -> None | str -> Some str in
137
138   (* No arguments and machine-readable mode?  Print out some facts
139    * about what this binary supports.  We only need to print out new
140    * things added since this option, or things which depend on features
141    * of the appliance.
142    *)
143   if !disks = [] && machine_readable then (
144     printf "virt-resize\n";
145     printf "ntfsresize-force\n";
146     printf "32bitok\n";
147     let g = new G.guestfs () in
148     g#add_drive_opts "/dev/null";
149     g#launch ();
150     if feature_available g [| "ntfsprogs"; "ntfs3g" |] then
151       printf "ntfs\n";
152     if feature_available g [| "btrfs" |] then
153       printf "btrfs\n";
154     exit 0
155   );
156
157   (* Verify we got exactly 2 disks. *)
158   let infile, outfile =
159     match List.rev !disks with
160     | [infile; outfile] -> infile, outfile
161     | _ ->
162         error "usage is: %s [--options] indisk outdisk" prog in
163
164   infile, outfile, copy_boot_loader, debug, deletes, dryrun,
165   expand, expand_content, extra_partition, format, ignores,
166   lv_expands, machine_readable, ntfsresize_force, output_format,
167   quiet, resizes, resizes_force, shrink
168
169 (* Default to true, since NTFS and btrfs support are usually available. *)
170 let ntfs_available = ref true
171 let btrfs_available = ref true
172
173 (* Add in and out disks to the handle and launch. *)
174 let connect_both_disks () =
175   let g = new G.guestfs () in
176   if debug then g#set_trace true;
177   g#add_drive_opts ?format ~readonly:true infile;
178   g#add_drive_opts ?format:output_format ~readonly:false outfile;
179   if not quiet then Progress.set_up_progress_bar ~machine_readable g;
180   g#launch ();
181
182   (* Set the filter to /dev/sda, in case there are any rogue
183    * PVs lying around on the target disk.
184    *)
185   g#lvm_set_filter [|"/dev/sda"|];
186
187   (* Update features available in the daemon. *)
188   ntfs_available := feature_available g [|"ntfsprogs"; "ntfs3g"|];
189   btrfs_available := feature_available g [|"btrfs"|];
190
191   g
192
193 let g =
194   if not quiet then
195     printf "Examining %s ...\n%!" infile;
196
197   let g = connect_both_disks () in
198
199   g
200
201 (* Get the size in bytes of each disk.
202  *
203  * Originally we computed this by looking at the same of the host file,
204  * but of course this failed for qcow2 images (RHBZ#633096).  The right
205  * way to do it is with g#blockdev_getsize64.
206  *)
207 let sectsize, insize, outsize =
208   let sectsize = g#blockdev_getss "/dev/sdb" in
209   let insize = g#blockdev_getsize64 "/dev/sda" in
210   let outsize = g#blockdev_getsize64 "/dev/sdb" in
211   if debug then (
212     eprintf "%s size %Ld bytes\n" infile insize;
213     eprintf "%s size %Ld bytes\n" outfile outsize
214   );
215   sectsize, insize, outsize
216
217 let max_bootloader =
218   (* In reality the number of sectors containing boot loader data will be
219    * less than this (although Windows 7 defaults to putting the first
220    * partition on sector 2048, and has quite a large boot loader).
221    *
222    * However make this large enough to be sure that we have copied over
223    * the boot loader.  We could also do this by looking for the sector
224    * offset of the first partition.
225    *
226    * It doesn't matter if we copy too much.
227    *)
228   4096 * 512
229
230 (* Check the disks are at least as big as the bootloader. *)
231 let () =
232   if insize < Int64.of_int max_bootloader then
233     error "%s: file is too small to be a disk image (%Ld bytes)"
234       infile insize;
235   if outsize < Int64.of_int max_bootloader then
236     error "%s: file is too small to be a disk image (%Ld bytes)"
237       outfile outsize
238
239 (* Build a data structure describing the source disk's partition layout. *)
240 type partition = {
241   p_name : string;               (* Device name, like /dev/sda1. *)
242   p_size : int64;                (* Current size of this partition. *)
243   p_part : G.partition;          (* Partition data from libguestfs. *)
244   p_bootable : bool;             (* Is it bootable? *)
245   p_mbr_id : int option;         (* MBR ID, if it has one. *)
246   p_type : partition_content;    (* Content type and content size. *)
247   mutable p_operation : partition_operation; (* What we're going to do. *)
248   mutable p_target_partnum : int; (* Partition number on target. *)
249 }
250 and partition_content =
251   | ContentUnknown               (* undetermined *)
252   | ContentPV of int64           (* physical volume (size of PV) *)
253   | ContentFS of string * int64  (* mountable filesystem (FS type, FS size) *)
254 and partition_operation =
255   | OpCopy                       (* copy it as-is, no resizing *)
256   | OpIgnore                     (* ignore it (create on target, but don't
257                                     copy any content) *)
258   | OpDelete                     (* delete it *)
259   | OpResize of int64            (* resize it to the new size *)
260
261 let rec debug_partition p =
262   eprintf "%s:\n" p.p_name;
263   eprintf "\tpartition data: %ld %Ld-%Ld (%Ld bytes)\n"
264     p.p_part.G.part_num p.p_part.G.part_start p.p_part.G.part_end
265     p.p_part.G.part_size;
266   eprintf "\tbootable: %b\n" p.p_bootable;
267   eprintf "\tpartition ID: %s\n"
268     (match p.p_mbr_id with None -> "(none)" | Some i -> sprintf "0x%x" i);
269   eprintf "\tcontent: %s\n" (string_of_partition_content p.p_type)
270 and string_of_partition_content = function
271   | ContentUnknown -> "unknown data"
272   | ContentPV sz -> sprintf "LVM PV (%Ld bytes)" sz
273   | ContentFS (fs, sz) -> sprintf "filesystem %s (%Ld bytes)" fs sz
274 and string_of_partition_content_no_size = function
275   | ContentUnknown -> "unknown data"
276   | ContentPV _ -> sprintf "LVM PV"
277   | ContentFS (fs, _) -> sprintf "filesystem %s" fs
278
279 let get_partition_content =
280   let pvs_full = Array.to_list (g#pvs_full ()) in
281   fun dev ->
282     try
283       let fs = g#vfs_type dev in
284       if fs = "unknown" then
285         ContentUnknown
286       else if fs = "LVM2_member" then (
287         let rec loop = function
288           | [] ->
289               error "%s: physical volume not returned by pvs_full"
290                 dev
291           | pv :: _ when canonicalize pv.G.pv_name = dev ->
292               ContentPV pv.G.pv_size
293           | _ :: pvs -> loop pvs
294         in
295         loop pvs_full
296       )
297       else (
298         g#mount_ro dev "/";
299         let stat = g#statvfs "/" in
300         let size = stat.G.bsize *^ stat.G.blocks in
301         ContentFS (fs, size)
302       )
303     with
304       G.Error _ -> ContentUnknown
305
306 let partitions : partition list =
307   let parts = Array.to_list (g#part_list "/dev/sda") in
308
309   if List.length parts = 0 then
310     error "the source disk has no partitions";
311
312   let partitions =
313     List.map (
314       fun ({ G.part_num = part_num } as part) ->
315         let part_num = Int32.to_int part_num in
316         let name = sprintf "/dev/sda%d" part_num in
317         let bootable = g#part_get_bootable "/dev/sda" part_num in
318         let mbr_id =
319           try Some (g#part_get_mbr_id "/dev/sda" part_num)
320           with G.Error _ -> None in
321         let typ = get_partition_content name in
322
323         { p_name = name; p_size = part.G.part_size; p_part = part;
324           p_bootable = bootable; p_mbr_id = mbr_id; p_type = typ;
325           p_operation = OpCopy; p_target_partnum = 0 }
326     ) parts in
327
328   if debug then (
329     eprintf "%d partitions found\n" (List.length partitions);
330     List.iter debug_partition partitions
331   );
332
333   (* Check content isn't larger than partitions.  If it is then
334    * something has gone wrong and we shouldn't continue.  Old
335    * virt-resize didn't do these checks.
336    *)
337   List.iter (
338     function
339     | { p_name = name; p_size = size; p_type = ContentPV pv_size }
340         when size < pv_size ->
341         error "%s: partition size %Ld < physical volume size %Ld"
342           name size pv_size
343     | { p_name = name; p_size = size; p_type = ContentFS (_, fs_size) }
344         when size < fs_size ->
345         error "%s: partition size %Ld < filesystem size %Ld"
346           name size fs_size
347     | _ -> ()
348   ) partitions;
349
350   (* Check partitions don't overlap. *)
351   let rec loop end_of_prev = function
352     | [] -> ()
353     | { p_name = name; p_part = { G.part_start = part_start } } :: _
354         when end_of_prev > part_start ->
355         error "%s: this partition overlaps the previous one" name
356     | { p_part = { G.part_end = part_end } } :: parts -> loop part_end parts
357   in
358   loop 0L partitions;
359
360   partitions
361
362 (* Build a data structure describing LVs on the source disk.
363  * This is only used if the user gave the --lv-expand option.
364  *)
365 type logvol = {
366   lv_name : string;
367   lv_type : logvol_content;
368   mutable lv_operation : logvol_operation
369 }
370 and logvol_content = partition_content (* except ContentPV cannot occur *)
371 and logvol_operation =
372   | LVOpNone                     (* nothing *)
373   | LVOpExpand                   (* expand it *)
374
375 let debug_logvol lv =
376   eprintf "%s:\n" lv.lv_name;
377   eprintf "\tcontent: %s\n" (string_of_partition_content lv.lv_type)
378
379 let lvs =
380   let lvs = Array.to_list (g#lvs ()) in
381
382   let lvs = List.map (
383     fun name ->
384       let typ = get_partition_content name in
385       assert (match typ with ContentPV _ -> false | _ -> true);
386
387       { lv_name = name; lv_type = typ; lv_operation = LVOpNone }
388   ) lvs in
389
390   if debug then (
391     eprintf "%d logical volumes found\n" (List.length lvs);
392     List.iter debug_logvol lvs
393   );
394
395   lvs
396
397 (* These functions tell us if we know how to expand the content of
398  * a particular partition or LV, and what method to use.
399  *)
400 type expand_content_method =
401   | PVResize | Resize2fs | NTFSResize | BtrfsFilesystemResize
402
403 let string_of_expand_content_method = function
404   | PVResize -> "pvresize"
405   | Resize2fs -> "resize2fs"
406   | NTFSResize -> "ntfsresize"
407   | BtrfsFilesystemResize -> "btrfs-filesystem-resize"
408
409 let can_expand_content =
410   if expand_content then
411     function
412     | ContentUnknown -> false
413     | ContentPV _ -> true
414     | ContentFS (("ext2"|"ext3"|"ext4"), _) -> true
415     | ContentFS (("ntfs"), _) when !ntfs_available -> true
416     | ContentFS (("btrfs"), _) when !btrfs_available -> true
417     | ContentFS (_, _) -> false
418   else
419     fun _ -> false
420
421 let expand_content_method =
422   if expand_content then
423     function
424     | ContentUnknown -> assert false
425     | ContentPV _ -> PVResize
426     | ContentFS (("ext2"|"ext3"|"ext4"), _) -> Resize2fs
427     | ContentFS (("ntfs"), _) when !ntfs_available -> NTFSResize
428     | ContentFS (("btrfs"), _) when !btrfs_available -> BtrfsFilesystemResize
429     | ContentFS (_, _) -> assert false
430   else
431     fun _ -> assert false
432
433 (* Helper function to locate a partition given what the user might
434  * type on the command line.  It also gives errors for partitions
435  * that the user has asked to be ignored or deleted.
436  *)
437 let find_partition =
438   let hash = Hashtbl.create 13 in
439   List.iter (fun ({ p_name = name } as p) -> Hashtbl.add hash name p)
440     partitions;
441   fun ~option name ->
442     let name =
443       if String.length name < 5 || String.sub name 0 5 <> "/dev/" then
444         "/dev/" ^ name
445       else
446         name in
447     let name = canonicalize name in
448
449     let partition =
450       try Hashtbl.find hash name
451       with Not_found ->
452         error "%s: partition not found in the source disk image (this error came from '%s' option on the command line).  Try running this command: virt-filesystems --partitions --long -a %s"
453           name option infile in
454
455     if partition.p_operation = OpIgnore then
456       error "%s: partition already ignored, you cannot use it in '%s' option"
457         name option;
458
459     if partition.p_operation = OpDelete then
460       error "%s: partition already deleted, you cannot use it in '%s' option"
461         name option;
462
463     partition
464
465 (* Handle --ignore option. *)
466 let () =
467   List.iter (
468     fun dev ->
469       let p = find_partition ~option:"--ignore" dev in
470       p.p_operation <- OpIgnore
471   ) ignores
472
473 (* Handle --delete option. *)
474 let () =
475   List.iter (
476     fun dev ->
477       let p = find_partition ~option:"--delete" dev in
478       p.p_operation <- OpDelete
479   ) deletes
480
481 (* Helper function to mark a partition for resizing.  It prevents the
482  * user from trying to mark the same partition twice.  If the force
483  * flag is given, then we will allow the user to shrink the partition
484  * even if we think that would destroy the content.
485  *)
486 let mark_partition_for_resize ~option ?(force = false) p newsize =
487   let name = p.p_name in
488   let oldsize = p.p_size in
489
490   (match p.p_operation with
491    | OpResize _ ->
492        error "%s: this partition has already been marked for resizing"
493          name
494    | OpIgnore | OpDelete ->
495        (* This error should have been caught already by find_partition ... *)
496        error "%s: this partition has already been ignored or deleted"
497          name
498    | OpCopy -> ()
499   );
500
501   (* Only do something if the size will change. *)
502   if oldsize <> newsize then (
503     let bigger = newsize > oldsize in
504
505     if not bigger && not force then (
506       (* Check if this contains filesystem content, and how big that is
507        * and whether we will destroy any content by shrinking this.
508        *)
509       match p.p_type with
510       | ContentUnknown ->
511           error "%s: This partition has unknown content which might be damaged by shrinking it.  If you want to shrink this partition, you need to use the '--resize-force' option, but that could destroy any data on this partition.  (This error came from '%s' option on the command line.)"
512             name option
513       | ContentPV size when size > newsize ->
514           error "%s: This partition has contains an LVM physical volume which will be damaged by shrinking it below %Ld bytes (user asked to shrink it to %Ld bytes).  If you want to shrink this partition, you need to use the '--resize-force' option, but that could destroy any data on this partition.  (This error came from '%s' option on the command line.)"
515             name size newsize option
516       | ContentPV _ -> ()
517       | ContentFS (fstype, size) when size > newsize ->
518           error "%s: This partition has contains a %s filesystem which will be damaged by shrinking it below %Ld bytes (user asked to shrink it to %Ld bytes).  If you want to shrink this partition, you need to use the '--resize-force' option, but that could destroy any data on this partition.  (This error came from '%s' option on the command line.)"
519             name fstype size newsize option
520       | ContentFS _ -> ()
521     );
522
523     p.p_operation <- OpResize newsize
524   )
525
526 (* Handle --resize and --resize-force options. *)
527 let () =
528   let do_resize ~option ?(force = false) arg =
529     (* Argument is "dev=size". *)
530     let dev, sizefield =
531       try
532         let i = String.index arg '=' in
533         let n = String.length arg - (i+1) in
534         if n == 0 then raise Not_found;
535         String.sub arg 0 i, String.sub arg (i+1) n
536       with Not_found ->
537         error "%s: missing size field in '%s' option" arg option in
538
539     let p = find_partition ~option dev in
540
541     (* Parse the size field. *)
542     let oldsize = p.p_size in
543     let newsize = parse_size oldsize sizefield in
544
545     if newsize <= 0L then
546       error "%s: new partition size is zero or negative" dev;
547
548     mark_partition_for_resize ~option ~force p newsize
549   in
550
551   List.iter (do_resize ~option:"--resize") resizes;
552   List.iter (do_resize ~option:"--resize-force" ~force:true) resizes_force
553
554 (* Helper function calculates the surplus space, given the total
555  * required so far for the current partition layout, compared to
556  * the size of the target disk.  If the return value >= 0 then it's
557  * a surplus, if it is < 0 then it's a deficit.
558  *)
559 let calculate_surplus () =
560   (* We need some overhead for partitioning.  Worst case would be for
561    * EFI partitioning + massive per-partition alignment.
562    *)
563   let nr_partitions = List.length partitions in
564   let overhead = (Int64.of_int sectsize) *^ (
565     2L *^ 64L +^                                 (* GPT start and end *)
566     (64L *^ (Int64.of_int (nr_partitions + 1)))  (* Maximum alignment *)
567   ) +^
568   (Int64.of_int (max_bootloader - 64 * 512)) in  (* Bootloader *)
569
570   let required = List.fold_left (
571     fun total p ->
572       let newsize =
573         match p.p_operation with
574         | OpCopy | OpIgnore -> p.p_size
575         | OpDelete -> 0L
576         | OpResize newsize -> newsize in
577       total +^ newsize
578   ) 0L partitions in
579
580   outsize -^ (required +^ overhead)
581
582 (* Handle --expand and --shrink options. *)
583 let () =
584   if expand <> None && shrink <> None then
585     error "you cannot use options --expand and --shrink together";
586
587   if expand <> None || shrink <> None then (
588     let surplus = calculate_surplus () in
589
590     if debug then
591       eprintf "surplus before --expand or --shrink: %Ld\n" surplus;
592
593     (match expand with
594      | None -> ()
595      | Some dev ->
596          if surplus < 0L then
597            error "You cannot use --expand when there is no surplus space to expand into.  You need to make the target disk larger by at least %s."
598              (human_size (Int64.neg surplus));
599
600          let option = "--expand" in
601          let p = find_partition ~option dev in
602          let oldsize = p.p_size in
603          mark_partition_for_resize ~option p (oldsize +^ surplus)
604     );
605     (match shrink with
606      | None -> ()
607      | Some dev ->
608          if surplus > 0L then
609            error "You cannot use --shrink when there is no deficit (see 'deficit' in the virt-resize(1) man page).";
610
611          let option = "--shrink" in
612          let p = find_partition ~option dev in
613          let oldsize = p.p_size in
614          mark_partition_for_resize ~option p (oldsize +^ surplus)
615     )
616   )
617
618 (* Calculate the final surplus.
619  * At this point, this number must be >= 0.
620  *)
621 let surplus =
622   let surplus = calculate_surplus () in
623
624   if surplus < 0L then (
625     let deficit = Int64.neg surplus in
626     error "There is a deficit of %Ld bytes (%s).  You need to make the target disk larger by at least this amount or adjust your resizing requests."
627       deficit (human_size deficit)
628   );
629
630   surplus
631
632 (* Mark the --lv-expand LVs. *)
633 let () =
634   let hash = Hashtbl.create 13 in
635   List.iter (fun ({ lv_name = name } as lv) -> Hashtbl.add hash name lv) lvs;
636
637   List.iter (
638     fun name ->
639       let lv =
640         try Hashtbl.find hash name
641         with Not_found ->
642           error "%s: logical volume not found in the source disk image (this error came from '--lv-expand' option on the command line).  Try running this command: virt-filesystems --logical-volumes --long -a %s"
643             name infile in
644       lv.lv_operation <- LVOpExpand
645   ) lv_expands
646
647 (* Print a summary of what we will do. *)
648 let () =
649   flush stderr;
650
651   if not quiet then (
652     printf "**********\n\n";
653     printf "Summary of changes:\n\n";
654
655     List.iter (
656       fun ({ p_name = name; p_size = oldsize } as p) ->
657         let text =
658           match p.p_operation with
659           | OpCopy ->
660               sprintf "%s: This partition will be left alone." name
661           | OpIgnore ->
662               sprintf "%s: This partition will be created, but the contents will be ignored (ie. not copied to the target)." name
663           | OpDelete ->
664               sprintf "%s: This partition will be deleted." name
665           | OpResize newsize ->
666               sprintf "%s: This partition will be resized from %s to %s."
667                 name (human_size oldsize) (human_size newsize) ^
668               if can_expand_content p.p_type then (
669                 sprintf "  The %s on %s will be expanded using the '%s' method."
670                   (string_of_partition_content_no_size p.p_type)
671                   name
672                   (string_of_expand_content_method
673                      (expand_content_method p.p_type))
674               ) else "" in
675
676         wrap ~hanging:4 (text ^ "\n\n")
677     ) partitions;
678
679     List.iter (
680       fun ({ lv_name = name } as lv) ->
681         match lv.lv_operation with
682         | LVOpNone -> ()
683         | LVOpExpand ->
684             let text =
685               sprintf "%s: This logical volume will be expanded to maximum size."
686                 name ^
687               if can_expand_content lv.lv_type then (
688                 sprintf "  The %s on %s will be expanded using the '%s' method."
689                   (string_of_partition_content_no_size lv.lv_type)
690                   name
691                   (string_of_expand_content_method
692                      (expand_content_method lv.lv_type))
693               ) else "" in
694
695             wrap ~hanging:4 (text ^ "\n\n")
696     ) lvs;
697
698     if surplus > 0L then (
699       let text =
700         sprintf "There is a surplus of %s." (human_size surplus) ^
701         if extra_partition then (
702           if surplus >= min_extra_partition then
703             sprintf "  An extra partition will be created for the surplus."
704           else
705             sprintf "  The surplus space is not large enough for an extra partition to be created and so it will just be ignored."
706         ) else
707           sprintf "  The surplus space will be ignored.  Run a partitioning program in the guest to partition this extra space if you want." in
708
709       wrap (text ^ "\n\n")
710     );
711
712     printf "**********\n";
713     flush stdout
714   );
715
716   if dryrun then exit 0
717
718 (* Create a partition table.
719  *
720  * We *must* do this before copying the bootloader across, and copying
721  * the bootloader must be careful not to disturb this partition table
722  * (RHBZ#633766).  There are two reasons for this:
723  *
724  * (1) The 'parted' library is stupid and broken.  In many ways.  In
725  * this particular instance the stupid and broken bit is that it
726  * overwrites the whole boot sector when initializating a partition
727  * table.  (Upstream don't consider this obvious problem to be a bug).
728  *
729  * (2) GPT has a backup partition table located at the end of the disk.
730  * It's non-movable, because the primary GPT contains fixed references
731  * to both the size of the disk and the backup partition table at the
732  * end.  This would be a problem for any resize that didn't either
733  * carefully move the backup GPT (and rewrite those references) or
734  * recreate the whole partition table from scratch.
735  *)
736 let g, parttype =
737   let parttype = g#part_get_parttype "/dev/sda" in
738   if debug then eprintf "partition table type: %s\n%!" parttype;
739
740   (* Try hard to initialize the partition table.  This might involve
741    * relaunching another handle.
742    *)
743   if not quiet then
744     printf "Setting up initial partition table on %s ...\n%!" outfile;
745
746   let last_error = ref "" in
747   let rec initialize_partition_table g attempts =
748     let ok =
749       try g#part_init "/dev/sdb" parttype; true
750       with G.Error error -> last_error := error; false in
751     if ok then g, true
752     else if attempts > 0 then (
753       g#zero "/dev/sdb";
754       g#sync ();
755       g#close ();
756
757       let g = connect_both_disks () in
758       initialize_partition_table g (attempts-1)
759     )
760     else g, false
761   in
762
763   let g, ok = initialize_partition_table g 5 in
764   if not ok then
765     error "Failed to initialize the partition table on the target disk.  You need to wipe or recreate the target disk and then run virt-resize again.\n\nThe underlying error was: %s" !last_error;
766
767   g, parttype
768
769 (* Copy the bootloader across.
770  * Don't disturb the partition table that we just wrote.
771  * https://secure.wikimedia.org/wikipedia/en/wiki/Master_Boot_Record
772  * https://secure.wikimedia.org/wikipedia/en/wiki/GUID_Partition_Table
773  *)
774 let () =
775   if copy_boot_loader then (
776     let bootsect = g#pread_device "/dev/sda" 446 0L in
777     if String.length bootsect < 446 then
778       error "pread-device: short read";
779     ignore (g#pwrite_device "/dev/sdb" bootsect 0L);
780
781     let start =
782       if parttype <> "gpt" then 512L
783       else
784         (* XXX With 4K sectors does GPT just fit more entries in a
785          * sector, or does it always use 34 sectors?
786          *)
787         17408L in
788
789     let loader = g#pread_device "/dev/sda" max_bootloader start in
790     if String.length loader < max_bootloader then
791       error "pread-device: short read";
792     ignore (g#pwrite_device "/dev/sdb" loader start)
793   )
794
795 (* Repartition the target disk. *)
796 let () =
797   (* The first partition must start at the same position as the old
798    * first partition.  Old virt-resize used to align this to 64
799    * sectors, but I suspect this is the cause of boot failures, so
800    * let's not do this.
801    *)
802   let sectsize = Int64.of_int sectsize in
803   let start = ref ((List.hd partitions).p_part.G.part_start /^ sectsize) in
804
805   (* This counts the partition numbers on the target disk. *)
806   let nextpart = ref 1 in
807
808   let rec repartition = function
809     | [] -> ()
810     | p :: ps ->
811         let target_partnum =
812           match p.p_operation with
813           | OpDelete -> None            (* do nothing *)
814           | OpIgnore | OpCopy ->        (* new partition, same size *)
815               (* Size in sectors. *)
816               let size = (p.p_size +^ sectsize -^ 1L) /^ sectsize in
817               Some (add_partition size)
818           | OpResize newsize ->         (* new partition, resized *)
819               (* Size in sectors. *)
820               let size = (newsize +^ sectsize -^ 1L) /^ sectsize in
821               Some (add_partition size) in
822
823         (match target_partnum with
824          | None ->                      (* OpDelete *)
825              ()
826          | Some target_partnum ->       (* not OpDelete *)
827              p.p_target_partnum <- target_partnum;
828
829              (* Set bootable and MBR IDs *)
830              if p.p_bootable then
831                g#part_set_bootable "/dev/sdb" target_partnum true;
832
833              (match p.p_mbr_id with
834               | None -> ()
835               | Some mbr_id ->
836                   g#part_set_mbr_id "/dev/sdb" target_partnum mbr_id
837              );
838         );
839
840         repartition ps
841
842   (* Add a partition, returns the partition number on the target. *)
843   and add_partition size (* in SECTORS *) =
844     let target_partnum, end_ =
845       if !nextpart <= 3 || parttype <> "msdos" then (
846         let target_partnum = !nextpart in
847         let end_ = !start +^ size -^ 1L in
848         g#part_add "/dev/sdb" "primary" !start end_;
849         incr nextpart;
850         target_partnum, end_
851       ) else (
852         if !nextpart = 4 then (
853           g#part_add "/dev/sdb" "extended" !start (-1L);
854           incr nextpart;
855           start := !start +^ 64L
856         );
857         let target_partnum = !nextpart in
858         let end_ = !start +^ size -^ 1L in
859         g#part_add "/dev/sdb" "logical" !start end_;
860         incr nextpart;
861         target_partnum, end_
862       ) in
863
864     (* Start of next partition + alignment to 64 sectors. *)
865     start := ((end_ +^ 1L) +^ 63L) &^ (~^ 63L);
866
867     target_partnum
868   in
869
870   repartition partitions;
871
872   (* Create the surplus partition. *)
873   if extra_partition && surplus >= min_extra_partition then (
874     let size = outsize /^ sectsize -^ 64L -^ !start in
875     ignore (add_partition size)
876   )
877
878 (* Copy over the data. *)
879 let () =
880   let rec copy_data = function
881     | [] -> ()
882
883     | ({ p_name = source; p_target_partnum = target_partnum;
884          p_operation = (OpCopy | OpResize _) } as p) :: ps
885         when target_partnum > 0 ->
886         let oldsize = p.p_size in
887         let newsize =
888           match p.p_operation with OpResize s -> s | _ -> oldsize in
889
890         let copysize = if newsize < oldsize then newsize else oldsize in
891
892         let target = sprintf "/dev/sdb%d" target_partnum in
893
894         if not quiet then
895           printf "Copying %s ...\n%!" source;
896
897         g#copy_size source target copysize;
898
899         copy_data ps
900
901     | _ :: ps ->
902         copy_data ps
903   in
904
905   copy_data partitions
906
907 (* After copying the data over we must shut down and restart the
908  * appliance in order to expand the content.  The reason for this may
909  * not be obvious, but it's because otherwise we'll have duplicate VGs
910  * (the old VG(s) and the new VG(s)) which breaks LVM.
911  *
912  * The restart is only required if we're going to expand something.
913  *)
914 let to_be_expanded =
915   List.exists (
916     function
917     | ({ p_operation = OpResize _ } as p) -> can_expand_content p.p_type
918     | _ -> false
919   ) partitions
920   || List.exists (
921     function
922     | ({ lv_operation = LVOpExpand } as lv) -> can_expand_content lv.lv_type
923     | _ -> false
924   ) lvs
925
926 let g =
927   if to_be_expanded then (
928     g#umount_all ();
929     g#sync ();
930     g#close ();
931
932     let g = new G.guestfs () in
933     if debug then g#set_trace true;
934     g#add_drive_opts ?format:output_format ~readonly:false outfile;
935     if not quiet then Progress.set_up_progress_bar ~machine_readable g;
936     g#launch ();
937
938     g (* Return new handle. *)
939   )
940   else g (* Return existing handle. *)
941
942 let () =
943   if to_be_expanded then (
944     (* Helper function to expand partition or LV content. *)
945     let do_expand_content target = function
946       | PVResize -> g#pvresize target
947       | Resize2fs ->
948           g#e2fsck_f target;
949           g#resize2fs target
950       | NTFSResize -> g#ntfsresize_opts ~force:ntfsresize_force target
951       | BtrfsFilesystemResize ->
952           (* Complicated ...  Btrfs forces us to mount the filesystem
953            * in order to resize it.
954            *)
955           assert (Array.length (g#mounts ()) = 0);
956           g#mount_options "" target "/";
957           g#btrfs_filesystem_resize "/";
958           g#umount "/"
959     in
960
961     (* Expand partition content as required. *)
962     List.iter (
963       function
964       | ({ p_operation = OpResize _ } as p) when can_expand_content p.p_type ->
965           let source = p.p_name in
966           let target = sprintf "/dev/sda%d" p.p_target_partnum in
967           let meth = expand_content_method p.p_type in
968
969           if not quiet then
970             printf "Expanding %s%s using the '%s' method ...\n%!"
971               source
972               (if source <> target then sprintf " (now %s)" target else "")
973               (string_of_expand_content_method meth);
974
975           do_expand_content target meth
976       | _ -> ()
977     ) partitions;
978
979     (* Expand logical volume content as required. *)
980     List.iter (
981       function
982       | ({ lv_operation = LVOpExpand } as lv) when can_expand_content lv.lv_type ->
983           let name = lv.lv_name in
984           let meth = expand_content_method lv.lv_type in
985
986           if not quiet then
987             printf "Expanding %s using the '%s' method ...\n%!"
988               name
989               (string_of_expand_content_method meth);
990
991           (* First expand the LV itself to maximum size. *)
992           g#lvresize_free name 100;
993
994           (* Then expand the content in the LV. *)
995           do_expand_content name meth
996       | _ -> ()
997     ) lvs
998   )
999
1000 (* Finished.  Unmount disks and exit. *)
1001 let () =
1002   g#umount_all ();
1003   g#sync ();
1004   g#close ();
1005
1006   if not quiet then (
1007     print_newline ();
1008     wrap "Resize operation completed with no errors.  Before deleting the old disk, carefully check that the resized disk boots and works correctly.\n";
1009   );
1010
1011   exit 0