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 NOTES_EXT
=> ".notes";
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 = (
44 our $MAX_VOLUMES_PER_GUEST = 1024;
46 cfs_register_file
('storage.cfg',
47 sub { __PACKAGE__-
>parse_config(@_); },
48 sub { __PACKAGE__-
>write_config(@_); });
52 type
=> 'integer', minimum
=> '0',
53 format_description
=> 'N',
56 our $prune_backups_format = {
59 description
=> 'Keep all backups. Conflicts with the other options when true.',
64 description
=> 'Keep the last <N> backups.',
68 description
=> 'Keep backups for the last <N> different hours. If there is more' .
69 'than one backup for a single hour, only the latest one is kept.'
73 description
=> 'Keep backups for the last <N> different days. If there is more' .
74 'than one backup for a single day, only the latest one is kept.'
78 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
79 'than one backup for a single week, only the latest one is kept.'
83 description
=> 'Keep backups for the last <N> different months. If there is more' .
84 'than one backup for a single month, only the latest one is kept.'
88 description
=> 'Keep backups for the last <N> different years. If there is more' .
89 'than one backup for a single year, only the latest one is kept.'
92 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format, \
&validate_prune_backups
);
93 sub validate_prune_backups
{
94 my ($prune_backups) = @_;
97 grep { $_ ne 'keep-all' && $prune_backups->{$_} > 0 } keys $prune_backups->%*;
99 if (scalar(@positive_opts) == 0) {
100 $prune_backups = { 'keep-all' => 1 };
101 } elsif ($prune_backups->{'keep-all'}) {
102 die "keep-all cannot be set together with other options.\n";
105 return $prune_backups;
107 register_standard_option
('prune-backups', {
108 description
=> "The retention options with shorter intervals are processed first " .
109 "with --keep-last being the very first one. Each option covers a " .
110 "specific period of time. We say that backups within this period " .
111 "are covered by this option. The next option does not take care " .
112 "of already covered backups and only considers older backups.",
115 format
=> 'prune-backups',
120 type
=> { description
=> "Storage type." },
121 storage
=> get_standard_option
('pve-storage-id',
122 { completion
=> \
&PVE
::Storage
::complete_storage
}),
123 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
125 description
=> "Allowed content types.\n\nNOTE: the value " .
126 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
127 type
=> 'string', format
=> 'pve-storage-content-list',
129 completion
=> \
&PVE
::Storage
::complete_content_type
,
132 description
=> "Flag to disable the storage.",
137 description
=> "Deprecated: use 'prune-backups' instead. " .
138 "Maximal number of backup files per VM. Use '0' for unlimited.",
143 'prune-backups' => get_standard_option
('prune-backups'),
145 description
=> "Mark storage as shared.",
150 description
=> "Default image format.",
151 type
=> 'string', format
=> 'pve-storage-format',
157 sub content_hash_to_string
{
161 foreach my $ct (keys %$hash) {
162 push @cta, $ct if $hash->{$ct};
165 return join(',', @cta);
168 sub valid_content_types
{
171 my $def = $defaultData->{plugindata
}->{$type};
175 return $def->{content
}->[0];
181 my $type = $scfg->{type
};
182 my $def = $defaultData->{plugindata
}->{$type};
184 my $def_format = 'raw';
185 my $valid_formats = [ $def_format ];
187 if (defined($def->{format
})) {
188 $def_format = $scfg->{format
} || $def->{format
}->[1];
189 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
192 return wantarray ?
($def_format, $valid_formats) : $def_format;
195 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
197 my ($path, $noerr) = @_;
199 # fixme: exclude more shell meta characters?
200 # we need absolute paths
201 if ($path !~ m
|^/[^;\
(\
)]+|) {
202 return undef if $noerr;
203 die "value does not look like a valid absolute path\n";
208 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
210 my ($server, $noerr) = @_;
212 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
213 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
215 return undef if $noerr;
216 die "value does not look like a valid server name or IP address\n";
221 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
223 my ($name, $noerr) = @_;
225 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
226 return undef if $noerr;
227 die "lvm name '$name' contains illegal characters\n";
233 # fixme: do we need this
234 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
236 # my ($portal, $noerr) = @_;
238 # # IP with optional port
239 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
240 # return undef if $noerr;
241 # die "value does not look like a valid portal address\n";
246 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
247 sub verify_portal_dns
{
248 my ($portal, $noerr) = @_;
250 # IP or DNS name with optional port
251 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
252 return undef if $noerr;
253 die "value does not look like a valid portal address\n";
258 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
260 my ($ct, $noerr) = @_;
262 my $valid_content = valid_content_types
('dir'); # dir includes all types
264 if (!$valid_content->{$ct}) {
265 return undef if $noerr;
266 die "invalid content type '$ct'\n";
272 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
274 my ($fmt, $noerr) = @_;
276 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
277 return undef if $noerr;
278 die "invalid format '$fmt'\n";
284 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
286 my ($value, $noerr) = @_;
288 # mount options (see man fstab)
289 if ($value !~ m/^\S+$/) {
290 return undef if $noerr;
291 die "invalid options '$value'\n";
297 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
298 sub parse_volume_id
{
299 my ($volid, $noerr) = @_;
301 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
302 return wantarray ?
($1, $2) : $1;
304 return undef if $noerr;
305 die "unable to parse volume ID '$volid'\n";
313 sub parse_section_header
{
314 my ($class, $line) = @_;
316 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
317 my ($type, $storeid) = (lc($1), $2);
318 my $errmsg = undef; # set if you want to skip whole section
319 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
321 my $config = {}; # to return additional attributes
322 return ($type, $storeid, $errmsg, $config);
328 my ($class, $type, $key, $value) = @_;
330 my $def = $defaultData->{plugindata
}->{$type};
332 if ($key eq 'content') {
333 my $valid_content = $def->{content
}->[0];
337 foreach my $c (PVE
::Tools
::split_list
($value)) {
338 if (!$valid_content->{$c}) {
339 warn "storage does not support content type '$c'\n";
345 if ($res->{none
} && scalar (keys %$res) > 1) {
346 die "unable to combine 'none' with other content types\n";
349 if (scalar(keys $res->%*) == 0 && !$valid_content->{none
}) {
350 die "storage does not support content type 'none'\n";
354 } elsif ($key eq 'format') {
355 my $valid_formats = $def->{format
}->[0];
357 if (!$valid_formats->{$value}) {
358 warn "storage does not support format '$value'\n";
363 } elsif ($key eq 'nodes') {
366 foreach my $node (PVE
::Tools
::split_list
($value)) {
367 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
373 # no node restrictions for local storage
374 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
375 # die "storage '$storeid' does not allow node restrictions\n";
385 my ($class, $type, $key, $value) = @_;
387 if ($key eq 'nodes') {
388 return join(',', keys(%$value));
389 } elsif ($key eq 'content') {
390 my $res = content_hash_to_string
($value) || 'none';
398 my ($class, $filename, $raw) = @_;
400 my $cfg = $class->SUPER::parse_config
($filename, $raw);
401 my $ids = $cfg->{ids
};
403 # make sure we have a reasonable 'local:' storage
404 # we want 'local' to be always the same 'type' (on all cluster nodes)
405 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
406 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
409 priority
=> 0, # force first entry
410 path
=> '/var/lib/vz',
411 'prune-backups' => 'keep-all=1',
423 # make sure we have a path
424 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
426 # remove node restrictions for local storage
427 delete($ids->{local}->{nodes
});
429 foreach my $storeid (keys %$ids) {
430 my $d = $ids->{$storeid};
431 my $type = $d->{type
};
433 my $def = $defaultData->{plugindata
}->{$type};
435 if ($def->{content
}) {
436 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
438 if (grep { $_ eq $type } @SHARED_STORAGE) {
446 # Storage implementation
448 # called during addition of storage (before the new storage config got written)
449 # die to abort addition if there are (grave) problems
450 # NOTE: runs in a storage config *locked* context
452 my ($class, $storeid, $scfg, %param) = @_;
454 # do nothing by default
458 # called during storage configuration update (before the updated storage config got written)
459 # die to abort the update if there are (grave) problems
460 # NOTE: runs in a storage config *locked* context
462 my ($class, $storeid, $scfg, %param) = @_;
464 # do nothing by default
468 # called during deletion of storage (before the new storage config got written)
469 # and if the activate check on addition fails, to cleanup all storage traces
470 # which on_add_hook may have created.
471 # die to abort deletion if there are (very grave) problems
472 # NOTE: runs in a storage config *locked* context
474 my ($class, $storeid, $scfg) = @_;
476 # do nothing by default
480 sub cluster_lock_storage
{
481 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
485 my $lockid = "pve-storage-$storeid";
486 my $lockdir = "/var/lock/pve-manager";
488 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
491 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
500 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
501 return ($1, $3, $2); # (name, format, isBase)
504 die "unable to parse volume filename '$name'\n";
508 my ($class, $volname) = @_;
510 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
511 my ($basedvmid, $basename) = ($1, $2);
512 parse_name_dir
($basename);
513 my ($vmid, $name) = ($3, $4);
514 my (undef, $format, $isBase) = parse_name_dir
($name);
515 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
516 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
517 my ($vmid, $name) = ($1, $2);
518 my (undef, $format, $isBase) = parse_name_dir
($name);
519 return ('images', $name, $vmid, undef, undef, $isBase, $format);
520 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
522 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::vztmpl_extension_re)$!) {
523 return ('vztmpl', $1);
524 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
525 return ('rootdir', $1, $1);
526 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
528 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
529 return ('backup', $fn, $2);
531 return ('backup', $fn);
532 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
533 return ('snippets', $1);
536 die "unable to parse directory volume name '$volname'\n";
539 my $vtype_subdirs = {
541 rootdir
=> 'private',
542 iso
=> 'template/iso',
543 vztmpl
=> 'template/cache',
545 snippets
=> 'snippets',
548 sub get_vtype_subdirs
{
549 return $vtype_subdirs;
553 my ($class, $scfg, $vtype) = @_;
555 my $path = $scfg->{path
};
557 die "storage definition has no path\n" if !$path;
559 my $subdir = $vtype_subdirs->{$vtype};
561 die "unknown vtype '$vtype'\n" if !defined($subdir);
563 return "$path/$subdir";
566 sub filesystem_path
{
567 my ($class, $scfg, $volname, $snapname) = @_;
569 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
570 $class->parse_volname($volname);
572 # Note: qcow2/qed has internal snapshot, so path is always
573 # the same (with or without snapshot => same file).
574 die "can't snapshot this image format\n"
575 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
577 my $dir = $class->get_subdir($scfg, $vtype);
579 $dir .= "/$vmid" if $vtype eq 'images';
581 my $path = "$dir/$name";
583 return wantarray ?
($path, $vmid, $vtype) : $path;
587 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
589 return $class->filesystem_path($scfg, $volname, $snapname);
593 my ($class, $storeid, $scfg, $volname) = @_;
595 # this only works for file based storage types
596 die "storage definition has no path\n" if !$scfg->{path
};
598 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
599 $class->parse_volname($volname);
601 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
603 die "create_base not possible with base image\n" if $isBase;
605 my $path = $class->filesystem_path($scfg, $volname);
607 my ($size, undef, $used, $parent) = file_size_info
($path);
608 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
610 die "volname '$volname' contains wrong information about parent\n"
611 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
614 $newname =~ s/^vm-/base-/;
616 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
619 my $newpath = $class->filesystem_path($scfg, $newvolname);
621 die "file '$newpath' already exists\n" if -f
$newpath;
623 rename($path, $newpath) ||
624 die "rename '$path' to '$newpath' failed - $!\n";
626 # We try to protect base volume
628 chmod(0444, $newpath); # nobody should write anything
630 # also try to set immutable flag
631 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
637 my $get_vm_disk_number = sub {
638 my ($disk_name, $scfg, $vmid, $suffix) = @_;
640 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
642 my $type = $scfg->{type
};
643 my $def = { %{$defaultData->{plugindata
}->{$type}} };
645 my $valid = $def->{format
}[0];
646 if ($valid->{subvol
}) {
647 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
650 if ($disk_name =~ m/$disk_regex/) {
657 sub get_next_vm_diskname
{
658 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
661 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
662 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
665 foreach my $disk (@$disk_list) {
666 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
667 $disk_ids->{$disknum} = 1 if defined($disknum);
670 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
671 if (!$disk_ids->{$i}) {
672 return "$prefix-$vmid-disk-$i$suffix";
676 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
679 sub find_free_diskname
{
680 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
682 my $disks = $class->list_images($storeid, $scfg, $vmid);
684 my $disk_list = [ map { $_->{volid
} } @$disks ];
686 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
690 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
692 # this only works for file based storage types
693 die "storage definition has no path\n" if !$scfg->{path
};
695 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
696 $class->parse_volname($volname);
698 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
700 die "this storage type does not support clone_image on snapshot\n" if $snap;
702 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
704 die "clone_image only works on base images\n" if !$isBase;
706 my $imagedir = $class->get_subdir($scfg, 'images');
707 $imagedir .= "/$vmid";
711 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
713 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
715 my $newvol = "$basevmid/$basename/$vmid/$name";
717 my $path = $class->filesystem_path($scfg, $newvol);
719 # Note: we use relative paths, so we need to call chdir before qemu-img
721 local $CWD = $imagedir;
723 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
724 '-F', $format, '-f', 'qcow2', $path];
736 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
738 my $imagedir = $class->get_subdir($scfg, 'images');
739 $imagedir .= "/$vmid";
743 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
745 my (undef, $tmpfmt) = parse_name_dir
($name);
747 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
750 my $path = "$imagedir/$name";
752 die "disk image '$path' already exists\n" if -e
$path;
754 if ($fmt eq 'subvol') {
755 # only allow this if size = 0, so that user knows what he is doing
756 die "storage does not support subvol quotas\n" if $size != 0;
758 my $old_umask = umask(0022);
760 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
764 my $cmd = ['/usr/bin/qemu-img', 'create'];
766 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
768 push @$cmd, '-f', $fmt, $path, "${size}K";
770 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
778 return "$vmid/$name";
782 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
784 my $path = $class->filesystem_path($scfg, $volname);
787 # try to remove immutable flag
788 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
792 if (defined($format) && ($format eq 'subvol')) {
793 File
::Path
::remove_tree
($path);
795 if (!(-f
$path || -l
$path)) {
796 warn "disk image '$path' does not exist\n";
800 unlink($path) || die "unlink '$path' failed - $!\n";
803 # try to cleanup directory to not clutter storage with empty $vmid dirs if
804 # all images from a guest got deleted
805 my $dir = dirname
($path);
812 my ($filename, $timeout) = @_;
814 my $st = File
::stat::stat($filename);
817 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
818 warn "failed to stat '$filename'$extramsg\n";
822 if (S_ISDIR
($st->mode)) {
823 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
828 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
830 outfunc
=> sub { $json .= shift },
831 errfunc
=> sub { warn "$_[0]\n" }
836 my $info = eval { decode_json
($json) };
838 warn "could not parse qemu-img info command output for '$filename' - $err\n";
839 return wantarray ?
(undef, undef, undef, undef, $st->ctime) : undef;
842 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
844 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
845 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
846 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
847 if (defined($parent)) {
848 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
850 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
853 sub get_volume_notes
{
854 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
856 die "volume notes are not supported for $class";
859 sub update_volume_notes
{
860 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
862 die "volume notes are not supported for $class";
865 sub volume_size_info
{
866 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
867 my $path = $class->filesystem_path($scfg, $volname);
868 return file_size_info
($path, $timeout);
873 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
875 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
877 return 1 if $running;
879 my $path = $class->filesystem_path($scfg, $volname);
881 my $format = ($class->parse_volname($volname))[6];
883 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
885 run_command
($cmd, timeout
=> 10);
890 sub volume_snapshot
{
891 my ($class, $scfg, $storeid, $volname, $snap) = @_;
893 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
895 my $path = $class->filesystem_path($scfg, $volname);
897 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
904 sub volume_rollback_is_possible
{
905 my ($class, $scfg, $storeid, $volname, $snap) = @_;
910 sub volume_snapshot_rollback
{
911 my ($class, $scfg, $storeid, $volname, $snap) = @_;
913 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
915 my $path = $class->filesystem_path($scfg, $volname);
917 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
924 sub volume_snapshot_delete
{
925 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
927 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
929 return 1 if $running;
931 my $path = $class->filesystem_path($scfg, $volname);
933 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
935 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
942 sub volume_snapshot_needs_fsfreeze
{
946 sub storage_can_replicate
{
947 my ($class, $scfg, $storeid, $format) = @_;
952 sub volume_has_feature
{
953 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
956 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
957 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
958 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
959 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
960 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
961 snap
=> {qcow2
=> 1} },
962 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
963 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
966 # clone_image creates a qcow2 volume
967 return 0 if $feature eq 'clone' &&
968 defined($opts->{valid_target_formats
}) &&
969 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
971 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
972 $class->parse_volname($volname);
978 $key = $isBase ?
'base' : 'current';
981 return 1 if defined($features->{$feature}->{$key}->{$format});
987 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
989 my $imagedir = $class->get_subdir($scfg, 'images');
991 my ($defFmt, $vaidFmts) = default_format
($scfg);
992 my $fmts = join ('|', @$vaidFmts);
996 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
998 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1004 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1006 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
1007 next if !($format && defined($size));
1010 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1011 my ($basevmid, $basename) = ($1, $2);
1012 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1014 $volid = "$storeid:$owner/$name";
1018 my $found = grep { $_ eq $volid } @$vollist;
1023 volid
=> $volid, format
=> $format,
1024 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
1027 $info->{ctime
} = $ctime if $ctime;
1035 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1036 my $get_subdir_files = sub {
1037 my ($sid, $path, $tt, $vmid) = @_;
1041 foreach my $fn (<$path/*>) {
1042 my $st = File
::stat::stat($fn);
1044 next if (!$st || S_ISDIR
($st->mode));
1049 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1051 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1053 } elsif ($tt eq 'vztmpl') {
1054 next if $fn !~ m!/([^/]+$PVE::Storage::vztmpl_extension_re)$!;
1056 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1058 } elsif ($tt eq 'backup') {
1059 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1064 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1065 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1067 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1069 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1071 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1073 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1074 $info->{vmid
} = $vmid // $1;
1077 my $notes_fn = $original.NOTES_EXT
;
1079 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1080 $info->{notes
} = $notes if defined($notes);
1083 } elsif ($tt eq 'snippets') {
1086 volid
=> "$sid:snippets/". basename
($fn),
1087 format
=> 'snippet',
1091 $info->{size
} = $st->size;
1092 $info->{ctime
} //= $st->ctime;
1101 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1104 my $vmlist = PVE
::Cluster
::get_vmlist
();
1105 foreach my $type (@$content_types) {
1108 if ($type eq 'images' || $type eq 'rootdir') {
1109 $data = $class->list_images($storeid, $scfg, $vmid);
1110 } elsif ($scfg->{path
}) {
1111 my $path = $class->get_subdir($scfg, $type);
1113 if ($type eq 'iso' && !defined($vmid)) {
1114 $data = $get_subdir_files->($storeid, $path, 'iso');
1115 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1116 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1117 } elsif ($type eq 'backup') {
1118 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1119 } elsif ($type eq 'snippets') {
1120 $data = $get_subdir_files->($storeid, $path, 'snippets');
1126 foreach my $item (@$data) {
1127 if ($type eq 'images' || $type eq 'rootdir') {
1128 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1130 if (defined($vminfo)) {
1131 $vmtype = $vminfo->{type
};
1133 if (defined($vmtype) && $vmtype eq 'lxc') {
1134 $item->{content
} = 'rootdir';
1136 $item->{content
} = 'images';
1138 next if $type ne $item->{content
};
1140 $item->{content
} = $type;
1151 my ($class, $storeid, $scfg, $cache) = @_;
1153 my $path = $scfg->{path
};
1155 die "storage definition has no path\n" if !$path;
1158 my $res = PVE
::Tools
::df
($path, $timeout);
1160 return undef if !$res || !$res->{total
};
1162 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1165 sub volume_snapshot_list
{
1166 my ($class, $scfg, $storeid, $volname) = @_;
1168 # implement in subclass
1169 die "Volume_snapshot_list is not implemented for $class";
1171 # return an empty array if dataset does not exist.
1174 sub activate_storage
{
1175 my ($class, $storeid, $scfg, $cache) = @_;
1177 my $path = $scfg->{path
};
1179 die "storage definition has no path\n" if !$path;
1181 # this path test may hang indefinitely on unresponsive mounts
1183 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1184 die "unable to activate storage '$storeid' - " .
1185 "directory '$path' does not exist or is unreachable\n";
1189 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1191 if (defined($scfg->{content
})) {
1192 foreach my $vtype (keys %$vtype_subdirs) {
1193 # OpenVZMigrate uses backup (dump) dir
1194 if (defined($scfg->{content
}->{$vtype}) ||
1195 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1196 my $subdir = $class->get_subdir($scfg, $vtype);
1197 mkpath
$subdir if $subdir ne $path;
1203 sub deactivate_storage
{
1204 my ($class, $storeid, $scfg, $cache) = @_;
1206 # do nothing by default
1210 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1212 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1217 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1222 sub activate_volume
{
1223 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1225 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1227 # check is volume exists
1228 if ($scfg->{path
}) {
1229 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1231 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1235 sub deactivate_volume
{
1236 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1238 # do nothing by default
1241 sub check_connection
{
1242 my ($class, $storeid, $scfg) = @_;
1243 # do nothing by default
1248 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1250 $logfunc //= sub { print "$_[1]\n" };
1252 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1254 my $backup_groups = {};
1255 my $prune_list = [];
1257 foreach my $backup (@{$backups}) {
1258 my $volid = $backup->{volid
};
1259 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1260 my $backup_type = $archive_info->{type
} // 'unknown';
1261 my $backup_vmid = $archive_info->{vmid
} // $backup->{vmid
};
1263 next if defined($type) && $type ne $backup_type;
1266 ctime
=> $backup->{ctime
},
1267 type
=> $backup_type,
1271 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1273 if ($archive_info->{is_std_name
}) {
1274 die "internal error - got no VMID\n" if !defined($backup_vmid);
1275 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1276 if defined($vmid) && $backup_vmid ne $vmid;
1278 $prune_entry->{ctime
} = $archive_info->{ctime
};
1279 my $group = "$backup_type/$backup_vmid";
1280 push @{$backup_groups->{$group}}, $prune_entry;
1282 # ignore backups that don't use the standard naming scheme
1283 $prune_entry->{mark
} = 'protected';
1286 push @{$prune_list}, $prune_entry;
1289 foreach my $backup_group (values %{$backup_groups}) {
1290 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1295 foreach my $prune_entry (@{$prune_list}) {
1296 next if $prune_entry->{mark
} ne 'remove';
1298 my $volid = $prune_entry->{volid
};
1299 $logfunc->('info', "removing backup '$volid'");
1301 my (undef, $volname) = parse_volume_id
($volid);
1302 my $archive_path = $class->filesystem_path($scfg, $volname);
1303 PVE
::Storage
::archive_remove
($archive_path);
1306 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1311 die "error pruning backups - check log\n" if $failed;
1316 # Import/Export interface:
1317 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1318 # the default implementations will return this if $scfg->{path} is set,
1319 # mimicking the old PVE::Storage::storage_migrate() function.
1321 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1322 # functions in case the format doesn't match their specialized
1323 # implementations to reuse the raw/tar code.
1325 # Format specification:
1326 # The following formats are all prefixed with image information in the form
1327 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1328 # to preallocate the image on storages which require it.
1330 # raw+size: (image files only)
1331 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1332 # qcow2+size, vmdk: (image files only)
1333 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1334 # files which are already in qcow2 format, or via `qemu-img convert`.
1335 # Note that these formats are only valid with $with_snapshots being true.
1336 # tar+size: (subvolumes only)
1337 # A GNU tar stream containing just the inner contents of the subvolume.
1338 # This does not distinguish between the contents of a privileged or
1339 # unprivileged container. In other words, this is from the root user
1340 # namespace's point of view with no uid-mapping in effect.
1341 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1343 # Plugins may reuse these helpers. Changes to the header format should be
1344 # reflected by changes to the function prototypes.
1345 sub write_common_header
($$) {
1346 my ($fh, $image_size_in_bytes) = @_;
1347 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1350 sub read_common_header
($) {
1352 sysread($fh, my $size, 8);
1353 $size = unpack('Q<', $size);
1354 die "import: no size found in export header, aborting.\n" if !defined($size);
1355 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1360 # Export a volume into a file handle as a stream of desired format.
1362 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1363 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1364 my $file = $class->path($scfg, $volname, $storeid)
1365 or goto unsupported
;
1366 my ($size, $file_format) = file_size_info
($file);
1368 if ($format eq 'raw+size') {
1369 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1370 write_common_header
($fh, $size);
1371 if ($file_format eq 'raw') {
1372 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1374 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1375 output
=> '>&'.fileno($fh));
1378 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1379 my $data_format = $1;
1380 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1381 write_common_header
($fh, $size);
1382 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1384 } elsif ($format eq 'tar+size') {
1385 goto unsupported
if $file_format ne 'subvol';
1386 write_common_header
($fh, $size);
1387 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1388 output
=> '>&'.fileno($fh));
1393 die "volume export format $format not available for $class";
1396 sub volume_export_formats
{
1397 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1398 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1399 my $file = $class->path($scfg, $volname, $storeid)
1401 my ($size, $format) = file_size_info
($file);
1403 if ($with_snapshots) {
1404 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1407 return ('tar+size') if $format eq 'subvol';
1408 return ('raw+size');
1413 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1415 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1417 die "volume import format '$format' not available for $class\n"
1418 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1419 my $data_format = $1;
1421 die "format $format cannot be imported without snapshots\n"
1422 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1423 die "format $format cannot be imported with snapshots\n"
1424 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1426 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1427 $class->parse_volname($volname);
1429 # XXX: Should we bother with conversion routines at this level? This won't
1430 # happen without manual CLI usage, so for now we just error out...
1431 die "cannot import format $format into a file of format $file_format\n"
1432 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1434 # Check for an existing file first since interrupting alloc_image doesn't
1436 my $file = $class->path($scfg, $volname, $storeid);
1438 die "file '$file' already exists\n" if !$allow_rename;
1439 warn "file '$file' already exists - importing with a different name\n";
1443 my ($size) = read_common_header
($fh);
1444 $size = int($size/1024);
1447 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1448 my $oldname = $volname;
1449 $volname = $allocname;
1450 if (defined($name) && $allocname ne $oldname) {
1451 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1453 my $file = $class->path($scfg, $volname, $storeid)
1454 or die "internal error: failed to get path to newly allocated volume $volname\n";
1455 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1456 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1457 input
=> '<&'.fileno($fh));
1458 } elsif ($data_format eq 'tar') {
1459 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1460 input
=> '<&'.fileno($fh));
1462 die "volume import format '$format' not available for $class";
1466 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1471 return "$storeid:$volname";
1474 sub volume_import_formats
{
1475 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1476 if ($scfg->{path
} && !defined($base_snapshot)) {
1477 my $format = ($class->parse_volname($volname))[6];
1478 if ($with_snapshots) {
1479 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1482 return ('tar+size') if $format eq 'subvol';
1483 return ('raw+size');