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 $keep_all = delete $prune_backups->{'keep-all'};
98 if (!scalar(grep {$_ > 0} values %{$prune_backups})) {
99 $prune_backups = { 'keep-all' => 1 };
100 } elsif ($keep_all) {
101 die "keep-all cannot be set together with other options.\n";
104 return $prune_backups;
106 register_standard_option
('prune-backups', {
107 description
=> "The retention options with shorter intervals are processed first " .
108 "with --keep-last being the very first one. Each option covers a " .
109 "specific period of time. We say that backups within this period " .
110 "are covered by this option. The next option does not take care " .
111 "of already covered backups and only considers older backups.",
114 format
=> 'prune-backups',
119 type
=> { description
=> "Storage type." },
120 storage
=> get_standard_option
('pve-storage-id',
121 { completion
=> \
&PVE
::Storage
::complete_storage
}),
122 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
124 description
=> "Allowed content types.\n\nNOTE: the value " .
125 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
126 type
=> 'string', format
=> 'pve-storage-content-list',
128 completion
=> \
&PVE
::Storage
::complete_content_type
,
131 description
=> "Flag to disable the storage.",
136 description
=> "Deprecated: use 'prune-backups' instead. " .
137 "Maximal number of backup files per VM. Use '0' for unlimited.",
142 'prune-backups' => get_standard_option
('prune-backups'),
144 description
=> "Mark storage as shared.",
149 description
=> "Default image format.",
150 type
=> 'string', format
=> 'pve-storage-format',
156 sub content_hash_to_string
{
160 foreach my $ct (keys %$hash) {
161 push @cta, $ct if $hash->{$ct};
164 return join(',', @cta);
167 sub valid_content_types
{
170 my $def = $defaultData->{plugindata
}->{$type};
174 return $def->{content
}->[0];
180 my $type = $scfg->{type
};
181 my $def = $defaultData->{plugindata
}->{$type};
183 my $def_format = 'raw';
184 my $valid_formats = [ $def_format ];
186 if (defined($def->{format
})) {
187 $def_format = $scfg->{format
} || $def->{format
}->[1];
188 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
191 return wantarray ?
($def_format, $valid_formats) : $def_format;
194 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
196 my ($path, $noerr) = @_;
198 # fixme: exclude more shell meta characters?
199 # we need absolute paths
200 if ($path !~ m
|^/[^;\
(\
)]+|) {
201 return undef if $noerr;
202 die "value does not look like a valid absolute path\n";
207 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
209 my ($server, $noerr) = @_;
211 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
212 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
214 return undef if $noerr;
215 die "value does not look like a valid server name or IP address\n";
220 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
222 my ($name, $noerr) = @_;
224 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
225 return undef if $noerr;
226 die "lvm name '$name' contains illegal characters\n";
232 # fixme: do we need this
233 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
235 # my ($portal, $noerr) = @_;
237 # # IP with optional port
238 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
239 # return undef if $noerr;
240 # die "value does not look like a valid portal address\n";
245 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
246 sub verify_portal_dns
{
247 my ($portal, $noerr) = @_;
249 # IP or DNS name with optional port
250 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
251 return undef if $noerr;
252 die "value does not look like a valid portal address\n";
257 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
259 my ($ct, $noerr) = @_;
261 my $valid_content = valid_content_types
('dir'); # dir includes all types
263 if (!$valid_content->{$ct}) {
264 return undef if $noerr;
265 die "invalid content type '$ct'\n";
271 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
273 my ($fmt, $noerr) = @_;
275 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
276 return undef if $noerr;
277 die "invalid format '$fmt'\n";
283 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
285 my ($value, $noerr) = @_;
287 # mount options (see man fstab)
288 if ($value !~ m/^\S+$/) {
289 return undef if $noerr;
290 die "invalid options '$value'\n";
296 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
297 sub parse_volume_id
{
298 my ($volid, $noerr) = @_;
300 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
301 return wantarray ?
($1, $2) : $1;
303 return undef if $noerr;
304 die "unable to parse volume ID '$volid'\n";
312 sub parse_section_header
{
313 my ($class, $line) = @_;
315 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
316 my ($type, $storeid) = (lc($1), $2);
317 my $errmsg = undef; # set if you want to skip whole section
318 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
320 my $config = {}; # to return additional attributes
321 return ($type, $storeid, $errmsg, $config);
327 my ($class, $type, $key, $value) = @_;
329 my $def = $defaultData->{plugindata
}->{$type};
331 if ($key eq 'content') {
332 my $valid_content = $def->{content
}->[0];
336 foreach my $c (PVE
::Tools
::split_list
($value)) {
337 if (!$valid_content->{$c}) {
338 warn "storage does not support content type '$c'\n";
344 if ($res->{none
} && scalar (keys %$res) > 1) {
345 die "unable to combine 'none' with other content types\n";
348 if (scalar(keys $res->%*) == 0 && !$valid_content->{none
}) {
349 die "storage does not support content type 'none'\n";
353 } elsif ($key eq 'format') {
354 my $valid_formats = $def->{format
}->[0];
356 if (!$valid_formats->{$value}) {
357 warn "storage does not support format '$value'\n";
362 } elsif ($key eq 'nodes') {
365 foreach my $node (PVE
::Tools
::split_list
($value)) {
366 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
372 # no node restrictions for local storage
373 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
374 # die "storage '$storeid' does not allow node restrictions\n";
384 my ($class, $type, $key, $value) = @_;
386 if ($key eq 'nodes') {
387 return join(',', keys(%$value));
388 } elsif ($key eq 'content') {
389 my $res = content_hash_to_string
($value) || 'none';
397 my ($class, $filename, $raw) = @_;
399 my $cfg = $class->SUPER::parse_config
($filename, $raw);
400 my $ids = $cfg->{ids
};
402 # make sure we have a reasonable 'local:' storage
403 # we want 'local' to be always the same 'type' (on all cluster nodes)
404 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
405 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
408 priority
=> 0, # force first entry
409 path
=> '/var/lib/vz',
410 'prune-backups' => 'keep-all=1',
422 # make sure we have a path
423 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
425 # remove node restrictions for local storage
426 delete($ids->{local}->{nodes
});
428 foreach my $storeid (keys %$ids) {
429 my $d = $ids->{$storeid};
430 my $type = $d->{type
};
432 my $def = $defaultData->{plugindata
}->{$type};
434 if ($def->{content
}) {
435 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
437 if (grep { $_ eq $type } @SHARED_STORAGE) {
445 # Storage implementation
447 # called during addition of storage (before the new storage config got written)
448 # die to abort addition if there are (grave) problems
449 # NOTE: runs in a storage config *locked* context
451 my ($class, $storeid, $scfg, %param) = @_;
453 # do nothing by default
457 # called during storage configuration update (before the updated storage config got written)
458 # die to abort the update if there are (grave) problems
459 # NOTE: runs in a storage config *locked* context
461 my ($class, $storeid, $scfg, %param) = @_;
463 # do nothing by default
467 # called during deletion of storage (before the new storage config got written)
468 # and if the activate check on addition fails, to cleanup all storage traces
469 # which on_add_hook may have created.
470 # die to abort deletion if there are (very grave) problems
471 # NOTE: runs in a storage config *locked* context
473 my ($class, $storeid, $scfg) = @_;
475 # do nothing by default
479 sub cluster_lock_storage
{
480 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
484 my $lockid = "pve-storage-$storeid";
485 my $lockdir = "/var/lock/pve-manager";
487 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
490 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
499 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
500 return ($1, $3, $2); # (name, format, isBase)
503 die "unable to parse volume filename '$name'\n";
507 my ($class, $volname) = @_;
509 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
510 my ($basedvmid, $basename) = ($1, $2);
511 parse_name_dir
($basename);
512 my ($vmid, $name) = ($3, $4);
513 my (undef, $format, $isBase) = parse_name_dir
($name);
514 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
515 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
516 my ($vmid, $name) = ($1, $2);
517 my (undef, $format, $isBase) = parse_name_dir
($name);
518 return ('images', $name, $vmid, undef, undef, $isBase, $format);
519 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
521 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::vztmpl_extension_re)$!) {
522 return ('vztmpl', $1);
523 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
524 return ('rootdir', $1, $1);
525 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
527 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
528 return ('backup', $fn, $2);
530 return ('backup', $fn);
531 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
532 return ('snippets', $1);
535 die "unable to parse directory volume name '$volname'\n";
538 my $vtype_subdirs = {
540 rootdir
=> 'private',
541 iso
=> 'template/iso',
542 vztmpl
=> 'template/cache',
544 snippets
=> 'snippets',
547 sub get_vtype_subdirs
{
548 return $vtype_subdirs;
552 my ($class, $scfg, $vtype) = @_;
554 my $path = $scfg->{path
};
556 die "storage definition has no path\n" if !$path;
558 my $subdir = $vtype_subdirs->{$vtype};
560 die "unknown vtype '$vtype'\n" if !defined($subdir);
562 return "$path/$subdir";
565 sub filesystem_path
{
566 my ($class, $scfg, $volname, $snapname) = @_;
568 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
569 $class->parse_volname($volname);
571 # Note: qcow2/qed has internal snapshot, so path is always
572 # the same (with or without snapshot => same file).
573 die "can't snapshot this image format\n"
574 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
576 my $dir = $class->get_subdir($scfg, $vtype);
578 $dir .= "/$vmid" if $vtype eq 'images';
580 my $path = "$dir/$name";
582 return wantarray ?
($path, $vmid, $vtype) : $path;
586 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
588 return $class->filesystem_path($scfg, $volname, $snapname);
592 my ($class, $storeid, $scfg, $volname) = @_;
594 # this only works for file based storage types
595 die "storage definition has no path\n" if !$scfg->{path
};
597 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
598 $class->parse_volname($volname);
600 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
602 die "create_base not possible with base image\n" if $isBase;
604 my $path = $class->filesystem_path($scfg, $volname);
606 my ($size, undef, $used, $parent) = file_size_info
($path);
607 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
609 die "volname '$volname' contains wrong information about parent\n"
610 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
613 $newname =~ s/^vm-/base-/;
615 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
618 my $newpath = $class->filesystem_path($scfg, $newvolname);
620 die "file '$newpath' already exists\n" if -f
$newpath;
622 rename($path, $newpath) ||
623 die "rename '$path' to '$newpath' failed - $!\n";
625 # We try to protect base volume
627 chmod(0444, $newpath); # nobody should write anything
629 # also try to set immutable flag
630 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
636 my $get_vm_disk_number = sub {
637 my ($disk_name, $scfg, $vmid, $suffix) = @_;
639 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
641 my $type = $scfg->{type
};
642 my $def = { %{$defaultData->{plugindata
}->{$type}} };
644 my $valid = $def->{format
}[0];
645 if ($valid->{subvol
}) {
646 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
649 if ($disk_name =~ m/$disk_regex/) {
656 sub get_next_vm_diskname
{
657 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
660 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
661 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
664 foreach my $disk (@$disk_list) {
665 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
666 $disk_ids->{$disknum} = 1 if defined($disknum);
669 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
670 if (!$disk_ids->{$i}) {
671 return "$prefix-$vmid-disk-$i$suffix";
675 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
678 sub find_free_diskname
{
679 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
681 my $disks = $class->list_images($storeid, $scfg, $vmid);
683 my $disk_list = [ map { $_->{volid
} } @$disks ];
685 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
689 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
691 # this only works for file based storage types
692 die "storage definition has no path\n" if !$scfg->{path
};
694 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
695 $class->parse_volname($volname);
697 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
699 die "this storage type does not support clone_image on snapshot\n" if $snap;
701 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
703 die "clone_image only works on base images\n" if !$isBase;
705 my $imagedir = $class->get_subdir($scfg, 'images');
706 $imagedir .= "/$vmid";
710 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
712 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
714 my $newvol = "$basevmid/$basename/$vmid/$name";
716 my $path = $class->filesystem_path($scfg, $newvol);
718 # Note: we use relative paths, so we need to call chdir before qemu-img
720 local $CWD = $imagedir;
722 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
723 '-F', $format, '-f', 'qcow2', $path];
735 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
737 my $imagedir = $class->get_subdir($scfg, 'images');
738 $imagedir .= "/$vmid";
742 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
744 my (undef, $tmpfmt) = parse_name_dir
($name);
746 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
749 my $path = "$imagedir/$name";
751 die "disk image '$path' already exists\n" if -e
$path;
753 if ($fmt eq 'subvol') {
754 # only allow this if size = 0, so that user knows what he is doing
755 die "storage does not support subvol quotas\n" if $size != 0;
757 my $old_umask = umask(0022);
759 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
763 my $cmd = ['/usr/bin/qemu-img', 'create'];
765 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
767 push @$cmd, '-f', $fmt, $path, "${size}K";
769 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
777 return "$vmid/$name";
781 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
783 my $path = $class->filesystem_path($scfg, $volname);
786 # try to remove immutable flag
787 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
791 if (defined($format) && ($format eq 'subvol')) {
792 File
::Path
::remove_tree
($path);
794 if (!(-f
$path || -l
$path)) {
795 warn "disk image '$path' does not exist\n";
799 unlink($path) || die "unlink '$path' failed - $!\n";
802 # try to cleanup directory to not clutter storage with empty $vmid dirs if
803 # all images from a guest got deleted
804 my $dir = dirname
($path);
811 my ($filename, $timeout) = @_;
813 my $st = File
::stat::stat($filename);
816 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
817 warn "failed to stat '$filename'$extramsg\n";
821 if (S_ISDIR
($st->mode)) {
822 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
827 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
829 outfunc
=> sub { $json .= shift },
830 errfunc
=> sub { warn "$_[0]\n" }
835 my $info = eval { decode_json
($json) };
837 warn "could not parse qemu-img info command output for '$filename' - $err\n";
838 return wantarray ?
(undef, undef, undef, undef, $st->ctime) : undef;
841 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
843 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
844 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
845 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
846 if (defined($parent)) {
847 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
849 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
852 sub get_volume_notes
{
853 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
855 die "volume notes are not supported for $class";
858 sub update_volume_notes
{
859 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
861 die "volume notes are not supported for $class";
864 sub volume_size_info
{
865 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
866 my $path = $class->filesystem_path($scfg, $volname);
867 return file_size_info
($path, $timeout);
872 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
874 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
876 return 1 if $running;
878 my $path = $class->filesystem_path($scfg, $volname);
880 my $format = ($class->parse_volname($volname))[6];
882 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
884 run_command
($cmd, timeout
=> 10);
889 sub volume_snapshot
{
890 my ($class, $scfg, $storeid, $volname, $snap) = @_;
892 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
894 my $path = $class->filesystem_path($scfg, $volname);
896 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
903 sub volume_rollback_is_possible
{
904 my ($class, $scfg, $storeid, $volname, $snap) = @_;
909 sub volume_snapshot_rollback
{
910 my ($class, $scfg, $storeid, $volname, $snap) = @_;
912 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
914 my $path = $class->filesystem_path($scfg, $volname);
916 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
923 sub volume_snapshot_delete
{
924 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
926 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
928 return 1 if $running;
930 my $path = $class->filesystem_path($scfg, $volname);
932 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
934 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
941 sub volume_snapshot_needs_fsfreeze
{
945 sub storage_can_replicate
{
946 my ($class, $scfg, $storeid, $format) = @_;
951 sub volume_has_feature
{
952 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
955 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
956 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
957 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
958 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
959 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
960 snap
=> {qcow2
=> 1} },
961 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
962 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
965 # clone_image creates a qcow2 volume
966 return 0 if $feature eq 'clone' &&
967 defined($opts->{valid_target_formats
}) &&
968 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
970 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
971 $class->parse_volname($volname);
977 $key = $isBase ?
'base' : 'current';
980 return 1 if defined($features->{$feature}->{$key}->{$format});
986 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
988 my $imagedir = $class->get_subdir($scfg, 'images');
990 my ($defFmt, $vaidFmts) = default_format
($scfg);
991 my $fmts = join ('|', @$vaidFmts);
995 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
997 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1003 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1005 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
1006 next if !($format && defined($size));
1009 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1010 my ($basevmid, $basename) = ($1, $2);
1011 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1013 $volid = "$storeid:$owner/$name";
1017 my $found = grep { $_ eq $volid } @$vollist;
1022 volid
=> $volid, format
=> $format,
1023 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
1026 $info->{ctime
} = $ctime if $ctime;
1034 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1035 my $get_subdir_files = sub {
1036 my ($sid, $path, $tt, $vmid) = @_;
1040 foreach my $fn (<$path/*>) {
1041 my $st = File
::stat::stat($fn);
1043 next if (!$st || S_ISDIR
($st->mode));
1048 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1050 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1052 } elsif ($tt eq 'vztmpl') {
1053 next if $fn !~ m!/([^/]+$PVE::Storage::vztmpl_extension_re)$!;
1055 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1057 } elsif ($tt eq 'backup') {
1058 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1063 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1064 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1066 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1068 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1070 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1072 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1073 $info->{vmid
} = $vmid // $1;
1076 my $notes_fn = $original.NOTES_EXT
;
1078 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1079 $info->{notes
} = $notes if defined($notes);
1082 } elsif ($tt eq 'snippets') {
1085 volid
=> "$sid:snippets/". basename
($fn),
1086 format
=> 'snippet',
1090 $info->{size
} = $st->size;
1091 $info->{ctime
} //= $st->ctime;
1100 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1103 my $vmlist = PVE
::Cluster
::get_vmlist
();
1104 foreach my $type (@$content_types) {
1107 if ($type eq 'images' || $type eq 'rootdir') {
1108 $data = $class->list_images($storeid, $scfg, $vmid);
1109 } elsif ($scfg->{path
}) {
1110 my $path = $class->get_subdir($scfg, $type);
1112 if ($type eq 'iso' && !defined($vmid)) {
1113 $data = $get_subdir_files->($storeid, $path, 'iso');
1114 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1115 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1116 } elsif ($type eq 'backup') {
1117 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1118 } elsif ($type eq 'snippets') {
1119 $data = $get_subdir_files->($storeid, $path, 'snippets');
1125 foreach my $item (@$data) {
1126 if ($type eq 'images' || $type eq 'rootdir') {
1127 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1129 if (defined($vminfo)) {
1130 $vmtype = $vminfo->{type
};
1132 if (defined($vmtype) && $vmtype eq 'lxc') {
1133 $item->{content
} = 'rootdir';
1135 $item->{content
} = 'images';
1137 next if $type ne $item->{content
};
1139 $item->{content
} = $type;
1150 my ($class, $storeid, $scfg, $cache) = @_;
1152 my $path = $scfg->{path
};
1154 die "storage definition has no path\n" if !$path;
1157 my $res = PVE
::Tools
::df
($path, $timeout);
1159 return undef if !$res || !$res->{total
};
1161 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1164 sub volume_snapshot_list
{
1165 my ($class, $scfg, $storeid, $volname) = @_;
1167 # implement in subclass
1168 die "Volume_snapshot_list is not implemented for $class";
1170 # return an empty array if dataset does not exist.
1173 sub activate_storage
{
1174 my ($class, $storeid, $scfg, $cache) = @_;
1176 my $path = $scfg->{path
};
1178 die "storage definition has no path\n" if !$path;
1180 # this path test may hang indefinitely on unresponsive mounts
1182 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1183 die "unable to activate storage '$storeid' - " .
1184 "directory '$path' does not exist or is unreachable\n";
1188 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1190 if (defined($scfg->{content
})) {
1191 foreach my $vtype (keys %$vtype_subdirs) {
1192 # OpenVZMigrate uses backup (dump) dir
1193 if (defined($scfg->{content
}->{$vtype}) ||
1194 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1195 my $subdir = $class->get_subdir($scfg, $vtype);
1196 mkpath
$subdir if $subdir ne $path;
1202 sub deactivate_storage
{
1203 my ($class, $storeid, $scfg, $cache) = @_;
1205 # do nothing by default
1209 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1211 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1216 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1221 sub activate_volume
{
1222 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1224 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1226 # check is volume exists
1227 if ($scfg->{path
}) {
1228 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1230 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1234 sub deactivate_volume
{
1235 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1237 # do nothing by default
1240 sub check_connection
{
1241 my ($class, $storeid, $scfg) = @_;
1242 # do nothing by default
1247 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1249 $logfunc //= sub { print "$_[1]\n" };
1251 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1253 my $backup_groups = {};
1254 my $prune_list = [];
1256 foreach my $backup (@{$backups}) {
1257 my $volid = $backup->{volid
};
1258 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1259 my $backup_type = $archive_info->{type
} // 'unknown';
1260 my $backup_vmid = $archive_info->{vmid
} // $backup->{vmid
};
1262 next if defined($type) && $type ne $backup_type;
1265 ctime
=> $backup->{ctime
},
1266 type
=> $backup_type,
1270 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1272 if ($archive_info->{is_std_name
}) {
1273 die "internal error - got no VMID\n" if !defined($backup_vmid);
1274 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1275 if defined($vmid) && $backup_vmid ne $vmid;
1277 $prune_entry->{ctime
} = $archive_info->{ctime
};
1278 my $group = "$backup_type/$backup_vmid";
1279 push @{$backup_groups->{$group}}, $prune_entry;
1281 # ignore backups that don't use the standard naming scheme
1282 $prune_entry->{mark
} = 'protected';
1285 push @{$prune_list}, $prune_entry;
1288 foreach my $backup_group (values %{$backup_groups}) {
1289 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1294 foreach my $prune_entry (@{$prune_list}) {
1295 next if $prune_entry->{mark
} ne 'remove';
1297 my $volid = $prune_entry->{volid
};
1298 $logfunc->('info', "removing backup '$volid'");
1300 my (undef, $volname) = parse_volume_id
($volid);
1301 my $archive_path = $class->filesystem_path($scfg, $volname);
1302 PVE
::Storage
::archive_remove
($archive_path);
1305 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1310 die "error pruning backups - check log\n" if $failed;
1315 # Import/Export interface:
1316 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1317 # the default implementations will return this if $scfg->{path} is set,
1318 # mimicking the old PVE::Storage::storage_migrate() function.
1320 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1321 # functions in case the format doesn't match their specialized
1322 # implementations to reuse the raw/tar code.
1324 # Format specification:
1325 # The following formats are all prefixed with image information in the form
1326 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1327 # to preallocate the image on storages which require it.
1329 # raw+size: (image files only)
1330 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1331 # qcow2+size, vmdk: (image files only)
1332 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1333 # files which are already in qcow2 format, or via `qemu-img convert`.
1334 # Note that these formats are only valid with $with_snapshots being true.
1335 # tar+size: (subvolumes only)
1336 # A GNU tar stream containing just the inner contents of the subvolume.
1337 # This does not distinguish between the contents of a privileged or
1338 # unprivileged container. In other words, this is from the root user
1339 # namespace's point of view with no uid-mapping in effect.
1340 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1342 # Plugins may reuse these helpers. Changes to the header format should be
1343 # reflected by changes to the function prototypes.
1344 sub write_common_header
($$) {
1345 my ($fh, $image_size_in_bytes) = @_;
1346 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1349 sub read_common_header
($) {
1351 sysread($fh, my $size, 8);
1352 $size = unpack('Q<', $size);
1353 die "import: no size found in export header, aborting.\n" if !defined($size);
1354 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1359 # Export a volume into a file handle as a stream of desired format.
1361 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1362 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1363 my $file = $class->path($scfg, $volname, $storeid)
1364 or goto unsupported
;
1365 my ($size, $file_format) = file_size_info
($file);
1367 if ($format eq 'raw+size') {
1368 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1369 write_common_header
($fh, $size);
1370 if ($file_format eq 'raw') {
1371 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1373 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1374 output
=> '>&'.fileno($fh));
1377 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1378 my $data_format = $1;
1379 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1380 write_common_header
($fh, $size);
1381 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1383 } elsif ($format eq 'tar+size') {
1384 goto unsupported
if $file_format ne 'subvol';
1385 write_common_header
($fh, $size);
1386 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1387 output
=> '>&'.fileno($fh));
1392 die "volume export format $format not available for $class";
1395 sub volume_export_formats
{
1396 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1397 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1398 my $file = $class->path($scfg, $volname, $storeid)
1400 my ($size, $format) = file_size_info
($file);
1402 if ($with_snapshots) {
1403 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1406 return ('tar+size') if $format eq 'subvol';
1407 return ('raw+size');
1412 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1414 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1416 die "volume import format '$format' not available for $class\n"
1417 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1418 my $data_format = $1;
1420 die "format $format cannot be imported without snapshots\n"
1421 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1422 die "format $format cannot be imported with snapshots\n"
1423 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1425 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1426 $class->parse_volname($volname);
1428 # XXX: Should we bother with conversion routines at this level? This won't
1429 # happen without manual CLI usage, so for now we just error out...
1430 die "cannot import format $format into a file of format $file_format\n"
1431 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1433 # Check for an existing file first since interrupting alloc_image doesn't
1435 my $file = $class->path($scfg, $volname, $storeid);
1437 die "file '$file' already exists\n" if !$allow_rename;
1438 warn "file '$file' already exists - importing with a different name\n";
1442 my ($size) = read_common_header
($fh);
1443 $size = int($size/1024);
1446 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1447 my $oldname = $volname;
1448 $volname = $allocname;
1449 if (defined($name) && $allocname ne $oldname) {
1450 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1452 my $file = $class->path($scfg, $volname, $storeid)
1453 or die "internal error: failed to get path to newly allocated volume $volname\n";
1454 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1455 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1456 input
=> '<&'.fileno($fh));
1457 } elsif ($data_format eq 'tar') {
1458 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1459 input
=> '<&'.fileno($fh));
1461 die "volume import format '$format' not available for $class";
1465 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1470 return "$storeid:$volname";
1473 sub volume_import_formats
{
1474 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1475 if ($scfg->{path
} && !defined($base_snapshot)) {
1476 my $format = ($class->parse_volname($volname))[6];
1477 if ($with_snapshots) {
1478 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1481 return ('tar+size') if $format eq 'subvol';
1482 return ('raw+size');