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 = (
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 all backups. Conflicts with the other options when true.',
62 description
=> 'Keep the last <N> backups.',
66 description
=> 'Keep backups for the last <N> different hours. If there is more' .
67 'than one backup for a single hour, only the latest one is kept.'
71 description
=> 'Keep backups for the last <N> different days. If there is more' .
72 'than one backup for a single day, only the latest one is kept.'
76 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
77 'than one backup for a single week, only the latest one is kept.'
81 description
=> 'Keep backups for the last <N> different months. If there is more' .
82 'than one backup for a single month, only the latest one is kept.'
86 description
=> 'Keep backups for the last <N> different years. If there is more' .
87 'than one backup for a single year, only the latest one is kept.'
90 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format, \
&validate_prune_backups
);
91 sub validate_prune_backups
{
92 my ($prune_backups) = @_;
94 my $keep_all = delete $prune_backups->{'keep-all'};
96 if (!scalar(grep {$_ > 0} values %{$prune_backups})) {
97 $prune_backups = { 'keep-all' => 1 };
99 die "keep-all cannot be set together with other options.\n";
102 return $prune_backups;
104 register_standard_option
('prune-backups', {
105 description
=> "The retention options with shorter intervals are processed first " .
106 "with --keep-last being the very first one. Each option covers a " .
107 "specific period of time. We say that backups within this period " .
108 "are covered by this option. The next option does not take care " .
109 "of already covered backups and only considers older backups.",
112 format
=> 'prune-backups',
117 type
=> { description
=> "Storage type." },
118 storage
=> get_standard_option
('pve-storage-id',
119 { completion
=> \
&PVE
::Storage
::complete_storage
}),
120 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
122 description
=> "Allowed content types.\n\nNOTE: the value " .
123 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
124 type
=> 'string', format
=> 'pve-storage-content-list',
126 completion
=> \
&PVE
::Storage
::complete_content_type
,
129 description
=> "Flag to disable the storage.",
134 description
=> "Maximal number of backup files per VM. Use '0' for unlimted.",
139 'prune-backups' => get_standard_option
('prune-backups'),
141 description
=> "Mark storage as shared.",
146 description
=> "Default image format.",
147 type
=> 'string', format
=> 'pve-storage-format',
153 sub content_hash_to_string
{
157 foreach my $ct (keys %$hash) {
158 push @cta, $ct if $hash->{$ct};
161 return join(',', @cta);
164 sub valid_content_types
{
167 my $def = $defaultData->{plugindata
}->{$type};
171 return $def->{content
}->[0];
177 my $type = $scfg->{type
};
178 my $def = $defaultData->{plugindata
}->{$type};
180 my $def_format = 'raw';
181 my $valid_formats = [ $def_format ];
183 if (defined($def->{format
})) {
184 $def_format = $scfg->{format
} || $def->{format
}->[1];
185 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
188 return wantarray ?
($def_format, $valid_formats) : $def_format;
191 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
193 my ($path, $noerr) = @_;
195 # fixme: exclude more shell meta characters?
196 # we need absolute paths
197 if ($path !~ m
|^/[^;\
(\
)]+|) {
198 return undef if $noerr;
199 die "value does not look like a valid absolute path\n";
204 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
206 my ($server, $noerr) = @_;
208 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
209 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
211 return undef if $noerr;
212 die "value does not look like a valid server name or IP address\n";
217 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
219 my ($name, $noerr) = @_;
221 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
222 return undef if $noerr;
223 die "lvm name '$name' contains illegal characters\n";
229 # fixme: do we need this
230 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
232 # my ($portal, $noerr) = @_;
234 # # IP with optional port
235 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
236 # return undef if $noerr;
237 # die "value does not look like a valid portal address\n";
242 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
243 sub verify_portal_dns
{
244 my ($portal, $noerr) = @_;
246 # IP or DNS name with optional port
247 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
248 return undef if $noerr;
249 die "value does not look like a valid portal address\n";
254 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
256 my ($ct, $noerr) = @_;
258 my $valid_content = valid_content_types
('dir'); # dir includes all types
260 if (!$valid_content->{$ct}) {
261 return undef if $noerr;
262 die "invalid content type '$ct'\n";
268 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
270 my ($fmt, $noerr) = @_;
272 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
273 return undef if $noerr;
274 die "invalid format '$fmt'\n";
280 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
282 my ($value, $noerr) = @_;
284 # mount options (see man fstab)
285 if ($value !~ m/^\S+$/) {
286 return undef if $noerr;
287 die "invalid options '$value'\n";
293 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
294 sub parse_volume_id
{
295 my ($volid, $noerr) = @_;
297 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
298 return wantarray ?
($1, $2) : $1;
300 return undef if $noerr;
301 die "unable to parse volume ID '$volid'\n";
309 sub parse_section_header
{
310 my ($class, $line) = @_;
312 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
313 my ($type, $storeid) = (lc($1), $2);
314 my $errmsg = undef; # set if you want to skip whole section
315 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
317 my $config = {}; # to return additional attributes
318 return ($type, $storeid, $errmsg, $config);
324 my ($class, $type, $key, $value) = @_;
326 my $def = $defaultData->{plugindata
}->{$type};
328 if ($key eq 'content') {
329 my $valid_content = $def->{content
}->[0];
333 foreach my $c (PVE
::Tools
::split_list
($value)) {
334 if (!$valid_content->{$c}) {
335 warn "storage does not support content type '$c'\n";
341 if ($res->{none
} && scalar (keys %$res) > 1) {
342 die "unable to combine 'none' with other content types\n";
346 } elsif ($key eq 'format') {
347 my $valid_formats = $def->{format
}->[0];
349 if (!$valid_formats->{$value}) {
350 warn "storage does not support format '$value'\n";
355 } elsif ($key eq 'nodes') {
358 foreach my $node (PVE
::Tools
::split_list
($value)) {
359 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
365 # no node restrictions for local storage
366 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
367 # die "storage '$storeid' does not allow node restrictions\n";
377 my ($class, $type, $key, $value) = @_;
379 if ($key eq 'nodes') {
380 return join(',', keys(%$value));
381 } elsif ($key eq 'content') {
382 my $res = content_hash_to_string
($value) || 'none';
390 my ($class, $filename, $raw) = @_;
392 my $cfg = $class->SUPER::parse_config
($filename, $raw);
393 my $ids = $cfg->{ids
};
395 # make sure we have a reasonable 'local:' storage
396 # we want 'local' to be always the same 'type' (on all cluster nodes)
397 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
398 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
401 priority
=> 0, # force first entry
402 path
=> '/var/lib/vz',
404 content
=> { images
=> 1, rootdir
=> 1, vztmpl
=> 1, iso
=> 1, snippets
=> 1},
408 # make sure we have a path
409 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
411 # remove node restrictions for local storage
412 delete($ids->{local}->{nodes
});
414 foreach my $storeid (keys %$ids) {
415 my $d = $ids->{$storeid};
416 my $type = $d->{type
};
418 my $def = $defaultData->{plugindata
}->{$type};
420 if ($def->{content
}) {
421 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
423 if (grep { $_ eq $type } @SHARED_STORAGE) {
431 # Storage implementation
433 # called during addition of storage (before the new storage config got written)
434 # die to abort additon if there are (grave) problems
435 # NOTE: runs in a storage config *locked* context
437 my ($class, $storeid, $scfg, %param) = @_;
439 # do nothing by default
443 # called during storage configuration update (before the updated storage config got written)
444 # die to abort the update if there are (grave) problems
445 # NOTE: runs in a storage config *locked* context
447 my ($class, $storeid, $scfg, %param) = @_;
449 # do nothing by default
453 # called during deletion of storage (before the new storage config got written)
454 # and if the activate check on addition fails, to cleanup all storage traces
455 # which on_add_hook may have created.
456 # die to abort deletion if there are (very grave) problems
457 # NOTE: runs in a storage config *locked* context
459 my ($class, $storeid, $scfg) = @_;
461 # do nothing by default
465 sub cluster_lock_storage
{
466 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
470 my $lockid = "pve-storage-$storeid";
471 my $lockdir = "/var/lock/pve-manager";
473 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
476 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
485 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
486 return ($1, $3, $2); # (name, format, isBase)
489 die "unable to parse volume filename '$name'\n";
493 my ($class, $volname) = @_;
495 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
496 my ($basedvmid, $basename) = ($1, $2);
497 parse_name_dir
($basename);
498 my ($vmid, $name) = ($3, $4);
499 my (undef, $format, $isBase) = parse_name_dir
($name);
500 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
501 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
502 my ($vmid, $name) = ($1, $2);
503 my (undef, $format, $isBase) = parse_name_dir
($name);
504 return ('images', $name, $vmid, undef, undef, $isBase, $format);
505 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
507 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
508 return ('vztmpl', $1);
509 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
510 return ('rootdir', $1, $1);
511 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
513 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
514 return ('backup', $fn, $2);
516 return ('backup', $fn);
517 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
518 return ('snippets', $1);
521 die "unable to parse directory volume name '$volname'\n";
524 my $vtype_subdirs = {
526 rootdir
=> 'private',
527 iso
=> 'template/iso',
528 vztmpl
=> 'template/cache',
530 snippets
=> 'snippets',
533 sub get_vtype_subdirs
{
534 return $vtype_subdirs;
538 my ($class, $scfg, $vtype) = @_;
540 my $path = $scfg->{path
};
542 die "storage definintion has no path\n" if !$path;
544 my $subdir = $vtype_subdirs->{$vtype};
546 die "unknown vtype '$vtype'\n" if !defined($subdir);
548 return "$path/$subdir";
551 sub filesystem_path
{
552 my ($class, $scfg, $volname, $snapname) = @_;
554 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
555 $class->parse_volname($volname);
557 # Note: qcow2/qed has internal snapshot, so path is always
558 # the same (with or without snapshot => same file).
559 die "can't snapshot this image format\n"
560 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
562 my $dir = $class->get_subdir($scfg, $vtype);
564 $dir .= "/$vmid" if $vtype eq 'images';
566 my $path = "$dir/$name";
568 return wantarray ?
($path, $vmid, $vtype) : $path;
572 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
574 return $class->filesystem_path($scfg, $volname, $snapname);
578 my ($class, $storeid, $scfg, $volname) = @_;
580 # this only works for file based storage types
581 die "storage definition has no path\n" if !$scfg->{path
};
583 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
584 $class->parse_volname($volname);
586 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
588 die "create_base not possible with base image\n" if $isBase;
590 my $path = $class->filesystem_path($scfg, $volname);
592 my ($size, undef, $used, $parent) = file_size_info
($path);
593 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
595 die "volname '$volname' contains wrong information about parent\n"
596 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
599 $newname =~ s/^vm-/base-/;
601 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
604 my $newpath = $class->filesystem_path($scfg, $newvolname);
606 die "file '$newpath' already exists\n" if -f
$newpath;
608 rename($path, $newpath) ||
609 die "rename '$path' to '$newpath' failed - $!\n";
611 # We try to protect base volume
613 chmod(0444, $newpath); # nobody should write anything
615 # also try to set immutable flag
616 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
622 my $get_vm_disk_number = sub {
623 my ($disk_name, $scfg, $vmid, $suffix) = @_;
625 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
627 my $type = $scfg->{type
};
628 my $def = { %{$defaultData->{plugindata
}->{$type}} };
630 my $valid = $def->{format
}[0];
631 if ($valid->{subvol
}) {
632 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
635 if ($disk_name =~ m/$disk_regex/) {
642 sub get_next_vm_diskname
{
643 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
646 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
647 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
650 foreach my $disk (@$disk_list) {
651 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
652 $disk_ids->{$disknum} = 1 if defined($disknum);
655 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
656 if (!$disk_ids->{$i}) {
657 return "$prefix-$vmid-disk-$i$suffix";
661 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
664 sub find_free_diskname
{
665 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
667 my $disks = $class->list_images($storeid, $scfg, $vmid);
669 my $disk_list = [ map { $_->{volid
} } @$disks ];
671 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
675 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
677 # this only works for file based storage types
678 die "storage definintion has no path\n" if !$scfg->{path
};
680 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
681 $class->parse_volname($volname);
683 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
685 die "this storage type does not support clone_image on snapshot\n" if $snap;
687 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
689 die "clone_image only works on base images\n" if !$isBase;
691 my $imagedir = $class->get_subdir($scfg, 'images');
692 $imagedir .= "/$vmid";
696 my $name = $class->find_free_diskname($imagedir, $scfg, $vmid, "qcow2", 1);
698 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
700 my $newvol = "$basevmid/$basename/$vmid/$name";
702 my $path = $class->filesystem_path($scfg, $newvol);
704 # Note: we use relative paths, so we need to call chdir before qemu-img
706 local $CWD = $imagedir;
708 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
709 '-f', 'qcow2', $path];
721 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
723 my $imagedir = $class->get_subdir($scfg, 'images');
724 $imagedir .= "/$vmid";
728 $name = $class->find_free_diskname($imagedir, $scfg, $vmid, $fmt, 1) if !$name;
730 my (undef, $tmpfmt) = parse_name_dir
($name);
732 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
735 my $path = "$imagedir/$name";
737 die "disk image '$path' already exists\n" if -e
$path;
739 if ($fmt eq 'subvol') {
740 # only allow this if size = 0, so that user knows what he is doing
741 die "storage does not support subvol quotas\n" if $size != 0;
743 my $old_umask = umask(0022);
745 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
749 my $cmd = ['/usr/bin/qemu-img', 'create'];
751 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
753 push @$cmd, '-f', $fmt, $path, "${size}K";
755 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
763 return "$vmid/$name";
767 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
769 my $path = $class->filesystem_path($scfg, $volname);
772 # try to remove immutable flag
773 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
777 if (defined($format) && ($format eq 'subvol')) {
778 File
::Path
::remove_tree
($path);
780 if (!(-f
$path || -l
$path)) {
781 warn "disk image '$path' does not exist\n";
785 unlink($path) || die "unlink '$path' failed - $!\n";
788 # try to cleanup directory to not clutter storage with empty $vmid dirs if
789 # all images from a guest got deleted
790 my $dir = dirname
($path);
797 my ($filename, $timeout) = @_;
799 my $st = File
::stat::stat($filename);
802 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
803 warn "failed to stat '$filename'$extramsg\n";
807 if (S_ISDIR
($st->mode)) {
808 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
813 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
815 outfunc
=> sub { $json .= shift },
816 errfunc
=> sub { warn "$_[0]\n" }
821 my $info = eval { decode_json
($json) };
822 warn "could not parse qemu-img info command output for '$filename'\n" if $@;
824 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
826 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
829 sub volume_size_info
{
830 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
831 my $path = $class->filesystem_path($scfg, $volname);
832 return file_size_info
($path, $timeout);
837 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
839 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
841 return 1 if $running;
843 my $path = $class->filesystem_path($scfg, $volname);
845 my $format = ($class->parse_volname($volname))[6];
847 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
849 run_command
($cmd, timeout
=> 10);
854 sub volume_snapshot
{
855 my ($class, $scfg, $storeid, $volname, $snap) = @_;
857 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
859 my $path = $class->filesystem_path($scfg, $volname);
861 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
868 sub volume_rollback_is_possible
{
869 my ($class, $scfg, $storeid, $volname, $snap) = @_;
874 sub volume_snapshot_rollback
{
875 my ($class, $scfg, $storeid, $volname, $snap) = @_;
877 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
879 my $path = $class->filesystem_path($scfg, $volname);
881 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
888 sub volume_snapshot_delete
{
889 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
891 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
893 return 1 if $running;
895 my $path = $class->filesystem_path($scfg, $volname);
897 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
899 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
906 sub volume_snapshot_needs_fsfreeze
{
910 sub storage_can_replicate
{
911 my ($class, $scfg, $storeid, $format) = @_;
916 sub volume_has_feature
{
917 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
920 snapshot
=> { current
=> { qcow2
=> 1}, snap
=> { qcow2
=> 1} },
921 clone
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
922 template
=> { current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1} },
923 copy
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
924 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
925 snap
=> {qcow2
=> 1} },
926 sparseinit
=> { base
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
927 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1} },
930 # clone_image creates a qcow2 volume
931 return 0 if $feature eq 'clone' &&
932 defined($opts->{valid_target_formats
}) &&
933 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}});
935 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
936 $class->parse_volname($volname);
942 $key = $isBase ?
'base' : 'current';
945 return 1 if defined($features->{$feature}->{$key}->{$format});
951 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
953 my $imagedir = $class->get_subdir($scfg, 'images');
955 my ($defFmt, $vaidFmts) = default_format
($scfg);
956 my $fmts = join ('|', @$vaidFmts);
960 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
962 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
968 next if !$vollist && defined($vmid) && ($owner ne $vmid);
970 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
971 next if !($format && defined($size));
974 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
975 my ($basevmid, $basename) = ($1, $2);
976 $volid = "$storeid:$basevmid/$basename/$owner/$name";
978 $volid = "$storeid:$owner/$name";
982 my $found = grep { $_ eq $volid } @$vollist;
987 volid
=> $volid, format
=> $format,
988 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
991 $info->{ctime
} = $ctime if $ctime;
999 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1000 my $get_subdir_files = sub {
1001 my ($sid, $path, $tt, $vmid) = @_;
1005 foreach my $fn (<$path/*>) {
1006 my $st = File
::stat::stat($fn);
1008 next if (!$st || S_ISDIR
($st->mode));
1013 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1015 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1017 } elsif ($tt eq 'vztmpl') {
1018 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
1020 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1022 } elsif ($tt eq 'backup') {
1023 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1024 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1028 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1030 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1032 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1034 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1035 $info->{vmid
} = $vmid // $1;
1038 my $notes_fn = $original.NOTES_EXT
;
1040 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1041 $info->{notes
} = $notes if defined($notes);
1044 } elsif ($tt eq 'snippets') {
1047 volid
=> "$sid:snippets/". basename
($fn),
1048 format
=> 'snippet',
1052 $info->{size
} = $st->size;
1053 $info->{ctime
} //= $st->ctime;
1062 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1065 my $vmlist = PVE
::Cluster
::get_vmlist
();
1066 foreach my $type (@$content_types) {
1069 if ($type eq 'images' || $type eq 'rootdir') {
1070 $data = $class->list_images($storeid, $scfg, $vmid);
1071 } elsif ($scfg->{path
}) {
1072 my $path = $class->get_subdir($scfg, $type);
1074 if ($type eq 'iso' && !defined($vmid)) {
1075 $data = $get_subdir_files->($storeid, $path, 'iso');
1076 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1077 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1078 } elsif ($type eq 'backup') {
1079 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1080 } elsif ($type eq 'snippets') {
1081 $data = $get_subdir_files->($storeid, $path, 'snippets');
1087 foreach my $item (@$data) {
1088 if ($type eq 'images' || $type eq 'rootdir') {
1089 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1091 if (defined($vminfo)) {
1092 $vmtype = $vminfo->{type
};
1094 if (defined($vmtype) && $vmtype eq 'lxc') {
1095 $item->{content
} = 'rootdir';
1097 $item->{content
} = 'images';
1099 next if $type ne $item->{content
};
1101 $item->{content
} = $type;
1112 my ($class, $storeid, $scfg, $cache) = @_;
1114 my $path = $scfg->{path
};
1116 die "storage definintion has no path\n" if !$path;
1119 my $res = PVE
::Tools
::df
($path, $timeout);
1121 return undef if !$res || !$res->{total
};
1123 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1126 sub volume_snapshot_list
{
1127 my ($class, $scfg, $storeid, $volname) = @_;
1129 # implement in subclass
1130 die "Volume_snapshot_list is not implemented for $class";
1132 # return an empty array if dataset does not exist.
1135 sub activate_storage
{
1136 my ($class, $storeid, $scfg, $cache) = @_;
1138 my $path = $scfg->{path
};
1140 die "storage definintion has no path\n" if !$path;
1142 # this path test may hang indefinitely on unresponsive mounts
1144 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1145 die "unable to activate storage '$storeid' - " .
1146 "directory '$path' does not exist or is unreachable\n";
1150 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1152 if (defined($scfg->{content
})) {
1153 foreach my $vtype (keys %$vtype_subdirs) {
1154 # OpenVZMigrate uses backup (dump) dir
1155 if (defined($scfg->{content
}->{$vtype}) ||
1156 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1157 my $subdir = $class->get_subdir($scfg, $vtype);
1158 mkpath
$subdir if $subdir ne $path;
1164 sub deactivate_storage
{
1165 my ($class, $storeid, $scfg, $cache) = @_;
1167 # do nothing by default
1171 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1173 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1178 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1183 sub activate_volume
{
1184 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1186 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1188 # check is volume exists
1189 if ($scfg->{path
}) {
1190 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1192 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1196 sub deactivate_volume
{
1197 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1199 # do nothing by default
1202 sub check_connection
{
1203 my ($class, $storeid, $scfg) = @_;
1204 # do nothing by default
1209 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1211 $logfunc //= sub { print "$_[1]\n" };
1213 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1215 my $backup_groups = {};
1216 my $prune_list = [];
1218 foreach my $backup (@{$backups}) {
1219 my $volid = $backup->{volid
};
1220 my $backup_vmid = $backup->{vmid
};
1221 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1222 my $backup_type = $archive_info->{type
} // 'unknown';
1224 next if defined($type) && $type ne $backup_type;
1227 ctime
=> $backup->{ctime
},
1228 type
=> $backup_type,
1232 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1234 if ($archive_info->{is_std_name
}) {
1235 $prune_entry->{ctime
} = $archive_info->{ctime
};
1236 my $group = "$backup_type/$backup_vmid";
1237 push @{$backup_groups->{$group}}, $prune_entry;
1239 # ignore backups that don't use the standard naming scheme
1240 $prune_entry->{mark
} = 'protected';
1243 push @{$prune_list}, $prune_entry;
1246 foreach my $backup_group (values %{$backup_groups}) {
1247 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1252 foreach my $prune_entry (@{$prune_list}) {
1253 next if $prune_entry->{mark
} ne 'remove';
1255 my $volid = $prune_entry->{volid
};
1256 $logfunc->('info', "removing backup '$volid'");
1258 my (undef, $volname) = parse_volume_id
($volid);
1259 my $archive_path = $class->filesystem_path($scfg, $volname);
1260 PVE
::Storage
::archive_remove
($archive_path);
1263 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1268 die "error pruning backups - check log\n" if $failed;
1273 # Import/Export interface:
1274 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1275 # the default implementations will return this if $scfg->{path} is set,
1276 # mimicking the old PVE::Storage::storage_migrate() function.
1278 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1279 # functions in case the format doesn't match their specialized
1280 # implementations to reuse the raw/tar code.
1282 # Format specification:
1283 # The following formats are all prefixed with image information in the form
1284 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1285 # to preallocate the image on storages which require it.
1287 # raw+size: (image files only)
1288 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1289 # qcow2+size, vmdk: (image files only)
1290 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1291 # files which are already in qcow2 format, or via `qemu-img convert`.
1292 # Note that these formats are only valid with $with_snapshots being true.
1293 # tar+size: (subvolumes only)
1294 # A GNU tar stream containing just the inner contents of the subvolume.
1295 # This does not distinguish between the contents of a privileged or
1296 # unprivileged container. In other words, this is from the root user
1297 # namespace's point of view with no uid-mapping in effect.
1298 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1300 # Plugins may reuse these helpers. Changes to the header format should be
1301 # reflected by changes to the function prototypes.
1302 sub write_common_header
($$) {
1303 my ($fh, $image_size_in_bytes) = @_;
1304 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1307 sub read_common_header
($) {
1309 sysread($fh, my $size, 8);
1310 $size = unpack('Q<', $size);
1311 die "import: no size found in export header, aborting.\n" if !defined($size);
1312 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1317 # Export a volume into a file handle as a stream of desired format.
1319 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1320 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1321 my $file = $class->path($scfg, $volname, $storeid)
1322 or goto unsupported
;
1323 my ($size, $file_format) = file_size_info
($file);
1325 if ($format eq 'raw+size') {
1326 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1327 write_common_header
($fh, $size);
1328 if ($file_format eq 'raw') {
1329 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1331 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1332 output
=> '>&'.fileno($fh));
1335 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1336 my $data_format = $1;
1337 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1338 write_common_header
($fh, $size);
1339 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1341 } elsif ($format eq 'tar+size') {
1342 goto unsupported
if $file_format ne 'subvol';
1343 write_common_header
($fh, $size);
1344 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1345 output
=> '>&'.fileno($fh));
1350 die "volume export format $format not available for $class";
1353 sub volume_export_formats
{
1354 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1355 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1356 my $file = $class->path($scfg, $volname, $storeid)
1358 my ($size, $format) = file_size_info
($file);
1360 if ($with_snapshots) {
1361 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1364 return ('tar+size') if $format eq 'subvol';
1365 return ('raw+size');
1370 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1372 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1374 die "volume import format '$format' not available for $class\n"
1375 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1376 my $data_format = $1;
1378 die "format $format cannot be imported without snapshots\n"
1379 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1380 die "format $format cannot be imported with snapshots\n"
1381 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1383 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1384 $class->parse_volname($volname);
1386 # XXX: Should we bother with conversion routines at this level? This won't
1387 # happen without manual CLI usage, so for now we just error out...
1388 die "cannot import format $format into a file of format $file_format\n"
1389 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1391 # Check for an existing file first since interrupting alloc_image doesn't
1393 my $file = $class->path($scfg, $volname, $storeid);
1395 die "file '$file' already exists\n" if !$allow_rename;
1396 warn "file '$file' already exists - importing with a different name\n";
1400 my ($size) = read_common_header
($fh);
1401 $size = int($size/1024);
1404 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1405 my $oldname = $volname;
1406 $volname = $allocname;
1407 if (defined($name) && $allocname ne $oldname) {
1408 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1410 my $file = $class->path($scfg, $volname, $storeid)
1411 or die "internal error: failed to get path to newly allocated volume $volname\n";
1412 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1413 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1414 input
=> '<&'.fileno($fh));
1415 } elsif ($data_format eq 'tar') {
1416 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1417 input
=> '<&'.fileno($fh));
1419 die "volume import format '$format' not available for $class";
1423 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1428 return "$storeid:$volname";
1431 sub volume_import_formats
{
1432 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1433 if ($scfg->{path
} && !defined($base_snapshot)) {
1434 my $format = ($class->parse_volname($volname))[6];
1435 if ($with_snapshots) {
1436 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1439 return ('tar+size') if $format eq 'subvol';
1440 return ('raw+size');