Skip to content

Instantly share code, notes, and snippets.

@windli2018
Created August 24, 2020 23:39
Show Gist options
  • Select an option

  • Save windli2018/9c505df9cdc21498fe2d79e04e1def0b to your computer and use it in GitHub Desktop.

Select an option

Save windli2018/9c505df9cdc21498fe2d79e04e1def0b to your computer and use it in GitHub Desktop.
used in shrink xfs filesystem
#!/usr/bin/perl -T
# Get from https://xfs.org/index.php/Shrinking_Support with some small fix to support lvm
use strict;
use warnings;
my $fd;
$ENV{PATH} = "/usr/sbin";
$ENV{LC_ALL} = "C";
my $XFSDB = "xfs_db";
sub help { print "Usage: freecount.pl device\n"; }
sub read_param {
my $param = shift or die;
my ($key, $val) = split(/ = /, <$fd>);
my $regex = quotemeta($param);
die "desired $param not received" unless $key =~ /$regex/;
return $val;
}
unless (@ARGV == 1) { help && exit }
my $dev = pop @ARGV;
# untaint
if ($dev =~ m!^(\/dev\/.*)$!) { $dev = $1 } else { help && exit }
open($fd, "$XFSDB -r -c 'sb' -c 'p agcount' -c 'p blocksize' $dev |")
or die "Can't open xfs_db: $!\n";
my ($agcount, $blksize) = map { read_param $_ } qw/agcount blocksize/;
close($fd);
my $free = 0;
for (my $i = 0; $i < $agcount; $i++) {
open($fd, "$XFSDB -r -c 'agf $i' -c 'p freeblks' -c 'p btreeblks' $dev |")
or die "Can't open xfs_db: $!\n";
# discount the space used in btreeblks from the free space
$free += read_param("freeblks") - read_param("btreeblks");
close($fd);
}
$free *= $blksize / (1024 ** 2);
print "$free M\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment