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 $QCOW2_PREALLOCATION = {
51 our $RAW_PREALLOCATION = {
57 our $MAX_VOLUMES_PER_GUEST = 1024;
59 cfs_register_file
('storage.cfg',
60 sub { __PACKAGE__-
>parse_config(@_); },
61 sub { __PACKAGE__-
>write_config(@_); });
65 type
=> 'integer', minimum
=> '0',
66 format_description
=> 'N',
69 our $prune_backups_format = {
72 description
=> 'Keep all backups. Conflicts with the other options when true.',
77 description
=> 'Keep the last <N> backups.',
81 description
=> 'Keep backups for the last <N> different hours. If there is more' .
82 'than one backup for a single hour, only the latest one is kept.'
86 description
=> 'Keep backups for the last <N> different days. If there is more' .
87 'than one backup for a single day, only the latest one is kept.'
91 description
=> 'Keep backups for the last <N> different weeks. If there is more' .
92 'than one backup for a single week, only the latest one is kept.'
96 description
=> 'Keep backups for the last <N> different months. If there is more' .
97 'than one backup for a single month, only the latest one is kept.'
101 description
=> 'Keep backups for the last <N> different years. If there is more' .
102 'than one backup for a single year, only the latest one is kept.'
105 PVE
::JSONSchema
::register_format
('prune-backups', $prune_backups_format, \
&validate_prune_backups
);
106 sub validate_prune_backups
{
107 my ($prune_backups) = @_;
109 my $res = { $prune_backups->%* };
111 my $keep_all = delete $res->{'keep-all'};
113 if (scalar(grep { $_ > 0 } values %{$res}) == 0) {
114 $res = { 'keep-all' => 1 };
115 } elsif ($keep_all) {
116 die "keep-all cannot be set together with other options.\n";
121 register_standard_option
('prune-backups', {
122 description
=> "The retention options with shorter intervals are processed first " .
123 "with --keep-last being the very first one. Each option covers a " .
124 "specific period of time. We say that backups within this period " .
125 "are covered by this option. The next option does not take care " .
126 "of already covered backups and only considers older backups.",
129 format
=> 'prune-backups',
134 type
=> { description
=> "Storage type." },
135 storage
=> get_standard_option
('pve-storage-id',
136 { completion
=> \
&PVE
::Storage
::complete_storage
}),
137 nodes
=> get_standard_option
('pve-node-list', { optional
=> 1 }),
139 description
=> "Allowed content types.\n\nNOTE: the value " .
140 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
141 type
=> 'string', format
=> 'pve-storage-content-list',
143 completion
=> \
&PVE
::Storage
::complete_content_type
,
146 description
=> "Flag to disable the storage.",
151 description
=> "Deprecated: use 'prune-backups' instead. " .
152 "Maximal number of backup files per VM. Use '0' for unlimited.",
157 'prune-backups' => get_standard_option
('prune-backups'),
158 'max-protected-backups' => {
159 description
=> "Maximal number of protected backups per guest. Use '-1' for unlimited.",
163 default => "Unlimited for users with Datastore.Allocate privilege, 5 for other users",
166 description
=> "Mark storage as shared.",
171 description
=> "Default image format.",
172 type
=> 'string', format
=> 'pve-storage-format',
176 description
=> "Preallocation mode for raw and qcow2 images. " .
177 "Using 'metadata' on raw images results in preallocation=off.",
178 type
=> 'string', enum
=> ['off', 'metadata', 'falloc', 'full'],
179 default => 'metadata',
185 sub content_hash_to_string
{
189 foreach my $ct (keys %$hash) {
190 push @cta, $ct if $hash->{$ct};
193 return join(',', @cta);
196 sub valid_content_types
{
199 my $def = $defaultData->{plugindata
}->{$type};
203 return $def->{content
}->[0];
209 my $type = $scfg->{type
};
210 my $def = $defaultData->{plugindata
}->{$type};
212 my $def_format = 'raw';
213 my $valid_formats = [ $def_format ];
215 if (defined($def->{format
})) {
216 $def_format = $scfg->{format
} || $def->{format
}->[1];
217 $valid_formats = [ sort keys %{$def->{format
}->[0]} ];
220 return wantarray ?
($def_format, $valid_formats) : $def_format;
223 PVE
::JSONSchema
::register_format
('pve-storage-path', \
&verify_path
);
225 my ($path, $noerr) = @_;
227 # fixme: exclude more shell meta characters?
228 # we need absolute paths
229 if ($path !~ m
|^/[^;\
(\
)]+|) {
230 return undef if $noerr;
231 die "value does not look like a valid absolute path\n";
236 PVE
::JSONSchema
::register_format
('pve-storage-server', \
&verify_server
);
238 my ($server, $noerr) = @_;
240 if (!(PVE
::JSONSchema
::pve_verify_ip
($server, 1) ||
241 PVE
::JSONSchema
::pve_verify_dns_name
($server, 1)))
243 return undef if $noerr;
244 die "value does not look like a valid server name or IP address\n";
249 PVE
::JSONSchema
::register_format
('pve-storage-vgname', \
&parse_lvm_name
);
251 my ($name, $noerr) = @_;
253 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
254 return undef if $noerr;
255 die "lvm name '$name' contains illegal characters\n";
261 # fixme: do we need this
262 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
264 # my ($portal, $noerr) = @_;
266 # # IP with optional port
267 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
268 # return undef if $noerr;
269 # die "value does not look like a valid portal address\n";
274 PVE
::JSONSchema
::register_format
('pve-storage-portal-dns', \
&verify_portal_dns
);
275 sub verify_portal_dns
{
276 my ($portal, $noerr) = @_;
278 # IP or DNS name with optional port
279 if (!PVE
::Tools
::parse_host_and_port
($portal)) {
280 return undef if $noerr;
281 die "value does not look like a valid portal address\n";
286 PVE
::JSONSchema
::register_format
('pve-storage-content', \
&verify_content
);
288 my ($ct, $noerr) = @_;
290 my $valid_content = valid_content_types
('dir'); # dir includes all types
292 if (!$valid_content->{$ct}) {
293 return undef if $noerr;
294 die "invalid content type '$ct'\n";
300 PVE
::JSONSchema
::register_format
('pve-storage-format', \
&verify_format
);
302 my ($fmt, $noerr) = @_;
304 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
305 return undef if $noerr;
306 die "invalid format '$fmt'\n";
312 PVE
::JSONSchema
::register_format
('pve-storage-options', \
&verify_options
);
314 my ($value, $noerr) = @_;
316 # mount options (see man fstab)
317 if ($value !~ m/^\S+$/) {
318 return undef if $noerr;
319 die "invalid options '$value'\n";
325 PVE
::JSONSchema
::register_format
('pve-volume-id', \
&parse_volume_id
);
326 sub parse_volume_id
{
327 my ($volid, $noerr) = @_;
329 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
330 return wantarray ?
($1, $2) : $1;
332 return undef if $noerr;
333 die "unable to parse volume ID '$volid'\n";
341 sub parse_section_header
{
342 my ($class, $line) = @_;
344 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
345 my ($type, $storeid) = (lc($1), $2);
346 my $errmsg = undef; # set if you want to skip whole section
347 eval { PVE
::JSONSchema
::parse_storage_id
($storeid); };
349 my $config = {}; # to return additional attributes
350 return ($type, $storeid, $errmsg, $config);
356 my ($class, $type, $key, $value) = @_;
358 my $def = $defaultData->{plugindata
}->{$type};
360 if ($key eq 'content') {
361 my $valid_content = $def->{content
}->[0];
365 foreach my $c (PVE
::Tools
::split_list
($value)) {
366 if (!$valid_content->{$c}) {
367 warn "storage does not support content type '$c'\n";
373 if ($res->{none
} && scalar (keys %$res) > 1) {
374 die "unable to combine 'none' with other content types\n";
377 if (scalar(keys $res->%*) == 0 && !$valid_content->{none
}) {
378 die "storage does not support content type 'none'\n";
382 } elsif ($key eq 'format') {
383 my $valid_formats = $def->{format
}->[0];
385 if (!$valid_formats->{$value}) {
386 warn "storage does not support format '$value'\n";
391 } elsif ($key eq 'nodes') {
394 foreach my $node (PVE
::Tools
::split_list
($value)) {
395 if (PVE
::JSONSchema
::pve_verify_node_name
($node)) {
401 # no node restrictions for local storage
402 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
403 # die "storage '$storeid' does not allow node restrictions\n";
413 my ($class, $type, $key, $value) = @_;
415 if ($key eq 'nodes') {
416 return join(',', keys(%$value));
417 } elsif ($key eq 'content') {
418 my $res = content_hash_to_string
($value) || 'none';
426 my ($class, $filename, $raw) = @_;
428 my $cfg = $class->SUPER::parse_config
($filename, $raw);
429 my $ids = $cfg->{ids
};
431 # make sure we have a reasonable 'local:' storage
432 # we want 'local' to be always the same 'type' (on all cluster nodes)
433 if (!$ids->{local} || $ids->{local}->{type
} ne 'dir' ||
434 ($ids->{local}->{path
} && $ids->{local}->{path
} ne '/var/lib/vz')) {
437 priority
=> 0, # force first entry
438 path
=> '/var/lib/vz',
439 'prune-backups' => 'keep-all=1',
451 # make sure we have a path
452 $ids->{local}->{path
} = '/var/lib/vz' if !$ids->{local}->{path
};
454 # remove node restrictions for local storage
455 delete($ids->{local}->{nodes
});
457 foreach my $storeid (keys %$ids) {
458 my $d = $ids->{$storeid};
459 my $type = $d->{type
};
461 my $def = $defaultData->{plugindata
}->{$type};
463 if ($def->{content
}) {
464 $d->{content
} = $def->{content
}->[1] if !$d->{content
};
466 if (grep { $_ eq $type } @SHARED_STORAGE) {
474 sub preallocation_cmd_option
{
475 my ($scfg, $fmt) = @_;
477 my $prealloc = $scfg->{preallocation
};
479 if ($fmt eq 'qcow2') {
480 $prealloc = $prealloc // 'metadata';
482 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
483 if !$QCOW2_PREALLOCATION->{$prealloc};
485 return "preallocation=$prealloc";
486 } elsif ($fmt eq 'raw') {
487 $prealloc = $prealloc // 'off';
488 $prealloc = 'off' if $prealloc eq 'metadata';
490 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
491 if !$RAW_PREALLOCATION->{$prealloc};
493 return "preallocation=$prealloc";
499 # Storage implementation
501 # called during addition of storage (before the new storage config got written)
502 # die to abort addition if there are (grave) problems
503 # NOTE: runs in a storage config *locked* context
505 my ($class, $storeid, $scfg, %param) = @_;
507 # do nothing by default
511 # called during storage configuration update (before the updated storage config got written)
512 # die to abort the update if there are (grave) problems
513 # NOTE: runs in a storage config *locked* context
515 my ($class, $storeid, $scfg, %param) = @_;
517 # do nothing by default
521 # called during deletion of storage (before the new storage config got written)
522 # and if the activate check on addition fails, to cleanup all storage traces
523 # which on_add_hook may have created.
524 # die to abort deletion if there are (very grave) problems
525 # NOTE: runs in a storage config *locked* context
527 my ($class, $storeid, $scfg) = @_;
529 # do nothing by default
533 sub cluster_lock_storage
{
534 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
538 my $lockid = "pve-storage-$storeid";
539 my $lockdir = "/var/lock/pve-manager";
541 $res = PVE
::Tools
::lock_file
("$lockdir/$lockid", $timeout, $func, @param);
544 $res = PVE
::Cluster
::cfs_lock_storage
($storeid, $timeout, $func, @param);
553 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
554 return ($1, $3, $2); # (name, format, isBase)
557 die "unable to parse volume filename '$name'\n";
561 my ($class, $volname) = @_;
563 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
564 my ($basedvmid, $basename) = ($1, $2);
565 parse_name_dir
($basename);
566 my ($vmid, $name) = ($3, $4);
567 my (undef, $format, $isBase) = parse_name_dir
($name);
568 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
569 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
570 my ($vmid, $name) = ($1, $2);
571 my (undef, $format, $isBase) = parse_name_dir
($name);
572 return ('images', $name, $vmid, undef, undef, $isBase, $format);
573 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!) {
575 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!) {
576 return ('vztmpl', $1);
577 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
578 return ('rootdir', $1, $1);
579 } elsif ($volname =~ m!^backup/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!) {
581 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
582 return ('backup', $fn, $2);
584 return ('backup', $fn);
585 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
586 return ('snippets', $1);
589 die "unable to parse directory volume name '$volname'\n";
592 my $vtype_subdirs = {
594 rootdir
=> 'private',
595 iso
=> 'template/iso',
596 vztmpl
=> 'template/cache',
598 snippets
=> 'snippets',
601 sub get_vtype_subdirs
{
602 return $vtype_subdirs;
606 my ($class, $scfg, $vtype) = @_;
608 my $path = $scfg->{path
};
610 die "storage definition has no path\n" if !$path;
612 my $subdir = $vtype_subdirs->{$vtype};
614 die "unknown vtype '$vtype'\n" if !defined($subdir);
616 return "$path/$subdir";
619 sub filesystem_path
{
620 my ($class, $scfg, $volname, $snapname) = @_;
622 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
623 $class->parse_volname($volname);
625 # Note: qcow2/qed has internal snapshot, so path is always
626 # the same (with or without snapshot => same file).
627 die "can't snapshot this image format\n"
628 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
630 my $dir = $class->get_subdir($scfg, $vtype);
632 $dir .= "/$vmid" if $vtype eq 'images';
634 my $path = "$dir/$name";
636 return wantarray ?
($path, $vmid, $vtype) : $path;
640 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
642 return $class->filesystem_path($scfg, $volname, $snapname);
646 my ($class, $storeid, $scfg, $volname) = @_;
648 # this only works for file based storage types
649 die "storage definition has no path\n" if !$scfg->{path
};
651 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
652 $class->parse_volname($volname);
654 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
656 die "create_base not possible with base image\n" if $isBase;
658 my $path = $class->filesystem_path($scfg, $volname);
660 my ($size, undef, $used, $parent) = file_size_info
($path);
661 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
663 die "volname '$volname' contains wrong information about parent\n"
664 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
667 $newname =~ s/^vm-/base-/;
669 my $newvolname = $basename ?
"$basevmid/$basename/$vmid/$newname" :
672 my $newpath = $class->filesystem_path($scfg, $newvolname);
674 die "file '$newpath' already exists\n" if -f
$newpath;
676 rename($path, $newpath) ||
677 die "rename '$path' to '$newpath' failed - $!\n";
679 # We try to protect base volume
681 chmod(0444, $newpath); # nobody should write anything
683 # also try to set immutable flag
684 eval { run_command
(['/usr/bin/chattr', '+i', $newpath]); };
690 my $get_vm_disk_number = sub {
691 my ($disk_name, $scfg, $vmid, $suffix) = @_;
693 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
695 my $type = $scfg->{type
};
696 my $def = { %{$defaultData->{plugindata
}->{$type}} };
698 my $valid = $def->{format
}[0];
699 if ($valid->{subvol
}) {
700 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
703 if ($disk_name =~ m/$disk_regex/) {
710 sub get_next_vm_diskname
{
711 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
714 my $prefix = ($fmt eq 'subvol') ?
'subvol' : 'vm';
715 my $suffix = $add_fmt_suffix ?
".$fmt" : '';
718 foreach my $disk (@$disk_list) {
719 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
720 $disk_ids->{$disknum} = 1 if defined($disknum);
723 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
724 if (!$disk_ids->{$i}) {
725 return "$prefix-$vmid-disk-$i$suffix";
729 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
732 sub find_free_diskname
{
733 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
735 my $disks = $class->list_images($storeid, $scfg, $vmid);
737 my $disk_list = [ map { $_->{volid
} } @$disks ];
739 return get_next_vm_diskname
($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
743 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
745 # this only works for file based storage types
746 die "storage definition has no path\n" if !$scfg->{path
};
748 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
749 $class->parse_volname($volname);
751 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
753 die "this storage type does not support clone_image on snapshot\n" if $snap;
755 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
757 die "clone_image only works on base images\n" if !$isBase;
759 my $imagedir = $class->get_subdir($scfg, 'images');
760 $imagedir .= "/$vmid";
764 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
766 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
768 my $newvol = "$basevmid/$basename/$vmid/$name";
770 my $path = $class->filesystem_path($scfg, $newvol);
772 # Note: we use relative paths, so we need to call chdir before qemu-img
774 local $CWD = $imagedir;
776 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
777 '-F', $format, '-f', 'qcow2', $path];
789 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
791 my $imagedir = $class->get_subdir($scfg, 'images');
792 $imagedir .= "/$vmid";
796 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
798 my (undef, $tmpfmt) = parse_name_dir
($name);
800 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
803 my $path = "$imagedir/$name";
805 die "disk image '$path' already exists\n" if -e
$path;
807 if ($fmt eq 'subvol') {
808 # only allow this if size = 0, so that user knows what he is doing
809 die "storage does not support subvol quotas\n" if $size != 0;
811 my $old_umask = umask(0022);
813 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
817 my $cmd = ['/usr/bin/qemu-img', 'create'];
819 my $prealloc_opt = preallocation_cmd_option
($scfg, $fmt);
820 push @$cmd, '-o', $prealloc_opt if defined($prealloc_opt);
822 push @$cmd, '-f', $fmt, $path, "${size}K";
824 eval { run_command
($cmd, errmsg
=> "unable to create image"); };
832 return "$vmid/$name";
836 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
838 die "cannot remove protected volume '$volname' on '$storeid'\n"
839 if $class->get_volume_attribute($scfg, $storeid, $volname, 'protected');
841 my $path = $class->filesystem_path($scfg, $volname);
844 # try to remove immutable flag
845 eval { run_command
(['/usr/bin/chattr', '-i', $path]); };
849 if (defined($format) && ($format eq 'subvol')) {
850 File
::Path
::remove_tree
($path);
852 if (!(-f
$path || -l
$path)) {
853 warn "disk image '$path' does not exist\n";
857 unlink($path) || die "unlink '$path' failed - $!\n";
860 # try to cleanup directory to not clutter storage with empty $vmid dirs if
861 # all images from a guest got deleted
862 my $dir = dirname
($path);
869 my ($filename, $timeout) = @_;
871 my $st = File
::stat::stat($filename);
874 my $extramsg = -l
$filename ?
' - dangling symlink?' : '';
875 warn "failed to stat '$filename'$extramsg\n";
879 if (S_ISDIR
($st->mode)) {
880 return wantarray ?
(0, 'subvol', 0, undef, $st->ctime) : 1;
885 run_command
(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
887 outfunc
=> sub { $json .= shift },
888 errfunc
=> sub { warn "$_[0]\n" }
893 my $info = eval { decode_json
($json) };
895 warn "could not parse qemu-img info command output for '$filename' - $err\n";
896 return wantarray ?
(undef, undef, undef, undef, $st->ctime) : undef;
899 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
901 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
902 # coerce back from string
904 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
905 # coerce back from string
907 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
908 if (defined($parent)) {
909 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
911 return wantarray ?
($size, $format, $used, $parent, $st->ctime) : $size;
914 # FIXME remove on the next APIAGE reset.
915 # Deprecated, use get_volume_attribute instead.
916 sub get_volume_notes
{
917 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
919 die "volume notes are not supported for $class";
922 # FIXME remove on the next APIAGE reset.
923 # Deprecated, use update_volume_attribute instead.
924 sub update_volume_notes
{
925 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
927 die "volume notes are not supported for $class";
930 # Returns undef if the attribute is not supported for the volume.
931 # Should die if there is an error fetching the attribute.
932 # Possible attributes:
933 # notes - user-provided comments/notes.
934 # protected - not to be removed by free_image, and for backups, ignored when pruning.
935 sub get_volume_attribute
{
936 my ($class, $scfg, $storeid, $volname, $attribute) = @_;
938 if ($attribute eq 'notes') {
939 my $notes = eval { $class->get_volume_notes($scfg, $storeid, $volname); };
941 return if $err =~ m/^volume notes are not supported/;
950 # Dies if the attribute is not supported for the volume.
951 sub update_volume_attribute
{
952 my ($class, $scfg, $storeid, $volname, $attribute, $value) = @_;
954 if ($attribute eq 'notes') {
955 $class->update_volume_notes($scfg, $storeid, $volname, $value);
958 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
961 sub volume_size_info
{
962 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
963 my $path = $class->filesystem_path($scfg, $volname);
964 return file_size_info
($path, $timeout);
969 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
971 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
973 return 1 if $running;
975 my $path = $class->filesystem_path($scfg, $volname);
977 my $format = ($class->parse_volname($volname))[6];
979 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
981 run_command
($cmd, timeout
=> 10);
986 sub volume_snapshot
{
987 my ($class, $scfg, $storeid, $volname, $snap) = @_;
989 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
991 my $path = $class->filesystem_path($scfg, $volname);
993 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
1000 # Asserts that a rollback to $snap on $volname is possible.
1001 # If certain snapshots are preventing the rollback and $blockers is an array
1002 # reference, the snapshot names can be pushed onto $blockers prior to dying.
1003 sub volume_rollback_is_possible
{
1004 my ($class, $scfg, $storeid, $volname, $snap, $blockers) = @_;
1009 sub volume_snapshot_rollback
{
1010 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1012 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1014 my $path = $class->filesystem_path($scfg, $volname);
1016 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
1023 sub volume_snapshot_delete
{
1024 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
1026 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1028 return 1 if $running;
1030 my $path = $class->filesystem_path($scfg, $volname);
1032 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
1034 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
1041 sub volume_snapshot_needs_fsfreeze
{
1045 sub storage_can_replicate
{
1046 my ($class, $scfg, $storeid, $format) = @_;
1051 sub volume_has_feature
{
1052 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
1056 current
=> { qcow2
=> 1 },
1057 snap
=> { qcow2
=> 1 },
1060 base
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1063 current
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1, subvol
=> 1 },
1066 base
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1067 current
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1068 snap
=> { qcow2
=> 1 },
1071 base
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1072 current
=> { qcow2
=> 1, raw
=> 1, vmdk
=> 1 },
1075 current
=> {qcow2
=> 1, raw
=> 1, vmdk
=> 1},
1079 if ($feature eq 'clone') {
1081 defined($opts->{valid_target_formats
})
1082 && !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats
}})
1084 return 0; # clone_image creates a qcow2 volume
1086 } elsif ($feature eq 'rename') {
1087 return 0 if $class->can('api') && $class->api() < 10;
1091 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) = $class->parse_volname($volname);
1097 $key = $isBase ?
'base' : 'current';
1100 return 1 if defined($features->{$feature}->{$key}->{$format});
1106 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
1108 my $imagedir = $class->get_subdir($scfg, 'images');
1110 my ($defFmt, $vaidFmts) = default_format
($scfg);
1111 my $fmts = join ('|', @$vaidFmts);
1115 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
1117 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1123 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1125 my ($size, $format, $used, $parent, $ctime) = file_size_info
($fn);
1126 next if !($format && defined($size));
1129 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1130 my ($basevmid, $basename) = ($1, $2);
1131 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1133 $volid = "$storeid:$owner/$name";
1137 my $found = grep { $_ eq $volid } @$vollist;
1142 volid
=> $volid, format
=> $format,
1143 size
=> $size, vmid
=> $owner, used
=> $used, parent
=> $parent
1146 $info->{ctime
} = $ctime if $ctime;
1154 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1155 my $get_subdir_files = sub {
1156 my ($sid, $path, $tt, $vmid) = @_;
1160 foreach my $fn (<$path/*>) {
1161 my $st = File
::stat::stat($fn);
1163 next if (!$st || S_ISDIR
($st->mode));
1168 next if $fn !~ m!/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!i;
1170 $info = { volid
=> "$sid:iso/$1", format
=> 'iso' };
1172 } elsif ($tt eq 'vztmpl') {
1173 next if $fn !~ m!/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!;
1175 $info = { volid
=> "$sid:vztmpl/$1", format
=> "t$2" };
1177 } elsif ($tt eq 'backup') {
1178 next if $fn !~ m!/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!;
1183 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1184 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1186 $info = { volid
=> "$sid:backup/$fn", format
=> $format };
1188 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
1190 $info->{ctime
} = $archive_info->{ctime
} if defined($archive_info->{ctime
});
1191 $info->{subtype
} = $archive_info->{type
} // 'unknown';
1193 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1194 $info->{vmid
} = $vmid // $1;
1197 my $notes_fn = $original.NOTES_EXT
;
1199 my $notes = PVE
::Tools
::file_read_firstline
($notes_fn);
1200 $info->{notes
} = $notes if defined($notes);
1203 $info->{protected
} = 1 if -e PVE
::Storage
::protection_file_path
($original);
1204 } elsif ($tt eq 'snippets') {
1207 volid
=> "$sid:snippets/". basename
($fn),
1208 format
=> 'snippet',
1212 $info->{size
} = $st->size;
1213 $info->{ctime
} //= $st->ctime;
1221 # If attributes are set on a volume, they should be included in the result.
1222 # See get_volume_attribute for a list of possible attributes.
1224 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1227 my $vmlist = PVE
::Cluster
::get_vmlist
();
1228 foreach my $type (@$content_types) {
1231 if ($type eq 'images' || $type eq 'rootdir') {
1232 $data = $class->list_images($storeid, $scfg, $vmid);
1233 } elsif ($scfg->{path
}) {
1234 my $path = $class->get_subdir($scfg, $type);
1236 if ($type eq 'iso' && !defined($vmid)) {
1237 $data = $get_subdir_files->($storeid, $path, 'iso');
1238 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1239 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1240 } elsif ($type eq 'backup') {
1241 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1242 } elsif ($type eq 'snippets') {
1243 $data = $get_subdir_files->($storeid, $path, 'snippets');
1249 foreach my $item (@$data) {
1250 if ($type eq 'images' || $type eq 'rootdir') {
1251 my $vminfo = $vmlist->{ids
}->{$item->{vmid
}};
1253 if (defined($vminfo)) {
1254 $vmtype = $vminfo->{type
};
1256 if (defined($vmtype) && $vmtype eq 'lxc') {
1257 $item->{content
} = 'rootdir';
1259 $item->{content
} = 'images';
1261 next if $type ne $item->{content
};
1263 $item->{content
} = $type;
1274 my ($class, $storeid, $scfg, $cache) = @_;
1276 my $path = $scfg->{path
};
1278 die "storage definition has no path\n" if !$path;
1281 my $res = PVE
::Tools
::df
($path, $timeout);
1283 return undef if !$res || !$res->{total
};
1285 return ($res->{total
}, $res->{avail
}, $res->{used
}, 1);
1288 # Returns a hash with the snapshot names as keys and the following data:
1289 # id - Unique id to distinguish different snapshots even if the have the same name.
1290 # timestamp - Creation time of the snapshot (seconds since epoch).
1291 # Returns an empty hash if the volume does not exist.
1292 sub volume_snapshot_info
{
1293 my ($class, $scfg, $storeid, $volname) = @_;
1295 die "volume_snapshot_info is not implemented for $class";
1298 sub activate_storage
{
1299 my ($class, $storeid, $scfg, $cache) = @_;
1301 my $path = $scfg->{path
};
1303 die "storage definition has no path\n" if !$path;
1305 # this path test may hang indefinitely on unresponsive mounts
1307 if (! PVE
::Tools
::run_fork_with_timeout
($timeout, sub {-d
$path})) {
1308 die "unable to activate storage '$storeid' - " .
1309 "directory '$path' does not exist or is unreachable\n";
1313 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1315 if (defined($scfg->{content
})) {
1316 foreach my $vtype (keys %$vtype_subdirs) {
1317 # OpenVZMigrate uses backup (dump) dir
1318 if (defined($scfg->{content
}->{$vtype}) ||
1319 ($vtype eq 'backup' && defined($scfg->{content
}->{'rootdir'}))) {
1320 my $subdir = $class->get_subdir($scfg, $vtype);
1321 mkpath
$subdir if $subdir ne $path;
1327 sub deactivate_storage
{
1328 my ($class, $storeid, $scfg, $cache) = @_;
1330 # do nothing by default
1334 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1336 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1341 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1346 sub activate_volume
{
1347 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1349 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1351 # check is volume exists
1352 if ($scfg->{path
}) {
1353 die "volume '$storeid:$volname' does not exist\n" if ! -e
$path;
1355 die "volume '$storeid:$volname' does not exist\n" if ! -b
$path;
1359 sub deactivate_volume
{
1360 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1362 # do nothing by default
1365 sub check_connection
{
1366 my ($class, $storeid, $scfg) = @_;
1367 # do nothing by default
1372 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1374 $logfunc //= sub { print "$_[1]\n" };
1376 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1378 my $backup_groups = {};
1379 my $prune_list = [];
1381 foreach my $backup (@{$backups}) {
1382 my $volid = $backup->{volid
};
1383 my $archive_info = eval { PVE
::Storage
::archive_info
($volid) } // {};
1384 my $backup_type = $archive_info->{type
} // 'unknown';
1385 my $backup_vmid = $archive_info->{vmid
} // $backup->{vmid
};
1387 next if defined($type) && $type ne $backup_type;
1390 ctime
=> $backup->{ctime
},
1391 type
=> $backup_type,
1395 $prune_entry->{vmid
} = $backup_vmid if defined($backup_vmid);
1397 if ($archive_info->{is_std_name
}) {
1398 die "internal error - got no VMID\n" if !defined($backup_vmid);
1399 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1400 if defined($vmid) && $backup_vmid ne $vmid;
1402 $prune_entry->{ctime
} = $archive_info->{ctime
};
1403 my $group = "$backup_type/$backup_vmid";
1404 push @{$backup_groups->{$group}}, $prune_entry;
1406 # ignore backups that don't use the standard naming scheme
1407 $prune_entry->{mark
} = 'renamed';
1410 $prune_entry->{mark
} = 'protected' if $backup->{protected
};
1412 push @{$prune_list}, $prune_entry;
1415 foreach my $backup_group (values %{$backup_groups}) {
1416 PVE
::Storage
::prune_mark_backup_group
($backup_group, $keep);
1421 foreach my $prune_entry (@{$prune_list}) {
1422 next if $prune_entry->{mark
} ne 'remove';
1424 my $volid = $prune_entry->{volid
};
1425 $logfunc->('info', "removing backup '$volid'");
1427 my (undef, $volname) = parse_volume_id
($volid);
1428 my $archive_path = $class->filesystem_path($scfg, $volname);
1429 PVE
::Storage
::archive_remove
($archive_path);
1432 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1437 die "error pruning backups - check log\n" if $failed;
1442 # Import/Export interface:
1443 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1444 # the default implementations will return this if $scfg->{path} is set,
1445 # mimicking the old PVE::Storage::storage_migrate() function.
1447 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1448 # functions in case the format doesn't match their specialized
1449 # implementations to reuse the raw/tar code.
1451 # Format specification:
1452 # The following formats are all prefixed with image information in the form
1453 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1454 # to preallocate the image on storages which require it.
1456 # raw+size: (image files only)
1457 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1458 # qcow2+size, vmdk: (image files only)
1459 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1460 # files which are already in qcow2 format, or via `qemu-img convert`.
1461 # Note that these formats are only valid with $with_snapshots being true.
1462 # tar+size: (subvolumes only)
1463 # A GNU tar stream containing just the inner contents of the subvolume.
1464 # This does not distinguish between the contents of a privileged or
1465 # unprivileged container. In other words, this is from the root user
1466 # namespace's point of view with no uid-mapping in effect.
1467 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1469 # Plugins may reuse these helpers. Changes to the header format should be
1470 # reflected by changes to the function prototypes.
1471 sub write_common_header
($$) {
1472 my ($fh, $image_size_in_bytes) = @_;
1473 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1476 sub read_common_header
($) {
1478 sysread($fh, my $size, 8);
1479 $size = unpack('Q<', $size);
1480 die "import: no size found in export header, aborting.\n" if !defined($size);
1485 # Export a volume into a file handle as a stream of desired format.
1487 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1488 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1489 my $file = $class->path($scfg, $volname, $storeid)
1490 or goto unsupported
;
1491 my ($size, $file_format) = file_size_info
($file);
1493 if ($format eq 'raw+size') {
1494 goto unsupported
if $with_snapshots || $file_format eq 'subvol';
1495 write_common_header
($fh, $size);
1496 if ($file_format eq 'raw') {
1497 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1499 run_command
(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1500 output
=> '>&'.fileno($fh));
1503 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1504 my $data_format = $1;
1505 goto unsupported
if !$with_snapshots || $file_format ne $data_format;
1506 write_common_header
($fh, $size);
1507 run_command
(['dd', "if=$file", "bs=4k"], output
=> '>&'.fileno($fh));
1509 } elsif ($format eq 'tar+size') {
1510 goto unsupported
if $file_format ne 'subvol';
1511 write_common_header
($fh, $size);
1512 run_command
(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1513 output
=> '>&'.fileno($fh));
1518 die "volume export format $format not available for $class";
1521 sub volume_export_formats
{
1522 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1523 if ($scfg->{path
} && !defined($snapshot) && !defined($base_snapshot)) {
1524 my $file = $class->path($scfg, $volname, $storeid)
1526 my ($size, $format) = file_size_info
($file);
1528 if ($with_snapshots) {
1529 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1532 return ('tar+size') if $format eq 'subvol';
1533 return ('raw+size');
1538 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1540 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1542 die "volume import format '$format' not available for $class\n"
1543 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1544 my $data_format = $1;
1546 die "format $format cannot be imported without snapshots\n"
1547 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1548 die "format $format cannot be imported with snapshots\n"
1549 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1551 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1552 $class->parse_volname($volname);
1554 # XXX: Should we bother with conversion routines at this level? This won't
1555 # happen without manual CLI usage, so for now we just error out...
1556 die "cannot import format $format into a file of format $file_format\n"
1557 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1559 # Check for an existing file first since interrupting alloc_image doesn't
1561 my $file = $class->path($scfg, $volname, $storeid);
1563 die "file '$file' already exists\n" if !$allow_rename;
1564 warn "file '$file' already exists - importing with a different name\n";
1568 my ($size) = read_common_header
($fh);
1569 $size = int($size/1024);
1572 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1573 my $oldname = $volname;
1574 $volname = $allocname;
1575 if (defined($name) && $allocname ne $oldname) {
1576 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1578 my $file = $class->path($scfg, $volname, $storeid)
1579 or die "internal error: failed to get path to newly allocated volume $volname\n";
1580 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1581 run_command
(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1582 input
=> '<&'.fileno($fh));
1583 } elsif ($data_format eq 'tar') {
1584 run_command
(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1585 input
=> '<&'.fileno($fh));
1587 die "volume import format '$format' not available for $class";
1591 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1596 return "$storeid:$volname";
1599 sub volume_import_formats
{
1600 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1601 if ($scfg->{path
} && !defined($base_snapshot)) {
1602 my $format = ($class->parse_volname($volname))[6];
1603 if ($with_snapshots) {
1604 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1607 return ('tar+size') if $format eq 'subvol';
1608 return ('raw+size');
1614 my ($class, $scfg, $storeid, $source_volname, $target_vmid, $target_volname) = @_;
1615 die "not implemented in storage plugin '$class'\n" if $class->can('api') && $class->api() < 10;
1616 die "no path found\n" if !$scfg->{path
};
1626 ) = $class->parse_volname($source_volname);
1628 $target_volname = $class->find_free_diskname($storeid, $scfg, $target_vmid, $format, 1)
1629 if !$target_volname;
1631 my $basedir = $class->get_subdir($scfg, 'images');
1633 mkpath
"${basedir}/${target_vmid}";
1635 my $old_path = "${basedir}/${source_vmid}/${source_image}";
1636 my $new_path = "${basedir}/${target_vmid}/${target_volname}";
1638 die "target volume '${target_volname}' already exists\n" if -e
$new_path;
1640 my $base = $base_name ?
"${base_vmid}/${base_name}/" : '';
1642 rename($old_path, $new_path) ||
1643 die "rename '$old_path' to '$new_path' failed - $!\n";
1645 return "${storeid}:${base}${target_vmid}/${target_volname}";