1 package PVE
::Storage
::Plugin
;
13 use PVE
::Tools
qw(run_command);
14 use PVE
::JSONSchema
qw(get_standard_option register_standard_option);
15 use PVE
::Cluster
qw(cfs_register_file);
19 use base
qw(PVE::SectionConfig);
21 use constant COMPRESSOR_RE
=> 'gz|lzo|zst';
23 use constant LOG_EXT
=> ".log";
24 use constant NOTES_EXT
=> ".notes";
26 our @COMMON_TAR_FLAGS = qw(
28 -p --sparse --numeric-owner --acls
29 --xattrs --xattrs-include=user.* --xattrs-include=security.capability
30 --warning=no-file-ignored --warning=no-xattr-write
33 our @SHARED_STORAGE = (
46 our $QCOW2_PREALLOCATION = {
53 our $RAW_PREALLOCATION = {
59 our $MAX_VOLUMES_PER_GUEST = 1024;
61 cfs_register_file
('storage.cfg',
62 sub { __PACKAGE__-
>parse_config(@_); },
63 sub { __PACKAGE__-
>write_config(@_); });
67 type
=> 'integer', minimum
=> '0',
68 format_description
=> 'N',
71 our $prune_backups_format = {
74 description
=> 'Keep all backups. Conflicts with the other options when true.',
79 description
=> 'Keep the last <N> backups.',
83 description
=> 'Keep backups for the last <N> different hours. If there is more' .
84 'than one backup for a single hour, only the latest one is kept.'
88 description
=> 'Keep backups for the last <N> different days. If there is more' .
89 'than one backup for a single day, only the latest one is kept.'
93 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
94 'than one backup for a single week, only the latest one is kept.'
98 description
=> 'Keep backups for the last <N> different months. If there is more' .
99 'than one backup for a single month, only the latest one is kept.'
103 description
=> 'Keep backups for the last <N> different years. If there is more' .
104 'than one backup for a single year, only the latest one is kept.'
107 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format, \
&validate_prune_backups
);
108 sub validate_prune_backups
{
109 my ($prune_backups) = @_;
111 my $res = { $prune_backups->%* };
113 my $keep_all = delete $res->{'keep-all'};
115 if (scalar(grep { $_ > 0 } values %{$res}) == 0) {
116 $res = { 'keep-all' => 1 };
117 } elsif ($keep_all) {
118 die "keep-all cannot be set together with other options.\n";
123 register_standard_option
('prune-backups', {
124 description
=> "The retention options with shorter intervals are processed first " .
125 "with --keep-last being the very first one. Each option covers a " .
126 "specific period of time. We say that backups within this period " .
127 "are covered by this option. The next option does not take care " .
128 "of already covered backups and only considers older backups.",
131 format
=> 'prune-backups',
136 type
=> { description
=> "Storage type." },
137 storage
=> get_standard_option
('pve-storage-id',
138 { completion
=> \
&PVE
::Storage
::complete_storage
}),
139 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
141 description
=> "Allowed content types.\n\nNOTE: the value " .
142 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
143 type
=> 'string', format
=> 'pve-storage-content-list',
145 completion
=> \
&PVE
::Storage
::complete_content_type
,
148 description
=> "Flag to disable the storage.",
153 description
=> "Deprecated: use 'prune-backups' instead. " .
154 "Maximal number of backup files per VM. Use '0' for unlimited.",
159 'prune-backups' => get_standard_option
('prune-backups'),
160 'max-protected-backups' => {
161 description
=> "Maximal number of protected backups per guest. Use '-1' for unlimited.",
165 default => "Unlimited for users with Datastore.Allocate privilege, 5 for other users",
168 description
=> "Mark storage as shared.",
173 description
=> "Subdir to mount.",
174 type
=> 'string', format
=> 'pve-storage-path',
178 description
=> "Default image format.",
179 type
=> 'string', format
=> 'pve-storage-format',
183 description
=> "Preallocation mode for raw and qcow2 images. " .
184 "Using 'metadata' on raw images results in preallocation=off.",
185 type
=> 'string', enum
=> ['off', 'metadata', 'falloc', 'full'],
186 default => 'metadata',
190 description
=> "Overrides for default content type directories.",
191 type
=> "string", format
=> "pve-dir-override-list",
197 sub content_hash_to_string
{
201 foreach my $ct (keys %$hash) {
202 push @cta, $ct if $hash->{$ct};
205 return join(',', @cta);
208 sub valid_content_types
{
211 my $def = $defaultData->{plugindata
}->{$type};
215 return $def->{content
}->[0];
218 sub dirs_hash_to_string
{
221 return join(',', map { "$_=$hash->{$_}" } sort keys %$hash);
227 my $type = $scfg->{type
};
228 my $def = $defaultData->{plugindata
}->{$type};
230 my $def_format = 'raw';
231 my $valid_formats = [ $def_format ];
233 if (defined($def->{format
})) {
234 $def_format = $scfg->{format
} || $def->{format
}->[1];
235 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
238 return wantarray ?
($def_format, $valid_formats) : $def_format;
241 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
243 my ($path, $noerr) = @_;
245 # fixme: exclude more shell meta characters?
246 # we need absolute paths
247 if ($path !~ m
|^/[^;\
(\
)]+|) {
248 return undef if $noerr;
249 die "value does not look like a valid absolute path\n";
254 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
256 my ($server, $noerr) = @_;
258 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
259 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
261 return undef if $noerr;
262 die "value does not look like a valid server name or IP address\n";
267 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
269 my ($name, $noerr) = @_;
271 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
272 return undef if $noerr;
273 die "lvm name '$name' contains illegal characters\n";
279 # fixme: do we need this
280 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
282 # my ($portal, $noerr) = @_;
284 # # IP with optional port
285 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
286 # return undef if $noerr;
287 # die "value does not look like a valid portal address\n";
292 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
293 sub verify_portal_dns
{
294 my ($portal, $noerr) = @_;
296 # IP or DNS name with optional port
297 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
298 return undef if $noerr;
299 die "value does not look like a valid portal address\n";
304 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
306 my ($ct, $noerr) = @_;
308 my $valid_content = valid_content_types
('dir'); # dir includes all types
310 if (!$valid_content->{$ct}) {
311 return undef if $noerr;
312 die "invalid content type '$ct'\n";
318 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
320 my ($fmt, $noerr) = @_;
322 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
323 return undef if $noerr;
324 die "invalid format '$fmt'\n";
330 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
332 my ($value, $noerr) = @_;
334 # mount options (see man fstab)
335 if ($value !~ m/^\S+$/) {
336 return undef if $noerr;
337 die "invalid options '$value'\n";
343 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
344 sub parse_volume_id
{
345 my ($volid, $noerr) = @_;
347 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
348 return wantarray ?
($1, $2) : $1;
350 return undef if $noerr;
351 die "unable to parse volume ID '$volid'\n";
354 PVE
::JSONSchema
::register_format
('pve-dir-override', \
&verify_dir_override
);
355 sub verify_dir_override
{
356 my ($value, $noerr) = @_;
358 if ($value =~ m/^([a-z]+)=[^.]+$/ && verify_content
($1, $noerr)) {
362 return undef if $noerr;
363 die "invalid override '$value'\n";
370 sub parse_section_header
{
371 my ($class, $line) = @_;
373 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
374 my ($type, $storeid) = (lc($1), $2);
375 my $errmsg = undef; # set if you want to skip whole section
376 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
378 my $config = {}; # to return additional attributes
379 return ($type, $storeid, $errmsg, $config);
385 my ($class, $type, $key, $value) = @_;
387 my $def = $defaultData->{plugindata
}->{$type};
389 if ($key eq 'content') {
390 my $valid_content = $def->{content
}->[0];
394 foreach my $c (PVE
::Tools
::split_list
($value)) {
395 if (!$valid_content->{$c}) {
396 warn "storage does not support content type '$c'\n";
402 if ($res->{none
} && scalar (keys %$res) > 1) {
403 die "unable to combine 'none' with other content types\n";
406 if (scalar(keys $res->%*) == 0 && !$valid_content->{none
}) {
407 die "storage does not support content type 'none'\n";
411 } elsif ($key eq 'format') {
412 my $valid_formats = $def->{format
}->[0];
414 if (!$valid_formats->{$value}) {
415 warn "storage does not support format '$value'\n";
420 } elsif ($key eq 'nodes') {
423 foreach my $node (PVE
::Tools
::split_list
($value)) {
424 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
430 # no node restrictions for local storage
431 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
432 # die "storage '$storeid' does not allow node restrictions\n";
436 } elsif ($key eq 'content-dirs') {
437 my $valid_content = $def->{content
}->[0];
440 foreach my $dir (PVE
::Tools
::split_list
($value)) {
441 my ($content, $path) = split(/=/, $dir, 2);
443 if (!$valid_content->{$content}) {
444 warn "storage does not support content type '$content'\n";
448 $res->{$content} = $path;
458 my ($class, $type, $key, $value) = @_;
460 if ($key eq 'nodes') {
461 return join(',', keys(%$value));
462 } elsif ($key eq 'content') {
463 my $res = content_hash_to_string
($value) || 'none';
465 } elsif ($key eq 'content-dirs') {
466 my $res = dirs_hash_to_string
($value);
474 my ($class, $filename, $raw) = @_;
476 my $cfg = $class->SUPER::parse_config
($filename, $raw);
477 my $ids = $cfg->{ids
};
479 # make sure we have a reasonable 'local:' storage
480 # we want 'local' to be always the same 'type' (on all cluster nodes)
481 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
482 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
485 priority
=> 0, # force first entry
486 path
=> '/var/lib/vz',
487 'prune-backups' => 'keep-all=1',
499 # make sure we have a path
500 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
502 # remove node restrictions for local storage
503 delete($ids->{local}->{nodes
});
505 foreach my $storeid (keys %$ids) {
506 my $d = $ids->{$storeid};
507 my $type = $d->{type
};
509 my $def = $defaultData->{plugindata
}->{$type};
511 if ($def->{content
}) {
512 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
514 if (grep { $_ eq $type } @SHARED_STORAGE) {
522 sub preallocation_cmd_option
{
523 my ($scfg, $fmt) = @_;
525 my $prealloc = $scfg->{preallocation
};
527 if ($fmt eq 'qcow2') {
528 $prealloc = $prealloc // 'metadata';
530 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
531 if !$QCOW2_PREALLOCATION->{$prealloc};
533 return "preallocation=$prealloc";
534 } elsif ($fmt eq 'raw') {
535 $prealloc = $prealloc // 'off';
536 $prealloc = 'off' if $prealloc eq 'metadata';
538 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
539 if !$RAW_PREALLOCATION->{$prealloc};
541 return "preallocation=$prealloc";
547 # Storage implementation
549 # called during addition of storage (before the new storage config got written)
550 # die to abort addition if there are (grave) problems
551 # NOTE: runs in a storage config *locked* context
553 my ($class, $storeid, $scfg, %param) = @_;
555 # do nothing by default
559 # called during storage configuration update (before the updated storage config got written)
560 # die to abort the update if there are (grave) problems
561 # NOTE: runs in a storage config *locked* context
563 my ($class, $storeid, $scfg, %param) = @_;
565 # do nothing by default
569 # called during deletion of storage (before the new storage config got written)
570 # and if the activate check on addition fails, to cleanup all storage traces
571 # which on_add_hook may have created.
572 # die to abort deletion if there are (very grave) problems
573 # NOTE: runs in a storage config *locked* context
575 my ($class, $storeid, $scfg) = @_;
577 # do nothing by default
581 sub cluster_lock_storage
{
582 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
586 my $lockid = "pve-storage-$storeid";
587 my $lockdir = "/var/lock/pve-manager";
589 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
592 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
601 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
602 return ($1, $3, $2); # (name, format, isBase)
605 die "unable to parse volume filename '$name'\n";
609 my ($class, $volname) = @_;
611 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
612 my ($basedvmid, $basename) = ($1, $2);
613 parse_name_dir
($basename);
614 my ($vmid, $name) = ($3, $4);
615 my (undef, $format, $isBase) = parse_name_dir
($name);
616 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
617 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
618 my ($vmid, $name) = ($1, $2);
619 my (undef, $format, $isBase) = parse_name_dir
($name);
620 return ('images', $name, $vmid, undef, undef, $isBase, $format);
621 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!) {
623 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!) {
624 return ('vztmpl', $1);
625 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
626 return ('rootdir', $1, $1);
627 } elsif ($volname =~ m!^backup/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!) {
629 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
630 return ('backup', $fn, $2);
632 return ('backup', $fn);
633 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
634 return ('snippets', $1);
637 die "unable to parse directory volume name '$volname'\n";
640 my $vtype_subdirs = {
642 rootdir
=> 'private',
643 iso
=> 'template/iso',
644 vztmpl
=> 'template/cache',
646 snippets
=> 'snippets',
649 sub get_vtype_subdirs
{
650 return $vtype_subdirs;
654 my ($class, $scfg, $vtype) = @_;
656 my $path = $scfg->{path
};
658 die "storage definition has no path\n" if !$path;
659 die "unknown vtype '$vtype'\n" if !exists($vtype_subdirs->{$vtype});
661 my $subdir = $scfg->{"content-dirs"}->{$vtype} // $vtype_subdirs->{$vtype};
663 return "$path/$subdir";
666 sub filesystem_path
{
667 my ($class, $scfg, $volname, $snapname) = @_;
669 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
670 $class->parse_volname($volname);
672 # Note: qcow2/qed has internal snapshot, so path is always
673 # the same (with or without snapshot => same file).
674 die "can't snapshot this image format\n"
675 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
677 my $dir = $class->get_subdir($scfg, $vtype);
679 $dir .= "/$vmid" if $vtype eq 'images';
681 my $path = "$dir/$name";
683 return wantarray ?
($path, $vmid, $vtype) : $path;
687 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
689 return $class->filesystem_path($scfg, $volname, $snapname);
693 my ($class, $storeid, $scfg, $volname) = @_;
695 # this only works for file based storage types
696 die "storage definition has no path\n" if !$scfg->{path
};
698 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
699 $class->parse_volname($volname);
701 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
703 die "create_base not possible with base image\n" if $isBase;
705 my $path = $class->filesystem_path($scfg, $volname);
707 my ($size, undef, $used, $parent) = file_size_info
($path);
708 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
710 die "volname '$volname' contains wrong information about parent\n"
711 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
714 $newname =~ s/^vm-/base-/;
716 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
719 my $newpath = $class->filesystem_path($scfg, $newvolname);
721 die "file '$newpath' already exists\n" if -f
$newpath;
723 rename($path, $newpath) ||
724 die "rename '$path' to '$newpath' failed - $!\n";
726 # We try to protect base volume
728 chmod(0444, $newpath); # nobody should write anything
730 # also try to set immutable flag
731 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
737 my $get_vm_disk_number = sub {
738 my ($disk_name, $scfg, $vmid, $suffix) = @_;
740 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
742 my $type = $scfg->{type
};
743 my $def = { %{$defaultData->{plugindata
}->{$type}} };
745 my $valid = $def->{format
}[0];
746 if ($valid->{subvol
}) {
747 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
750 if ($disk_name =~ m/$disk_regex/) {
757 sub get_next_vm_diskname
{
758 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
761 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
762 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
765 foreach my $disk (@$disk_list) {
766 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
767 $disk_ids->{$disknum} = 1 if defined($disknum);
770 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
771 if (!$disk_ids->{$i}) {
772 return "$prefix-$vmid-disk-$i$suffix";
776 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
779 sub find_free_diskname
{
780 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
782 my $disks = $class->list_images($storeid, $scfg, $vmid);
784 my $disk_list = [ map { $_->{volid
} } @$disks ];
786 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
790 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
792 # this only works for file based storage types
793 die "storage definition has no path\n" if !$scfg->{path
};
795 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
796 $class->parse_volname($volname);
798 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
800 die "this storage type does not support clone_image on snapshot\n" if $snap;
802 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
804 die "clone_image only works on base images\n" if !$isBase;
806 my $imagedir = $class->get_subdir($scfg, 'images');
807 $imagedir .= "/$vmid";
811 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
813 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
815 my $newvol = "$basevmid/$basename/$vmid/$name";
817 my $path = $class->filesystem_path($scfg, $newvol);
819 # Note: we use relative paths, so we need to call chdir before qemu-img
821 local $CWD = $imagedir;
823 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
824 '-F', $format, '-f', 'qcow2', $path];
836 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
838 my $imagedir = $class->get_subdir($scfg, 'images');
839 $imagedir .= "/$vmid";
843 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
845 my (undef, $tmpfmt) = parse_name_dir
($name);
847 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
850 my $path = "$imagedir/$name";
852 die "disk image '$path' already exists\n" if -e
$path;
854 if ($fmt eq 'subvol') {
855 # only allow this if size = 0, so that user knows what he is doing
856 die "storage does not support subvol quotas\n" if $size != 0;
858 my $old_umask = umask(0022);
860 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
864 my $cmd = ['/usr/bin/qemu-img', 'create'];
866 my $prealloc_opt = preallocation_cmd_option
($scfg, $fmt);
867 push @$cmd, '-o', $prealloc_opt if defined($prealloc_opt);
869 push @$cmd, '-f', $fmt, $path, "${size}K";
871 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
879 return "$vmid/$name";
883 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
885 die "cannot remove protected volume '$volname' on '$storeid'\n"
886 if $class->get_volume_attribute($scfg, $storeid, $volname, 'protected');
888 my $path = $class->filesystem_path($scfg, $volname);
891 # try to remove immutable flag
892 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
896 if (defined($format) && ($format eq 'subvol')) {
897 File
::Path
::remove_tree
($path);
899 if (!(-f
$path || -l
$path)) {
900 warn "disk image '$path' does not exist\n";
904 unlink($path) || die "unlink '$path' failed - $!\n";
907 # try to cleanup directory to not clutter storage with empty $vmid dirs if
908 # all images from a guest got deleted
909 my $dir = dirname
($path);
916 my ($filename, $timeout) = @_;
918 my $st = File
::stat::stat($filename);
921 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
922 warn "failed to stat '$filename'$extramsg\n";
926 if (S_ISDIR
($st->mode)) {
927 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
932 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
934 outfunc
=> sub { $json .= shift },
935 errfunc
=> sub { warn "$_[0]\n" }
940 my $info = eval { decode_json
($json) };
942 warn "could not parse qemu-img info command output for '$filename' - $err\n";
943 return wantarray ?
(undef, undef, undef, undef, $st->ctime) : undef;
946 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
948 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
949 # coerce back from string
951 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
952 # coerce back from string
954 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
955 if (defined($parent)) {
956 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
958 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
961 # FIXME remove on the next APIAGE reset.
962 # Deprecated, use get_volume_attribute instead.
963 sub get_volume_notes
{
964 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
966 die "volume notes are not supported for $class";
969 # FIXME remove on the next APIAGE reset.
970 # Deprecated, use update_volume_attribute instead.
971 sub update_volume_notes
{
972 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
974 die "volume notes are not supported for $class";
977 # Returns undef if the attribute is not supported for the volume.
978 # Should die if there is an error fetching the attribute.
979 # Possible attributes:
980 # notes - user-provided comments/notes.
981 # protected - not to be removed by free_image, and for backups, ignored when pruning.
982 sub get_volume_attribute
{
983 my ($class, $scfg, $storeid, $volname, $attribute) = @_;
985 if ($attribute eq 'notes') {
986 my $notes = eval { $class->get_volume_notes($scfg, $storeid, $volname); };
988 return if $err =~ m/^volume notes are not supported/;
997 # Dies if the attribute is not supported for the volume.
998 sub update_volume_attribute
{
999 my ($class, $scfg, $storeid, $volname, $attribute, $value) = @_;
1001 if ($attribute eq 'notes') {
1002 $class->update_volume_notes($scfg, $storeid, $volname, $value);
1005 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
1008 sub volume_size_info
{
1009 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
1010 my $path = $class->filesystem_path($scfg, $volname);
1011 return file_size_info
($path, $timeout);
1016 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
1018 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
1020 return 1 if $running;
1022 my $path = $class->filesystem_path($scfg, $volname);
1024 my $format = ($class->parse_volname($volname))[6];
1026 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
1028 run_command
($cmd, timeout
=> 10);
1033 sub volume_snapshot
{
1034 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1036 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1038 my $path = $class->filesystem_path($scfg, $volname);
1040 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
1047 # Asserts that a rollback to $snap on $volname is possible.
1048 # If certain snapshots are preventing the rollback and $blockers is an array
1049 # reference, the snapshot names can be pushed onto $blockers prior to dying.
1050 sub volume_rollback_is_possible
{
1051 my ($class, $scfg, $storeid, $volname, $snap, $blockers) = @_;
1056 sub volume_snapshot_rollback
{
1057 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1059 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1061 my $path = $class->filesystem_path($scfg, $volname);
1063 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
1070 sub volume_snapshot_delete
{
1071 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
1073 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1075 return 1 if $running;
1077 my $path = $class->filesystem_path($scfg, $volname);
1079 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
1081 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
1088 sub volume_snapshot_needs_fsfreeze
{
1092 sub storage_can_replicate
{
1093 my ($class, $scfg, $storeid, $format) = @_;
1098 sub volume_has_feature
{
1099 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
1103 current
=> { qcow2
=> 1 },
1104 snap
=> { qcow2
=> 1 },
1107 base
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1110 current
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1 },
1113 base
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1114 current
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1115 snap
=> { qcow2
=> 1 },
1118 base
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1119 current
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1122 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
1126 if ($feature eq 'clone') {
1128 defined($opts->{valid_target_formats
})
1129 && !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}})
1131 return 0; # clone_image creates a qcow2 volume
1133 } elsif ($feature eq 'rename') {
1134 return 0 if $class->can('api') && $class->api() < 10;
1138 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) = $class->parse_volname($volname);
1144 $key = $isBase ?
'base' : 'current';
1147 return 1 if defined($features->{$feature}->{$key}->{$format});
1153 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
1155 my $imagedir = $class->get_subdir($scfg, 'images');
1157 my ($defFmt, $vaidFmts) = default_format
($scfg);
1158 my $fmts = join ('|', @$vaidFmts);
1162 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
1164 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1170 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1172 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
1173 next if !($format && defined($size));
1176 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1177 my ($basevmid, $basename) = ($1, $2);
1178 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1180 $volid = "$storeid:$owner/$name";
1184 my $found = grep { $_ eq $volid } @$vollist;
1189 volid
=> $volid, format
=> $format,
1190 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
1193 $info->{ctime
} = $ctime if $ctime;
1201 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1202 my $get_subdir_files = sub {
1203 my ($sid, $path, $tt, $vmid) = @_;
1207 foreach my $fn (<$path/*>) {
1208 my $st = File
::stat::stat($fn);
1210 next if (!$st || S_ISDIR
($st->mode));
1215 next if $fn !~ m!/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!i;
1217 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1219 } elsif ($tt eq 'vztmpl') {
1220 next if $fn !~ m!/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!;
1222 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1224 } elsif ($tt eq 'backup') {
1225 next if $fn !~ m!/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!;
1230 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1231 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1233 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1235 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1237 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1238 $info->{subtype
} = $archive_info->{type
} // 'unknown';
1240 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1241 $info->{vmid
} = $vmid // $1;
1244 my $notes_fn = $original.NOTES_EXT
;
1246 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1247 $info->{notes
} = eval { decode
('UTF-8', $notes, 1) } // $notes if defined($notes);
1250 $info->{protected
} = 1 if -e PVE
::Storage
::protection_file_path
($original);
1251 } elsif ($tt eq 'snippets') {
1254 volid
=> "$sid:snippets/". basename
($fn),
1255 format
=> 'snippet',
1259 $info->{size
} = $st->size;
1260 $info->{ctime
} //= $st->ctime;
1268 # If attributes are set on a volume, they should be included in the result.
1269 # See get_volume_attribute for a list of possible attributes.
1271 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1274 my $vmlist = PVE
::Cluster
::get_vmlist
();
1275 foreach my $type (@$content_types) {
1278 if ($type eq 'images' || $type eq 'rootdir') {
1279 $data = $class->list_images($storeid, $scfg, $vmid);
1280 } elsif ($scfg->{path
}) {
1281 my $path = $class->get_subdir($scfg, $type);
1283 if ($type eq 'iso' && !defined($vmid)) {
1284 $data = $get_subdir_files->($storeid, $path, 'iso');
1285 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1286 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1287 } elsif ($type eq 'backup') {
1288 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1289 } elsif ($type eq 'snippets') {
1290 $data = $get_subdir_files->($storeid, $path, 'snippets');
1296 foreach my $item (@$data) {
1297 if ($type eq 'images' || $type eq 'rootdir') {
1298 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1300 if (defined($vminfo)) {
1301 $vmtype = $vminfo->{type
};
1303 if (defined($vmtype) && $vmtype eq 'lxc') {
1304 $item->{content
} = 'rootdir';
1306 $item->{content
} = 'images';
1308 next if $type ne $item->{content
};
1310 $item->{content
} = $type;
1321 my ($class, $storeid, $scfg, $cache) = @_;
1323 my $path = $scfg->{path
};
1325 die "storage definition has no path\n" if !$path;
1328 my $res = PVE
::Tools
::df
($path, $timeout);
1330 return undef if !$res || !$res->{total
};
1332 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1335 # Returns a hash with the snapshot names as keys and the following data:
1336 # id - Unique id to distinguish different snapshots even if the have the same name.
1337 # timestamp - Creation time of the snapshot (seconds since epoch).
1338 # Returns an empty hash if the volume does not exist.
1339 sub volume_snapshot_info
{
1340 my ($class, $scfg, $storeid, $volname) = @_;
1342 die "volume_snapshot_info is not implemented for $class";
1345 sub activate_storage
{
1346 my ($class, $storeid, $scfg, $cache) = @_;
1348 my $path = $scfg->{path
};
1350 die "storage definition has no path\n" if !$path;
1352 # this path test may hang indefinitely on unresponsive mounts
1354 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1355 die "unable to activate storage '$storeid' - " .
1356 "directory '$path' does not exist or is unreachable\n";
1360 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1362 if (defined($scfg->{content
})) {
1363 foreach my $vtype (keys %$vtype_subdirs) {
1364 # OpenVZMigrate uses backup (dump) dir
1365 if (defined($scfg->{content
}->{$vtype}) ||
1366 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1367 my $subdir = $class->get_subdir($scfg, $vtype);
1368 mkpath
$subdir if $subdir ne $path;
1374 sub deactivate_storage
{
1375 my ($class, $storeid, $scfg, $cache) = @_;
1377 # do nothing by default
1381 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1383 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1388 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1393 sub activate_volume
{
1394 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1396 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1398 # check is volume exists
1399 if ($scfg->{path
}) {
1400 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1402 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1406 sub deactivate_volume
{
1407 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1409 # do nothing by default
1412 sub check_connection
{
1413 my ($class, $storeid, $scfg) = @_;
1414 # do nothing by default
1419 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1421 $logfunc //= sub { print "$_[1]\n" };
1423 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1425 my $backup_groups = {};
1426 my $prune_list = [];
1428 foreach my $backup (@{$backups}) {
1429 my $volid = $backup->{volid
};
1430 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1431 my $backup_type = $archive_info->{type
} // 'unknown';
1432 my $backup_vmid = $archive_info->{vmid
} // $backup->{vmid
};
1434 next if defined($type) && $type ne $backup_type;
1437 ctime
=> $backup->{ctime
},
1438 type
=> $backup_type,
1442 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1444 if ($archive_info->{is_std_name
}) {
1445 die "internal error - got no VMID\n" if !defined($backup_vmid);
1446 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1447 if defined($vmid) && $backup_vmid ne $vmid;
1449 $prune_entry->{ctime
} = $archive_info->{ctime
};
1450 my $group = "$backup_type/$backup_vmid";
1451 push @{$backup_groups->{$group}}, $prune_entry;
1453 # ignore backups that don't use the standard naming scheme
1454 $prune_entry->{mark
} = 'renamed';
1457 $prune_entry->{mark
} = 'protected' if $backup->{protected
};
1459 push @{$prune_list}, $prune_entry;
1462 foreach my $backup_group (values %{$backup_groups}) {
1463 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1468 foreach my $prune_entry (@{$prune_list}) {
1469 next if $prune_entry->{mark
} ne 'remove';
1471 my $volid = $prune_entry->{volid
};
1472 $logfunc->('info', "removing backup '$volid'");
1474 my (undef, $volname) = parse_volume_id
($volid);
1475 my $archive_path = $class->filesystem_path($scfg, $volname);
1476 PVE
::Storage
::archive_remove
($archive_path);
1479 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1484 die "error pruning backups - check log\n" if $failed;
1489 # Import/Export interface:
1490 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1491 # the default implementations will return this if $scfg->{path} is set,
1492 # mimicking the old PVE::Storage::storage_migrate() function.
1494 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1495 # functions in case the format doesn't match their specialized
1496 # implementations to reuse the raw/tar code.
1498 # Format specification:
1499 # The following formats are all prefixed with image information in the form
1500 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1501 # to preallocate the image on storages which require it.
1503 # raw+size: (image files only)
1504 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1505 # qcow2+size, vmdk: (image files only)
1506 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1507 # files which are already in qcow2 format, or via `qemu-img convert`.
1508 # Note that these formats are only valid with $with_snapshots being true.
1509 # tar+size: (subvolumes only)
1510 # A GNU tar stream containing just the inner contents of the subvolume.
1511 # This does not distinguish between the contents of a privileged or
1512 # unprivileged container. In other words, this is from the root user
1513 # namespace's point of view with no uid-mapping in effect.
1514 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1516 # Plugins may reuse these helpers. Changes to the header format should be
1517 # reflected by changes to the function prototypes.
1518 sub write_common_header
($$) {
1519 my ($fh, $image_size_in_bytes) = @_;
1520 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1523 sub read_common_header
($) {
1525 sysread($fh, my $size, 8);
1526 $size = unpack('Q<', $size);
1527 die "import: no size found in export header, aborting.\n" if !defined($size);
1532 # Export a volume into a file handle as a stream of desired format.
1534 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1535 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1536 my $file = $class->path($scfg, $volname, $storeid)
1537 or goto unsupported
;
1538 my ($size, $file_format) = file_size_info
($file);
1540 if ($format eq 'raw+size') {
1541 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1542 write_common_header
($fh, $size);
1543 if ($file_format eq 'raw') {
1544 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1546 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1547 output
=> '>&'.fileno($fh));
1550 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1551 my $data_format = $1;
1552 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1553 write_common_header
($fh, $size);
1554 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1556 } elsif ($format eq 'tar+size') {
1557 goto unsupported
if $file_format ne 'subvol';
1558 write_common_header
($fh, $size);
1559 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1560 output
=> '>&'.fileno($fh));
1565 die "volume export format $format not available for $class";
1568 sub volume_export_formats
{
1569 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1570 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1571 my $file = $class->path($scfg, $volname, $storeid)
1573 my ($size, $format) = file_size_info
($file);
1575 if ($with_snapshots) {
1576 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1579 return ('tar+size') if $format eq 'subvol';
1580 return ('raw+size');
1585 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1587 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1589 die "volume import format '$format' not available for $class\n"
1590 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1591 my $data_format = $1;
1593 die "format $format cannot be imported without snapshots\n"
1594 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1595 die "format $format cannot be imported with snapshots\n"
1596 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1598 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1599 $class->parse_volname($volname);
1601 # XXX: Should we bother with conversion routines at this level? This won't
1602 # happen without manual CLI usage, so for now we just error out...
1603 die "cannot import format $format into a file of format $file_format\n"
1604 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1606 # Check for an existing file first since interrupting alloc_image doesn't
1608 my $file = $class->path($scfg, $volname, $storeid);
1610 die "file '$file' already exists\n" if !$allow_rename;
1611 warn "file '$file' already exists - importing with a different name\n";
1615 my ($size) = read_common_header
($fh);
1616 $size = int($size/1024);
1619 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1620 my $oldname = $volname;
1621 $volname = $allocname;
1622 if (defined($name) && $allocname ne $oldname) {
1623 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1625 my $file = $class->path($scfg, $volname, $storeid)
1626 or die "internal error: failed to get path to newly allocated volume $volname\n";
1627 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1628 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1629 input
=> '<&'.fileno($fh));
1630 } elsif ($data_format eq 'tar') {
1631 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1632 input
=> '<&'.fileno($fh));
1634 die "volume import format '$format' not available for $class";
1638 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1643 return "$storeid:$volname";
1646 sub volume_import_formats
{
1647 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1648 if ($scfg->{path
} && !defined($base_snapshot)) {
1649 my $format = ($class->parse_volname($volname))[6];
1650 if ($with_snapshots) {
1651 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1654 return ('tar+size') if $format eq 'subvol';
1655 return ('raw+size');
1661 my ($class, $scfg, $storeid, $source_volname, $target_vmid, $target_volname) = @_;
1662 die "not implemented in storage plugin '$class'\n" if $class->can('api') && $class->api() < 10;
1663 die "no path found\n" if !$scfg->{path
};
1673 ) = $class->parse_volname($source_volname);
1675 $target_volname = $class->find_free_diskname($storeid, $scfg, $target_vmid, $format, 1)
1676 if !$target_volname;
1678 my $basedir = $class->get_subdir($scfg, 'images');
1680 mkpath
"${basedir}/${target_vmid}";
1682 my $old_path = "${basedir}/${source_vmid}/${source_image}";
1683 my $new_path = "${basedir}/${target_vmid}/${target_volname}";
1685 die "target volume '${target_volname}' already exists\n" if -e
$new_path;
1687 my $base = $base_name ?
"${base_vmid}/${base_name}/" : '';
1689 rename($old_path, $new_path) ||
1690 die "rename '$old_path' to '$new_path' failed - $!\n";
1692 return "${storeid}:${base}${target_vmid}/${target_volname}";