[pve-devel] [PATCH guest-common 1/3] reformat code for snapshot tree into GuestHelpers

Oguz Bektas o.bektas at proxmox.com
Tue Oct 1 09:34:38 CEST 2019


correction: s/reformat/refactor

On Tue, Oct 01, 2019 at 09:32:45AM +0200, Oguz Bektas wrote:
> qm/pct listsnapshot lack feature parity w.r.t. showing snapshots in a
> tree ordered by the date. by moving this code into GuestHelpers, it can
> be shared.
> 
> Signed-off-by: Oguz Bektas <o.bektas at proxmox.com>
> ---
>  PVE/GuestHelpers.pm | 54 +++++++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 54 insertions(+)
> 
> diff --git a/PVE/GuestHelpers.pm b/PVE/GuestHelpers.pm
> index ebe2781..64e26c9 100644
> --- a/PVE/GuestHelpers.pm
> +++ b/PVE/GuestHelpers.pm
> @@ -6,6 +6,8 @@ use warnings;
>  use PVE::Tools;
>  use PVE::Storage;
>  
> +use POSIX qw(strftime);
> +
>  # We use a separate lock to block migration while a replication job
>  # is running.
>  
> @@ -60,4 +62,56 @@ sub exec_hookscript {
>      }
>  }
>  
> +sub snapshot_tree {
> +    my ($res) = @_;
> +
> +    my $snapshots = { map { $_->{name} => $_ } @$res };
> +
> +    my @roots;
> +    foreach my $e (@$res) {
> +	my $parent;
> +	if (($parent = $e->{parent}) && defined $snapshots->{$parent}) {
> +	    push @{$snapshots->{$parent}->{children}}, $e->{name};
> +	} else {
> +	    push @roots, $e->{name};
> +	}
> +    }
> +
> +    # sort the elements by snaptime - with "current" (no snaptime) highest
> +    my $snaptimesort = sub {
> +	return +1 if !defined $snapshots->{$a}->{snaptime};
> +	return -1 if !defined $snapshots->{$b}->{snaptime};
> +	return $snapshots->{$a}->{snaptime} <=> $snapshots->{$b}->{snaptime};
> +    };
> +
> +    # recursion function for displaying the tree
> +    my $snapshottree;
> +    $snapshottree = sub {
> +	my ($prefix, $root, $snapshots) = @_;
> +	my $e = $snapshots->{$root};
> +
> +	my $description = $e->{description} || 'no-description';
> +	($description) = $description =~ m/(.*)$/m;
> +
> +	my $timestring = "";
> +	if (defined $e->{snaptime}) {
> +	    $timestring = strftime("%F %H:%M:%S", localtime($e->{snaptime}));
> +	}
> +
> +	my $len = 30 - length($prefix); # for aligning the description
> +	printf("%s %-${len}s %-23s %s\n", $prefix, $root, $timestring, $description);
> +
> +	if ($e->{children}) {
> +	    $prefix = "    $prefix";
> +	    foreach my $child (sort $snaptimesort @{$e->{children}}) {
> +		$snapshottree->($prefix, $child, $snapshots);
> +	    }
> +	}
> +    };
> +
> +    foreach my $root (sort $snaptimesort @roots) {
> +	$snapshottree->('`->', $root, $snapshots);
> +    }
> +}
> +
>  1;
> -- 
> 2.20.1
> 
> 




More information about the pve-devel mailing list