edit: Add -e 'expr' option to non-interactively apply expression to the file.
[libguestfs.git] / tools / virt-df
1 #!/usr/bin/perl -w
2 # virt-df
3 # Copyright (C) 2009 Red Hat Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 use warnings;
20 use strict;
21
22 use Sys::Guestfs;
23 use Sys::Guestfs::Lib qw(open_guest get_partitions);
24
25 use Pod::Usage;
26 use Getopt::Long;
27 use Data::Dumper;
28 use XML::Writer;
29 use POSIX qw(ceil);
30
31 use Locale::TextDomain 'libguestfs';
32
33 =encoding utf8
34
35 =head1 NAME
36
37 virt-df - Display free space on virtual filesystems
38
39 =head1 SYNOPSIS
40
41  virt-df [--options]
42
43  virt-df [--options] domname
44
45  virt-df [--options] disk.img [disk.img ...]
46
47 =head1 DESCRIPTION
48
49 C<virt-df> is a command line tool to display free space on virtual
50 machine filesystems.  Unlike other tools, it doesn't just display the
51 amount of space allocated to a virtual machine, but can look inside
52 the virtual machine to see how much space is really being used.
53
54 It is like the L<df(1)> command, but for virtual machines, except that
55 it also works for Windows virtual machines.
56
57 If used without any arguments, C<virt-df> checks with libvirt to get a
58 list of all active and inactive guests, and performs a C<df>-type
59 operation on each one in turn, printing out the results.
60
61 If used with any argument(s), C<virt-df> performs a C<df>-type
62 operation on either the single named libvirt domain, or on the disk
63 image(s) listed on the command line (which must all belong to a single
64 VM).  In this mode (with arguments), C<virt-df> will I<only work for a
65 single guest>.  If you want to run on multiple guests, then you have
66 to invoke C<virt-df> multiple times.
67
68 Use the C<--csv> option to get a format which can be easily parsed by
69 other programs.  Other options are mostly similar to standard C<df>
70 options.  See below for the complete list.
71
72 =head1 OPTIONS
73
74 =over 4
75
76 =cut
77
78 my $help;
79
80 =item B<--help>
81
82 Display brief help.
83
84 =cut
85
86 my $version;
87
88 =item B<--version>
89
90 Display version number and exit.
91
92 =cut
93
94 my $uri;
95
96 =item B<--connect URI> | B<-c URI>
97
98 If using libvirt, connect to the given I<URI>.  If omitted, then we
99 connect to the default libvirt hypervisor.
100
101 If you specify guest block devices directly, then libvirt is not used
102 at all.
103
104 =cut
105
106 my $csv;
107
108 =item B<--csv>
109
110 Write out the results in CSV format (comma-separated values).  This format
111 can be imported easily into databases and spreadsheets, but
112 read L</NOTE ABOUT CSV FORMAT> below.
113
114 =cut
115
116 my $human;
117
118 =item B<--human-readable> | B<-h>
119
120 Print sizes in human-readable format.
121
122 You are not allowed to use I<-h> and I<--csv> at the same time.
123
124 =cut
125
126 my $inodes;
127
128 =item B<--inodes> | B<-i>
129
130 Print inodes instead of blocks.
131
132 =back
133
134 =cut
135
136 GetOptions ("help|?" => \$help,
137             "version" => \$version,
138             "connect|c=s" => \$uri,
139             "csv" => \$csv,
140             "human-readable|human|h" => \$human,
141             "inodes|i" => \$inodes,
142     ) or pod2usage (2);
143 pod2usage (1) if $help;
144 if ($version) {
145     my $g = Sys::Guestfs->new ();
146     my %h = $g->version ();
147     print "$h{major}.$h{minor}.$h{release}$h{extra}\n";
148     exit
149 }
150
151 # RHBZ#600977
152 die __"virt-df: cannot use -h and --csv options together\n" if $human && $csv;
153
154 # Open the guest handle.
155
156 if (@ARGV == 0) {
157     my $conn;
158
159     if ($uri) {
160         $conn = Sys::Virt->new (readonly => 1, address => $uri);
161     } else {
162         $conn = Sys::Virt->new (readonly => 1);
163     }
164
165     my @doms = $conn->list_defined_domains ();
166     push @doms, $conn->list_domains ();
167
168     # https://bugzilla.redhat.com/show_bug.cgi?id=538041
169     @doms = grep { $_->get_id () != 0 } @doms;
170
171     my @domnames = sort (map { $_->get_name () } @doms);
172
173     if (@domnames) {
174         print_title ();
175         foreach (@domnames) {
176             eval { do_df ($_); };
177             warn $@ if $@;
178         }
179     }
180 } else {
181     print_title ();
182     do_df (@ARGV);
183 }
184
185 sub do_df
186 {
187     my $g;
188
189     if ($uri) {
190         $g = open_guest (\@_, address => $uri);
191     } else {
192         $g = open_guest (\@_);
193     }
194
195     $g->launch ();
196
197     my @partitions = get_partitions ($g);
198
199     # Think of a printable name for this domain.  Just choose the
200     # first parameter passed to this function, which will work for
201     # most cases (it'll either be the domain name or the first disk
202     # image name).
203     my $domname = $_[0];
204
205     # Mount each partition in turn, and if mountable, do a statvfs on it.
206     foreach my $partition (@partitions) {
207         my %stat;
208         eval {
209             $g->mount_ro ($partition, "/");
210             %stat = $g->statvfs ("/");
211         };
212         if (!$@) {
213             print_stat ($domname, $partition, \%stat);
214         }
215         $g->umount_all ();
216     }
217 }
218
219 sub print_stat
220 {
221     my $domname = shift;
222     my $partition = shift;
223     my $stat = shift;
224
225     my @cols = ($domname, $partition);
226
227     if (!$inodes) {
228         my $bsize = $stat->{bsize};     # block size
229         my $blocks = $stat->{blocks};   # total number of blocks
230         my $bfree = $stat->{bfree};     # blocks free (total)
231         my $bavail = $stat->{bavail};   # blocks free (for non-root users)
232
233         my $factor = $bsize / 1024;
234
235         push @cols, $blocks*$factor;    # total 1K blocks
236         push @cols, ($blocks-$bfree)*$factor; # total 1K blocks used
237         push @cols, $bavail*$factor;    # total 1K blocks available
238
239         push @cols, 100.0 - 100.0 * $bfree / $blocks;
240
241         if ($human) {
242             $cols[2] = human_size ($cols[2]);
243             $cols[3] = human_size ($cols[3]);
244             $cols[4] = human_size ($cols[4]);
245         }
246     } else {
247         my $files = $stat->{files};     # total number of inodes
248         my $ffree = $stat->{ffree};     # inodes free (total)
249         my $favail = $stat->{favail};   # inodes free (for non-root users)
250
251         push @cols, $files;
252         push @cols, $files-$ffree;
253         push @cols, $ffree;
254
255         push @cols, 100.0 - 100.0 * $ffree / $files;
256     }
257
258     print_cols (@cols);
259 }
260
261 sub print_title
262 {
263     my @cols = (__"Virtual Machine", __"Filesystem");
264     if (!$inodes) {
265         if (!$human) {
266             push @cols, __"1K-blocks";
267         } else {
268             push @cols, __"Size";
269         }
270         push @cols, __"Used";
271         push @cols, __"Available";
272         push @cols, __"Use%";
273     } else {
274         push @cols, __"Inodes";
275         push @cols, __"IUsed";
276         push @cols, __"IFree";
277         push @cols, __"IUse%";
278     }
279
280     if (!$csv) {
281         # ignore $cols[0] in this mode
282         printf "%-36s%10s %10s %10s %5s\n",
283           $cols[1], $cols[2], $cols[3], $cols[4], $cols[5];
284     } else {
285         print (join (",", @cols), "\n");
286     }
287 }
288
289 sub print_cols
290 {
291     if (!$csv) {
292         my $label = sprintf "%s:%s", $_[0], $_[1];
293
294         printf ("%-36s", $label);
295         print "\n"," "x36 if length ($label) > 36;
296
297         # Use 'ceil' on the percentage in order to emulate
298         # what df itself does.
299         my $percent = sprintf "%3d%%", ceil($_[5]);
300
301         printf ("%10s %10s %10s %5s\n", $_[2], $_[3], $_[4], $percent);
302     } else {
303         printf ("\"%s\",\"%s\",%d,%d,%d,%.1f%%\n", @_);
304     }
305 }
306
307 # Convert a number of 1K blocks to a human-readable number.
308 sub human_size
309 {
310     local $_ = shift;
311
312     if ($_ < 1024) {
313         sprintf "%dK", $_;
314     } elsif ($_ < 1024 * 1024) {
315         sprintf "%.1fM", ($_ / 1024);
316     } else {
317         sprintf "%.1fG", ($_ / 1024 / 1024);
318     }
319 }
320
321 =head1 NOTE ABOUT CSV FORMAT
322
323 Comma-separated values (CSV) is a deceptive format.  It I<seems> like
324 it should be easy to parse, but it is definitely not easy to parse.
325
326 Myth: Just split fields at commas.  Reality: This does I<not> work
327 reliably.  This example has two columns:
328
329  "foo,bar",baz
330
331 Myth: Read the file one line at a time.  Reality: This does I<not>
332 work reliably.  This example has one row:
333
334  "foo
335  bar",baz
336
337 For shell scripts, use C<csvtool> (L<http://merjis.com/developers/csv>
338 also packaged in major Linux distributions).
339
340 For other languages, use a CSV processing library (eg. C<Text::CSV>
341 for Perl or Python's built-in csv library).
342
343 Most spreadsheets and databases can import CSV directly.
344
345 =head1 SEE ALSO
346
347 L<guestfs(3)>,
348 L<guestfish(1)>,
349 L<Sys::Guestfs(3)>,
350 L<Sys::Guestfs::Lib(3)>,
351 L<Sys::Virt(3)>,
352 L<http://libguestfs.org/>.
353
354 =head1 AUTHOR
355
356 Richard W.M. Jones L<http://people.redhat.com/~rjones/>
357
358 =head1 COPYRIGHT
359
360 Copyright (C) 2009-2010 Red Hat Inc.
361
362 This program is free software; you can redistribute it and/or modify
363 it under the terms of the GNU General Public License as published by
364 the Free Software Foundation; either version 2 of the License, or
365 (at your option) any later version.
366
367 This program is distributed in the hope that it will be useful,
368 but WITHOUT ANY WARRANTY; without even the implied warranty of
369 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
370 GNU General Public License for more details.
371
372 You should have received a copy of the GNU General Public License
373 along with this program; if not, write to the Free Software
374 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.