Skip to content

Instantly share code, notes, and snippets.

@Ranlvor
Last active May 25, 2018 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ranlvor/2958bb4e7c9906717a7f55330ba95654 to your computer and use it in GitHub Desktop.
Save Ranlvor/2958bb4e7c9906717a7f55330ba95654 to your computer and use it in GitHub Desktop.
<?php
//do not use this. zfs list -o name,referenced,usedbysnapshots does the same thing without php hackery.
function startsWith($string, $query) {
return substr($string, 0, strlen($query)) === $query;
}
function calculateChileUsed($value, $output) {
$name = $value['name']."/"; //echo "\n\n\n".$name."\n";
$children = array_filter($output, function ($v) use($name) { return startsWith($v['name'], $name); });
$directChildren = array_filter($children, function ($v) use($name) { return strpos(str_replace($name, "", $v['name']), "/") === false; });
//print_r($directChildren);
$childUsed = array_reduce($directChildren, function($carry, $item) { return $carry + $item['used']; }, 0);
return $childUsed;
}
function toHuman($size) {
if($size < 1000*10) {
return $size." B";
} else if ($size < 1000*1024*10) {
return round($size / 1024 ) . " KiB";
} else if ($size < 1000*1024*1024*10) {
return round($size / (1024*1024) ) . " MiB";
} else {
return round($size / (1024*1024*1024) ) . " GiB";
}
}
$output = array();
exec("sudo zfs list -Hp", $output);
$output = array_map(function ($value) { return explode("\t", $value); }, $output);
$output = array_map(function ($value) { return array("name" => $value[0], "used" => $value[1], "ref" => $value[3]); }, $output);
$output = array_map(function ($value) use($output) { $value['childUsed'] = calculateChileUsed($value, $output); return $value; }, $output);
$output = array_map(function ($value) { $value['snap'] = $value['used'] - $value['ref'] - $value['childUsed']; return $value; }, $output);
$maxLength = array_reduce(array_map(function ($value) { return strlen($value['name']); }, $output), "max");
//print_r($output);
echo str_pad("NAME", $maxLength+2).str_pad("Ref", 10, " ", STR_PAD_LEFT).str_pad("Snap", 10, " ", STR_PAD_LEFT)."\n";
foreach($output as $value) {
echo str_pad($value['name'], $maxLength+2).
str_pad(toHuman($value['ref']),10, " ", STR_PAD_LEFT).
str_pad(toHuman($value['snap']),10, " ", STR_PAD_LEFT).
"\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment