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 use constant COMMENT_EXT
=> ".comment";
24 our @COMMON_TAR_FLAGS = qw(
26 -p --sparse --numeric-owner --acls
27 --xattrs --xattrs-include=user.* --xattrs-include=security.capability
28 --warning=no-file-ignored --warning=no-xattr-write
31 our @SHARED_STORAGE = (
42 our $MAX_VOLUMES_PER_GUEST = 1024;
44 cfs_register_file
('storage.cfg',
45 sub { __PACKAGE__-
>parse_config(@_); },
46 sub { __PACKAGE__-
>write_config(@_); });
50 type
=> 'integer', minimum
=> '0',
51 format_description
=> 'N',
54 our $prune_backups_format = {
57 description
=> 'Keep the last <N> backups.',
61 description
=> 'Keep backups for the last <N> different hours. If there is more' .
62 'than one backup for a single hour, only the latest one is kept.'
66 description
=> 'Keep backups for the last <N> different days. If there is more' .
67 'than one backup for a single day, only the latest one is kept.'
71 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
72 'than one backup for a single week, only the latest one is kept.'
76 description
=> 'Keep backups for the last <N> different months. If there is more' .
77 'than one backup for a single month, only the latest one is kept.'
81 description
=> 'Keep backups for the last <N> different years. If there is more' .
82 'than one backup for a single year, only the latest one is kept.'
85 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format);
86 register_standard_option
('prune-backups', {
87 description
=> "The retention options with shorter intervals are processed first " .
88 "with --keep-last being the very first one. Each option covers a " .
89 "specific period of time. We say that backups within this period " .
90 "are covered by this option. The next option does not take care " .
91 "of already covered backups and only considers older backups.",
94 format
=> 'prune-backups',
99 type
=> { description
=> "Storage type." },
100 storage
=> get_standard_option
('pve-storage-id',
101 { completion
=> \
&PVE
::Storage
::complete_storage
}),
102 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
104 description
=> "Allowed content types.\n\nNOTE: the value " .
105 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
106 type
=> 'string', format
=> 'pve-storage-content-list',
108 completion
=> \
&PVE
::Storage
::complete_content_type
,
111 description
=> "Flag to disable the storage.",
116 description
=> "Maximal number of backup files per VM. Use '0' for unlimted.",
121 'prune-backups' => get_standard_option
('prune-backups'),
123 description
=> "Mark storage as shared.",
128 description
=> "Default image format.",
129 type
=> 'string', format
=> 'pve-storage-format',
135 sub content_hash_to_string
{
139 foreach my $ct (keys %$hash) {
140 push @cta, $ct if $hash->{$ct};
143 return join(',', @cta);
146 sub valid_content_types
{
149 my $def = $defaultData->{plugindata
}->{$type};
153 return $def->{content
}->[0];
159 my $type = $scfg->{type
};
160 my $def = $defaultData->{plugindata
}->{$type};
162 my $def_format = 'raw';
163 my $valid_formats = [ $def_format ];
165 if (defined($def->{format
})) {
166 $def_format = $scfg->{format
} || $def->{format
}->[1];
167 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
170 return wantarray ?
($def_format, $valid_formats) : $def_format;
173 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
175 my ($path, $noerr) = @_;
177 # fixme: exclude more shell meta characters?
178 # we need absolute paths
179 if ($path !~ m
|^/[^;\
(\
)]+|) {
180 return undef if $noerr;
181 die "value does not look like a valid absolute path\n";
186 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
188 my ($server, $noerr) = @_;
190 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
191 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
193 return undef if $noerr;
194 die "value does not look like a valid server name or IP address\n";
199 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
201 my ($name, $noerr) = @_;
203 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
204 return undef if $noerr;
205 die "lvm name '$name' contains illegal characters\n";
211 # fixme: do we need this
212 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
214 # my ($portal, $noerr) = @_;
216 # # IP with optional port
217 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
218 # return undef if $noerr;
219 # die "value does not look like a valid portal address\n";
224 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
225 sub verify_portal_dns
{
226 my ($portal, $noerr) = @_;
228 # IP or DNS name with optional port
229 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
230 return undef if $noerr;
231 die "value does not look like a valid portal address\n";
236 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
238 my ($ct, $noerr) = @_;
240 my $valid_content = valid_content_types
('dir'); # dir includes all types
242 if (!$valid_content->{$ct}) {
243 return undef if $noerr;
244 die "invalid content type '$ct'\n";
250 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
252 my ($fmt, $noerr) = @_;
254 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
255 return undef if $noerr;
256 die "invalid format '$fmt'\n";
262 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
264 my ($value, $noerr) = @_;
266 # mount options (see man fstab)
267 if ($value !~ m/^\S+$/) {
268 return undef if $noerr;
269 die "invalid options '$value'\n";
275 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
276 sub parse_volume_id
{
277 my ($volid, $noerr) = @_;
279 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
280 return wantarray ?
($1, $2) : $1;
282 return undef if $noerr;
283 die "unable to parse volume ID '$volid'\n";
291 sub parse_section_header
{
292 my ($class, $line) = @_;
294 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
295 my ($type, $storeid) = (lc($1), $2);
296 my $errmsg = undef; # set if you want to skip whole section
297 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
299 my $config = {}; # to return additional attributes
300 return ($type, $storeid, $errmsg, $config);
306 my ($class, $type, $key, $value) = @_;
308 my $def = $defaultData->{plugindata
}->{$type};
310 if ($key eq 'content') {
311 my $valid_content = $def->{content
}->[0];
315 foreach my $c (PVE
::Tools
::split_list
($value)) {
316 if (!$valid_content->{$c}) {
317 warn "storage does not support content type '$c'\n";
323 if ($res->{none
} && scalar (keys %$res) > 1) {
324 die "unable to combine 'none' with other content types\n";
328 } elsif ($key eq 'format') {
329 my $valid_formats = $def->{format
}->[0];
331 if (!$valid_formats->{$value}) {
332 warn "storage does not support format '$value'\n";
337 } elsif ($key eq 'nodes') {
340 foreach my $node (PVE
::Tools
::split_list
($value)) {
341 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
347 # no node restrictions for local storage
348 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
349 # die "storage '$storeid' does not allow node restrictions\n";
359 my ($class, $type, $key, $value) = @_;
361 if ($key eq 'nodes') {
362 return join(',', keys(%$value));
363 } elsif ($key eq 'content') {
364 my $res = content_hash_to_string
($value) || 'none';
372 my ($class, $filename, $raw) = @_;
374 my $cfg = $class->SUPER::parse_config
($filename, $raw);
375 my $ids = $cfg->{ids
};
377 # make sure we have a reasonable 'local:' storage
378 # we want 'local' to be always the same 'type' (on all cluster nodes)
379 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
380 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
383 priority
=> 0, # force first entry
384 path
=> '/var/lib/vz',
386 content
=> { images
=> 1, rootdir
=> 1, vztmpl
=> 1, iso
=> 1, snippets
=> 1},
390 # make sure we have a path
391 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
393 # remove node restrictions for local storage
394 delete($ids->{local}->{nodes
});
396 foreach my $storeid (keys %$ids) {
397 my $d = $ids->{$storeid};
398 my $type = $d->{type
};
400 my $def = $defaultData->{plugindata
}->{$type};
402 if ($def->{content
}) {
403 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
405 if (grep { $_ eq $type } @SHARED_STORAGE) {
413 # Storage implementation
415 # called during addition of storage (before the new storage config got written)
416 # die to abort additon if there are (grave) problems
417 # NOTE: runs in a storage config *locked* context
419 my ($class, $storeid, $scfg, %param) = @_;
421 # do nothing by default
425 # called during storage configuration update (before the updated storage config got written)
426 # die to abort the update if there are (grave) problems
427 # NOTE: runs in a storage config *locked* context
429 my ($class, $storeid, $scfg, %param) = @_;
431 # do nothing by default
435 # called during deletion of storage (before the new storage config got written)
436 # and if the activate check on addition fails, to cleanup all storage traces
437 # which on_add_hook may have created.
438 # die to abort deletion if there are (very grave) problems
439 # NOTE: runs in a storage config *locked* context
441 my ($class, $storeid, $scfg) = @_;
443 # do nothing by default
447 sub cluster_lock_storage
{
448 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
452 my $lockid = "pve-storage-$storeid";
453 my $lockdir = "/var/lock/pve-manager";
455 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
458 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
467 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
468 return ($1, $3, $2); # (name, format, isBase)
471 die "unable to parse volume filename '$name'\n";
475 my ($class, $volname) = @_;
477 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
478 my ($basedvmid, $basename) = ($1, $2);
479 parse_name_dir
($basename);
480 my ($vmid, $name) = ($3, $4);
481 my (undef, $format, $isBase) = parse_name_dir
($name);
482 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
483 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
484 my ($vmid, $name) = ($1, $2);
485 my (undef, $format, $isBase) = parse_name_dir
($name);
486 return ('images', $name, $vmid, undef, undef, $isBase, $format);
487 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
489 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
490 return ('vztmpl', $1);
491 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
492 return ('rootdir', $1, $1);
493 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
495 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
496 return ('backup', $fn, $2);
498 return ('backup', $fn);
499 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
500 return ('snippets', $1);
503 die "unable to parse directory volume name '$volname'\n";
506 my $vtype_subdirs = {
508 rootdir
=> 'private',
509 iso
=> 'template/iso',
510 vztmpl
=> 'template/cache',
512 snippets
=> 'snippets',
515 sub get_vtype_subdirs
{
516 return $vtype_subdirs;
520 my ($class, $scfg, $vtype) = @_;
522 my $path = $scfg->{path
};
524 die "storage definintion has no path\n" if !$path;
526 my $subdir = $vtype_subdirs->{$vtype};
528 die "unknown vtype '$vtype'\n" if !defined($subdir);
530 return "$path/$subdir";
533 sub filesystem_path
{
534 my ($class, $scfg, $volname, $snapname) = @_;
536 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
537 $class->parse_volname($volname);
539 # Note: qcow2/qed has internal snapshot, so path is always
540 # the same (with or without snapshot => same file).
541 die "can't snapshot this image format\n"
542 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
544 my $dir = $class->get_subdir($scfg, $vtype);
546 $dir .= "/$vmid" if $vtype eq 'images';
548 my $path = "$dir/$name";
550 return wantarray ?
($path, $vmid, $vtype) : $path;
554 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
556 return $class->filesystem_path($scfg, $volname, $snapname);
560 my ($class, $storeid, $scfg, $volname) = @_;
562 # this only works for file based storage types
563 die "storage definition has no path\n" if !$scfg->{path
};
565 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
566 $class->parse_volname($volname);
568 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
570 die "create_base not possible with base image\n" if $isBase;
572 my $path = $class->filesystem_path($scfg, $volname);
574 my ($size, undef, $used, $parent) = file_size_info
($path);
575 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
577 die "volname '$volname' contains wrong information about parent\n"
578 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
581 $newname =~ s/^vm-/base-/;
583 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
586 my $newpath = $class->filesystem_path($scfg, $newvolname);
588 die "file '$newpath' already exists\n" if -f
$newpath;
590 rename($path, $newpath) ||
591 die "rename '$path' to '$newpath' failed - $!\n";
593 # We try to protect base volume
595 chmod(0444, $newpath); # nobody should write anything
597 # also try to set immutable flag
598 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
604 my $get_vm_disk_number = sub {
605 my ($disk_name, $scfg, $vmid, $suffix) = @_;
607 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
609 my $type = $scfg->{type
};
610 my $def = { %{$defaultData->{plugindata
}->{$type}} };
612 my $valid = $def->{format
}[0];
613 if ($valid->{subvol
}) {
614 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
617 if ($disk_name =~ m/$disk_regex/) {
624 sub get_next_vm_diskname
{
625 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
628 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
629 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
632 foreach my $disk (@$disk_list) {
633 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
634 $disk_ids->{$disknum} = 1 if defined($disknum);
637 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
638 if (!$disk_ids->{$i}) {
639 return "$prefix-$vmid-disk-$i$suffix";
643 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
646 sub find_free_diskname
{
647 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
649 my $disks = $class->list_images($storeid, $scfg, $vmid);
651 my $disk_list = [ map { $_->{volid
} } @$disks ];
653 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
657 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
659 # this only works for file based storage types
660 die "storage definintion has no path\n" if !$scfg->{path
};
662 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
663 $class->parse_volname($volname);
665 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
667 die "this storage type does not support clone_image on snapshot\n" if $snap;
669 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
671 die "clone_image only works on base images\n" if !$isBase;
673 my $imagedir = $class->get_subdir($scfg, 'images');
674 $imagedir .= "/$vmid";
678 my $name = $class->find_free_diskname($imagedir, $scfg, $vmid, "qcow2", 1);
680 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
682 my $newvol = "$basevmid/$basename/$vmid/$name";
684 my $path = $class->filesystem_path($scfg, $newvol);
686 # Note: we use relative paths, so we need to call chdir before qemu-img
688 local $CWD = $imagedir;
690 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
691 '-f', 'qcow2', $path];
703 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
705 my $imagedir = $class->get_subdir($scfg, 'images');
706 $imagedir .= "/$vmid";
710 $name = $class->find_free_diskname($imagedir, $scfg, $vmid, $fmt, 1) if !$name;
712 my (undef, $tmpfmt) = parse_name_dir
($name);
714 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
717 my $path = "$imagedir/$name";
719 die "disk image '$path' already exists\n" if -e
$path;
721 if ($fmt eq 'subvol') {
722 # only allow this if size = 0, so that user knows what he is doing
723 die "storage does not support subvol quotas\n" if $size != 0;
725 my $old_umask = umask(0022);
727 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
731 my $cmd = ['/usr/bin/qemu-img', 'create'];
733 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
735 push @$cmd, '-f', $fmt, $path, "${size}K";
737 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
745 return "$vmid/$name";
749 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
751 my $path = $class->filesystem_path($scfg, $volname);
754 # try to remove immutable flag
755 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
759 if (defined($format) && ($format eq 'subvol')) {
760 File
::Path
::remove_tree
($path);
762 if (!(-f
$path || -l
$path)) {
763 warn "disk image '$path' does not exist\n";
767 unlink($path) || die "unlink '$path' failed - $!\n";
770 # try to cleanup directory to not clutter storage with empty $vmid dirs if
771 # all images from a guest got deleted
772 my $dir = dirname
($path);
779 my ($filename, $timeout) = @_;
781 my $st = File
::stat::stat($filename);
784 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
785 warn "failed to stat '$filename'$extramsg\n";
789 if (S_ISDIR
($st->mode)) {
790 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
795 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
797 outfunc
=> sub { $json .= shift },
798 errfunc
=> sub { warn "$_[0]\n" }
803 my $info = eval { decode_json
($json) };
804 warn "could not parse qemu-img info command output for '$filename'\n" if $@;
806 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
808 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
811 sub volume_size_info
{
812 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
813 my $path = $class->filesystem_path($scfg, $volname);
814 return file_size_info
($path, $timeout);
819 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
821 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
823 return 1 if $running;
825 my $path = $class->filesystem_path($scfg, $volname);
827 my $format = ($class->parse_volname($volname))[6];
829 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
831 run_command
($cmd, timeout
=> 10);
836 sub volume_snapshot
{
837 my ($class, $scfg, $storeid, $volname, $snap) = @_;
839 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
841 my $path = $class->filesystem_path($scfg, $volname);
843 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
850 sub volume_rollback_is_possible
{
851 my ($class, $scfg, $storeid, $volname, $snap) = @_;
856 sub volume_snapshot_rollback
{
857 my ($class, $scfg, $storeid, $volname, $snap) = @_;
859 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
861 my $path = $class->filesystem_path($scfg, $volname);
863 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
870 sub volume_snapshot_delete
{
871 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
873 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
875 return 1 if $running;
877 my $path = $class->filesystem_path($scfg, $volname);
879 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
881 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
888 sub volume_snapshot_needs_fsfreeze
{
892 sub storage_can_replicate
{
893 my ($class, $scfg, $storeid, $format) = @_;
898 sub volume_has_feature
{
899 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
902 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
903 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
904 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
905 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
906 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
907 snap
=> {qcow2
=> 1} },
908 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
909 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
912 # clone_image creates a qcow2 volume
913 return 0 if $feature eq 'clone' &&
914 defined($opts->{valid_target_formats
}) &&
915 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
917 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
918 $class->parse_volname($volname);
924 $key = $isBase ?
'base' : 'current';
927 return 1 if defined($features->{$feature}->{$key}->{$format});
933 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
935 my $imagedir = $class->get_subdir($scfg, 'images');
937 my ($defFmt, $vaidFmts) = default_format
($scfg);
938 my $fmts = join ('|', @$vaidFmts);
942 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
944 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
950 next if !$vollist && defined($vmid) && ($owner ne $vmid);
952 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
953 next if !($format && defined($size));
956 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
957 my ($basevmid, $basename) = ($1, $2);
958 $volid = "$storeid:$basevmid/$basename/$owner/$name";
960 $volid = "$storeid:$owner/$name";
964 my $found = grep { $_ eq $volid } @$vollist;
969 volid
=> $volid, format
=> $format,
970 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
973 $info->{ctime
} = $ctime if $ctime;
981 # list templates ($tt = <iso|vztmpl|backup|snippets>)
982 my $get_subdir_files = sub {
983 my ($sid, $path, $tt, $vmid) = @_;
987 foreach my $fn (<$path/*>) {
988 my $st = File
::stat::stat($fn);
990 next if (!$st || S_ISDIR
($st->mode));
995 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
997 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
999 } elsif ($tt eq 'vztmpl') {
1000 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
1002 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1004 } elsif ($tt eq 'backup') {
1005 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1006 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1010 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1012 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1014 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1016 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1017 $info->{vmid
} = $vmid // $1;
1020 my $comment_fn = $original.COMMENT_EXT
;
1021 if (-f
$comment_fn) {
1022 my $comment = PVE
::Tools
::file_read_firstline
($comment_fn);
1023 $info->{comment
} = $comment if defined($comment);
1026 } elsif ($tt eq 'snippets') {
1029 volid
=> "$sid:snippets/". basename
($fn),
1030 format
=> 'snippet',
1034 $info->{size
} = $st->size;
1035 $info->{ctime
} //= $st->ctime;
1044 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1047 my $vmlist = PVE
::Cluster
::get_vmlist
();
1048 foreach my $type (@$content_types) {
1051 if ($type eq 'images' || $type eq 'rootdir') {
1052 $data = $class->list_images($storeid, $scfg, $vmid);
1053 } elsif ($scfg->{path
}) {
1054 my $path = $class->get_subdir($scfg, $type);
1056 if ($type eq 'iso' && !defined($vmid)) {
1057 $data = $get_subdir_files->($storeid, $path, 'iso');
1058 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1059 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1060 } elsif ($type eq 'backup') {
1061 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1062 } elsif ($type eq 'snippets') {
1063 $data = $get_subdir_files->($storeid, $path, 'snippets');
1069 foreach my $item (@$data) {
1070 if ($type eq 'images' || $type eq 'rootdir') {
1071 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1073 if (defined($vminfo)) {
1074 $vmtype = $vminfo->{type
};
1076 if (defined($vmtype) && $vmtype eq 'lxc') {
1077 $item->{content
} = 'rootdir';
1079 $item->{content
} = 'images';
1081 next if $type ne $item->{content
};
1083 $item->{content
} = $type;
1094 my ($class, $storeid, $scfg, $cache) = @_;
1096 my $path = $scfg->{path
};
1098 die "storage definintion has no path\n" if !$path;
1101 my $res = PVE
::Tools
::df
($path, $timeout);
1103 return undef if !$res || !$res->{total
};
1105 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1108 sub volume_snapshot_list
{
1109 my ($class, $scfg, $storeid, $volname) = @_;
1111 # implement in subclass
1112 die "Volume_snapshot_list is not implemented for $class";
1114 # return an empty array if dataset does not exist.
1117 sub activate_storage
{
1118 my ($class, $storeid, $scfg, $cache) = @_;
1120 my $path = $scfg->{path
};
1122 die "storage definintion has no path\n" if !$path;
1124 # this path test may hang indefinitely on unresponsive mounts
1126 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1127 die "unable to activate storage '$storeid' - " .
1128 "directory '$path' does not exist or is unreachable\n";
1132 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1134 if (defined($scfg->{content
})) {
1135 foreach my $vtype (keys %$vtype_subdirs) {
1136 # OpenVZMigrate uses backup (dump) dir
1137 if (defined($scfg->{content
}->{$vtype}) ||
1138 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1139 my $subdir = $class->get_subdir($scfg, $vtype);
1140 mkpath
$subdir if $subdir ne $path;
1146 sub deactivate_storage
{
1147 my ($class, $storeid, $scfg, $cache) = @_;
1149 # do nothing by default
1153 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1155 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1160 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1165 sub activate_volume
{
1166 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1168 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1170 # check is volume exists
1171 if ($scfg->{path
}) {
1172 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1174 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1178 sub deactivate_volume
{
1179 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1181 # do nothing by default
1184 sub check_connection
{
1185 my ($class, $storeid, $scfg) = @_;
1186 # do nothing by default
1191 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1193 $logfunc //= sub { print "$_[1]\n" };
1195 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1197 my $backup_groups = {};
1198 my $prune_list = [];
1200 foreach my $backup (@{$backups}) {
1201 my $volid = $backup->{volid
};
1202 my $backup_vmid = $backup->{vmid
};
1203 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1204 my $backup_type = $archive_info->{type
} // 'unknown';
1206 next if defined($type) && $type ne $backup_type;
1209 ctime
=> $backup->{ctime
},
1210 type
=> $backup_type,
1214 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1216 if ($archive_info->{is_std_name
}) {
1217 $prune_entry->{ctime
} = $archive_info->{ctime
};
1218 my $group = "$backup_type/$backup_vmid";
1219 push @{$backup_groups->{$group}}, $prune_entry;
1221 # ignore backups that don't use the standard naming scheme
1222 $prune_entry->{mark
} = 'protected';
1225 push @{$prune_list}, $prune_entry;
1228 foreach my $backup_group (values %{$backup_groups}) {
1229 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1234 foreach my $prune_entry (@{$prune_list}) {
1235 next if $prune_entry->{mark
} ne 'remove';
1237 my $volid = $prune_entry->{volid
};
1238 $logfunc->('info', "removing backup '$volid'");
1240 my (undef, $volname) = parse_volume_id
($volid);
1241 my $archive_path = $class->filesystem_path($scfg, $volname);
1242 PVE
::Storage
::archive_remove
($archive_path);
1245 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1250 die "error pruning backups - check log\n" if $failed;
1255 # Import/Export interface:
1256 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1257 # the default implementations will return this if $scfg->{path} is set,
1258 # mimicking the old PVE::Storage::storage_migrate() function.
1260 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1261 # functions in case the format doesn't match their specialized
1262 # implementations to reuse the raw/tar code.
1264 # Format specification:
1265 # The following formats are all prefixed with image information in the form
1266 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1267 # to preallocate the image on storages which require it.
1269 # raw+size: (image files only)
1270 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1271 # qcow2+size, vmdk: (image files only)
1272 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1273 # files which are already in qcow2 format, or via `qemu-img convert`.
1274 # Note that these formats are only valid with $with_snapshots being true.
1275 # tar+size: (subvolumes only)
1276 # A GNU tar stream containing just the inner contents of the subvolume.
1277 # This does not distinguish between the contents of a privileged or
1278 # unprivileged container. In other words, this is from the root user
1279 # namespace's point of view with no uid-mapping in effect.
1280 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1282 # Plugins may reuse these helpers. Changes to the header format should be
1283 # reflected by changes to the function prototypes.
1284 sub write_common_header
($$) {
1285 my ($fh, $image_size_in_bytes) = @_;
1286 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1289 sub read_common_header
($) {
1291 sysread($fh, my $size, 8);
1292 $size = unpack('Q<', $size);
1293 die "import: no size found in export header, aborting.\n" if !defined($size);
1294 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1299 # Export a volume into a file handle as a stream of desired format.
1301 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1302 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1303 my $file = $class->path($scfg, $volname, $storeid)
1304 or goto unsupported
;
1305 my ($size, $file_format) = file_size_info
($file);
1307 if ($format eq 'raw+size') {
1308 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1309 write_common_header
($fh, $size);
1310 if ($file_format eq 'raw') {
1311 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1313 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1314 output
=> '>&'.fileno($fh));
1317 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1318 my $data_format = $1;
1319 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1320 write_common_header
($fh, $size);
1321 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1323 } elsif ($format eq 'tar+size') {
1324 goto unsupported
if $file_format ne 'subvol';
1325 write_common_header
($fh, $size);
1326 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1327 output
=> '>&'.fileno($fh));
1332 die "volume export format $format not available for $class";
1335 sub volume_export_formats
{
1336 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1337 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1338 my $file = $class->path($scfg, $volname, $storeid)
1340 my ($size, $format) = file_size_info
($file);
1342 if ($with_snapshots) {
1343 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1346 return ('tar+size') if $format eq 'subvol';
1347 return ('raw+size');
1352 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1354 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1356 die "volume import format '$format' not available for $class\n"
1357 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1358 my $data_format = $1;
1360 die "format $format cannot be imported without snapshots\n"
1361 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1362 die "format $format cannot be imported with snapshots\n"
1363 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1365 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1366 $class->parse_volname($volname);
1368 # XXX: Should we bother with conversion routines at this level? This won't
1369 # happen without manual CLI usage, so for now we just error out...
1370 die "cannot import format $format into a file of format $file_format\n"
1371 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1373 # Check for an existing file first since interrupting alloc_image doesn't
1375 my $file = $class->path($scfg, $volname, $storeid);
1377 die "file '$file' already exists\n" if !$allow_rename;
1378 warn "file '$file' already exists - importing with a different name\n";
1382 my ($size) = read_common_header
($fh);
1383 $size = int($size/1024);
1386 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1387 my $oldname = $volname;
1388 $volname = $allocname;
1389 if (defined($name) && $allocname ne $oldname) {
1390 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1392 my $file = $class->path($scfg, $volname, $storeid)
1393 or die "internal error: failed to get path to newly allocated volume $volname\n";
1394 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1395 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1396 input
=> '<&'.fileno($fh));
1397 } elsif ($data_format eq 'tar') {
1398 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1399 input
=> '<&'.fileno($fh));
1401 die "volume import format '$format' not available for $class";
1405 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1410 return "$storeid:$volname";
1413 sub volume_import_formats
{
1414 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1415 if ($scfg->{path
} && !defined($base_snapshot)) {
1416 my $format = ($class->parse_volname($volname))[6];
1417 if ($with_snapshots) {
1418 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1421 return ('tar+size') if $format eq 'subvol';
1422 return ('raw+size');