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