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 $QCOW2_PREALLOCATION = {
51 our $RAW_PREALLOCATION = {
57 our $MAX_VOLUMES_PER_GUEST = 1024;
59 cfs_register_file
('storage.cfg',
60 sub { __PACKAGE__-
>parse_config(@_); },
61 sub { __PACKAGE__-
>write_config(@_); });
65 type
=> 'integer', minimum
=> '0',
66 format_description
=> 'N',
69 our $prune_backups_format = {
72 description
=> 'Keep all backups. Conflicts with the other options when true.',
77 description
=> 'Keep the last <N> backups.',
81 description
=> 'Keep backups for the last <N> different hours. If there is more' .
82 'than one backup for a single hour, only the latest one is kept.'
86 description
=> 'Keep backups for the last <N> different days. If there is more' .
87 'than one backup for a single day, only the latest one is kept.'
91 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
92 'than one backup for a single week, only the latest one is kept.'
96 description
=> 'Keep backups for the last <N> different months. If there is more' .
97 'than one backup for a single month, only the latest one is kept.'
101 description
=> 'Keep backups for the last <N> different years. If there is more' .
102 'than one backup for a single year, only the latest one is kept.'
105 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format, \
&validate_prune_backups
);
106 sub validate_prune_backups
{
107 my ($prune_backups) = @_;
109 my $res = { $prune_backups->%* };
111 my $keep_all = delete $res->{'keep-all'};
113 if (scalar(grep { $_ > 0 } values %{$res}) == 0) {
114 $res = { 'keep-all' => 1 };
115 } elsif ($keep_all) {
116 die "keep-all cannot be set together with other options.\n";
121 register_standard_option
('prune-backups', {
122 description
=> "The retention options with shorter intervals are processed first " .
123 "with --keep-last being the very first one. Each option covers a " .
124 "specific period of time. We say that backups within this period " .
125 "are covered by this option. The next option does not take care " .
126 "of already covered backups and only considers older backups.",
129 format
=> 'prune-backups',
134 type
=> { description
=> "Storage type." },
135 storage
=> get_standard_option
('pve-storage-id',
136 { completion
=> \
&PVE
::Storage
::complete_storage
}),
137 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
139 description
=> "Allowed content types.\n\nNOTE: the value " .
140 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
141 type
=> 'string', format
=> 'pve-storage-content-list',
143 completion
=> \
&PVE
::Storage
::complete_content_type
,
146 description
=> "Flag to disable the storage.",
151 description
=> "Deprecated: use 'prune-backups' instead. " .
152 "Maximal number of backup files per VM. Use '0' for unlimited.",
157 'prune-backups' => get_standard_option
('prune-backups'),
159 description
=> "Mark storage as shared.",
164 description
=> "Default image format.",
165 type
=> 'string', format
=> 'pve-storage-format',
169 description
=> "Preallocation mode for raw and qcow2 images. " .
170 "Using 'metadata' on raw images results in preallocation=off.",
171 type
=> 'string', enum
=> ['off', 'metadata', 'falloc', 'full'],
172 default => 'metadata',
178 sub content_hash_to_string
{
182 foreach my $ct (keys %$hash) {
183 push @cta, $ct if $hash->{$ct};
186 return join(',', @cta);
189 sub valid_content_types
{
192 my $def = $defaultData->{plugindata
}->{$type};
196 return $def->{content
}->[0];
202 my $type = $scfg->{type
};
203 my $def = $defaultData->{plugindata
}->{$type};
205 my $def_format = 'raw';
206 my $valid_formats = [ $def_format ];
208 if (defined($def->{format
})) {
209 $def_format = $scfg->{format
} || $def->{format
}->[1];
210 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
213 return wantarray ?
($def_format, $valid_formats) : $def_format;
216 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
218 my ($path, $noerr) = @_;
220 # fixme: exclude more shell meta characters?
221 # we need absolute paths
222 if ($path !~ m
|^/[^;\
(\
)]+|) {
223 return undef if $noerr;
224 die "value does not look like a valid absolute path\n";
229 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
231 my ($server, $noerr) = @_;
233 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
234 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
236 return undef if $noerr;
237 die "value does not look like a valid server name or IP address\n";
242 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
244 my ($name, $noerr) = @_;
246 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
247 return undef if $noerr;
248 die "lvm name '$name' contains illegal characters\n";
254 # fixme: do we need this
255 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
257 # my ($portal, $noerr) = @_;
259 # # IP with optional port
260 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
261 # return undef if $noerr;
262 # die "value does not look like a valid portal address\n";
267 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
268 sub verify_portal_dns
{
269 my ($portal, $noerr) = @_;
271 # IP or DNS name with optional port
272 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
273 return undef if $noerr;
274 die "value does not look like a valid portal address\n";
279 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
281 my ($ct, $noerr) = @_;
283 my $valid_content = valid_content_types
('dir'); # dir includes all types
285 if (!$valid_content->{$ct}) {
286 return undef if $noerr;
287 die "invalid content type '$ct'\n";
293 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
295 my ($fmt, $noerr) = @_;
297 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
298 return undef if $noerr;
299 die "invalid format '$fmt'\n";
305 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
307 my ($value, $noerr) = @_;
309 # mount options (see man fstab)
310 if ($value !~ m/^\S+$/) {
311 return undef if $noerr;
312 die "invalid options '$value'\n";
318 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
319 sub parse_volume_id
{
320 my ($volid, $noerr) = @_;
322 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
323 return wantarray ?
($1, $2) : $1;
325 return undef if $noerr;
326 die "unable to parse volume ID '$volid'\n";
334 sub parse_section_header
{
335 my ($class, $line) = @_;
337 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
338 my ($type, $storeid) = (lc($1), $2);
339 my $errmsg = undef; # set if you want to skip whole section
340 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
342 my $config = {}; # to return additional attributes
343 return ($type, $storeid, $errmsg, $config);
349 my ($class, $type, $key, $value) = @_;
351 my $def = $defaultData->{plugindata
}->{$type};
353 if ($key eq 'content') {
354 my $valid_content = $def->{content
}->[0];
358 foreach my $c (PVE
::Tools
::split_list
($value)) {
359 if (!$valid_content->{$c}) {
360 warn "storage does not support content type '$c'\n";
366 if ($res->{none
} && scalar (keys %$res) > 1) {
367 die "unable to combine 'none' with other content types\n";
370 if (scalar(keys $res->%*) == 0 && !$valid_content->{none
}) {
371 die "storage does not support content type 'none'\n";
375 } elsif ($key eq 'format') {
376 my $valid_formats = $def->{format
}->[0];
378 if (!$valid_formats->{$value}) {
379 warn "storage does not support format '$value'\n";
384 } elsif ($key eq 'nodes') {
387 foreach my $node (PVE
::Tools
::split_list
($value)) {
388 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
394 # no node restrictions for local storage
395 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
396 # die "storage '$storeid' does not allow node restrictions\n";
406 my ($class, $type, $key, $value) = @_;
408 if ($key eq 'nodes') {
409 return join(',', keys(%$value));
410 } elsif ($key eq 'content') {
411 my $res = content_hash_to_string
($value) || 'none';
419 my ($class, $filename, $raw) = @_;
421 my $cfg = $class->SUPER::parse_config
($filename, $raw);
422 my $ids = $cfg->{ids
};
424 # make sure we have a reasonable 'local:' storage
425 # we want 'local' to be always the same 'type' (on all cluster nodes)
426 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
427 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
430 priority
=> 0, # force first entry
431 path
=> '/var/lib/vz',
432 'prune-backups' => 'keep-all=1',
444 # make sure we have a path
445 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
447 # remove node restrictions for local storage
448 delete($ids->{local}->{nodes
});
450 foreach my $storeid (keys %$ids) {
451 my $d = $ids->{$storeid};
452 my $type = $d->{type
};
454 my $def = $defaultData->{plugindata
}->{$type};
456 if ($def->{content
}) {
457 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
459 if (grep { $_ eq $type } @SHARED_STORAGE) {
467 sub preallocation_cmd_option
{
468 my ($scfg, $fmt) = @_;
470 my $prealloc = $scfg->{preallocation
};
472 if ($fmt eq 'qcow2') {
473 $prealloc = $prealloc // 'metadata';
475 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
476 if !$QCOW2_PREALLOCATION->{$prealloc};
478 return "preallocation=$prealloc";
479 } elsif ($fmt eq 'raw') {
480 $prealloc = $prealloc // 'off';
481 $prealloc = 'off' if $prealloc eq 'metadata';
483 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
484 if !$RAW_PREALLOCATION->{$prealloc};
486 return "preallocation=$prealloc";
492 # Storage implementation
494 # called during addition of storage (before the new storage config got written)
495 # die to abort addition if there are (grave) problems
496 # NOTE: runs in a storage config *locked* context
498 my ($class, $storeid, $scfg, %param) = @_;
500 # do nothing by default
504 # called during storage configuration update (before the updated storage config got written)
505 # die to abort the update if there are (grave) problems
506 # NOTE: runs in a storage config *locked* context
508 my ($class, $storeid, $scfg, %param) = @_;
510 # do nothing by default
514 # called during deletion of storage (before the new storage config got written)
515 # and if the activate check on addition fails, to cleanup all storage traces
516 # which on_add_hook may have created.
517 # die to abort deletion if there are (very grave) problems
518 # NOTE: runs in a storage config *locked* context
520 my ($class, $storeid, $scfg) = @_;
522 # do nothing by default
526 sub cluster_lock_storage
{
527 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
531 my $lockid = "pve-storage-$storeid";
532 my $lockdir = "/var/lock/pve-manager";
534 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
537 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
546 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
547 return ($1, $3, $2); # (name, format, isBase)
550 die "unable to parse volume filename '$name'\n";
554 my ($class, $volname) = @_;
556 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
557 my ($basedvmid, $basename) = ($1, $2);
558 parse_name_dir
($basename);
559 my ($vmid, $name) = ($3, $4);
560 my (undef, $format, $isBase) = parse_name_dir
($name);
561 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
562 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
563 my ($vmid, $name) = ($1, $2);
564 my (undef, $format, $isBase) = parse_name_dir
($name);
565 return ('images', $name, $vmid, undef, undef, $isBase, $format);
566 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
568 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::vztmpl_extension_re)$!) {
569 return ('vztmpl', $1);
570 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
571 return ('rootdir', $1, $1);
572 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
574 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
575 return ('backup', $fn, $2);
577 return ('backup', $fn);
578 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
579 return ('snippets', $1);
582 die "unable to parse directory volume name '$volname'\n";
585 my $vtype_subdirs = {
587 rootdir
=> 'private',
588 iso
=> 'template/iso',
589 vztmpl
=> 'template/cache',
591 snippets
=> 'snippets',
594 sub get_vtype_subdirs
{
595 return $vtype_subdirs;
599 my ($class, $scfg, $vtype) = @_;
601 my $path = $scfg->{path
};
603 die "storage definition has no path\n" if !$path;
605 my $subdir = $vtype_subdirs->{$vtype};
607 die "unknown vtype '$vtype'\n" if !defined($subdir);
609 return "$path/$subdir";
612 sub filesystem_path
{
613 my ($class, $scfg, $volname, $snapname) = @_;
615 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
616 $class->parse_volname($volname);
618 # Note: qcow2/qed has internal snapshot, so path is always
619 # the same (with or without snapshot => same file).
620 die "can't snapshot this image format\n"
621 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
623 my $dir = $class->get_subdir($scfg, $vtype);
625 $dir .= "/$vmid" if $vtype eq 'images';
627 my $path = "$dir/$name";
629 return wantarray ?
($path, $vmid, $vtype) : $path;
633 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
635 return $class->filesystem_path($scfg, $volname, $snapname);
639 my ($class, $storeid, $scfg, $volname) = @_;
641 # this only works for file based storage types
642 die "storage definition has no path\n" if !$scfg->{path
};
644 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
645 $class->parse_volname($volname);
647 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
649 die "create_base not possible with base image\n" if $isBase;
651 my $path = $class->filesystem_path($scfg, $volname);
653 my ($size, undef, $used, $parent) = file_size_info
($path);
654 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
656 die "volname '$volname' contains wrong information about parent\n"
657 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
660 $newname =~ s/^vm-/base-/;
662 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
665 my $newpath = $class->filesystem_path($scfg, $newvolname);
667 die "file '$newpath' already exists\n" if -f
$newpath;
669 rename($path, $newpath) ||
670 die "rename '$path' to '$newpath' failed - $!\n";
672 # We try to protect base volume
674 chmod(0444, $newpath); # nobody should write anything
676 # also try to set immutable flag
677 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
683 my $get_vm_disk_number = sub {
684 my ($disk_name, $scfg, $vmid, $suffix) = @_;
686 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
688 my $type = $scfg->{type
};
689 my $def = { %{$defaultData->{plugindata
}->{$type}} };
691 my $valid = $def->{format
}[0];
692 if ($valid->{subvol
}) {
693 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
696 if ($disk_name =~ m/$disk_regex/) {
703 sub get_next_vm_diskname
{
704 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
707 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
708 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
711 foreach my $disk (@$disk_list) {
712 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
713 $disk_ids->{$disknum} = 1 if defined($disknum);
716 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
717 if (!$disk_ids->{$i}) {
718 return "$prefix-$vmid-disk-$i$suffix";
722 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
725 sub find_free_diskname
{
726 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
728 my $disks = $class->list_images($storeid, $scfg, $vmid);
730 my $disk_list = [ map { $_->{volid
} } @$disks ];
732 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
736 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
738 # this only works for file based storage types
739 die "storage definition has no path\n" if !$scfg->{path
};
741 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
742 $class->parse_volname($volname);
744 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
746 die "this storage type does not support clone_image on snapshot\n" if $snap;
748 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
750 die "clone_image only works on base images\n" if !$isBase;
752 my $imagedir = $class->get_subdir($scfg, 'images');
753 $imagedir .= "/$vmid";
757 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
759 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
761 my $newvol = "$basevmid/$basename/$vmid/$name";
763 my $path = $class->filesystem_path($scfg, $newvol);
765 # Note: we use relative paths, so we need to call chdir before qemu-img
767 local $CWD = $imagedir;
769 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
770 '-F', $format, '-f', 'qcow2', $path];
782 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
784 my $imagedir = $class->get_subdir($scfg, 'images');
785 $imagedir .= "/$vmid";
789 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
791 my (undef, $tmpfmt) = parse_name_dir
($name);
793 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
796 my $path = "$imagedir/$name";
798 die "disk image '$path' already exists\n" if -e
$path;
800 if ($fmt eq 'subvol') {
801 # only allow this if size = 0, so that user knows what he is doing
802 die "storage does not support subvol quotas\n" if $size != 0;
804 my $old_umask = umask(0022);
806 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
810 my $cmd = ['/usr/bin/qemu-img', 'create'];
812 my $prealloc_opt = preallocation_cmd_option
($scfg, $fmt);
813 push @$cmd, '-o', $prealloc_opt if defined($prealloc_opt);
815 push @$cmd, '-f', $fmt, $path, "${size}K";
817 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
825 return "$vmid/$name";
829 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
831 my $path = $class->filesystem_path($scfg, $volname);
834 # try to remove immutable flag
835 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
839 if (defined($format) && ($format eq 'subvol')) {
840 File
::Path
::remove_tree
($path);
842 if (!(-f
$path || -l
$path)) {
843 warn "disk image '$path' does not exist\n";
847 unlink($path) || die "unlink '$path' failed - $!\n";
850 # try to cleanup directory to not clutter storage with empty $vmid dirs if
851 # all images from a guest got deleted
852 my $dir = dirname
($path);
859 my ($filename, $timeout) = @_;
861 my $st = File
::stat::stat($filename);
864 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
865 warn "failed to stat '$filename'$extramsg\n";
869 if (S_ISDIR
($st->mode)) {
870 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
875 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
877 outfunc
=> sub { $json .= shift },
878 errfunc
=> sub { warn "$_[0]\n" }
883 my $info = eval { decode_json
($json) };
885 warn "could not parse qemu-img info command output for '$filename' - $err\n";
886 return wantarray ?
(undef, undef, undef, undef, $st->ctime) : undef;
889 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
891 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
892 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
893 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
894 if (defined($parent)) {
895 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
897 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
900 sub get_volume_notes
{
901 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
903 die "volume notes are not supported for $class";
906 sub update_volume_notes
{
907 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
909 die "volume notes are not supported for $class";
912 sub volume_size_info
{
913 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
914 my $path = $class->filesystem_path($scfg, $volname);
915 return file_size_info
($path, $timeout);
920 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
922 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
924 return 1 if $running;
926 my $path = $class->filesystem_path($scfg, $volname);
928 my $format = ($class->parse_volname($volname))[6];
930 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
932 run_command
($cmd, timeout
=> 10);
937 sub volume_snapshot
{
938 my ($class, $scfg, $storeid, $volname, $snap) = @_;
940 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
942 my $path = $class->filesystem_path($scfg, $volname);
944 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
951 sub volume_rollback_is_possible
{
952 my ($class, $scfg, $storeid, $volname, $snap) = @_;
957 sub volume_snapshot_rollback
{
958 my ($class, $scfg, $storeid, $volname, $snap) = @_;
960 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
962 my $path = $class->filesystem_path($scfg, $volname);
964 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
971 sub volume_snapshot_delete
{
972 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
974 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
976 return 1 if $running;
978 my $path = $class->filesystem_path($scfg, $volname);
980 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
982 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
989 sub volume_snapshot_needs_fsfreeze
{
993 sub storage_can_replicate
{
994 my ($class, $scfg, $storeid, $format) = @_;
999 sub volume_has_feature
{
1000 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
1003 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
1004 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
1005 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
1006 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
1007 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
1008 snap
=> {qcow2
=> 1} },
1009 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
1010 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
1013 # clone_image creates a qcow2 volume
1014 return 0 if $feature eq 'clone' &&
1015 defined($opts->{valid_target_formats
}) &&
1016 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
1018 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
1019 $class->parse_volname($volname);
1025 $key = $isBase ?
'base' : 'current';
1028 return 1 if defined($features->{$feature}->{$key}->{$format});
1034 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
1036 my $imagedir = $class->get_subdir($scfg, 'images');
1038 my ($defFmt, $vaidFmts) = default_format
($scfg);
1039 my $fmts = join ('|', @$vaidFmts);
1043 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
1045 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1051 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1053 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
1054 next if !($format && defined($size));
1057 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1058 my ($basevmid, $basename) = ($1, $2);
1059 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1061 $volid = "$storeid:$owner/$name";
1065 my $found = grep { $_ eq $volid } @$vollist;
1070 volid
=> $volid, format
=> $format,
1071 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
1074 $info->{ctime
} = $ctime if $ctime;
1082 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1083 my $get_subdir_files = sub {
1084 my ($sid, $path, $tt, $vmid) = @_;
1088 foreach my $fn (<$path/*>) {
1089 my $st = File
::stat::stat($fn);
1091 next if (!$st || S_ISDIR
($st->mode));
1096 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1098 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1100 } elsif ($tt eq 'vztmpl') {
1101 next if $fn !~ m!/([^/]+$PVE::Storage::vztmpl_extension_re)$!;
1103 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1105 } elsif ($tt eq 'backup') {
1106 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1111 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1112 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1114 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1116 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1118 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1120 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1121 $info->{vmid
} = $vmid // $1;
1124 my $notes_fn = $original.NOTES_EXT
;
1126 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1127 $info->{notes
} = $notes if defined($notes);
1130 } elsif ($tt eq 'snippets') {
1133 volid
=> "$sid:snippets/". basename
($fn),
1134 format
=> 'snippet',
1138 $info->{size
} = $st->size;
1139 $info->{ctime
} //= $st->ctime;
1148 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1151 my $vmlist = PVE
::Cluster
::get_vmlist
();
1152 foreach my $type (@$content_types) {
1155 if ($type eq 'images' || $type eq 'rootdir') {
1156 $data = $class->list_images($storeid, $scfg, $vmid);
1157 } elsif ($scfg->{path
}) {
1158 my $path = $class->get_subdir($scfg, $type);
1160 if ($type eq 'iso' && !defined($vmid)) {
1161 $data = $get_subdir_files->($storeid, $path, 'iso');
1162 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1163 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1164 } elsif ($type eq 'backup') {
1165 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1166 } elsif ($type eq 'snippets') {
1167 $data = $get_subdir_files->($storeid, $path, 'snippets');
1173 foreach my $item (@$data) {
1174 if ($type eq 'images' || $type eq 'rootdir') {
1175 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1177 if (defined($vminfo)) {
1178 $vmtype = $vminfo->{type
};
1180 if (defined($vmtype) && $vmtype eq 'lxc') {
1181 $item->{content
} = 'rootdir';
1183 $item->{content
} = 'images';
1185 next if $type ne $item->{content
};
1187 $item->{content
} = $type;
1198 my ($class, $storeid, $scfg, $cache) = @_;
1200 my $path = $scfg->{path
};
1202 die "storage definition has no path\n" if !$path;
1205 my $res = PVE
::Tools
::df
($path, $timeout);
1207 return undef if !$res || !$res->{total
};
1209 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1212 sub volume_snapshot_list
{
1213 my ($class, $scfg, $storeid, $volname) = @_;
1215 # implement in subclass
1216 die "Volume_snapshot_list is not implemented for $class";
1218 # return an empty array if dataset does not exist.
1221 sub activate_storage
{
1222 my ($class, $storeid, $scfg, $cache) = @_;
1224 my $path = $scfg->{path
};
1226 die "storage definition has no path\n" if !$path;
1228 # this path test may hang indefinitely on unresponsive mounts
1230 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1231 die "unable to activate storage '$storeid' - " .
1232 "directory '$path' does not exist or is unreachable\n";
1236 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1238 if (defined($scfg->{content
})) {
1239 foreach my $vtype (keys %$vtype_subdirs) {
1240 # OpenVZMigrate uses backup (dump) dir
1241 if (defined($scfg->{content
}->{$vtype}) ||
1242 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1243 my $subdir = $class->get_subdir($scfg, $vtype);
1244 mkpath
$subdir if $subdir ne $path;
1250 sub deactivate_storage
{
1251 my ($class, $storeid, $scfg, $cache) = @_;
1253 # do nothing by default
1257 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1259 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1264 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1269 sub activate_volume
{
1270 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1272 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1274 # check is volume exists
1275 if ($scfg->{path
}) {
1276 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1278 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1282 sub deactivate_volume
{
1283 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1285 # do nothing by default
1288 sub check_connection
{
1289 my ($class, $storeid, $scfg) = @_;
1290 # do nothing by default
1295 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1297 $logfunc //= sub { print "$_[1]\n" };
1299 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1301 my $backup_groups = {};
1302 my $prune_list = [];
1304 foreach my $backup (@{$backups}) {
1305 my $volid = $backup->{volid
};
1306 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1307 my $backup_type = $archive_info->{type
} // 'unknown';
1308 my $backup_vmid = $archive_info->{vmid
} // $backup->{vmid
};
1310 next if defined($type) && $type ne $backup_type;
1313 ctime
=> $backup->{ctime
},
1314 type
=> $backup_type,
1318 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1320 if ($archive_info->{is_std_name
}) {
1321 die "internal error - got no VMID\n" if !defined($backup_vmid);
1322 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1323 if defined($vmid) && $backup_vmid ne $vmid;
1325 $prune_entry->{ctime
} = $archive_info->{ctime
};
1326 my $group = "$backup_type/$backup_vmid";
1327 push @{$backup_groups->{$group}}, $prune_entry;
1329 # ignore backups that don't use the standard naming scheme
1330 $prune_entry->{mark
} = 'protected';
1333 push @{$prune_list}, $prune_entry;
1336 foreach my $backup_group (values %{$backup_groups}) {
1337 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1342 foreach my $prune_entry (@{$prune_list}) {
1343 next if $prune_entry->{mark
} ne 'remove';
1345 my $volid = $prune_entry->{volid
};
1346 $logfunc->('info', "removing backup '$volid'");
1348 my (undef, $volname) = parse_volume_id
($volid);
1349 my $archive_path = $class->filesystem_path($scfg, $volname);
1350 PVE
::Storage
::archive_remove
($archive_path);
1353 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1358 die "error pruning backups - check log\n" if $failed;
1363 # Import/Export interface:
1364 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1365 # the default implementations will return this if $scfg->{path} is set,
1366 # mimicking the old PVE::Storage::storage_migrate() function.
1368 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1369 # functions in case the format doesn't match their specialized
1370 # implementations to reuse the raw/tar code.
1372 # Format specification:
1373 # The following formats are all prefixed with image information in the form
1374 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1375 # to preallocate the image on storages which require it.
1377 # raw+size: (image files only)
1378 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1379 # qcow2+size, vmdk: (image files only)
1380 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1381 # files which are already in qcow2 format, or via `qemu-img convert`.
1382 # Note that these formats are only valid with $with_snapshots being true.
1383 # tar+size: (subvolumes only)
1384 # A GNU tar stream containing just the inner contents of the subvolume.
1385 # This does not distinguish between the contents of a privileged or
1386 # unprivileged container. In other words, this is from the root user
1387 # namespace's point of view with no uid-mapping in effect.
1388 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1390 # Plugins may reuse these helpers. Changes to the header format should be
1391 # reflected by changes to the function prototypes.
1392 sub write_common_header
($$) {
1393 my ($fh, $image_size_in_bytes) = @_;
1394 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1397 sub read_common_header
($) {
1399 sysread($fh, my $size, 8);
1400 $size = unpack('Q<', $size);
1401 die "import: no size found in export header, aborting.\n" if !defined($size);
1406 # Export a volume into a file handle as a stream of desired format.
1408 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1409 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1410 my $file = $class->path($scfg, $volname, $storeid)
1411 or goto unsupported
;
1412 my ($size, $file_format) = file_size_info
($file);
1414 if ($format eq 'raw+size') {
1415 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1416 write_common_header
($fh, $size);
1417 if ($file_format eq 'raw') {
1418 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1420 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1421 output
=> '>&'.fileno($fh));
1424 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1425 my $data_format = $1;
1426 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1427 write_common_header
($fh, $size);
1428 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1430 } elsif ($format eq 'tar+size') {
1431 goto unsupported
if $file_format ne 'subvol';
1432 write_common_header
($fh, $size);
1433 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1434 output
=> '>&'.fileno($fh));
1439 die "volume export format $format not available for $class";
1442 sub volume_export_formats
{
1443 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1444 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1445 my $file = $class->path($scfg, $volname, $storeid)
1447 my ($size, $format) = file_size_info
($file);
1449 if ($with_snapshots) {
1450 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1453 return ('tar+size') if $format eq 'subvol';
1454 return ('raw+size');
1459 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1461 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1463 die "volume import format '$format' not available for $class\n"
1464 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1465 my $data_format = $1;
1467 die "format $format cannot be imported without snapshots\n"
1468 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1469 die "format $format cannot be imported with snapshots\n"
1470 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1472 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1473 $class->parse_volname($volname);
1475 # XXX: Should we bother with conversion routines at this level? This won't
1476 # happen without manual CLI usage, so for now we just error out...
1477 die "cannot import format $format into a file of format $file_format\n"
1478 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1480 # Check for an existing file first since interrupting alloc_image doesn't
1482 my $file = $class->path($scfg, $volname, $storeid);
1484 die "file '$file' already exists\n" if !$allow_rename;
1485 warn "file '$file' already exists - importing with a different name\n";
1489 my ($size) = read_common_header
($fh);
1490 $size = int($size/1024);
1493 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1494 my $oldname = $volname;
1495 $volname = $allocname;
1496 if (defined($name) && $allocname ne $oldname) {
1497 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1499 my $file = $class->path($scfg, $volname, $storeid)
1500 or die "internal error: failed to get path to newly allocated volume $volname\n";
1501 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1502 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1503 input
=> '<&'.fileno($fh));
1504 } elsif ($data_format eq 'tar') {
1505 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1506 input
=> '<&'.fileno($fh));
1508 die "volume import format '$format' not available for $class";
1512 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1517 return "$storeid:$volname";
1520 sub volume_import_formats
{
1521 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1522 if ($scfg->{path
} && !defined($base_snapshot)) {
1523 my $format = ($class->parse_volname($volname))[6];
1524 if ($with_snapshots) {
1525 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1528 return ('tar+size') if $format eq 'subvol';
1529 return ('raw+size');