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) = @_;
96 my $res = { $prune_backups->%* };
98 my $keep_all = delete $res->{'keep-all'};
100 if (scalar(grep { $_ > 0 } values %{$res}) == 0) {
101 $res = { 'keep-all' => 1 };
102 } elsif ($keep_all) {
103 die "keep-all cannot be set together with other options.\n";
108 register_standard_option
('prune-backups', {
109 description
=> "The retention options with shorter intervals are processed first " .
110 "with --keep-last being the very first one. Each option covers a " .
111 "specific period of time. We say that backups within this period " .
112 "are covered by this option. The next option does not take care " .
113 "of already covered backups and only considers older backups.",
116 format
=> 'prune-backups',
121 type
=> { description
=> "Storage type." },
122 storage
=> get_standard_option
('pve-storage-id',
123 { completion
=> \
&PVE
::Storage
::complete_storage
}),
124 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
126 description
=> "Allowed content types.\n\nNOTE: the value " .
127 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
128 type
=> 'string', format
=> 'pve-storage-content-list',
130 completion
=> \
&PVE
::Storage
::complete_content_type
,
133 description
=> "Flag to disable the storage.",
138 description
=> "Deprecated: use 'prune-backups' instead. " .
139 "Maximal number of backup files per VM. Use '0' for unlimited.",
144 'prune-backups' => get_standard_option
('prune-backups'),
146 description
=> "Mark storage as shared.",
151 description
=> "Default image format.",
152 type
=> 'string', format
=> 'pve-storage-format',
158 sub content_hash_to_string
{
162 foreach my $ct (keys %$hash) {
163 push @cta, $ct if $hash->{$ct};
166 return join(',', @cta);
169 sub valid_content_types
{
172 my $def = $defaultData->{plugindata
}->{$type};
176 return $def->{content
}->[0];
182 my $type = $scfg->{type
};
183 my $def = $defaultData->{plugindata
}->{$type};
185 my $def_format = 'raw';
186 my $valid_formats = [ $def_format ];
188 if (defined($def->{format
})) {
189 $def_format = $scfg->{format
} || $def->{format
}->[1];
190 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
193 return wantarray ?
($def_format, $valid_formats) : $def_format;
196 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
198 my ($path, $noerr) = @_;
200 # fixme: exclude more shell meta characters?
201 # we need absolute paths
202 if ($path !~ m
|^/[^;\
(\
)]+|) {
203 return undef if $noerr;
204 die "value does not look like a valid absolute path\n";
209 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
211 my ($server, $noerr) = @_;
213 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
214 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
216 return undef if $noerr;
217 die "value does not look like a valid server name or IP address\n";
222 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
224 my ($name, $noerr) = @_;
226 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
227 return undef if $noerr;
228 die "lvm name '$name' contains illegal characters\n";
234 # fixme: do we need this
235 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
237 # my ($portal, $noerr) = @_;
239 # # IP with optional port
240 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
241 # return undef if $noerr;
242 # die "value does not look like a valid portal address\n";
247 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
248 sub verify_portal_dns
{
249 my ($portal, $noerr) = @_;
251 # IP or DNS name with optional port
252 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
253 return undef if $noerr;
254 die "value does not look like a valid portal address\n";
259 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
261 my ($ct, $noerr) = @_;
263 my $valid_content = valid_content_types
('dir'); # dir includes all types
265 if (!$valid_content->{$ct}) {
266 return undef if $noerr;
267 die "invalid content type '$ct'\n";
273 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
275 my ($fmt, $noerr) = @_;
277 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
278 return undef if $noerr;
279 die "invalid format '$fmt'\n";
285 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
287 my ($value, $noerr) = @_;
289 # mount options (see man fstab)
290 if ($value !~ m/^\S+$/) {
291 return undef if $noerr;
292 die "invalid options '$value'\n";
298 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
299 sub parse_volume_id
{
300 my ($volid, $noerr) = @_;
302 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
303 return wantarray ?
($1, $2) : $1;
305 return undef if $noerr;
306 die "unable to parse volume ID '$volid'\n";
314 sub parse_section_header
{
315 my ($class, $line) = @_;
317 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
318 my ($type, $storeid) = (lc($1), $2);
319 my $errmsg = undef; # set if you want to skip whole section
320 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
322 my $config = {}; # to return additional attributes
323 return ($type, $storeid, $errmsg, $config);
329 my ($class, $type, $key, $value) = @_;
331 my $def = $defaultData->{plugindata
}->{$type};
333 if ($key eq 'content') {
334 my $valid_content = $def->{content
}->[0];
338 foreach my $c (PVE
::Tools
::split_list
($value)) {
339 if (!$valid_content->{$c}) {
340 warn "storage does not support content type '$c'\n";
346 if ($res->{none
} && scalar (keys %$res) > 1) {
347 die "unable to combine 'none' with other content types\n";
350 if (scalar(keys $res->%*) == 0 && !$valid_content->{none
}) {
351 die "storage does not support content type 'none'\n";
355 } elsif ($key eq 'format') {
356 my $valid_formats = $def->{format
}->[0];
358 if (!$valid_formats->{$value}) {
359 warn "storage does not support format '$value'\n";
364 } elsif ($key eq 'nodes') {
367 foreach my $node (PVE
::Tools
::split_list
($value)) {
368 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
374 # no node restrictions for local storage
375 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
376 # die "storage '$storeid' does not allow node restrictions\n";
386 my ($class, $type, $key, $value) = @_;
388 if ($key eq 'nodes') {
389 return join(',', keys(%$value));
390 } elsif ($key eq 'content') {
391 my $res = content_hash_to_string
($value) || 'none';
399 my ($class, $filename, $raw) = @_;
401 my $cfg = $class->SUPER::parse_config
($filename, $raw);
402 my $ids = $cfg->{ids
};
404 # make sure we have a reasonable 'local:' storage
405 # we want 'local' to be always the same 'type' (on all cluster nodes)
406 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
407 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
410 priority
=> 0, # force first entry
411 path
=> '/var/lib/vz',
412 'prune-backups' => 'keep-all=1',
424 # make sure we have a path
425 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
427 # remove node restrictions for local storage
428 delete($ids->{local}->{nodes
});
430 foreach my $storeid (keys %$ids) {
431 my $d = $ids->{$storeid};
432 my $type = $d->{type
};
434 my $def = $defaultData->{plugindata
}->{$type};
436 if ($def->{content
}) {
437 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
439 if (grep { $_ eq $type } @SHARED_STORAGE) {
447 # Storage implementation
449 # called during addition of storage (before the new storage config got written)
450 # die to abort addition if there are (grave) problems
451 # NOTE: runs in a storage config *locked* context
453 my ($class, $storeid, $scfg, %param) = @_;
455 # do nothing by default
459 # called during storage configuration update (before the updated storage config got written)
460 # die to abort the update if there are (grave) problems
461 # NOTE: runs in a storage config *locked* context
463 my ($class, $storeid, $scfg, %param) = @_;
465 # do nothing by default
469 # called during deletion of storage (before the new storage config got written)
470 # and if the activate check on addition fails, to cleanup all storage traces
471 # which on_add_hook may have created.
472 # die to abort deletion if there are (very grave) problems
473 # NOTE: runs in a storage config *locked* context
475 my ($class, $storeid, $scfg) = @_;
477 # do nothing by default
481 sub cluster_lock_storage
{
482 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
486 my $lockid = "pve-storage-$storeid";
487 my $lockdir = "/var/lock/pve-manager";
489 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
492 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
501 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
502 return ($1, $3, $2); # (name, format, isBase)
505 die "unable to parse volume filename '$name'\n";
509 my ($class, $volname) = @_;
511 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
512 my ($basedvmid, $basename) = ($1, $2);
513 parse_name_dir
($basename);
514 my ($vmid, $name) = ($3, $4);
515 my (undef, $format, $isBase) = parse_name_dir
($name);
516 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
517 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
518 my ($vmid, $name) = ($1, $2);
519 my (undef, $format, $isBase) = parse_name_dir
($name);
520 return ('images', $name, $vmid, undef, undef, $isBase, $format);
521 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
523 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::vztmpl_extension_re)$!) {
524 return ('vztmpl', $1);
525 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
526 return ('rootdir', $1, $1);
527 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
529 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
530 return ('backup', $fn, $2);
532 return ('backup', $fn);
533 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
534 return ('snippets', $1);
537 die "unable to parse directory volume name '$volname'\n";
540 my $vtype_subdirs = {
542 rootdir
=> 'private',
543 iso
=> 'template/iso',
544 vztmpl
=> 'template/cache',
546 snippets
=> 'snippets',
549 sub get_vtype_subdirs
{
550 return $vtype_subdirs;
554 my ($class, $scfg, $vtype) = @_;
556 my $path = $scfg->{path
};
558 die "storage definition has no path\n" if !$path;
560 my $subdir = $vtype_subdirs->{$vtype};
562 die "unknown vtype '$vtype'\n" if !defined($subdir);
564 return "$path/$subdir";
567 sub filesystem_path
{
568 my ($class, $scfg, $volname, $snapname) = @_;
570 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
571 $class->parse_volname($volname);
573 # Note: qcow2/qed has internal snapshot, so path is always
574 # the same (with or without snapshot => same file).
575 die "can't snapshot this image format\n"
576 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
578 my $dir = $class->get_subdir($scfg, $vtype);
580 $dir .= "/$vmid" if $vtype eq 'images';
582 my $path = "$dir/$name";
584 return wantarray ?
($path, $vmid, $vtype) : $path;
588 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
590 return $class->filesystem_path($scfg, $volname, $snapname);
594 my ($class, $storeid, $scfg, $volname) = @_;
596 # this only works for file based storage types
597 die "storage definition has no path\n" if !$scfg->{path
};
599 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
600 $class->parse_volname($volname);
602 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
604 die "create_base not possible with base image\n" if $isBase;
606 my $path = $class->filesystem_path($scfg, $volname);
608 my ($size, undef, $used, $parent) = file_size_info
($path);
609 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
611 die "volname '$volname' contains wrong information about parent\n"
612 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
615 $newname =~ s/^vm-/base-/;
617 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
620 my $newpath = $class->filesystem_path($scfg, $newvolname);
622 die "file '$newpath' already exists\n" if -f
$newpath;
624 rename($path, $newpath) ||
625 die "rename '$path' to '$newpath' failed - $!\n";
627 # We try to protect base volume
629 chmod(0444, $newpath); # nobody should write anything
631 # also try to set immutable flag
632 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
638 my $get_vm_disk_number = sub {
639 my ($disk_name, $scfg, $vmid, $suffix) = @_;
641 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
643 my $type = $scfg->{type
};
644 my $def = { %{$defaultData->{plugindata
}->{$type}} };
646 my $valid = $def->{format
}[0];
647 if ($valid->{subvol
}) {
648 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
651 if ($disk_name =~ m/$disk_regex/) {
658 sub get_next_vm_diskname
{
659 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
662 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
663 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
666 foreach my $disk (@$disk_list) {
667 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
668 $disk_ids->{$disknum} = 1 if defined($disknum);
671 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
672 if (!$disk_ids->{$i}) {
673 return "$prefix-$vmid-disk-$i$suffix";
677 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
680 sub find_free_diskname
{
681 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
683 my $disks = $class->list_images($storeid, $scfg, $vmid);
685 my $disk_list = [ map { $_->{volid
} } @$disks ];
687 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
691 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
693 # this only works for file based storage types
694 die "storage definition has no path\n" if !$scfg->{path
};
696 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
697 $class->parse_volname($volname);
699 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
701 die "this storage type does not support clone_image on snapshot\n" if $snap;
703 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
705 die "clone_image only works on base images\n" if !$isBase;
707 my $imagedir = $class->get_subdir($scfg, 'images');
708 $imagedir .= "/$vmid";
712 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
714 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
716 my $newvol = "$basevmid/$basename/$vmid/$name";
718 my $path = $class->filesystem_path($scfg, $newvol);
720 # Note: we use relative paths, so we need to call chdir before qemu-img
722 local $CWD = $imagedir;
724 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
725 '-F', $format, '-f', 'qcow2', $path];
737 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
739 my $imagedir = $class->get_subdir($scfg, 'images');
740 $imagedir .= "/$vmid";
744 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
746 my (undef, $tmpfmt) = parse_name_dir
($name);
748 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
751 my $path = "$imagedir/$name";
753 die "disk image '$path' already exists\n" if -e
$path;
755 if ($fmt eq 'subvol') {
756 # only allow this if size = 0, so that user knows what he is doing
757 die "storage does not support subvol quotas\n" if $size != 0;
759 my $old_umask = umask(0022);
761 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
765 my $cmd = ['/usr/bin/qemu-img', 'create'];
767 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
769 push @$cmd, '-f', $fmt, $path, "${size}K";
771 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
779 return "$vmid/$name";
783 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
785 my $path = $class->filesystem_path($scfg, $volname);
788 # try to remove immutable flag
789 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
793 if (defined($format) && ($format eq 'subvol')) {
794 File
::Path
::remove_tree
($path);
796 if (!(-f
$path || -l
$path)) {
797 warn "disk image '$path' does not exist\n";
801 unlink($path) || die "unlink '$path' failed - $!\n";
804 # try to cleanup directory to not clutter storage with empty $vmid dirs if
805 # all images from a guest got deleted
806 my $dir = dirname
($path);
813 my ($filename, $timeout) = @_;
815 my $st = File
::stat::stat($filename);
818 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
819 warn "failed to stat '$filename'$extramsg\n";
823 if (S_ISDIR
($st->mode)) {
824 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
829 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
831 outfunc
=> sub { $json .= shift },
832 errfunc
=> sub { warn "$_[0]\n" }
837 my $info = eval { decode_json
($json) };
839 warn "could not parse qemu-img info command output for '$filename' - $err\n";
840 return wantarray ?
(undef, undef, undef, undef, $st->ctime) : undef;
843 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
845 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
846 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
847 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
848 if (defined($parent)) {
849 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
851 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
854 sub get_volume_notes
{
855 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
857 die "volume notes are not supported for $class";
860 sub update_volume_notes
{
861 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
863 die "volume notes are not supported for $class";
866 sub volume_size_info
{
867 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
868 my $path = $class->filesystem_path($scfg, $volname);
869 return file_size_info
($path, $timeout);
874 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
876 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
878 return 1 if $running;
880 my $path = $class->filesystem_path($scfg, $volname);
882 my $format = ($class->parse_volname($volname))[6];
884 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
886 run_command
($cmd, timeout
=> 10);
891 sub volume_snapshot
{
892 my ($class, $scfg, $storeid, $volname, $snap) = @_;
894 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
896 my $path = $class->filesystem_path($scfg, $volname);
898 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
905 sub volume_rollback_is_possible
{
906 my ($class, $scfg, $storeid, $volname, $snap) = @_;
911 sub volume_snapshot_rollback
{
912 my ($class, $scfg, $storeid, $volname, $snap) = @_;
914 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
916 my $path = $class->filesystem_path($scfg, $volname);
918 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
925 sub volume_snapshot_delete
{
926 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
928 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
930 return 1 if $running;
932 my $path = $class->filesystem_path($scfg, $volname);
934 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
936 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
943 sub volume_snapshot_needs_fsfreeze
{
947 sub storage_can_replicate
{
948 my ($class, $scfg, $storeid, $format) = @_;
953 sub volume_has_feature
{
954 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
957 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
958 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
959 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
960 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
961 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
962 snap
=> {qcow2
=> 1} },
963 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
964 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
967 # clone_image creates a qcow2 volume
968 return 0 if $feature eq 'clone' &&
969 defined($opts->{valid_target_formats
}) &&
970 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
972 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
973 $class->parse_volname($volname);
979 $key = $isBase ?
'base' : 'current';
982 return 1 if defined($features->{$feature}->{$key}->{$format});
988 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
990 my $imagedir = $class->get_subdir($scfg, 'images');
992 my ($defFmt, $vaidFmts) = default_format
($scfg);
993 my $fmts = join ('|', @$vaidFmts);
997 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
999 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1005 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1007 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
1008 next if !($format && defined($size));
1011 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1012 my ($basevmid, $basename) = ($1, $2);
1013 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1015 $volid = "$storeid:$owner/$name";
1019 my $found = grep { $_ eq $volid } @$vollist;
1024 volid
=> $volid, format
=> $format,
1025 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
1028 $info->{ctime
} = $ctime if $ctime;
1036 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1037 my $get_subdir_files = sub {
1038 my ($sid, $path, $tt, $vmid) = @_;
1042 foreach my $fn (<$path/*>) {
1043 my $st = File
::stat::stat($fn);
1045 next if (!$st || S_ISDIR
($st->mode));
1050 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1052 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1054 } elsif ($tt eq 'vztmpl') {
1055 next if $fn !~ m!/([^/]+$PVE::Storage::vztmpl_extension_re)$!;
1057 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1059 } elsif ($tt eq 'backup') {
1060 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1065 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1066 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1068 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1070 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1072 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1074 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1075 $info->{vmid
} = $vmid // $1;
1078 my $notes_fn = $original.NOTES_EXT
;
1080 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1081 $info->{notes
} = $notes if defined($notes);
1084 } elsif ($tt eq 'snippets') {
1087 volid
=> "$sid:snippets/". basename
($fn),
1088 format
=> 'snippet',
1092 $info->{size
} = $st->size;
1093 $info->{ctime
} //= $st->ctime;
1102 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1105 my $vmlist = PVE
::Cluster
::get_vmlist
();
1106 foreach my $type (@$content_types) {
1109 if ($type eq 'images' || $type eq 'rootdir') {
1110 $data = $class->list_images($storeid, $scfg, $vmid);
1111 } elsif ($scfg->{path
}) {
1112 my $path = $class->get_subdir($scfg, $type);
1114 if ($type eq 'iso' && !defined($vmid)) {
1115 $data = $get_subdir_files->($storeid, $path, 'iso');
1116 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1117 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1118 } elsif ($type eq 'backup') {
1119 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1120 } elsif ($type eq 'snippets') {
1121 $data = $get_subdir_files->($storeid, $path, 'snippets');
1127 foreach my $item (@$data) {
1128 if ($type eq 'images' || $type eq 'rootdir') {
1129 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1131 if (defined($vminfo)) {
1132 $vmtype = $vminfo->{type
};
1134 if (defined($vmtype) && $vmtype eq 'lxc') {
1135 $item->{content
} = 'rootdir';
1137 $item->{content
} = 'images';
1139 next if $type ne $item->{content
};
1141 $item->{content
} = $type;
1152 my ($class, $storeid, $scfg, $cache) = @_;
1154 my $path = $scfg->{path
};
1156 die "storage definition has no path\n" if !$path;
1159 my $res = PVE
::Tools
::df
($path, $timeout);
1161 return undef if !$res || !$res->{total
};
1163 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1166 sub volume_snapshot_list
{
1167 my ($class, $scfg, $storeid, $volname) = @_;
1169 # implement in subclass
1170 die "Volume_snapshot_list is not implemented for $class";
1172 # return an empty array if dataset does not exist.
1175 sub activate_storage
{
1176 my ($class, $storeid, $scfg, $cache) = @_;
1178 my $path = $scfg->{path
};
1180 die "storage definition has no path\n" if !$path;
1182 # this path test may hang indefinitely on unresponsive mounts
1184 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1185 die "unable to activate storage '$storeid' - " .
1186 "directory '$path' does not exist or is unreachable\n";
1190 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1192 if (defined($scfg->{content
})) {
1193 foreach my $vtype (keys %$vtype_subdirs) {
1194 # OpenVZMigrate uses backup (dump) dir
1195 if (defined($scfg->{content
}->{$vtype}) ||
1196 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1197 my $subdir = $class->get_subdir($scfg, $vtype);
1198 mkpath
$subdir if $subdir ne $path;
1204 sub deactivate_storage
{
1205 my ($class, $storeid, $scfg, $cache) = @_;
1207 # do nothing by default
1211 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1213 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1218 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1223 sub activate_volume
{
1224 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1226 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1228 # check is volume exists
1229 if ($scfg->{path
}) {
1230 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1232 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1236 sub deactivate_volume
{
1237 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1239 # do nothing by default
1242 sub check_connection
{
1243 my ($class, $storeid, $scfg) = @_;
1244 # do nothing by default
1249 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1251 $logfunc //= sub { print "$_[1]\n" };
1253 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1255 my $backup_groups = {};
1256 my $prune_list = [];
1258 foreach my $backup (@{$backups}) {
1259 my $volid = $backup->{volid
};
1260 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1261 my $backup_type = $archive_info->{type
} // 'unknown';
1262 my $backup_vmid = $archive_info->{vmid
} // $backup->{vmid
};
1264 next if defined($type) && $type ne $backup_type;
1267 ctime
=> $backup->{ctime
},
1268 type
=> $backup_type,
1272 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1274 if ($archive_info->{is_std_name
}) {
1275 die "internal error - got no VMID\n" if !defined($backup_vmid);
1276 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1277 if defined($vmid) && $backup_vmid ne $vmid;
1279 $prune_entry->{ctime
} = $archive_info->{ctime
};
1280 my $group = "$backup_type/$backup_vmid";
1281 push @{$backup_groups->{$group}}, $prune_entry;
1283 # ignore backups that don't use the standard naming scheme
1284 $prune_entry->{mark
} = 'protected';
1287 push @{$prune_list}, $prune_entry;
1290 foreach my $backup_group (values %{$backup_groups}) {
1291 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1296 foreach my $prune_entry (@{$prune_list}) {
1297 next if $prune_entry->{mark
} ne 'remove';
1299 my $volid = $prune_entry->{volid
};
1300 $logfunc->('info', "removing backup '$volid'");
1302 my (undef, $volname) = parse_volume_id
($volid);
1303 my $archive_path = $class->filesystem_path($scfg, $volname);
1304 PVE
::Storage
::archive_remove
($archive_path);
1307 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1312 die "error pruning backups - check log\n" if $failed;
1317 # Import/Export interface:
1318 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1319 # the default implementations will return this if $scfg->{path} is set,
1320 # mimicking the old PVE::Storage::storage_migrate() function.
1322 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1323 # functions in case the format doesn't match their specialized
1324 # implementations to reuse the raw/tar code.
1326 # Format specification:
1327 # The following formats are all prefixed with image information in the form
1328 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1329 # to preallocate the image on storages which require it.
1331 # raw+size: (image files only)
1332 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1333 # qcow2+size, vmdk: (image files only)
1334 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1335 # files which are already in qcow2 format, or via `qemu-img convert`.
1336 # Note that these formats are only valid with $with_snapshots being true.
1337 # tar+size: (subvolumes only)
1338 # A GNU tar stream containing just the inner contents of the subvolume.
1339 # This does not distinguish between the contents of a privileged or
1340 # unprivileged container. In other words, this is from the root user
1341 # namespace's point of view with no uid-mapping in effect.
1342 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1344 # Plugins may reuse these helpers. Changes to the header format should be
1345 # reflected by changes to the function prototypes.
1346 sub write_common_header
($$) {
1347 my ($fh, $image_size_in_bytes) = @_;
1348 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1351 sub read_common_header
($) {
1353 sysread($fh, my $size, 8);
1354 $size = unpack('Q<', $size);
1355 die "import: no size found in export header, aborting.\n" if !defined($size);
1356 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1361 # Export a volume into a file handle as a stream of desired format.
1363 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1364 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1365 my $file = $class->path($scfg, $volname, $storeid)
1366 or goto unsupported
;
1367 my ($size, $file_format) = file_size_info
($file);
1369 if ($format eq 'raw+size') {
1370 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1371 write_common_header
($fh, $size);
1372 if ($file_format eq 'raw') {
1373 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1375 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1376 output
=> '>&'.fileno($fh));
1379 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1380 my $data_format = $1;
1381 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1382 write_common_header
($fh, $size);
1383 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1385 } elsif ($format eq 'tar+size') {
1386 goto unsupported
if $file_format ne 'subvol';
1387 write_common_header
($fh, $size);
1388 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1389 output
=> '>&'.fileno($fh));
1394 die "volume export format $format not available for $class";
1397 sub volume_export_formats
{
1398 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1399 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1400 my $file = $class->path($scfg, $volname, $storeid)
1402 my ($size, $format) = file_size_info
($file);
1404 if ($with_snapshots) {
1405 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1408 return ('tar+size') if $format eq 'subvol';
1409 return ('raw+size');
1414 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1416 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1418 die "volume import format '$format' not available for $class\n"
1419 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1420 my $data_format = $1;
1422 die "format $format cannot be imported without snapshots\n"
1423 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1424 die "format $format cannot be imported with snapshots\n"
1425 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1427 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1428 $class->parse_volname($volname);
1430 # XXX: Should we bother with conversion routines at this level? This won't
1431 # happen without manual CLI usage, so for now we just error out...
1432 die "cannot import format $format into a file of format $file_format\n"
1433 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1435 # Check for an existing file first since interrupting alloc_image doesn't
1437 my $file = $class->path($scfg, $volname, $storeid);
1439 die "file '$file' already exists\n" if !$allow_rename;
1440 warn "file '$file' already exists - importing with a different name\n";
1444 my ($size) = read_common_header
($fh);
1445 $size = int($size/1024);
1448 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1449 my $oldname = $volname;
1450 $volname = $allocname;
1451 if (defined($name) && $allocname ne $oldname) {
1452 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1454 my $file = $class->path($scfg, $volname, $storeid)
1455 or die "internal error: failed to get path to newly allocated volume $volname\n";
1456 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1457 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1458 input
=> '<&'.fileno($fh));
1459 } elsif ($data_format eq 'tar') {
1460 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1461 input
=> '<&'.fileno($fh));
1463 die "volume import format '$format' not available for $class";
1467 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1472 return "$storeid:$volname";
1475 sub volume_import_formats
{
1476 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1477 if ($scfg->{path
} && !defined($base_snapshot)) {
1478 my $format = ($class->parse_volname($volname))[6];
1479 if ($with_snapshots) {
1480 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1483 return ('tar+size') if $format eq 'subvol';
1484 return ('raw+size');