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, \
&validate_prune_backups
);
86 sub validate_prune_backups
{
89 die "at least one keep-option must be set and positive\n"
90 if !grep { $_ } values %{$keep};
94 register_standard_option
('prune-backups', {
95 description
=> "The retention options with shorter intervals are processed first " .
96 "with --keep-last being the very first one. Each option covers a " .
97 "specific period of time. We say that backups within this period " .
98 "are covered by this option. The next option does not take care " .
99 "of already covered backups and only considers older backups.",
102 format
=> 'prune-backups',
107 type
=> { description
=> "Storage type." },
108 storage
=> get_standard_option
('pve-storage-id',
109 { completion
=> \
&PVE
::Storage
::complete_storage
}),
110 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
112 description
=> "Allowed content types.\n\nNOTE: the value " .
113 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
114 type
=> 'string', format
=> 'pve-storage-content-list',
116 completion
=> \
&PVE
::Storage
::complete_content_type
,
119 description
=> "Flag to disable the storage.",
124 description
=> "Maximal number of backup files per VM. Use '0' for unlimted.",
129 'prune-backups' => get_standard_option
('prune-backups'),
131 description
=> "Mark storage as shared.",
136 description
=> "Default image format.",
137 type
=> 'string', format
=> 'pve-storage-format',
143 sub content_hash_to_string
{
147 foreach my $ct (keys %$hash) {
148 push @cta, $ct if $hash->{$ct};
151 return join(',', @cta);
154 sub valid_content_types
{
157 my $def = $defaultData->{plugindata
}->{$type};
161 return $def->{content
}->[0];
167 my $type = $scfg->{type
};
168 my $def = $defaultData->{plugindata
}->{$type};
170 my $def_format = 'raw';
171 my $valid_formats = [ $def_format ];
173 if (defined($def->{format
})) {
174 $def_format = $scfg->{format
} || $def->{format
}->[1];
175 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
178 return wantarray ?
($def_format, $valid_formats) : $def_format;
181 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
183 my ($path, $noerr) = @_;
185 # fixme: exclude more shell meta characters?
186 # we need absolute paths
187 if ($path !~ m
|^/[^;\
(\
)]+|) {
188 return undef if $noerr;
189 die "value does not look like a valid absolute path\n";
194 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
196 my ($server, $noerr) = @_;
198 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
199 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
201 return undef if $noerr;
202 die "value does not look like a valid server name or IP address\n";
207 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
209 my ($name, $noerr) = @_;
211 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
212 return undef if $noerr;
213 die "lvm name '$name' contains illegal characters\n";
219 # fixme: do we need this
220 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
222 # my ($portal, $noerr) = @_;
224 # # IP with optional port
225 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
226 # return undef if $noerr;
227 # die "value does not look like a valid portal address\n";
232 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
233 sub verify_portal_dns
{
234 my ($portal, $noerr) = @_;
236 # IP or DNS name with optional port
237 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
238 return undef if $noerr;
239 die "value does not look like a valid portal address\n";
244 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
246 my ($ct, $noerr) = @_;
248 my $valid_content = valid_content_types
('dir'); # dir includes all types
250 if (!$valid_content->{$ct}) {
251 return undef if $noerr;
252 die "invalid content type '$ct'\n";
258 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
260 my ($fmt, $noerr) = @_;
262 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
263 return undef if $noerr;
264 die "invalid format '$fmt'\n";
270 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
272 my ($value, $noerr) = @_;
274 # mount options (see man fstab)
275 if ($value !~ m/^\S+$/) {
276 return undef if $noerr;
277 die "invalid options '$value'\n";
283 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
284 sub parse_volume_id
{
285 my ($volid, $noerr) = @_;
287 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
288 return wantarray ?
($1, $2) : $1;
290 return undef if $noerr;
291 die "unable to parse volume ID '$volid'\n";
299 sub parse_section_header
{
300 my ($class, $line) = @_;
302 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
303 my ($type, $storeid) = (lc($1), $2);
304 my $errmsg = undef; # set if you want to skip whole section
305 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
307 my $config = {}; # to return additional attributes
308 return ($type, $storeid, $errmsg, $config);
314 my ($class, $type, $key, $value) = @_;
316 my $def = $defaultData->{plugindata
}->{$type};
318 if ($key eq 'content') {
319 my $valid_content = $def->{content
}->[0];
323 foreach my $c (PVE
::Tools
::split_list
($value)) {
324 if (!$valid_content->{$c}) {
325 warn "storage does not support content type '$c'\n";
331 if ($res->{none
} && scalar (keys %$res) > 1) {
332 die "unable to combine 'none' with other content types\n";
336 } elsif ($key eq 'format') {
337 my $valid_formats = $def->{format
}->[0];
339 if (!$valid_formats->{$value}) {
340 warn "storage does not support format '$value'\n";
345 } elsif ($key eq 'nodes') {
348 foreach my $node (PVE
::Tools
::split_list
($value)) {
349 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
355 # no node restrictions for local storage
356 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
357 # die "storage '$storeid' does not allow node restrictions\n";
367 my ($class, $type, $key, $value) = @_;
369 if ($key eq 'nodes') {
370 return join(',', keys(%$value));
371 } elsif ($key eq 'content') {
372 my $res = content_hash_to_string
($value) || 'none';
380 my ($class, $filename, $raw) = @_;
382 my $cfg = $class->SUPER::parse_config
($filename, $raw);
383 my $ids = $cfg->{ids
};
385 # make sure we have a reasonable 'local:' storage
386 # we want 'local' to be always the same 'type' (on all cluster nodes)
387 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
388 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
391 priority
=> 0, # force first entry
392 path
=> '/var/lib/vz',
394 content
=> { images
=> 1, rootdir
=> 1, vztmpl
=> 1, iso
=> 1, snippets
=> 1},
398 # make sure we have a path
399 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
401 # remove node restrictions for local storage
402 delete($ids->{local}->{nodes
});
404 foreach my $storeid (keys %$ids) {
405 my $d = $ids->{$storeid};
406 my $type = $d->{type
};
408 my $def = $defaultData->{plugindata
}->{$type};
410 if ($def->{content
}) {
411 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
413 if (grep { $_ eq $type } @SHARED_STORAGE) {
421 # Storage implementation
423 # called during addition of storage (before the new storage config got written)
424 # die to abort additon if there are (grave) problems
425 # NOTE: runs in a storage config *locked* context
427 my ($class, $storeid, $scfg, %param) = @_;
429 # do nothing by default
432 # called during storage configuration update (before the updated storage config got written)
433 # die to abort the update if there are (grave) problems
434 # NOTE: runs in a storage config *locked* context
436 my ($class, $storeid, $scfg, %param) = @_;
438 # do nothing by default
441 # called during deletion of storage (before the new storage config got written)
442 # and if the activate check on addition fails, to cleanup all storage traces
443 # which on_add_hook may have created.
444 # die to abort deletion if there are (very grave) problems
445 # NOTE: runs in a storage config *locked* context
447 my ($class, $storeid, $scfg) = @_;
449 # do nothing by default
452 sub cluster_lock_storage
{
453 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
457 my $lockid = "pve-storage-$storeid";
458 my $lockdir = "/var/lock/pve-manager";
460 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
463 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
472 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
473 return ($1, $3, $2); # (name, format, isBase)
476 die "unable to parse volume filename '$name'\n";
480 my ($class, $volname) = @_;
482 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
483 my ($basedvmid, $basename) = ($1, $2);
484 parse_name_dir
($basename);
485 my ($vmid, $name) = ($3, $4);
486 my (undef, $format, $isBase) = parse_name_dir
($name);
487 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
488 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
489 my ($vmid, $name) = ($1, $2);
490 my (undef, $format, $isBase) = parse_name_dir
($name);
491 return ('images', $name, $vmid, undef, undef, $isBase, $format);
492 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
494 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
495 return ('vztmpl', $1);
496 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
497 return ('rootdir', $1, $1);
498 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
500 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
501 return ('backup', $fn, $2);
503 return ('backup', $fn);
504 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
505 return ('snippets', $1);
508 die "unable to parse directory volume name '$volname'\n";
511 my $vtype_subdirs = {
513 rootdir
=> 'private',
514 iso
=> 'template/iso',
515 vztmpl
=> 'template/cache',
517 snippets
=> 'snippets',
520 sub get_vtype_subdirs
{
521 return $vtype_subdirs;
525 my ($class, $scfg, $vtype) = @_;
527 my $path = $scfg->{path
};
529 die "storage definintion has no path\n" if !$path;
531 my $subdir = $vtype_subdirs->{$vtype};
533 die "unknown vtype '$vtype'\n" if !defined($subdir);
535 return "$path/$subdir";
538 sub filesystem_path
{
539 my ($class, $scfg, $volname, $snapname) = @_;
541 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
542 $class->parse_volname($volname);
544 # Note: qcow2/qed has internal snapshot, so path is always
545 # the same (with or without snapshot => same file).
546 die "can't snapshot this image format\n"
547 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
549 my $dir = $class->get_subdir($scfg, $vtype);
551 $dir .= "/$vmid" if $vtype eq 'images';
553 my $path = "$dir/$name";
555 return wantarray ?
($path, $vmid, $vtype) : $path;
559 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
561 return $class->filesystem_path($scfg, $volname, $snapname);
565 my ($class, $storeid, $scfg, $volname) = @_;
567 # this only works for file based storage types
568 die "storage definition has no path\n" if !$scfg->{path
};
570 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
571 $class->parse_volname($volname);
573 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
575 die "create_base not possible with base image\n" if $isBase;
577 my $path = $class->filesystem_path($scfg, $volname);
579 my ($size, undef, $used, $parent) = file_size_info
($path);
580 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
582 die "volname '$volname' contains wrong information about parent\n"
583 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
586 $newname =~ s/^vm-/base-/;
588 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
591 my $newpath = $class->filesystem_path($scfg, $newvolname);
593 die "file '$newpath' already exists\n" if -f
$newpath;
595 rename($path, $newpath) ||
596 die "rename '$path' to '$newpath' failed - $!\n";
598 # We try to protect base volume
600 chmod(0444, $newpath); # nobody should write anything
602 # also try to set immutable flag
603 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
609 my $get_vm_disk_number = sub {
610 my ($disk_name, $scfg, $vmid, $suffix) = @_;
612 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
614 my $type = $scfg->{type
};
615 my $def = { %{$defaultData->{plugindata
}->{$type}} };
617 my $valid = $def->{format
}[0];
618 if ($valid->{subvol
}) {
619 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
622 if ($disk_name =~ m/$disk_regex/) {
629 sub get_next_vm_diskname
{
630 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
633 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
634 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
637 foreach my $disk (@$disk_list) {
638 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
639 $disk_ids->{$disknum} = 1 if defined($disknum);
642 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
643 if (!$disk_ids->{$i}) {
644 return "$prefix-$vmid-disk-$i$suffix";
648 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
651 sub find_free_diskname
{
652 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
654 my $disks = $class->list_images($storeid, $scfg, $vmid);
656 my $disk_list = [ map { $_->{volid
} } @$disks ];
658 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
662 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
664 # this only works for file based storage types
665 die "storage definintion has no path\n" if !$scfg->{path
};
667 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
668 $class->parse_volname($volname);
670 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
672 die "this storage type does not support clone_image on snapshot\n" if $snap;
674 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
676 die "clone_image only works on base images\n" if !$isBase;
678 my $imagedir = $class->get_subdir($scfg, 'images');
679 $imagedir .= "/$vmid";
683 my $name = $class->find_free_diskname($imagedir, $scfg, $vmid, "qcow2", 1);
685 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
687 my $newvol = "$basevmid/$basename/$vmid/$name";
689 my $path = $class->filesystem_path($scfg, $newvol);
691 # Note: we use relative paths, so we need to call chdir before qemu-img
693 local $CWD = $imagedir;
695 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
696 '-f', 'qcow2', $path];
708 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
710 my $imagedir = $class->get_subdir($scfg, 'images');
711 $imagedir .= "/$vmid";
715 $name = $class->find_free_diskname($imagedir, $scfg, $vmid, $fmt, 1) if !$name;
717 my (undef, $tmpfmt) = parse_name_dir
($name);
719 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
722 my $path = "$imagedir/$name";
724 die "disk image '$path' already exists\n" if -e
$path;
726 if ($fmt eq 'subvol') {
727 # only allow this if size = 0, so that user knows what he is doing
728 die "storage does not support subvol quotas\n" if $size != 0;
730 my $old_umask = umask(0022);
732 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
736 my $cmd = ['/usr/bin/qemu-img', 'create'];
738 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
740 push @$cmd, '-f', $fmt, $path, "${size}K";
742 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
750 return "$vmid/$name";
754 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
756 my $path = $class->filesystem_path($scfg, $volname);
759 # try to remove immutable flag
760 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
764 if (defined($format) && ($format eq 'subvol')) {
765 File
::Path
::remove_tree
($path);
767 if (!(-f
$path || -l
$path)) {
768 warn "disk image '$path' does not exist\n";
772 unlink($path) || die "unlink '$path' failed - $!\n";
775 # try to cleanup directory to not clutter storage with empty $vmid dirs if
776 # all images from a guest got deleted
777 my $dir = dirname
($path);
784 my ($filename, $timeout) = @_;
786 my $st = File
::stat::stat($filename);
789 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
790 warn "failed to stat '$filename'$extramsg\n";
794 if (S_ISDIR
($st->mode)) {
795 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
800 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
802 outfunc
=> sub { $json .= shift },
803 errfunc
=> sub { warn "$_[0]\n" }
808 my $info = eval { decode_json
($json) };
809 warn "could not parse qemu-img info command output for '$filename'\n" if $@;
811 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
813 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
816 sub volume_size_info
{
817 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
818 my $path = $class->filesystem_path($scfg, $volname);
819 return file_size_info
($path, $timeout);
824 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
826 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
828 return 1 if $running;
830 my $path = $class->filesystem_path($scfg, $volname);
832 my $format = ($class->parse_volname($volname))[6];
834 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
836 run_command
($cmd, timeout
=> 10);
841 sub volume_snapshot
{
842 my ($class, $scfg, $storeid, $volname, $snap) = @_;
844 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
846 my $path = $class->filesystem_path($scfg, $volname);
848 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
855 sub volume_rollback_is_possible
{
856 my ($class, $scfg, $storeid, $volname, $snap) = @_;
861 sub volume_snapshot_rollback
{
862 my ($class, $scfg, $storeid, $volname, $snap) = @_;
864 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
866 my $path = $class->filesystem_path($scfg, $volname);
868 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
875 sub volume_snapshot_delete
{
876 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
878 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
880 return 1 if $running;
882 my $path = $class->filesystem_path($scfg, $volname);
884 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
886 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
893 sub volume_snapshot_needs_fsfreeze
{
897 sub storage_can_replicate
{
898 my ($class, $scfg, $storeid, $format) = @_;
903 sub volume_has_feature
{
904 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
907 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
908 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
909 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
910 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
911 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
912 snap
=> {qcow2
=> 1} },
913 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
914 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
917 # clone_image creates a qcow2 volume
918 return 0 if $feature eq 'clone' &&
919 defined($opts->{valid_target_formats
}) &&
920 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
922 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
923 $class->parse_volname($volname);
929 $key = $isBase ?
'base' : 'current';
932 return 1 if defined($features->{$feature}->{$key}->{$format});
938 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
940 my $imagedir = $class->get_subdir($scfg, 'images');
942 my ($defFmt, $vaidFmts) = default_format
($scfg);
943 my $fmts = join ('|', @$vaidFmts);
947 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
949 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
955 next if !$vollist && defined($vmid) && ($owner ne $vmid);
957 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
958 next if !($format && defined($size));
961 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
962 my ($basevmid, $basename) = ($1, $2);
963 $volid = "$storeid:$basevmid/$basename/$owner/$name";
965 $volid = "$storeid:$owner/$name";
969 my $found = grep { $_ eq $volid } @$vollist;
974 volid
=> $volid, format
=> $format,
975 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
978 $info->{ctime
} = $ctime if $ctime;
986 # list templates ($tt = <iso|vztmpl|backup|snippets>)
987 my $get_subdir_files = sub {
988 my ($sid, $path, $tt, $vmid) = @_;
992 my $has_comment = {};
994 foreach my $fn (<$path/*>) {
996 if (COMMENT_EXT
eq substr($fn, -length(COMMENT_EXT
))) {
997 my $real_fn = substr($fn, 0, length($fn) - length(COMMENT_EXT
));
998 if (!defined($has_comment->{$real_fn})) {
999 $has_comment->{$real_fn} = (-f
$fn);
1001 next; # we do not need to do anything with comments themselves
1004 my $st = File
::stat::stat($fn);
1006 next if (!$st || S_ISDIR
($st->mode));
1011 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1013 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1015 } elsif ($tt eq 'vztmpl') {
1016 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
1018 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1020 } elsif ($tt eq 'backup') {
1021 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1022 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1026 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1028 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1030 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1032 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1033 $info->{vmid
} = $vmid // $1;
1036 my $comment_fn = $original.COMMENT_EXT
;
1037 if (!defined($has_comment->{$original})) {
1038 $has_comment->{$original} = (-f
$comment_fn);
1041 if ($has_comment->{$original}) {
1042 my $comment = PVE
::Tools
::file_read_firstline
($comment_fn);
1043 $info->{comment
} = $comment if defined($comment);
1046 } elsif ($tt eq 'snippets') {
1049 volid
=> "$sid:snippets/". basename
($fn),
1050 format
=> 'snippet',
1054 $info->{size
} = $st->size;
1055 $info->{ctime
} //= $st->ctime;
1064 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1067 my $vmlist = PVE
::Cluster
::get_vmlist
();
1068 foreach my $type (@$content_types) {
1071 if ($type eq 'images' || $type eq 'rootdir') {
1072 $data = $class->list_images($storeid, $scfg, $vmid);
1073 } elsif ($scfg->{path
}) {
1074 my $path = $class->get_subdir($scfg, $type);
1076 if ($type eq 'iso' && !defined($vmid)) {
1077 $data = $get_subdir_files->($storeid, $path, 'iso');
1078 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1079 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1080 } elsif ($type eq 'backup') {
1081 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1082 } elsif ($type eq 'snippets') {
1083 $data = $get_subdir_files->($storeid, $path, 'snippets');
1089 foreach my $item (@$data) {
1090 if ($type eq 'images' || $type eq 'rootdir') {
1091 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1093 if (defined($vminfo)) {
1094 $vmtype = $vminfo->{type
};
1096 if (defined($vmtype) && $vmtype eq 'lxc') {
1097 $item->{content
} = 'rootdir';
1099 $item->{content
} = 'images';
1101 next if $type ne $item->{content
};
1103 $item->{content
} = $type;
1114 my ($class, $storeid, $scfg, $cache) = @_;
1116 my $path = $scfg->{path
};
1118 die "storage definintion has no path\n" if !$path;
1121 my $res = PVE
::Tools
::df
($path, $timeout);
1123 return undef if !$res || !$res->{total
};
1125 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1128 sub volume_snapshot_list
{
1129 my ($class, $scfg, $storeid, $volname) = @_;
1131 # implement in subclass
1132 die "Volume_snapshot_list is not implemented for $class";
1134 # return an empty array if dataset does not exist.
1137 sub activate_storage
{
1138 my ($class, $storeid, $scfg, $cache) = @_;
1140 my $path = $scfg->{path
};
1142 die "storage definintion has no path\n" if !$path;
1144 # this path test may hang indefinitely on unresponsive mounts
1146 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1147 die "unable to activate storage '$storeid' - " .
1148 "directory '$path' does not exist or is unreachable\n";
1152 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1154 if (defined($scfg->{content
})) {
1155 foreach my $vtype (keys %$vtype_subdirs) {
1156 # OpenVZMigrate uses backup (dump) dir
1157 if (defined($scfg->{content
}->{$vtype}) ||
1158 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1159 my $subdir = $class->get_subdir($scfg, $vtype);
1160 mkpath
$subdir if $subdir ne $path;
1166 sub deactivate_storage
{
1167 my ($class, $storeid, $scfg, $cache) = @_;
1169 # do nothing by default
1173 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1175 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1180 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1185 sub activate_volume
{
1186 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1188 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1190 # check is volume exists
1191 if ($scfg->{path
}) {
1192 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1194 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1198 sub deactivate_volume
{
1199 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1201 # do nothing by default
1204 sub check_connection
{
1205 my ($class, $storeid, $scfg) = @_;
1206 # do nothing by default
1211 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1213 $logfunc //= sub { print "$_[1]\n" };
1215 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1217 my $backup_groups = {};
1218 my $prune_list = [];
1220 foreach my $backup (@{$backups}) {
1221 my $volid = $backup->{volid
};
1222 my $backup_vmid = $backup->{vmid
};
1223 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1224 my $backup_type = $archive_info->{type
} // 'unknown';
1226 next if defined($type) && $type ne $backup_type;
1229 ctime
=> $backup->{ctime
},
1230 type
=> $backup_type,
1234 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1236 if ($archive_info->{is_std_name
}) {
1237 $prune_entry->{ctime
} = $archive_info->{ctime
};
1238 my $group = "$backup_type/$backup_vmid";
1239 push @{$backup_groups->{$group}}, $prune_entry;
1241 # ignore backups that don't use the standard naming scheme
1242 $prune_entry->{mark
} = 'protected';
1245 push @{$prune_list}, $prune_entry;
1248 foreach my $backup_group (values %{$backup_groups}) {
1249 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1254 foreach my $prune_entry (@{$prune_list}) {
1255 next if $prune_entry->{mark
} ne 'remove';
1257 my $volid = $prune_entry->{volid
};
1258 $logfunc->('info', "removing backup '$volid'");
1260 my (undef, $volname) = parse_volume_id
($volid);
1261 my $archive_path = $class->filesystem_path($scfg, $volname);
1262 PVE
::Storage
::archive_remove
($archive_path);
1265 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1270 die "error pruning backups - check log\n" if $failed;
1275 # Import/Export interface:
1276 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1277 # the default implementations will return this if $scfg->{path} is set,
1278 # mimicking the old PVE::Storage::storage_migrate() function.
1280 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1281 # functions in case the format doesn't match their specialized
1282 # implementations to reuse the raw/tar code.
1284 # Format specification:
1285 # The following formats are all prefixed with image information in the form
1286 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1287 # to preallocate the image on storages which require it.
1289 # raw+size: (image files only)
1290 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1291 # qcow2+size, vmdk: (image files only)
1292 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1293 # files which are already in qcow2 format, or via `qemu-img convert`.
1294 # Note that these formats are only valid with $with_snapshots being true.
1295 # tar+size: (subvolumes only)
1296 # A GNU tar stream containing just the inner contents of the subvolume.
1297 # This does not distinguish between the contents of a privileged or
1298 # unprivileged container. In other words, this is from the root user
1299 # namespace's point of view with no uid-mapping in effect.
1300 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1302 # Plugins may reuse these helpers. Changes to the header format should be
1303 # reflected by changes to the function prototypes.
1304 sub write_common_header
($$) {
1305 my ($fh, $image_size_in_bytes) = @_;
1306 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1309 sub read_common_header
($) {
1311 sysread($fh, my $size, 8);
1312 $size = unpack('Q<', $size);
1313 die "import: no size found in export header, aborting.\n" if !defined($size);
1314 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1319 # Export a volume into a file handle as a stream of desired format.
1321 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1322 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1323 my $file = $class->path($scfg, $volname, $storeid)
1324 or goto unsupported
;
1325 my ($size, $file_format) = file_size_info
($file);
1327 if ($format eq 'raw+size') {
1328 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1329 write_common_header
($fh, $size);
1330 if ($file_format eq 'raw') {
1331 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1333 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1334 output
=> '>&'.fileno($fh));
1337 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1338 my $data_format = $1;
1339 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1340 write_common_header
($fh, $size);
1341 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1343 } elsif ($format eq 'tar+size') {
1344 goto unsupported
if $file_format ne 'subvol';
1345 write_common_header
($fh, $size);
1346 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1347 output
=> '>&'.fileno($fh));
1352 die "volume export format $format not available for $class";
1355 sub volume_export_formats
{
1356 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1357 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1358 my $file = $class->path($scfg, $volname, $storeid)
1360 my ($size, $format) = file_size_info
($file);
1362 if ($with_snapshots) {
1363 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1366 return ('tar+size') if $format eq 'subvol';
1367 return ('raw+size');
1372 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1374 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1376 die "volume import format '$format' not available for $class\n"
1377 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1378 my $data_format = $1;
1380 die "format $format cannot be imported without snapshots\n"
1381 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1382 die "format $format cannot be imported with snapshots\n"
1383 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1385 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1386 $class->parse_volname($volname);
1388 # XXX: Should we bother with conversion routines at this level? This won't
1389 # happen without manual CLI usage, so for now we just error out...
1390 die "cannot import format $format into a file of format $file_format\n"
1391 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1393 # Check for an existing file first since interrupting alloc_image doesn't
1395 my $file = $class->path($scfg, $volname, $storeid);
1397 die "file '$file' already exists\n" if !$allow_rename;
1398 warn "file '$file' already exists - importing with a different name\n";
1402 my ($size) = read_common_header
($fh);
1403 $size = int($size/1024);
1406 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1407 my $oldname = $volname;
1408 $volname = $allocname;
1409 if (defined($name) && $allocname ne $oldname) {
1410 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1412 my $file = $class->path($scfg, $volname, $storeid)
1413 or die "internal error: failed to get path to newly allocated volume $volname\n";
1414 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1415 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1416 input
=> '<&'.fileno($fh));
1417 } elsif ($data_format eq 'tar') {
1418 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1419 input
=> '<&'.fileno($fh));
1421 die "volume import format '$format' not available for $class";
1425 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1430 return "$storeid:$volname";
1433 sub volume_import_formats
{
1434 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1435 if ($scfg->{path
} && !defined($base_snapshot)) {
1436 my $format = ($class->parse_volname($volname))[6];
1437 if ($with_snapshots) {
1438 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1441 return ('tar+size') if $format eq 'subvol';
1442 return ('raw+size');