1 package PVE
::Storage
::Plugin
;
12 use PVE
::Tools
qw(run_command);
13 use PVE
::JSONSchema
qw(get_standard_option register_standard_option);
14 use PVE
::Cluster
qw(cfs_register_file);
18 use base
qw(PVE::SectionConfig);
20 use constant COMPRESSOR_RE
=> 'gz|lzo|zst';
22 our @COMMON_TAR_FLAGS = qw(
24 -p --sparse --numeric-owner --acls
25 --xattrs --xattrs-include=user.* --xattrs-include=security.capability
26 --warning=no-file-ignored --warning=no-xattr-write
29 our @SHARED_STORAGE = (
40 our $MAX_VOLUMES_PER_GUEST = 1024;
42 cfs_register_file
('storage.cfg',
43 sub { __PACKAGE__-
>parse_config(@_); },
44 sub { __PACKAGE__-
>write_config(@_); });
48 type
=> 'integer', minimum
=> '0',
49 format_description
=> 'N',
52 my $prune_backups_format = {
55 description
=> 'Keep the last <N> backups.',
59 description
=> 'Keep backups for the last <N> different hours. If there is more' .
60 'than one backup for a single hour, only the latest one is kept.'
64 description
=> 'Keep backups for the last <N> different days. If there is more' .
65 'than one backup for a single day, only the latest one is kept.'
69 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
70 'than one backup for a single week, only the latest one is kept.'
74 description
=> 'Keep backups for the last <N> different months. If there is more' .
75 'than one backup for a single month, only the latest one is kept.'
79 description
=> 'Keep backups for the last <N> different years. If there is more' .
80 'than one backup for a single year, only the latest one is kept.'
83 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format, \
&validate_prune_backups
);
84 sub validate_prune_backups
{
87 die "at least one keep-option must be set and positive\n"
88 if !grep { $_ } values %{$keep};
92 register_standard_option
('prune-backups', {
93 description
=> "The retention options with shorter intervals are processed first " .
94 "with --keep-last being the very first one. Each option covers a " .
95 "specific period of time. We say that backups within this period " .
96 "are covered by this option. The next option does not take care " .
97 "of already covered backups and only considers older backups.",
100 format
=> 'prune-backups',
105 type
=> { description
=> "Storage type." },
106 storage
=> get_standard_option
('pve-storage-id',
107 { completion
=> \
&PVE
::Storage
::complete_storage
}),
108 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
110 description
=> "Allowed content types.\n\nNOTE: the value " .
111 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
112 type
=> 'string', format
=> 'pve-storage-content-list',
114 completion
=> \
&PVE
::Storage
::complete_content_type
,
117 description
=> "Flag to disable the storage.",
122 description
=> "Maximal number of backup files per VM. Use '0' for unlimted.",
127 'prune-backups' => get_standard_option
('prune-backups'),
129 description
=> "Mark storage as shared.",
134 description
=> "Default image format.",
135 type
=> 'string', format
=> 'pve-storage-format',
141 sub content_hash_to_string
{
145 foreach my $ct (keys %$hash) {
146 push @cta, $ct if $hash->{$ct};
149 return join(',', @cta);
152 sub valid_content_types
{
155 my $def = $defaultData->{plugindata
}->{$type};
159 return $def->{content
}->[0];
165 my $type = $scfg->{type
};
166 my $def = $defaultData->{plugindata
}->{$type};
168 my $def_format = 'raw';
169 my $valid_formats = [ $def_format ];
171 if (defined($def->{format
})) {
172 $def_format = $scfg->{format
} || $def->{format
}->[1];
173 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
176 return wantarray ?
($def_format, $valid_formats) : $def_format;
179 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
181 my ($path, $noerr) = @_;
183 # fixme: exclude more shell meta characters?
184 # we need absolute paths
185 if ($path !~ m
|^/[^;\
(\
)]+|) {
186 return undef if $noerr;
187 die "value does not look like a valid absolute path\n";
192 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
194 my ($server, $noerr) = @_;
196 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
197 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
199 return undef if $noerr;
200 die "value does not look like a valid server name or IP address\n";
205 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
207 my ($name, $noerr) = @_;
209 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
210 return undef if $noerr;
211 die "lvm name '$name' contains illegal characters\n";
217 # fixme: do we need this
218 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
220 # my ($portal, $noerr) = @_;
222 # # IP with optional port
223 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
224 # return undef if $noerr;
225 # die "value does not look like a valid portal address\n";
230 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
231 sub verify_portal_dns
{
232 my ($portal, $noerr) = @_;
234 # IP or DNS name with optional port
235 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
236 return undef if $noerr;
237 die "value does not look like a valid portal address\n";
242 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
244 my ($ct, $noerr) = @_;
246 my $valid_content = valid_content_types
('dir'); # dir includes all types
248 if (!$valid_content->{$ct}) {
249 return undef if $noerr;
250 die "invalid content type '$ct'\n";
256 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
258 my ($fmt, $noerr) = @_;
260 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
261 return undef if $noerr;
262 die "invalid format '$fmt'\n";
268 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
270 my ($value, $noerr) = @_;
272 # mount options (see man fstab)
273 if ($value !~ m/^\S+$/) {
274 return undef if $noerr;
275 die "invalid options '$value'\n";
281 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
282 sub parse_volume_id
{
283 my ($volid, $noerr) = @_;
285 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
286 return wantarray ?
($1, $2) : $1;
288 return undef if $noerr;
289 die "unable to parse volume ID '$volid'\n";
297 sub parse_section_header
{
298 my ($class, $line) = @_;
300 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
301 my ($type, $storeid) = (lc($1), $2);
302 my $errmsg = undef; # set if you want to skip whole section
303 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
305 my $config = {}; # to return additional attributes
306 return ($type, $storeid, $errmsg, $config);
312 my ($class, $type, $key, $value) = @_;
314 my $def = $defaultData->{plugindata
}->{$type};
316 if ($key eq 'content') {
317 my $valid_content = $def->{content
}->[0];
321 foreach my $c (PVE
::Tools
::split_list
($value)) {
322 if (!$valid_content->{$c}) {
323 warn "storage does not support content type '$c'\n";
329 if ($res->{none
} && scalar (keys %$res) > 1) {
330 die "unable to combine 'none' with other content types\n";
334 } elsif ($key eq 'format') {
335 my $valid_formats = $def->{format
}->[0];
337 if (!$valid_formats->{$value}) {
338 warn "storage does not support format '$value'\n";
343 } elsif ($key eq 'nodes') {
346 foreach my $node (PVE
::Tools
::split_list
($value)) {
347 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
353 # no node restrictions for local storage
354 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
355 # die "storage '$storeid' does not allow node restrictions\n";
365 my ($class, $type, $key, $value) = @_;
367 if ($key eq 'nodes') {
368 return join(',', keys(%$value));
369 } elsif ($key eq 'content') {
370 my $res = content_hash_to_string
($value) || 'none';
378 my ($class, $filename, $raw) = @_;
380 my $cfg = $class->SUPER::parse_config
($filename, $raw);
381 my $ids = $cfg->{ids
};
383 # make sure we have a reasonable 'local:' storage
384 # we want 'local' to be always the same 'type' (on all cluster nodes)
385 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
386 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
389 priority
=> 0, # force first entry
390 path
=> '/var/lib/vz',
392 content
=> { images
=> 1, rootdir
=> 1, vztmpl
=> 1, iso
=> 1, snippets
=> 1},
396 # make sure we have a path
397 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
399 # remove node restrictions for local storage
400 delete($ids->{local}->{nodes
});
402 foreach my $storeid (keys %$ids) {
403 my $d = $ids->{$storeid};
404 my $type = $d->{type
};
406 my $def = $defaultData->{plugindata
}->{$type};
408 if ($def->{content
}) {
409 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
411 if (grep { $_ eq $type } @SHARED_STORAGE) {
419 # Storage implementation
421 # called during addition of storage (before the new storage config got written)
422 # die to abort additon if there are (grave) problems
423 # NOTE: runs in a storage config *locked* context
425 my ($class, $storeid, $scfg, %param) = @_;
427 # do nothing by default
430 # called during storage configuration update (before the updated storage config got written)
431 # die to abort the update if there are (grave) problems
432 # NOTE: runs in a storage config *locked* context
434 my ($class, $storeid, $scfg, %param) = @_;
436 # do nothing by default
439 # called during deletion of storage (before the new storage config got written)
440 # and if the activate check on addition fails, to cleanup all storage traces
441 # which on_add_hook may have created.
442 # die to abort deletion if there are (very grave) problems
443 # NOTE: runs in a storage config *locked* context
445 my ($class, $storeid, $scfg) = @_;
447 # do nothing by default
450 sub cluster_lock_storage
{
451 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
455 my $lockid = "pve-storage-$storeid";
456 my $lockdir = "/var/lock/pve-manager";
458 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
461 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
470 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
471 return ($1, $3, $2); # (name, format, isBase)
474 die "unable to parse volume filename '$name'\n";
478 my ($class, $volname) = @_;
480 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
481 my ($basedvmid, $basename) = ($1, $2);
482 parse_name_dir
($basename);
483 my ($vmid, $name) = ($3, $4);
484 my (undef, $format, $isBase) = parse_name_dir
($name);
485 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
486 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
487 my ($vmid, $name) = ($1, $2);
488 my (undef, $format, $isBase) = parse_name_dir
($name);
489 return ('images', $name, $vmid, undef, undef, $isBase, $format);
490 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
492 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
493 return ('vztmpl', $1);
494 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
495 return ('rootdir', $1, $1);
496 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
498 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
499 return ('backup', $fn, $2);
501 return ('backup', $fn);
502 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
503 return ('snippets', $1);
506 die "unable to parse directory volume name '$volname'\n";
509 my $vtype_subdirs = {
511 rootdir
=> 'private',
512 iso
=> 'template/iso',
513 vztmpl
=> 'template/cache',
515 snippets
=> 'snippets',
518 sub get_vtype_subdirs
{
519 return $vtype_subdirs;
523 my ($class, $scfg, $vtype) = @_;
525 my $path = $scfg->{path
};
527 die "storage definintion has no path\n" if !$path;
529 my $subdir = $vtype_subdirs->{$vtype};
531 die "unknown vtype '$vtype'\n" if !defined($subdir);
533 return "$path/$subdir";
536 sub filesystem_path
{
537 my ($class, $scfg, $volname, $snapname) = @_;
539 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
540 $class->parse_volname($volname);
542 # Note: qcow2/qed has internal snapshot, so path is always
543 # the same (with or without snapshot => same file).
544 die "can't snapshot this image format\n"
545 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
547 my $dir = $class->get_subdir($scfg, $vtype);
549 $dir .= "/$vmid" if $vtype eq 'images';
551 my $path = "$dir/$name";
553 return wantarray ?
($path, $vmid, $vtype) : $path;
557 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
559 return $class->filesystem_path($scfg, $volname, $snapname);
563 my ($class, $storeid, $scfg, $volname) = @_;
565 # this only works for file based storage types
566 die "storage definition has no path\n" if !$scfg->{path
};
568 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
569 $class->parse_volname($volname);
571 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
573 die "create_base not possible with base image\n" if $isBase;
575 my $path = $class->filesystem_path($scfg, $volname);
577 my ($size, undef, $used, $parent) = file_size_info
($path);
578 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
580 die "volname '$volname' contains wrong information about parent\n"
581 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
584 $newname =~ s/^vm-/base-/;
586 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
589 my $newpath = $class->filesystem_path($scfg, $newvolname);
591 die "file '$newpath' already exists\n" if -f
$newpath;
593 rename($path, $newpath) ||
594 die "rename '$path' to '$newpath' failed - $!\n";
596 # We try to protect base volume
598 chmod(0444, $newpath); # nobody should write anything
600 # also try to set immutable flag
601 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
607 my $get_vm_disk_number = sub {
608 my ($disk_name, $scfg, $vmid, $suffix) = @_;
610 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
612 my $type = $scfg->{type
};
613 my $def = { %{$defaultData->{plugindata
}->{$type}} };
615 my $valid = $def->{format
}[0];
616 if ($valid->{subvol
}) {
617 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
620 if ($disk_name =~ m/$disk_regex/) {
627 sub get_next_vm_diskname
{
628 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
631 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
632 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
635 foreach my $disk (@$disk_list) {
636 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
637 $disk_ids->{$disknum} = 1 if defined($disknum);
640 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
641 if (!$disk_ids->{$i}) {
642 return "$prefix-$vmid-disk-$i$suffix";
646 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
649 sub find_free_diskname
{
650 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
652 my $disks = $class->list_images($storeid, $scfg, $vmid);
654 my $disk_list = [ map { $_->{volid
} } @$disks ];
656 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
660 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
662 # this only works for file based storage types
663 die "storage definintion has no path\n" if !$scfg->{path
};
665 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
666 $class->parse_volname($volname);
668 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
670 die "this storage type does not support clone_image on snapshot\n" if $snap;
672 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
674 die "clone_image only works on base images\n" if !$isBase;
676 my $imagedir = $class->get_subdir($scfg, 'images');
677 $imagedir .= "/$vmid";
681 my $name = $class->find_free_diskname($imagedir, $scfg, $vmid, "qcow2", 1);
683 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
685 my $newvol = "$basevmid/$basename/$vmid/$name";
687 my $path = $class->filesystem_path($scfg, $newvol);
689 # Note: we use relative paths, so we need to call chdir before qemu-img
691 local $CWD = $imagedir;
693 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
694 '-f', 'qcow2', $path];
706 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
708 my $imagedir = $class->get_subdir($scfg, 'images');
709 $imagedir .= "/$vmid";
713 $name = $class->find_free_diskname($imagedir, $scfg, $vmid, $fmt, 1) if !$name;
715 my (undef, $tmpfmt) = parse_name_dir
($name);
717 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
720 my $path = "$imagedir/$name";
722 die "disk image '$path' already exists\n" if -e
$path;
724 if ($fmt eq 'subvol') {
725 # only allow this if size = 0, so that user knows what he is doing
726 die "storage does not support subvol quotas\n" if $size != 0;
728 my $old_umask = umask(0022);
730 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
734 my $cmd = ['/usr/bin/qemu-img', 'create'];
736 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
738 push @$cmd, '-f', $fmt, $path, "${size}K";
740 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
748 return "$vmid/$name";
752 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
754 my $path = $class->filesystem_path($scfg, $volname);
757 # try to remove immutable flag
758 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
762 if (defined($format) && ($format eq 'subvol')) {
763 File
::Path
::remove_tree
($path);
765 if (!(-f
$path || -l
$path)) {
766 warn "disk image '$path' does not exist\n";
770 unlink($path) || die "unlink '$path' failed - $!\n";
773 # try to cleanup directory to not clutter storage with empty $vmid dirs if
774 # all images from a guest got deleted
775 my $dir = dirname
($path);
782 my ($filename, $timeout) = @_;
784 my $st = File
::stat::stat($filename);
786 if (S_ISDIR
($st->mode)) {
787 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
792 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
794 outfunc
=> sub { $json .= shift },
795 errfunc
=> sub { warn "$_[0]\n" }
800 my $info = eval { decode_json
($json) };
801 warn "could not parse qemu-img info command output for '$filename'\n" if $@;
803 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
805 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
808 sub volume_size_info
{
809 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
810 my $path = $class->filesystem_path($scfg, $volname);
811 return file_size_info
($path, $timeout);
816 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
818 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
820 return 1 if $running;
822 my $path = $class->filesystem_path($scfg, $volname);
824 my $format = ($class->parse_volname($volname))[6];
826 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
828 run_command
($cmd, timeout
=> 10);
833 sub volume_snapshot
{
834 my ($class, $scfg, $storeid, $volname, $snap) = @_;
836 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
838 my $path = $class->filesystem_path($scfg, $volname);
840 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
847 sub volume_rollback_is_possible
{
848 my ($class, $scfg, $storeid, $volname, $snap) = @_;
853 sub volume_snapshot_rollback
{
854 my ($class, $scfg, $storeid, $volname, $snap) = @_;
856 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
858 my $path = $class->filesystem_path($scfg, $volname);
860 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
867 sub volume_snapshot_delete
{
868 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
870 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
872 return 1 if $running;
874 my $path = $class->filesystem_path($scfg, $volname);
876 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
878 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
885 sub storage_can_replicate
{
886 my ($class, $scfg, $storeid, $format) = @_;
891 sub volume_has_feature
{
892 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
895 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
896 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
897 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
898 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
899 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
900 snap
=> {qcow2
=> 1} },
901 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
902 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
905 # clone_image creates a qcow2 volume
906 return 0 if $feature eq 'clone' &&
907 defined($opts->{valid_target_formats
}) &&
908 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
910 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
911 $class->parse_volname($volname);
917 $key = $isBase ?
'base' : 'current';
920 return 1 if defined($features->{$feature}->{$key}->{$format});
926 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
928 my $imagedir = $class->get_subdir($scfg, 'images');
930 my ($defFmt, $vaidFmts) = default_format
($scfg);
931 my $fmts = join ('|', @$vaidFmts);
935 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
937 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
943 next if !$vollist && defined($vmid) && ($owner ne $vmid);
945 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
946 next if !($format && defined($size));
949 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
950 my ($basevmid, $basename) = ($1, $2);
951 $volid = "$storeid:$basevmid/$basename/$owner/$name";
953 $volid = "$storeid:$owner/$name";
957 my $found = grep { $_ eq $volid } @$vollist;
962 volid
=> $volid, format
=> $format,
963 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
966 $info->{ctime
} = $ctime if $ctime;
974 # list templates ($tt = <iso|vztmpl|backup|snippets>)
975 my $get_subdir_files = sub {
976 my ($sid, $path, $tt, $vmid) = @_;
980 foreach my $fn (<$path/*>) {
982 my $st = File
::stat::stat($fn);
984 next if (!$st || S_ISDIR
($st->mode));
989 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
991 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
993 } elsif ($tt eq 'vztmpl') {
994 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
996 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
998 } elsif ($tt eq 'backup') {
999 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1000 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1003 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1005 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1007 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1009 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1010 $info->{vmid
} = $vmid // $1;
1013 } elsif ($tt eq 'snippets') {
1016 volid
=> "$sid:snippets/". basename
($fn),
1017 format
=> 'snippet',
1021 $info->{size
} = $st->size;
1022 $info->{ctime
} //= $st->ctime;
1031 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1034 my $vmlist = PVE
::Cluster
::get_vmlist
();
1035 foreach my $type (@$content_types) {
1038 if ($type eq 'images' || $type eq 'rootdir') {
1039 $data = $class->list_images($storeid, $scfg, $vmid);
1040 } elsif ($scfg->{path
}) {
1041 my $path = $class->get_subdir($scfg, $type);
1043 if ($type eq 'iso' && !defined($vmid)) {
1044 $data = $get_subdir_files->($storeid, $path, 'iso');
1045 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1046 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1047 } elsif ($type eq 'backup') {
1048 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1049 } elsif ($type eq 'snippets') {
1050 $data = $get_subdir_files->($storeid, $path, 'snippets');
1056 foreach my $item (@$data) {
1057 if ($type eq 'images' || $type eq 'rootdir') {
1058 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1060 if (defined($vminfo)) {
1061 $vmtype = $vminfo->{type
};
1063 if (defined($vmtype) && $vmtype eq 'lxc') {
1064 $item->{content
} = 'rootdir';
1066 $item->{content
} = 'images';
1068 next if $type ne $item->{content
};
1070 $item->{content
} = $type;
1081 my ($class, $storeid, $scfg, $cache) = @_;
1083 my $path = $scfg->{path
};
1085 die "storage definintion has no path\n" if !$path;
1088 my $res = PVE
::Tools
::df
($path, $timeout);
1090 return undef if !$res || !$res->{total
};
1092 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1095 sub volume_snapshot_list
{
1096 my ($class, $scfg, $storeid, $volname) = @_;
1098 # implement in subclass
1099 die "Volume_snapshot_list is not implemented for $class";
1101 # return an empty array if dataset does not exist.
1104 sub activate_storage
{
1105 my ($class, $storeid, $scfg, $cache) = @_;
1107 my $path = $scfg->{path
};
1109 die "storage definintion has no path\n" if !$path;
1111 # this path test may hang indefinitely on unresponsive mounts
1113 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1114 die "unable to activate storage '$storeid' - " .
1115 "directory '$path' does not exist or is unreachable\n";
1119 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1121 if (defined($scfg->{content
})) {
1122 foreach my $vtype (keys %$vtype_subdirs) {
1123 # OpenVZMigrate uses backup (dump) dir
1124 if (defined($scfg->{content
}->{$vtype}) ||
1125 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1126 my $subdir = $class->get_subdir($scfg, $vtype);
1127 mkpath
$subdir if $subdir ne $path;
1133 sub deactivate_storage
{
1134 my ($class, $storeid, $scfg, $cache) = @_;
1136 # do nothing by default
1140 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1142 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1147 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1152 sub activate_volume
{
1153 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1155 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1157 # check is volume exists
1158 if ($scfg->{path
}) {
1159 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1161 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1165 sub deactivate_volume
{
1166 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1168 # do nothing by default
1171 sub check_connection
{
1172 my ($class, $storeid, $scfg) = @_;
1173 # do nothing by default
1178 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1180 $logfunc //= sub { print "$_[1]\n" };
1182 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1184 my $backup_groups = {};
1185 my $prune_list = [];
1187 foreach my $backup (@{$backups}) {
1188 my $volid = $backup->{volid
};
1189 my $backup_vmid = $backup->{vmid
};
1190 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1191 my $backup_type = $archive_info->{type
} // 'unknown';
1193 next if defined($type) && $type ne $backup_type;
1196 ctime
=> $backup->{ctime
},
1197 type
=> $backup_type,
1201 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1203 if ($archive_info->{is_std_name
}) {
1204 $prune_entry->{ctime
} = $archive_info->{ctime
};
1205 my $group = "$backup_type/$backup_vmid";
1206 push @{$backup_groups->{$group}}, $prune_entry;
1208 # ignore backups that don't use the standard naming scheme
1209 $prune_entry->{mark
} = 'protected';
1212 push @{$prune_list}, $prune_entry;
1215 foreach my $backup_group (values %{$backup_groups}) {
1216 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1221 foreach my $prune_entry (@{$prune_list}) {
1222 next if $prune_entry->{mark
} ne 'remove';
1224 my $volid = $prune_entry->{volid
};
1225 $logfunc->('info', "removing backup '$volid'");
1227 my (undef, $volname) = parse_volume_id
($volid);
1228 my $archive_path = $class->filesystem_path($scfg, $volname);
1229 PVE
::Storage
::archive_remove
($archive_path);
1232 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1237 die "error pruning backups - check log\n" if $failed;
1242 # Import/Export interface:
1243 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1244 # the default implementations will return this if $scfg->{path} is set,
1245 # mimicking the old PVE::Storage::storage_migrate() function.
1247 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1248 # functions in case the format doesn't match their specialized
1249 # implementations to reuse the raw/tar code.
1251 # Format specification:
1252 # The following formats are all prefixed with image information in the form
1253 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1254 # to preallocate the image on storages which require it.
1256 # raw+size: (image files only)
1257 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1258 # qcow2+size, vmdk: (image files only)
1259 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1260 # files which are already in qcow2 format, or via `qemu-img convert`.
1261 # Note that these formats are only valid with $with_snapshots being true.
1262 # tar+size: (subvolumes only)
1263 # A GNU tar stream containing just the inner contents of the subvolume.
1264 # This does not distinguish between the contents of a privileged or
1265 # unprivileged container. In other words, this is from the root user
1266 # namespace's point of view with no uid-mapping in effect.
1267 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1269 # Plugins may reuse these helpers. Changes to the header format should be
1270 # reflected by changes to the function prototypes.
1271 sub write_common_header
($$) {
1272 my ($fh, $image_size_in_bytes) = @_;
1273 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1276 sub read_common_header
($) {
1278 sysread($fh, my $size, 8);
1279 $size = unpack('Q<', $size);
1280 die "import: no size found in export header, aborting.\n" if !defined($size);
1281 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1286 # Export a volume into a file handle as a stream of desired format.
1288 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1289 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1290 my $file = $class->path($scfg, $volname, $storeid)
1291 or goto unsupported
;
1292 my ($size, $file_format) = file_size_info
($file);
1294 if ($format eq 'raw+size') {
1295 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1296 write_common_header
($fh, $size);
1297 if ($file_format eq 'raw') {
1298 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1300 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1301 output
=> '>&'.fileno($fh));
1304 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1305 my $data_format = $1;
1306 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1307 write_common_header
($fh, $size);
1308 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1310 } elsif ($format eq 'tar+size') {
1311 goto unsupported
if $file_format ne 'subvol';
1312 write_common_header
($fh, $size);
1313 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1314 output
=> '>&'.fileno($fh));
1319 die "volume export format $format not available for $class";
1322 sub volume_export_formats
{
1323 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1324 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1325 my $file = $class->path($scfg, $volname, $storeid)
1327 my ($size, $format) = file_size_info
($file);
1329 if ($with_snapshots) {
1330 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1333 return ('tar+size') if $format eq 'subvol';
1334 return ('raw+size');
1339 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1341 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1343 die "volume import format '$format' not available for $class\n"
1344 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1345 my $data_format = $1;
1347 die "format $format cannot be imported without snapshots\n"
1348 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1349 die "format $format cannot be imported with snapshots\n"
1350 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1352 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1353 $class->parse_volname($volname);
1355 # XXX: Should we bother with conversion routines at this level? This won't
1356 # happen without manual CLI usage, so for now we just error out...
1357 die "cannot import format $format into a file of format $file_format\n"
1358 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1360 # Check for an existing file first since interrupting alloc_image doesn't
1362 my $file = $class->path($scfg, $volname, $storeid);
1364 die "file '$file' already exists\n" if !$allow_rename;
1365 warn "file '$file' already exists - importing with a different name\n";
1369 my ($size) = read_common_header
($fh);
1370 $size = int($size/1024);
1373 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1374 my $oldname = $volname;
1375 $volname = $allocname;
1376 if (defined($name) && $allocname ne $oldname) {
1377 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1379 my $file = $class->path($scfg, $volname, $storeid)
1380 or die "internal error: failed to get path to newly allocated volume $volname\n";
1381 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1382 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1383 input
=> '<&'.fileno($fh));
1384 } elsif ($data_format eq 'tar') {
1385 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1386 input
=> '<&'.fileno($fh));
1388 die "volume import format '$format' not available for $class";
1392 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1397 return "$storeid:$volname";
1400 sub volume_import_formats
{
1401 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1402 if ($scfg->{path
} && !defined($base_snapshot)) {
1403 my $format = ($class->parse_volname($volname))[6];
1404 if ($with_snapshots) {
1405 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1408 return ('tar+size') if $format eq 'subvol';
1409 return ('raw+size');