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
424 # called during storage configuration update (before the updated storage config got written)
425 # die to abort the update if there are (grave) problems
426 # NOTE: runs in a storage config *locked* context
428 my ($class, $storeid, $scfg, %param) = @_;
430 # do nothing by default
433 # called during deletion of storage (before the new storage config got written)
434 # and if the activate check on addition fails, to cleanup all storage traces
435 # which on_add_hook may have created.
436 # die to abort deletion if there are (very grave) problems
437 # NOTE: runs in a storage config *locked* context
439 my ($class, $storeid, $scfg) = @_;
441 # do nothing by default
444 sub cluster_lock_storage
{
445 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
449 my $lockid = "pve-storage-$storeid";
450 my $lockdir = "/var/lock/pve-manager";
452 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
455 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
464 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
465 return ($1, $3, $2); # (name, format, isBase)
468 die "unable to parse volume filename '$name'\n";
472 my ($class, $volname) = @_;
474 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
475 my ($basedvmid, $basename) = ($1, $2);
476 parse_name_dir
($basename);
477 my ($vmid, $name) = ($3, $4);
478 my (undef, $format, $isBase) = parse_name_dir
($name);
479 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
480 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
481 my ($vmid, $name) = ($1, $2);
482 my (undef, $format, $isBase) = parse_name_dir
($name);
483 return ('images', $name, $vmid, undef, undef, $isBase, $format);
484 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
486 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
487 return ('vztmpl', $1);
488 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
489 return ('rootdir', $1, $1);
490 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
492 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
493 return ('backup', $fn, $2);
495 return ('backup', $fn);
496 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
497 return ('snippets', $1);
500 die "unable to parse directory volume name '$volname'\n";
503 my $vtype_subdirs = {
505 rootdir
=> 'private',
506 iso
=> 'template/iso',
507 vztmpl
=> 'template/cache',
509 snippets
=> 'snippets',
512 sub get_vtype_subdirs
{
513 return $vtype_subdirs;
517 my ($class, $scfg, $vtype) = @_;
519 my $path = $scfg->{path
};
521 die "storage definintion has no path\n" if !$path;
523 my $subdir = $vtype_subdirs->{$vtype};
525 die "unknown vtype '$vtype'\n" if !defined($subdir);
527 return "$path/$subdir";
530 sub filesystem_path
{
531 my ($class, $scfg, $volname, $snapname) = @_;
533 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
534 $class->parse_volname($volname);
536 # Note: qcow2/qed has internal snapshot, so path is always
537 # the same (with or without snapshot => same file).
538 die "can't snapshot this image format\n"
539 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
541 my $dir = $class->get_subdir($scfg, $vtype);
543 $dir .= "/$vmid" if $vtype eq 'images';
545 my $path = "$dir/$name";
547 return wantarray ?
($path, $vmid, $vtype) : $path;
551 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
553 return $class->filesystem_path($scfg, $volname, $snapname);
557 my ($class, $storeid, $scfg, $volname) = @_;
559 # this only works for file based storage types
560 die "storage definition has no path\n" if !$scfg->{path
};
562 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
563 $class->parse_volname($volname);
565 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
567 die "create_base not possible with base image\n" if $isBase;
569 my $path = $class->filesystem_path($scfg, $volname);
571 my ($size, undef, $used, $parent) = file_size_info
($path);
572 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
574 die "volname '$volname' contains wrong information about parent\n"
575 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
578 $newname =~ s/^vm-/base-/;
580 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
583 my $newpath = $class->filesystem_path($scfg, $newvolname);
585 die "file '$newpath' already exists\n" if -f
$newpath;
587 rename($path, $newpath) ||
588 die "rename '$path' to '$newpath' failed - $!\n";
590 # We try to protect base volume
592 chmod(0444, $newpath); # nobody should write anything
594 # also try to set immutable flag
595 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
601 my $get_vm_disk_number = sub {
602 my ($disk_name, $scfg, $vmid, $suffix) = @_;
604 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
606 my $type = $scfg->{type
};
607 my $def = { %{$defaultData->{plugindata
}->{$type}} };
609 my $valid = $def->{format
}[0];
610 if ($valid->{subvol
}) {
611 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
614 if ($disk_name =~ m/$disk_regex/) {
621 sub get_next_vm_diskname
{
622 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
625 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
626 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
629 foreach my $disk (@$disk_list) {
630 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
631 $disk_ids->{$disknum} = 1 if defined($disknum);
634 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
635 if (!$disk_ids->{$i}) {
636 return "$prefix-$vmid-disk-$i$suffix";
640 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
643 sub find_free_diskname
{
644 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
646 my $disks = $class->list_images($storeid, $scfg, $vmid);
648 my $disk_list = [ map { $_->{volid
} } @$disks ];
650 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
654 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
656 # this only works for file based storage types
657 die "storage definintion has no path\n" if !$scfg->{path
};
659 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
660 $class->parse_volname($volname);
662 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
664 die "this storage type does not support clone_image on snapshot\n" if $snap;
666 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
668 die "clone_image only works on base images\n" if !$isBase;
670 my $imagedir = $class->get_subdir($scfg, 'images');
671 $imagedir .= "/$vmid";
675 my $name = $class->find_free_diskname($imagedir, $scfg, $vmid, "qcow2", 1);
677 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
679 my $newvol = "$basevmid/$basename/$vmid/$name";
681 my $path = $class->filesystem_path($scfg, $newvol);
683 # Note: we use relative paths, so we need to call chdir before qemu-img
685 local $CWD = $imagedir;
687 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
688 '-f', 'qcow2', $path];
700 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
702 my $imagedir = $class->get_subdir($scfg, 'images');
703 $imagedir .= "/$vmid";
707 $name = $class->find_free_diskname($imagedir, $scfg, $vmid, $fmt, 1) if !$name;
709 my (undef, $tmpfmt) = parse_name_dir
($name);
711 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
714 my $path = "$imagedir/$name";
716 die "disk image '$path' already exists\n" if -e
$path;
718 if ($fmt eq 'subvol') {
719 # only allow this if size = 0, so that user knows what he is doing
720 die "storage does not support subvol quotas\n" if $size != 0;
722 my $old_umask = umask(0022);
724 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
728 my $cmd = ['/usr/bin/qemu-img', 'create'];
730 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
732 push @$cmd, '-f', $fmt, $path, "${size}K";
734 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
742 return "$vmid/$name";
746 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
748 my $path = $class->filesystem_path($scfg, $volname);
751 # try to remove immutable flag
752 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
756 if (defined($format) && ($format eq 'subvol')) {
757 File
::Path
::remove_tree
($path);
759 if (!(-f
$path || -l
$path)) {
760 warn "disk image '$path' does not exist\n";
764 unlink($path) || die "unlink '$path' failed - $!\n";
767 # try to cleanup directory to not clutter storage with empty $vmid dirs if
768 # all images from a guest got deleted
769 my $dir = dirname
($path);
776 my ($filename, $timeout) = @_;
778 my $st = File
::stat::stat($filename);
781 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
782 warn "failed to stat '$filename'$extramsg\n";
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 volume_snapshot_needs_fsfreeze
{
889 sub storage_can_replicate
{
890 my ($class, $scfg, $storeid, $format) = @_;
895 sub volume_has_feature
{
896 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
899 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
900 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
901 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
902 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
903 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
904 snap
=> {qcow2
=> 1} },
905 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
906 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
909 # clone_image creates a qcow2 volume
910 return 0 if $feature eq 'clone' &&
911 defined($opts->{valid_target_formats
}) &&
912 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
914 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
915 $class->parse_volname($volname);
921 $key = $isBase ?
'base' : 'current';
924 return 1 if defined($features->{$feature}->{$key}->{$format});
930 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
932 my $imagedir = $class->get_subdir($scfg, 'images');
934 my ($defFmt, $vaidFmts) = default_format
($scfg);
935 my $fmts = join ('|', @$vaidFmts);
939 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
941 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
947 next if !$vollist && defined($vmid) && ($owner ne $vmid);
949 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
950 next if !($format && defined($size));
953 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
954 my ($basevmid, $basename) = ($1, $2);
955 $volid = "$storeid:$basevmid/$basename/$owner/$name";
957 $volid = "$storeid:$owner/$name";
961 my $found = grep { $_ eq $volid } @$vollist;
966 volid
=> $volid, format
=> $format,
967 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
970 $info->{ctime
} = $ctime if $ctime;
978 # list templates ($tt = <iso|vztmpl|backup|snippets>)
979 my $get_subdir_files = sub {
980 my ($sid, $path, $tt, $vmid) = @_;
984 foreach my $fn (<$path/*>) {
985 my $st = File
::stat::stat($fn);
987 next if (!$st || S_ISDIR
($st->mode));
992 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
994 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
996 } elsif ($tt eq 'vztmpl') {
997 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
999 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1001 } elsif ($tt eq 'backup') {
1002 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1003 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1007 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1009 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1011 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1013 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1014 $info->{vmid
} = $vmid // $1;
1017 my $comment_fn = $original.COMMENT_EXT
;
1018 if (-f
$comment_fn) {
1019 my $comment = PVE
::Tools
::file_read_firstline
($comment_fn);
1020 $info->{comment
} = $comment if defined($comment);
1023 } elsif ($tt eq 'snippets') {
1026 volid
=> "$sid:snippets/". basename
($fn),
1027 format
=> 'snippet',
1031 $info->{size
} = $st->size;
1032 $info->{ctime
} //= $st->ctime;
1041 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1044 my $vmlist = PVE
::Cluster
::get_vmlist
();
1045 foreach my $type (@$content_types) {
1048 if ($type eq 'images' || $type eq 'rootdir') {
1049 $data = $class->list_images($storeid, $scfg, $vmid);
1050 } elsif ($scfg->{path
}) {
1051 my $path = $class->get_subdir($scfg, $type);
1053 if ($type eq 'iso' && !defined($vmid)) {
1054 $data = $get_subdir_files->($storeid, $path, 'iso');
1055 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1056 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1057 } elsif ($type eq 'backup') {
1058 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1059 } elsif ($type eq 'snippets') {
1060 $data = $get_subdir_files->($storeid, $path, 'snippets');
1066 foreach my $item (@$data) {
1067 if ($type eq 'images' || $type eq 'rootdir') {
1068 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1070 if (defined($vminfo)) {
1071 $vmtype = $vminfo->{type
};
1073 if (defined($vmtype) && $vmtype eq 'lxc') {
1074 $item->{content
} = 'rootdir';
1076 $item->{content
} = 'images';
1078 next if $type ne $item->{content
};
1080 $item->{content
} = $type;
1091 my ($class, $storeid, $scfg, $cache) = @_;
1093 my $path = $scfg->{path
};
1095 die "storage definintion has no path\n" if !$path;
1098 my $res = PVE
::Tools
::df
($path, $timeout);
1100 return undef if !$res || !$res->{total
};
1102 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1105 sub volume_snapshot_list
{
1106 my ($class, $scfg, $storeid, $volname) = @_;
1108 # implement in subclass
1109 die "Volume_snapshot_list is not implemented for $class";
1111 # return an empty array if dataset does not exist.
1114 sub activate_storage
{
1115 my ($class, $storeid, $scfg, $cache) = @_;
1117 my $path = $scfg->{path
};
1119 die "storage definintion has no path\n" if !$path;
1121 # this path test may hang indefinitely on unresponsive mounts
1123 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1124 die "unable to activate storage '$storeid' - " .
1125 "directory '$path' does not exist or is unreachable\n";
1129 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1131 if (defined($scfg->{content
})) {
1132 foreach my $vtype (keys %$vtype_subdirs) {
1133 # OpenVZMigrate uses backup (dump) dir
1134 if (defined($scfg->{content
}->{$vtype}) ||
1135 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1136 my $subdir = $class->get_subdir($scfg, $vtype);
1137 mkpath
$subdir if $subdir ne $path;
1143 sub deactivate_storage
{
1144 my ($class, $storeid, $scfg, $cache) = @_;
1146 # do nothing by default
1150 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1152 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1157 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1162 sub activate_volume
{
1163 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1165 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1167 # check is volume exists
1168 if ($scfg->{path
}) {
1169 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1171 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1175 sub deactivate_volume
{
1176 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1178 # do nothing by default
1181 sub check_connection
{
1182 my ($class, $storeid, $scfg) = @_;
1183 # do nothing by default
1188 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1190 $logfunc //= sub { print "$_[1]\n" };
1192 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1194 my $backup_groups = {};
1195 my $prune_list = [];
1197 foreach my $backup (@{$backups}) {
1198 my $volid = $backup->{volid
};
1199 my $backup_vmid = $backup->{vmid
};
1200 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1201 my $backup_type = $archive_info->{type
} // 'unknown';
1203 next if defined($type) && $type ne $backup_type;
1206 ctime
=> $backup->{ctime
},
1207 type
=> $backup_type,
1211 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1213 if ($archive_info->{is_std_name
}) {
1214 $prune_entry->{ctime
} = $archive_info->{ctime
};
1215 my $group = "$backup_type/$backup_vmid";
1216 push @{$backup_groups->{$group}}, $prune_entry;
1218 # ignore backups that don't use the standard naming scheme
1219 $prune_entry->{mark
} = 'protected';
1222 push @{$prune_list}, $prune_entry;
1225 foreach my $backup_group (values %{$backup_groups}) {
1226 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1231 foreach my $prune_entry (@{$prune_list}) {
1232 next if $prune_entry->{mark
} ne 'remove';
1234 my $volid = $prune_entry->{volid
};
1235 $logfunc->('info', "removing backup '$volid'");
1237 my (undef, $volname) = parse_volume_id
($volid);
1238 my $archive_path = $class->filesystem_path($scfg, $volname);
1239 PVE
::Storage
::archive_remove
($archive_path);
1242 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1247 die "error pruning backups - check log\n" if $failed;
1252 # Import/Export interface:
1253 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1254 # the default implementations will return this if $scfg->{path} is set,
1255 # mimicking the old PVE::Storage::storage_migrate() function.
1257 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1258 # functions in case the format doesn't match their specialized
1259 # implementations to reuse the raw/tar code.
1261 # Format specification:
1262 # The following formats are all prefixed with image information in the form
1263 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1264 # to preallocate the image on storages which require it.
1266 # raw+size: (image files only)
1267 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1268 # qcow2+size, vmdk: (image files only)
1269 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1270 # files which are already in qcow2 format, or via `qemu-img convert`.
1271 # Note that these formats are only valid with $with_snapshots being true.
1272 # tar+size: (subvolumes only)
1273 # A GNU tar stream containing just the inner contents of the subvolume.
1274 # This does not distinguish between the contents of a privileged or
1275 # unprivileged container. In other words, this is from the root user
1276 # namespace's point of view with no uid-mapping in effect.
1277 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1279 # Plugins may reuse these helpers. Changes to the header format should be
1280 # reflected by changes to the function prototypes.
1281 sub write_common_header
($$) {
1282 my ($fh, $image_size_in_bytes) = @_;
1283 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1286 sub read_common_header
($) {
1288 sysread($fh, my $size, 8);
1289 $size = unpack('Q<', $size);
1290 die "import: no size found in export header, aborting.\n" if !defined($size);
1291 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1296 # Export a volume into a file handle as a stream of desired format.
1298 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1299 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1300 my $file = $class->path($scfg, $volname, $storeid)
1301 or goto unsupported
;
1302 my ($size, $file_format) = file_size_info
($file);
1304 if ($format eq 'raw+size') {
1305 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1306 write_common_header
($fh, $size);
1307 if ($file_format eq 'raw') {
1308 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1310 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1311 output
=> '>&'.fileno($fh));
1314 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1315 my $data_format = $1;
1316 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1317 write_common_header
($fh, $size);
1318 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1320 } elsif ($format eq 'tar+size') {
1321 goto unsupported
if $file_format ne 'subvol';
1322 write_common_header
($fh, $size);
1323 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1324 output
=> '>&'.fileno($fh));
1329 die "volume export format $format not available for $class";
1332 sub volume_export_formats
{
1333 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1334 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1335 my $file = $class->path($scfg, $volname, $storeid)
1337 my ($size, $format) = file_size_info
($file);
1339 if ($with_snapshots) {
1340 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1343 return ('tar+size') if $format eq 'subvol';
1344 return ('raw+size');
1349 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1351 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1353 die "volume import format '$format' not available for $class\n"
1354 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1355 my $data_format = $1;
1357 die "format $format cannot be imported without snapshots\n"
1358 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1359 die "format $format cannot be imported with snapshots\n"
1360 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1362 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1363 $class->parse_volname($volname);
1365 # XXX: Should we bother with conversion routines at this level? This won't
1366 # happen without manual CLI usage, so for now we just error out...
1367 die "cannot import format $format into a file of format $file_format\n"
1368 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1370 # Check for an existing file first since interrupting alloc_image doesn't
1372 my $file = $class->path($scfg, $volname, $storeid);
1374 die "file '$file' already exists\n" if !$allow_rename;
1375 warn "file '$file' already exists - importing with a different name\n";
1379 my ($size) = read_common_header
($fh);
1380 $size = int($size/1024);
1383 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1384 my $oldname = $volname;
1385 $volname = $allocname;
1386 if (defined($name) && $allocname ne $oldname) {
1387 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1389 my $file = $class->path($scfg, $volname, $storeid)
1390 or die "internal error: failed to get path to newly allocated volume $volname\n";
1391 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1392 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1393 input
=> '<&'.fileno($fh));
1394 } elsif ($data_format eq 'tar') {
1395 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1396 input
=> '<&'.fileno($fh));
1398 die "volume import format '$format' not available for $class";
1402 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1407 return "$storeid:$volname";
1410 sub volume_import_formats
{
1411 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1412 if ($scfg->{path
} && !defined($base_snapshot)) {
1413 my $format = ($class->parse_volname($volname))[6];
1414 if ($with_snapshots) {
1415 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1418 return ('tar+size') if $format eq 'subvol';
1419 return ('raw+size');