15 use Time
::Local
qw(timelocal);
17 use PVE
::Tools
qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
18 use PVE
::Cluster
qw(cfs_read_file cfs_write_file cfs_lock_file);
19 use PVE
::DataCenterConfig
;
20 use PVE
::Exception
qw(raise_param_exc raise);
23 use PVE
::RPCEnvironment
;
25 use PVE
::RESTEnvironment
qw(log_warn);
27 use PVE
::Storage
::Plugin
;
28 use PVE
::Storage
::DirPlugin
;
29 use PVE
::Storage
::LVMPlugin
;
30 use PVE
::Storage
::LvmThinPlugin
;
31 use PVE
::Storage
::NFSPlugin
;
32 use PVE
::Storage
::CIFSPlugin
;
33 use PVE
::Storage
::ISCSIPlugin
;
34 use PVE
::Storage
::RBDPlugin
;
35 use PVE
::Storage
::CephFSPlugin
;
36 use PVE
::Storage
::ISCSIDirectPlugin
;
37 use PVE
::Storage
::GlusterfsPlugin
;
38 use PVE
::Storage
::ZFSPoolPlugin
;
39 use PVE
::Storage
::ZFSPlugin
;
40 use PVE
::Storage
::PBSPlugin
;
41 use PVE
::Storage
::BTRFSPlugin
;
43 # Storage API version. Increment it on changes in storage API interface.
44 use constant APIVER
=> 10;
45 # Age is the number of versions we're backward compatible with.
46 # This is like having 'current=APIVER' and age='APIAGE' in libtool,
47 # see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
48 use constant APIAGE
=> 1;
50 our $KNOWN_EXPORT_FORMATS = ['raw+size', 'tar+size', 'qcow2+size', 'vmdk+size', 'zfs', 'btrfs'];
52 # load standard plugins
53 PVE
::Storage
::DirPlugin-
>register();
54 PVE
::Storage
::LVMPlugin-
>register();
55 PVE
::Storage
::LvmThinPlugin-
>register();
56 PVE
::Storage
::NFSPlugin-
>register();
57 PVE
::Storage
::CIFSPlugin-
>register();
58 PVE
::Storage
::ISCSIPlugin-
>register();
59 PVE
::Storage
::RBDPlugin-
>register();
60 PVE
::Storage
::CephFSPlugin-
>register();
61 PVE
::Storage
::ISCSIDirectPlugin-
>register();
62 PVE
::Storage
::GlusterfsPlugin-
>register();
63 PVE
::Storage
::ZFSPoolPlugin-
>register();
64 PVE
::Storage
::ZFSPlugin-
>register();
65 PVE
::Storage
::PBSPlugin-
>register();
66 PVE
::Storage
::BTRFSPlugin-
>register();
68 # load third-party plugins
69 if ( -d
'/usr/share/perl5/PVE/Storage/Custom' ) {
70 dir_glob_foreach
('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
72 my $modname = 'PVE::Storage::Custom::' . $file;
73 $modname =~ s!\.pm$!!;
74 $file = 'PVE/Storage/Custom/' . $file;
79 # Check perl interface:
80 die "not derived from PVE::Storage::Plugin\n" if !$modname->isa('PVE::Storage::Plugin');
81 die "does not provide an api() method\n" if !$modname->can('api');
82 # Check storage API version and that file is really storage plugin.
83 my $version = $modname->api();
84 die "implements an API version newer than current ($version > " . APIVER
. ")\n"
86 my $min_version = (APIVER
- APIAGE
);
87 die "API version too old, please update the plugin ($version < $min_version)\n"
88 if $version < $min_version;
89 # all OK, do import and register (i.e., "use")
93 # If we got this far and the API version is not the same, make some noise:
94 warn "Plugin \"$modname\" is implementing an older storage API
, an upgrade
is recommended
\n"
95 if $version != APIVER;
98 warn "Error loading storage plugin
\"$modname\": $@";
103 # initialize all plugins
104 PVE
::Storage
::Plugin-
>init();
106 # the following REs indicate the number or capture groups via the trailing digit
107 # CAUTION don't forget to update the digits accordingly after messing with the capture groups
109 our $ISO_EXT_RE_0 = qr/\.(?:iso|img)/i;
111 our $VZTMPL_EXT_RE_1 = qr/\.tar\.(gz|xz|zst)/i;
113 our $BACKUP_EXT_RE_2 = qr/\.(tgz|(?:tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)/;
115 # FIXME remove with PVE 8.0, add versioned breaks for pve-manager
116 our $vztmpl_extension_re = $VZTMPL_EXT_RE_1;
118 # PVE::Storage utility functions
121 return cfs_read_file
("storage.cfg");
127 cfs_write_file
('storage.cfg', $cfg);
130 sub lock_storage_config
{
131 my ($code, $errmsg) = @_;
133 cfs_lock_file
("storage.cfg", undef, $code);
136 $errmsg ?
die "$errmsg: $err" : die $err;
140 # FIXME remove maxfiles for PVE 8.0 or PVE 9.0
141 my $convert_maxfiles_to_prune_backups = sub {
146 my $maxfiles = delete $scfg->{maxfiles
};
148 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
151 $prune_backups = { 'keep-last' => $maxfiles };
152 } else { # maxfiles 0 means no limit
153 $prune_backups = { 'keep-all' => 1 };
155 $scfg->{'prune-backups'} = PVE
::JSONSchema
::print_property_string
(
163 my ($cfg, $storeid, $noerr) = @_;
165 die "no storage ID specified\n" if !$storeid;
167 my $scfg = $cfg->{ids
}->{$storeid};
169 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
171 $convert_maxfiles_to_prune_backups->($scfg);
176 sub storage_check_node
{
177 my ($cfg, $storeid, $node, $noerr) = @_;
179 my $scfg = storage_config
($cfg, $storeid);
181 if ($scfg->{nodes
}) {
182 $node = PVE
::INotify
::nodename
() if !$node || ($node eq 'localhost');
183 if (!$scfg->{nodes
}->{$node}) {
184 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
192 sub storage_check_enabled
{
193 my ($cfg, $storeid, $node, $noerr) = @_;
195 my $scfg = storage_config
($cfg, $storeid);
197 if ($scfg->{disable
}) {
198 die "storage '$storeid' is disabled\n" if !$noerr;
202 return storage_check_node
($cfg, $storeid, $node, $noerr);
205 # storage_can_replicate:
206 # return true if storage supports replication
207 # (volumes allocated with vdisk_alloc() has replication feature)
208 sub storage_can_replicate
{
209 my ($cfg, $storeid, $format) = @_;
211 my $scfg = storage_config
($cfg, $storeid);
212 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
213 return $plugin->storage_can_replicate($scfg, $storeid, $format);
216 sub get_max_protected_backups
{
217 my ($scfg, $storeid) = @_;
219 return $scfg->{'max-protected-backups'} if defined($scfg->{'max-protected-backups'});
221 my $rpcenv = PVE
::RPCEnvironment
::get
();
222 my $authuser = $rpcenv->get_user();
224 return $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.Allocate'], 1) ?
-1 : 5;
230 return keys %{$cfg->{ids
}};
234 my ($filename, $timeout) = @_;
236 return PVE
::Storage
::Plugin
::file_size_info
($filename, $timeout);
239 sub get_volume_attribute
{
240 my ($cfg, $volid, $attribute) = @_;
242 my ($storeid, $volname) = parse_volume_id
($volid);
243 my $scfg = storage_config
($cfg, $storeid);
244 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
246 return $plugin->get_volume_attribute($scfg, $storeid, $volname, $attribute);
249 sub update_volume_attribute
{
250 my ($cfg, $volid, $attribute, $value) = @_;
252 my ($storeid, $volname) = parse_volume_id
($volid);
253 my $scfg = storage_config
($cfg, $storeid);
254 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
256 my ($vtype, undef, $vmid) = $plugin->parse_volname($volname);
257 my $max_protected_backups = get_max_protected_backups
($scfg, $storeid);
262 && $attribute eq 'protected'
264 && !$plugin->get_volume_attribute($scfg, $storeid, $volname, 'protected')
265 && $max_protected_backups > -1 # -1 is unlimited
267 my $backups = $plugin->list_volumes($storeid, $scfg, $vmid, ['backup']);
268 my ($backup_type) = map { $_->{subtype
} } grep { $_->{volid
} eq $volid } $backups->@*;
270 my $protected_count = grep {
271 $_->{protected
} && (!$backup_type || ($_->{subtype
} && $_->{subtype
} eq $backup_type))
274 if ($max_protected_backups <= $protected_count) {
275 die "The number of protected backups per guest is limited to $max_protected_backups ".
276 "on storage '$storeid'\n";
280 return $plugin->update_volume_attribute($scfg, $storeid, $volname, $attribute, $value);
283 sub volume_size_info
{
284 my ($cfg, $volid, $timeout) = @_;
286 my ($storeid, $volname) = parse_volume_id
($volid, 1);
288 my $scfg = storage_config
($cfg, $storeid);
289 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
290 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
291 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
292 return file_size_info
($volid, $timeout);
299 my ($cfg, $volid, $size, $running) = @_;
301 my $padding = (1024 - $size % 1024) % 1024;
302 $size = $size + $padding;
304 my ($storeid, $volname) = parse_volume_id
($volid, 1);
306 my $scfg = storage_config
($cfg, $storeid);
307 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
308 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
309 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
310 die "resize file/device '$volid' is not possible\n";
312 die "unable to parse volume ID '$volid'\n";
316 sub volume_rollback_is_possible
{
317 my ($cfg, $volid, $snap, $blockers) = @_;
319 my ($storeid, $volname) = parse_volume_id
($volid, 1);
321 my $scfg = storage_config
($cfg, $storeid);
322 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
323 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap, $blockers);
324 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
325 die "snapshot rollback file/device '$volid' is not possible\n";
327 die "unable to parse volume ID '$volid'\n";
331 sub volume_snapshot
{
332 my ($cfg, $volid, $snap) = @_;
334 my ($storeid, $volname) = parse_volume_id
($volid, 1);
336 my $scfg = storage_config
($cfg, $storeid);
337 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
338 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
339 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
340 die "snapshot file/device '$volid' is not possible\n";
342 die "unable to parse volume ID '$volid'\n";
346 sub volume_snapshot_rollback
{
347 my ($cfg, $volid, $snap) = @_;
349 my ($storeid, $volname) = parse_volume_id
($volid, 1);
351 my $scfg = storage_config
($cfg, $storeid);
352 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
353 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
354 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
355 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
356 die "snapshot rollback file/device '$volid' is not possible\n";
358 die "unable to parse volume ID '$volid'\n";
362 # FIXME PVE 8.x remove $running parameter (needs APIAGE reset)
363 sub volume_snapshot_delete
{
364 my ($cfg, $volid, $snap, $running) = @_;
366 my ($storeid, $volname) = parse_volume_id
($volid, 1);
368 my $scfg = storage_config
($cfg, $storeid);
369 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
370 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
371 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
372 die "snapshot delete file/device '$volid' is not possible\n";
374 die "unable to parse volume ID '$volid'\n";
378 # check if a filesystem on top of a volume needs to flush its journal for
379 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
380 # container mountpoints
381 sub volume_snapshot_needs_fsfreeze
{
382 my ($cfg, $volid) = @_;
384 my ($storeid, $volname) = parse_volume_id
($volid);
385 my $scfg = storage_config
($cfg, $storeid);
386 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
387 return $plugin->volume_snapshot_needs_fsfreeze();
390 # check if a volume or snapshot supports a given feature
392 # clone - linked clone is possible
393 # copy - full clone is possible
394 # replicate - replication is possible
395 # snapshot - taking a snapshot is possible
396 # sparseinit - volume is sparsely initialized
397 # template - conversion to base image is possible
398 # rename - renaming volumes is possible
399 # $snap - check if the feature is supported for a given snapshot
400 # $running - if the guest owning the volume is running
401 # $opts - hash with further options:
402 # valid_target_formats - list of formats for the target of a copy/clone
403 # operation that the caller could work with. The
404 # format of $volid is always considered valid and if
405 # no list is specified, all formats are considered valid.
406 sub volume_has_feature
{
407 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
409 my ($storeid, $volname) = parse_volume_id
($volid, 1);
411 my $scfg = storage_config
($cfg, $storeid);
412 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
413 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
414 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
421 sub volume_snapshot_info
{
422 my ($cfg, $volid) = @_;
424 my ($storeid, $volname) = parse_volume_id
($volid);
425 my $scfg = storage_config
($cfg, $storeid);
426 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
427 return $plugin->volume_snapshot_info($scfg, $storeid, $volname);
431 my ($cfg, $storeid, $vmid) = @_;
433 my $scfg = storage_config
($cfg, $storeid);
434 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
436 my $path = $plugin->get_subdir($scfg, 'images');
438 return $vmid ?
"$path/$vmid" : $path;
441 sub get_private_dir
{
442 my ($cfg, $storeid, $vmid) = @_;
444 my $scfg = storage_config
($cfg, $storeid);
445 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
447 my $path = $plugin->get_subdir($scfg, 'rootdir');
449 return $vmid ?
"$path/$vmid" : $path;
453 my ($cfg, $storeid) = @_;
455 my $scfg = storage_config
($cfg, $storeid);
456 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
458 return $plugin->get_subdir($scfg, 'iso');
462 my ($cfg, $storeid) = @_;
464 my $scfg = storage_config
($cfg, $storeid);
465 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
467 return $plugin->get_subdir($scfg, 'vztmpl');
471 my ($cfg, $storeid) = @_;
473 my $scfg = storage_config
($cfg, $storeid);
474 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
476 return $plugin->get_subdir($scfg, 'backup');
479 # library implementation
484 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
489 # NOTE: basename and basevmid are always undef for LVM-thin, where the
490 # clone -> base reference is not encoded in the volume ID.
491 # see note in PVE::Storage::LvmThinPlugin for details.
493 my ($cfg, $volid) = @_;
495 my ($storeid, $volname) = parse_volume_id
($volid);
497 my $scfg = storage_config
($cfg, $storeid);
499 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
501 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
503 return $plugin->parse_volname($volname);
506 sub parse_volume_id
{
507 my ($volid, $noerr) = @_;
509 return PVE
::Storage
::Plugin
::parse_volume_id
($volid, $noerr);
512 # test if we have read access to volid
513 sub check_volume_access
{
514 my ($rpcenv, $user, $cfg, $vmid, $volid, $type) = @_;
516 my ($sid, $volname) = parse_volume_id
($volid, 1);
518 my ($vtype, undef, $ownervm) = parse_volname
($cfg, $volid);
520 # Need to allow 'images' when expecting 'rootdir' too - not cleanly separated in plugins.
521 die "unable to use volume $volid - content type needs to be '$type'\n"
522 if defined($type) && $vtype ne $type && ($type ne 'rootdir' || $vtype ne 'images');
524 return if $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate'], 1);
526 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
527 # require at least read access to storage, (custom) templates/ISOs could be sensitive
528 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
529 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
530 # we are owner - allow access
531 } elsif ($vtype eq 'backup' && $ownervm) {
532 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
533 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
534 } elsif (($vtype eq 'images' || $vtype eq 'rootdir') && $ownervm) {
535 $rpcenv->check($user, "/storage/$sid", ['Datastore.Audit']);
536 $rpcenv->check($user, "/vms/$ownervm", ['VM.Config.Disk']);
538 die "missing privileges to access $volid\n";
541 die "Only root can pass arbitrary filesystem paths."
542 if $user ne 'root@pam';
548 # NOTE: this check does not work for LVM-thin, where the clone -> base
549 # reference is not encoded in the volume ID.
550 # see note in PVE::Storage::LvmThinPlugin for details.
551 sub volume_is_base_and_used
{
552 my ($cfg, $volid) = @_;
554 my ($storeid, $volname) = parse_volume_id
($volid);
555 my $scfg = storage_config
($cfg, $storeid);
556 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
558 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
559 $plugin->parse_volname($volname);
562 my $vollist = $plugin->list_images($storeid, $scfg);
563 foreach my $info (@$vollist) {
564 my (undef, $tmpvolname) = parse_volume_id
($info->{volid
});
565 my $basename = undef;
566 my $basevmid = undef;
569 (undef, undef, undef, $basename, $basevmid) =
570 $plugin->parse_volname($tmpvolname);
573 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
581 # try to map a filesystem path to a volume identifier
582 sub path_to_volume_id
{
583 my ($cfg, $path) = @_;
585 my $ids = $cfg->{ids
};
587 my ($sid, $volname) = parse_volume_id
($path, 1);
589 if (my $scfg = $ids->{$sid}) {
591 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
592 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
593 return ($vtype, $path);
599 # Note: abs_path() return undef if $path doesn not exist
600 # for example when nfs storage is not mounted
601 $path = abs_path
($path) || $path;
603 foreach my $sid (keys %$ids) {
604 my $scfg = $ids->{$sid};
605 next if !$scfg->{path
};
606 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
607 my $imagedir = $plugin->get_subdir($scfg, 'images');
608 my $isodir = $plugin->get_subdir($scfg, 'iso');
609 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
610 my $backupdir = $plugin->get_subdir($scfg, 'backup');
611 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
612 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
614 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
618 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
619 foreach my $info (@$vollist) {
620 my ($storeid, $volname) = parse_volume_id
($info->{volid
});
621 my $volpath = $plugin->path($scfg, $volname, $storeid);
622 if ($volpath eq $path) {
623 return ('images', $info->{volid
});
626 } elsif ($path =~ m!^$isodir/([^/]+$ISO_EXT_RE_0)$!) {
628 return ('iso', "$sid:iso/$name");
629 } elsif ($path =~ m!^$tmpldir/([^/]+$VZTMPL_EXT_RE_1)$!) {
631 return ('vztmpl', "$sid:vztmpl/$name");
632 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
634 return ('rootdir', "$sid:rootdir/$vmid");
635 } elsif ($path =~ m!^$backupdir/([^/]+$BACKUP_EXT_RE_2)$!) {
637 return ('backup', "$sid:backup/$name");
638 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
640 return ('snippets', "$sid:snippets/$name");
644 # can't map path to volume id
649 my ($cfg, $volid, $snapname) = @_;
651 my ($storeid, $volname) = parse_volume_id
($volid);
653 my $scfg = storage_config
($cfg, $storeid);
655 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
656 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
657 return wantarray ?
($path, $owner, $vtype) : $path;
660 sub abs_filesystem_path
{
661 my ($cfg, $volid, $allow_blockdev) = @_;
664 if (parse_volume_id
($volid, 1)) {
665 activate_volumes
($cfg, [ $volid ]);
666 $path = PVE
::Storage
::path
($cfg, $volid);
668 if (-f
$volid || ($allow_blockdev && -b
$volid)) {
669 my $abspath = abs_path
($volid);
670 if ($abspath && $abspath =~ m
|^(/.+)$|) {
671 $path = $1; # untaint any path
675 die "can't find file '$volid'\n"
676 if !($path && (-f
$path || ($allow_blockdev && -b
$path)));
681 # used as last resort to adapt volnames when migrating
682 my $volname_for_storage = sub {
683 my ($cfg, $storeid, $name, $vmid, $format) = @_;
685 my $scfg = storage_config
($cfg, $storeid);
687 my (undef, $valid_formats) = PVE
::Storage
::Plugin
::default_format
($scfg);
688 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
689 die "unsupported format '$format' for storage type $scfg->{type}\n"
690 if !$format_is_valid;
692 (my $name_without_extension = $name) =~ s/\.$format$//;
695 return "$vmid/$name_without_extension.$format";
697 return "$name_without_extension";
701 # whether a migration snapshot is needed for a given storage
702 sub storage_migrate_snapshot
{
703 my ($cfg, $storeid, $existing_snapshots) = @_;
704 my $scfg = storage_config
($cfg, $storeid);
706 return $scfg->{type
} eq 'zfspool' || ($scfg->{type
} eq 'btrfs' && $existing_snapshots);
709 my $volume_import_prepare = sub {
710 my ($volid, $format, $path, $apiver, $opts) = @_;
712 my $base_snapshot = $opts->{base_snapshot
};
713 my $snapshot = $opts->{snapshot
};
714 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
715 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
716 my $allow_rename = $opts->{allow_rename
} ?
1 : 0;
718 my $recv = ['pvesm', 'import', $volid, $format, $path, '-with-snapshots', $with_snapshots];
719 if (defined($snapshot)) {
720 push @$recv, '-snapshot', $snapshot;
722 if ($migration_snapshot) {
723 push @$recv, '-delete-snapshot', $snapshot;
725 push @$recv, '-allow-rename', $allow_rename if $apiver >= 5;
727 if (defined($base_snapshot)) {
728 # Check if the snapshot exists on the remote side:
729 push @$recv, '-base', $base_snapshot if $apiver >= 9;
735 my $volume_export_prepare = sub {
736 my ($cfg, $volid, $format, $logfunc, $opts) = @_;
737 my $base_snapshot = $opts->{base_snapshot
};
738 my $snapshot = $opts->{snapshot
};
739 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
740 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
741 my $ratelimit_bps = $opts->{ratelimit_bps
};
743 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
744 if (defined($snapshot)) {
745 push @$send, '-snapshot', $snapshot;
747 if (defined($base_snapshot)) {
748 push @$send, '-base', $base_snapshot;
752 if (defined($ratelimit_bps)) {
753 $cstream = [ '/usr/bin/cstream', '-t', $ratelimit_bps ];
754 $logfunc->("using a bandwidth limit of $ratelimit_bps bytes per second for transferring '$volid'") if $logfunc;
757 volume_snapshot
($cfg, $volid, $snapshot) if $migration_snapshot;
759 if (defined($snapshot)) {
760 activate_volumes
($cfg, [$volid], $snapshot);
762 activate_volumes
($cfg, [$volid]);
765 return $cstream ?
[ $send, $cstream ] : [ $send ];
768 sub storage_migrate
{
769 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
771 my $insecure = $opts->{insecure
};
773 my ($storeid, $volname) = parse_volume_id
($volid);
775 my $scfg = storage_config
($cfg, $storeid);
777 # no need to migrate shared content
778 return $volid if $storeid eq $target_storeid && $scfg->{shared
};
780 my $tcfg = storage_config
($cfg, $target_storeid);
783 if ($opts->{target_volname
}) {
784 $target_volname = $opts->{target_volname
};
785 } elsif ($scfg->{type
} eq $tcfg->{type
}) {
786 $target_volname = $volname;
788 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname
($cfg, $volid);
789 $target_volname = $volname_for_storage->($cfg, $target_storeid, $name, $vmid, $format);
792 my $target_volid = "${target_storeid}:${target_volname}";
794 my $target_ip = $target_sshinfo->{ip
};
796 my $ssh = PVE
::SSHInfo
::ssh_info_to_command
($target_sshinfo);
797 my $ssh_base = PVE
::SSHInfo
::ssh_info_to_command_base
($target_sshinfo);
798 local $ENV{RSYNC_RSH
} = PVE
::Tools
::cmd2string
($ssh_base);
800 if (!defined($opts->{snapshot
})) {
801 $opts->{migration_snapshot
} = storage_migrate_snapshot
($cfg, $storeid, $opts->{with_snapshots
});
802 $opts->{snapshot
} = '__migration__' if $opts->{migration_snapshot
};
805 my @formats = volume_transfer_formats
($cfg, $volid, $target_volid, $opts->{snapshot
}, $opts->{base_snapshot
}, $opts->{with_snapshots
});
806 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
807 my $format = $formats[0];
809 my $import_fn = '-'; # let pvesm import read from stdin per default
811 my $net = $target_sshinfo->{network
} // $target_sshinfo->{ip
};
812 $import_fn = "tcp://$net";
815 my $target_apiver = 1; # if there is no apiinfo call, assume 1
816 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
817 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
818 eval { run_command
($get_api_version, logfunc
=> $match_api_version); };
820 my $recv = [ @$ssh, '--', $volume_import_prepare->($target_volid, $format, $import_fn, $target_apiver, $opts)->@* ];
823 my $pattern = volume_imported_message
(undef, 1);
824 # Matches new volid and rate-limits dd output
825 my $match_volid_and_log = sub {
829 if ($line =~ /(?:\d+ bytes)(?:.+?copied, )(\d+) s/) { # rate-limit dd logs
830 my $elapsed = int($1);
833 } elsif ($elapsed < 600) {
840 $new_volid = $1 if ($line =~ $pattern);
842 if ($logfunc && $show) {
848 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
852 my $input = IO
::File-
>new();
853 my $info = IO
::File-
>new();
854 open3
($input, $info, $info, @$recv)
855 or die "receive command failed: $!\n";
858 my $try_ip = <$info> // '';
859 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
860 or die "no tunnel IP received, got '$try_ip'\n";
862 my $try_port = <$info> // '';
863 my ($port) = $try_port =~ /^(\d+)$/ # untaint
864 or die "no tunnel port received, got '$try_port'\n";
866 my $socket = IO
::Socket
::IP-
>new(PeerHost
=> $ip, PeerPort
=> $port, Type
=> SOCK_STREAM
)
867 or die "failed to connect to tunnel at $ip:$port\n";
868 # we won't be reading from the socket
869 shutdown($socket, 0);
871 eval { run_command
($cmds, output
=> '>&'.fileno($socket), errfunc
=> $match_volid_and_log); };
874 # don't close the connection entirely otherwise the receiving end
875 # might not get all buffered data (and fails with 'connection reset by peer')
876 shutdown($socket, 1);
878 # wait for the remote process to finish
879 while (my $line = <$info>) {
880 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
883 # now close the socket
885 if (!close($info)) { # does waitpid()
886 die "import failed: $!\n" if $!;
887 die "import failed: exit code ".($?>>8)."\n";
890 die $send_error if $send_error;
893 run_command
($cmds, logfunc
=> $match_volid_and_log);
896 die "unable to get ID of the migrated volume\n"
897 if !defined($new_volid) && $target_apiver >= 5;
900 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
901 if ($opts->{migration_snapshot
}) {
902 eval { volume_snapshot_delete
($cfg, $volid, $opts->{snapshot
}, 0) };
903 warn "could not remove source snapshot: $@\n" if $@;
907 return $new_volid // $target_volid;
911 my ($cfg, $volid, $vmid, $snap) = @_;
913 my ($storeid, $volname) = parse_volume_id
($volid);
915 my $scfg = storage_config
($cfg, $storeid);
917 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
919 activate_storage
($cfg, $storeid);
921 # lock shared storage
922 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
923 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
924 return "$storeid:$volname";
928 sub vdisk_create_base
{
929 my ($cfg, $volid) = @_;
931 my ($storeid, $volname) = parse_volume_id
($volid);
933 my $scfg = storage_config
($cfg, $storeid);
935 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
937 activate_storage
($cfg, $storeid);
939 # lock shared storage
940 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
941 my $volname = $plugin->create_base($storeid, $scfg, $volname);
942 return "$storeid:$volname";
947 my ($cfg, $volid, $snapname) = @_;
949 my ($storeid, $volname) = parse_volume_id
($volid);
951 my $scfg = storage_config
($cfg, $storeid);
953 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
955 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
959 my ($cfg, $volid, $snapname) = @_;
961 my ($storeid, $volname) = parse_volume_id
($volid);
963 my $scfg = storage_config
($cfg, $storeid);
965 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
967 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
971 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
973 die "no storage ID specified\n" if !$storeid;
975 PVE
::JSONSchema
::parse_storage_id
($storeid);
977 my $scfg = storage_config
($cfg, $storeid);
979 die "no VMID specified\n" if !$vmid;
981 $vmid = parse_vmid
($vmid);
983 my $defformat = PVE
::Storage
::Plugin
::default_format
($scfg);
985 $fmt = $defformat if !$fmt;
987 activate_storage
($cfg, $storeid);
989 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
991 # lock shared storage
992 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
993 my $old_umask = umask(umask|0037);
994 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
998 return "$storeid:$volname";
1003 my ($cfg, $volid) = @_;
1005 my ($storeid, $volname) = parse_volume_id
($volid);
1006 my $scfg = storage_config
($cfg, $storeid);
1007 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1009 activate_storage
($cfg, $storeid);
1013 # lock shared storage
1014 $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
1015 # LVM-thin allows deletion of still referenced base volumes!
1016 die "base volume '$volname' is still in use by linked clones\n"
1017 if volume_is_base_and_used
($cfg, $volid);
1019 my (undef, undef, undef, undef, undef, $isBase, $format) =
1020 $plugin->parse_volname($volname);
1021 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1024 return if !$cleanup_worker;
1026 my $rpcenv = PVE
::RPCEnvironment
::get
();
1027 my $authuser = $rpcenv->get_user();
1029 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
1033 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
1035 my $ids = $cfg->{ids
};
1037 storage_check_enabled
($cfg, $storeid) if ($storeid);
1039 my $res = $storeid ?
{ $storeid => [] } : {};
1041 # prepare/activate/refresh all storages
1043 my $storage_list = [];
1045 foreach my $volid (@$vollist) {
1046 my ($sid, undef) = parse_volume_id
($volid);
1047 next if !defined($ids->{$sid});
1048 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1049 push @$storage_list, $sid;
1052 foreach my $sid (keys %$ids) {
1053 next if $storeid && $storeid ne $sid;
1054 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1055 my $content = $ids->{$sid}->{content
};
1056 next if defined($ctype) && !$content->{$ctype};
1057 next if !($content->{rootdir
} || $content->{images
});
1058 push @$storage_list, $sid;
1064 activate_storage_list
($cfg, $storage_list, $cache);
1066 for my $sid ($storage_list->@*) {
1067 next if $storeid && $storeid ne $sid;
1069 my $scfg = $ids->{$sid};
1070 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1071 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
1072 @{$res->{$sid}} = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @{$res->{$sid}} if $res->{$sid};
1079 my ($cfg, $storeid, $tt) = @_;
1081 die "unknown template type '$tt'\n"
1082 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1084 my $ids = $cfg->{ids
};
1086 storage_check_enabled
($cfg, $storeid) if ($storeid);
1091 foreach my $sid (keys %$ids) {
1092 next if $storeid && $storeid ne $sid;
1094 my $scfg = $ids->{$sid};
1095 my $type = $scfg->{type
};
1097 next if !$scfg->{content
}->{$tt};
1099 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1101 $res->{$sid} = volume_list
($cfg, $sid, undef, $tt);
1108 my ($cfg, $storeid, $vmid, $content) = @_;
1110 my @ctypes = qw(rootdir images vztmpl iso backup snippets import);
1112 my $cts = $content ?
[ $content ] : [ @ctypes ];
1114 my $scfg = PVE
::Storage
::storage_config
($cfg, $storeid);
1116 $cts = [ grep { defined($scfg->{content
}->{$_}) } @$cts ];
1118 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1120 activate_storage
($cfg, $storeid);
1122 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1124 @$res = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @$res;
1131 my $filename = "/sys/kernel/uevent_seqnum";
1134 if (my $fh = IO
::File-
>new($filename, "r")) {
1136 if ($line =~ m/^(\d+)$/) {
1144 sub activate_storage
{
1145 my ($cfg, $storeid, $cache) = @_;
1147 $cache = {} if !$cache;
1149 my $scfg = storage_check_enabled
($cfg, $storeid);
1151 return if $cache->{activated
}->{$storeid};
1153 $cache->{uevent_seqnum
} = uevent_seqnum
() if !$cache->{uevent_seqnum
};
1155 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1157 if ($scfg->{base
}) {
1158 my ($baseid, undef) = parse_volume_id
($scfg->{base
});
1159 activate_storage
($cfg, $baseid, $cache);
1162 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1163 die "connection check for storage '$storeid' failed - $@\n" if $@;
1164 die "storage '$storeid' is not online\n";
1167 $plugin->activate_storage($storeid, $scfg, $cache);
1169 my $newseq = uevent_seqnum
();
1171 # only call udevsettle if there are events
1172 if ($newseq > $cache->{uevent_seqnum
}) {
1173 system ("udevadm settle --timeout=30"); # ignore errors
1174 $cache->{uevent_seqnum
} = $newseq;
1177 $cache->{activated
}->{$storeid} = 1;
1180 sub activate_storage_list
{
1181 my ($cfg, $storeid_list, $cache) = @_;
1183 $cache = {} if !$cache;
1185 foreach my $storeid (@$storeid_list) {
1186 activate_storage
($cfg, $storeid, $cache);
1190 sub deactivate_storage
{
1191 my ($cfg, $storeid) = @_;
1193 my $scfg = storage_config
($cfg, $storeid);
1194 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1197 $plugin->deactivate_storage($storeid, $scfg, $cache);
1200 sub activate_volumes
{
1201 my ($cfg, $vollist, $snapname) = @_;
1203 return if !($vollist && scalar(@$vollist));
1205 my $storagehash = {};
1206 foreach my $volid (@$vollist) {
1207 my ($storeid, undef) = parse_volume_id
($volid);
1208 $storagehash->{$storeid} = 1;
1213 activate_storage_list
($cfg, [keys %$storagehash], $cache);
1215 foreach my $volid (@$vollist) {
1216 my ($storeid, $volname) = parse_volume_id
($volid);
1217 my $scfg = storage_config
($cfg, $storeid);
1218 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1219 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1223 sub deactivate_volumes
{
1224 my ($cfg, $vollist, $snapname) = @_;
1226 return if !($vollist && scalar(@$vollist));
1231 foreach my $volid (@$vollist) {
1232 my ($storeid, $volname) = parse_volume_id
($volid);
1234 my $scfg = storage_config
($cfg, $storeid);
1235 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1238 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1242 push @errlist, $volid;
1246 die "volume deactivation failed: " . join(' ', @errlist)
1247 if scalar(@errlist);
1251 my ($cfg, $content, $includeformat) = @_;
1253 my $ids = $cfg->{ids
};
1257 my @ctypes = PVE
::Tools
::split_list
($content);
1260 foreach my $storeid (keys %$ids) {
1261 my $storage_enabled = defined(storage_check_enabled
($cfg, $storeid, undef, 1));
1263 if (defined($content)) {
1265 foreach my $ctype (@ctypes) {
1266 if ($ids->{$storeid}->{content
}->{$ctype}) {
1271 next if !$want_ctype || !$storage_enabled;
1274 my $type = $ids->{$storeid}->{type
};
1276 $info->{$storeid} = {
1281 shared
=> $ids->{$storeid}->{shared
} ?
1 : 0,
1282 content
=> PVE
::Storage
::Plugin
::content_hash_to_string
($ids->{$storeid}->{content
}),
1284 enabled
=> $storage_enabled ?
1 : 0,
1287 push @$slist, $storeid;
1292 foreach my $storeid (keys %$ids) {
1293 my $scfg = $ids->{$storeid};
1295 next if !$info->{$storeid};
1296 next if !$info->{$storeid}->{enabled
};
1298 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1299 if ($includeformat) {
1300 my $pd = $plugin->plugindata();
1301 $info->{$storeid}->{format
} = $pd->{format
}
1303 $info->{$storeid}->{select_existing
} = $pd->{select_existing
}
1304 if $pd->{select_existing
};
1307 eval { activate_storage
($cfg, $storeid, $cache); };
1313 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1316 $info->{$storeid}->{total
} = int($total);
1317 $info->{$storeid}->{avail
} = int($avail);
1318 $info->{$storeid}->{used
} = int($used);
1319 $info->{$storeid}->{active
} = $active;
1328 my ($packed_ip, $family);
1330 my @res = PVE
::Tools
::getaddrinfo_all
($server);
1331 $family = $res[0]->{family
};
1332 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
1334 if (defined $packed_ip) {
1335 return Socket
::inet_ntop
($family, $packed_ip);
1341 my ($server_in) = @_;
1344 if (!($server = resolv_server
($server_in))) {
1345 die "unable to resolve address for server '${server_in}'\n";
1348 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1351 run_command
($cmd, outfunc
=> sub {
1354 # note: howto handle white spaces in export path??
1355 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1364 my ($server_in, $user, $password, $domain) = @_;
1366 my $server = resolv_server
($server_in);
1367 die "unable to resolve address for server '${server_in}'\n" if !$server;
1369 # we only support Windows 2012 and newer, so just use smb3
1370 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1371 push @$cmd, '-W', $domain if defined($domain);
1373 push @$cmd, '-N' if !defined($password);
1374 local $ENV{USER
} = $user if defined($user);
1375 local $ENV{PASSWD
} = $password if defined($password);
1386 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1388 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1390 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1394 # only die if we got no share, else it's just some followup check error
1395 # (like workgroup querying)
1396 raise
($err) if $err && !%$res;
1403 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1406 run_command
($cmd, outfunc
=> sub {
1409 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1410 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1411 my $size = $size_str + 0;
1412 my $used = $used_str + 0;
1413 # ignore subvolumes generated by our ZFSPoolPlugin
1414 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1415 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1416 push @$res, { pool
=> $pool, size
=> $size, free
=> $size-$used };
1424 my ($portal, $noerr) = @_;
1426 my ($server, $port) = PVE
::Tools
::parse_host_and_port
($portal);
1428 if (my $ip = resolv_server
($server)) {
1430 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1431 return $port ?
"$server:$port" : $server;
1434 return undef if $noerr;
1436 raise_param_exc
({ portal
=> "unable to resolve portal address '$portal'" });
1441 my ($portal_in) = @_;
1444 if (!($portal = resolv_portal
($portal_in))) {
1445 die "unable to parse/resolve portal address '${portal_in}'\n";
1448 return PVE
::Storage
::ISCSIPlugin
::iscsi_discovery
([ $portal ]);
1451 sub storage_default_format
{
1452 my ($cfg, $storeid) = @_;
1454 my $scfg = storage_config
($cfg, $storeid);
1456 return PVE
::Storage
::Plugin
::default_format
($scfg);
1459 sub vgroup_is_used
{
1460 my ($cfg, $vgname) = @_;
1462 foreach my $storeid (keys %{$cfg->{ids
}}) {
1463 my $scfg = storage_config
($cfg, $storeid);
1464 if ($scfg->{type
} eq 'lvm' && $scfg->{vgname
} eq $vgname) {
1472 sub target_is_used
{
1473 my ($cfg, $target) = @_;
1475 foreach my $storeid (keys %{$cfg->{ids
}}) {
1476 my $scfg = storage_config
($cfg, $storeid);
1477 if ($scfg->{type
} eq 'iscsi' && $scfg->{target
} eq $target) {
1485 sub volume_is_used
{
1486 my ($cfg, $volid) = @_;
1488 foreach my $storeid (keys %{$cfg->{ids
}}) {
1489 my $scfg = storage_config
($cfg, $storeid);
1490 if ($scfg->{base
} && $scfg->{base
} eq $volid) {
1498 sub storage_is_used
{
1499 my ($cfg, $storeid) = @_;
1501 foreach my $sid (keys %{$cfg->{ids
}}) {
1502 my $scfg = storage_config
($cfg, $sid);
1503 next if !$scfg->{base
};
1504 my ($st) = parse_volume_id
($scfg->{base
});
1505 return 1 if $st && $st eq $storeid;
1512 my ($list, $func) = @_;
1516 foreach my $sid (keys %$list) {
1517 foreach my $info (@{$list->{$sid}}) {
1518 my $volid = $info->{volid
};
1519 my ($sid1, $volname) = parse_volume_id
($volid, 1);
1520 if ($sid1 && $sid1 eq $sid) {
1521 &$func ($volid, $sid, $info);
1523 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1529 sub decompressor_info
{
1530 my ($format, $comp) = @_;
1532 if ($format eq 'tgz' && !defined($comp)) {
1533 ($format, $comp) = ('tar', 'gz');
1536 my $decompressor = {
1538 gz
=> ['tar', '-z'],
1539 lzo
=> ['tar', '--lzop'],
1540 zst
=> ['tar', '--zstd'],
1544 lzo
=> ['lzop', '-d', '-c'],
1545 zst
=> ['zstd', '-q', '-d', '-c'],
1549 lzo
=> ['lzop', '-d', '-c'],
1550 zst
=> ['zstd', '-q', '-d', '-c'],
1554 die "ERROR: archive format not defined\n"
1555 if !defined($decompressor->{$format});
1558 $decomp = $decompressor->{$format}->{$comp} if $comp;
1562 compression
=> $comp,
1563 decompressor
=> $decomp,
1569 sub protection_file_path
{
1572 return "${path}.protected";
1576 my ($archive) = shift;
1579 my $volid = basename
($archive);
1580 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
1581 my $filename = "$1"; # untaint
1582 my ($type, $extension, $comp) = ($2, $3, $4);
1583 (my $format = $extension) =~ s/\..*//;
1584 $info = decompressor_info
($format, $comp);
1585 $info->{filename
} = $filename;
1586 $info->{type
} = $type;
1588 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${extension}$/) {
1589 $info->{logfilename
} = "$1".PVE
::Storage
::Plugin
::LOG_EXT
;
1590 $info->{notesfilename
} = "$filename".PVE
::Storage
::Plugin
::NOTES_EXT
;
1591 $info->{vmid
} = int($2);
1592 $info->{ctime
} = timelocal
($8, $7, $6, $5, $4 - 1, $3);
1593 $info->{is_std_name
} = 1;
1595 $info->{is_std_name
} = 0;
1598 die "ERROR: couldn't determine archive info from '$archive'\n";
1604 sub archive_remove
{
1605 my ($archive_path) = @_;
1607 die "cannot remove protected archive '$archive_path'\n"
1608 if -e protection_file_path
($archive_path);
1610 unlink $archive_path or $! == ENOENT
or die "removing archive $archive_path failed: $!\n";
1612 archive_auxiliaries_remove
($archive_path);
1615 sub archive_auxiliaries_remove
{
1616 my ($archive_path) = @_;
1618 my $dirname = dirname
($archive_path);
1619 my $archive_info = eval { archive_info
($archive_path) } // {};
1621 for my $type (qw(log notes)) {
1622 my $filename = $archive_info->{"${type}filename"} or next;
1623 my $path = "$dirname/$filename";
1626 unlink $path or $! == ENOENT
or log_warn
("Removing $type file failed: $!");
1631 sub extract_vzdump_config_tar
{
1632 my ($archive, $conf_re) = @_;
1634 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
1636 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1637 die "unable to open file '$archive'\n";
1640 while (defined($file = <$fh>)) {
1641 if ($file =~ $conf_re) {
1642 $file = $1; # untaint
1651 die "ERROR: archive contains no configuration file\n" if !$file;
1657 $raw .= "$output\n";
1660 run_command
(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc
=> $out);
1662 return wantarray ?
($raw, $file) : $raw;
1665 sub extract_vzdump_config_vma
{
1666 my ($archive, $comp) = @_;
1669 my $out = sub { $raw .= "$_[0]\n"; };
1671 my $info = archive_info
($archive);
1672 $comp //= $info->{compression
};
1673 my $decompressor = $info->{decompressor
};
1676 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1678 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1683 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
1685 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1686 $errstring = "Failed to extract config from VMA archive: $output\n";
1690 my $rc = eval { run_command
($cmd, outfunc
=> $out, errfunc
=> $err, noerr
=> 1) };
1693 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1695 if (!$errstring && !$broken_pipe && $rc != 0) {
1696 die "$rerr\n" if $rerr;
1697 die "config extraction failed with exit code $rc\n";
1699 die "$errstring\n" if $errstring;
1701 run_command
(["vma", "config", $archive], outfunc
=> $out);
1704 return wantarray ?
($raw, undef) : $raw;
1707 sub extract_vzdump_config
{
1708 my ($cfg, $volid) = @_;
1710 my ($storeid, $volname) = parse_volume_id
($volid);
1711 if (defined($storeid)) {
1712 my $scfg = storage_config
($cfg, $storeid);
1713 if ($scfg->{type
} eq 'pbs') {
1714 storage_check_enabled
($cfg, $storeid);
1715 return PVE
::Storage
::PBSPlugin-
>extract_vzdump_config($scfg, $volname, $storeid);
1719 my $archive = abs_filesystem_path
($cfg, $volid);
1720 my $info = archive_info
($archive);
1721 my $format = $info->{format
};
1722 my $comp = $info->{compression
};
1723 my $type = $info->{type
};
1725 if ($type eq 'lxc' || $type eq 'openvz') {
1726 return extract_vzdump_config_tar
($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1727 } elsif ($type eq 'qemu') {
1728 if ($format eq 'tar') {
1729 return extract_vzdump_config_tar
($archive, qr!\(\./qemu-server\.conf\)!);
1731 return extract_vzdump_config_vma
($archive, $comp);
1734 die "cannot determine backup guest type for backup archive '$volid'\n";
1739 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1741 my $scfg = storage_config
($cfg, $storeid);
1742 die "storage '$storeid' does not support backups\n" if !$scfg->{content
}->{backup
};
1744 if (!defined($keep)) {
1745 die "no prune-backups options configured for storage '$storeid'\n"
1746 if !defined($scfg->{'prune-backups'});
1747 $keep = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'});
1750 activate_storage
($cfg, $storeid);
1752 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1753 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1756 my $prune_mark = sub {
1757 my ($prune_entries, $keep_count, $id_func) = @_;
1759 return if !$keep_count;
1761 my $already_included = {};
1762 my $newly_included = {};
1764 foreach my $prune_entry (@{$prune_entries}) {
1765 my $mark = $prune_entry->{mark
};
1766 my $id = $id_func->($prune_entry->{ctime
});
1767 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1770 foreach my $prune_entry (@{$prune_entries}) {
1771 my $mark = $prune_entry->{mark
};
1772 my $id = $id_func->($prune_entry->{ctime
});
1774 next if defined($mark) || $already_included->{$id};
1776 if (!$newly_included->{$id}) {
1777 last if scalar(keys %{$newly_included}) >= $keep_count;
1778 $newly_included->{$id} = 1;
1779 $prune_entry->{mark
} = 'keep';
1781 $prune_entry->{mark
} = 'remove';
1786 sub prune_mark_backup_group
{
1787 my ($backup_group, $keep) = @_;
1789 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1791 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
1792 foreach my $prune_entry (@{$backup_group}) {
1793 # preserve additional information like 'protected'
1794 next if $prune_entry->{mark
} && $prune_entry->{mark
} ne 'remove';
1795 $prune_entry->{mark
} = 'keep';
1800 my $prune_list = [ sort { $b->{ctime
} <=> $a->{ctime
} } @{$backup_group} ];
1802 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1806 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1808 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1809 return "$hour/$day/$month/$year";
1811 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1813 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1814 return "$day/$month/$year";
1816 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1818 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1819 my $iso_week = int(strftime
("%V", $sec, $min, $hour, $day, $month, $year));
1820 my $iso_week_year = int(strftime
("%G", $sec, $min, $hour, $day, $month, $year));
1821 return "$iso_week/$iso_week_year";
1823 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1825 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1826 return "$month/$year";
1828 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1830 my $year = (localtime($ctime))[5];
1834 foreach my $prune_entry (@{$prune_list}) {
1835 $prune_entry->{mark
} //= 'remove';
1839 sub volume_export
: prototype($$$$$$$) {
1840 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1842 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1843 die "cannot export volume '$volid'\n" if !$storeid;
1844 my $scfg = storage_config
($cfg, $storeid);
1845 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1846 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1847 $snapshot, $base_snapshot, $with_snapshots);
1850 sub volume_import
: prototype($$$$$$$$) {
1851 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1853 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1854 die "cannot import into volume '$volid'\n" if !$storeid;
1855 my $scfg = storage_config
($cfg, $storeid);
1856 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1857 return $plugin->volume_import(
1870 sub volume_export_formats
: prototype($$$$$) {
1871 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1873 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1874 return if !$storeid;
1875 my $scfg = storage_config
($cfg, $storeid);
1876 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1877 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1878 $snapshot, $base_snapshot,
1882 sub volume_import_formats
: prototype($$$$$) {
1883 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1885 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1886 return if !$storeid;
1887 my $scfg = storage_config
($cfg, $storeid);
1888 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1889 return $plugin->volume_import_formats(
1899 sub volume_transfer_formats
{
1900 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1901 my @export_formats = volume_export_formats
($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1902 my @import_formats = volume_import_formats
($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
1903 my %import_hash = map { $_ => 1 } @import_formats;
1904 my @common = grep { $import_hash{$_} } @export_formats;
1908 sub volume_imported_message
{
1909 my ($volid, $want_pattern) = @_;
1911 if ($want_pattern) {
1912 return qr/successfully imported '([^']*)'$/;
1914 return "successfully imported '$volid'\n";
1918 # $format and $volname are requests and might be overruled depending on $opts
1920 # - with_snapshots: passed to `pvesm import` and used to select import format
1921 # - allow_rename: passed to `pvesm import`
1922 # - export_formats: used to select common transport format
1923 # - unix: unix socket path
1924 sub volume_import_start
{
1925 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1927 my $with_snapshots = $opts->{'with_snapshots'} ?
1 : 0;
1929 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1931 my $volid = "$storeid:$volname";
1933 # find common import/export format, like volume_transfer_formats
1934 my @import_formats = PVE
::Storage
::volume_import_formats
($cfg, $volid, $opts->{snapshot
}, undef, $with_snapshots);
1935 my @export_formats = PVE
::Tools
::split_list
($opts->{export_formats
});
1936 my %import_hash = map { $_ => 1 } @import_formats;
1937 my @common = grep { $import_hash{$_} } @export_formats;
1938 die "no matching import/export format found for storage '$storeid'\n"
1940 $format = $common[0];
1942 my $input = IO
::File-
>new();
1943 my $info = IO
::File-
>new();
1945 my $unix = $opts->{unix
} // "/run/pve/storage-migrate-$vmid.$$.unix";
1946 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER
, $opts);
1949 my $cpid = open3
($input, $info, $info, @$import)
1950 or die "failed to spawn disk-import child - $!\n";
1954 PVE
::Tools
::run_with_timeout
(5, sub { $ready = <$info>; });
1957 die "failed to read readyness from disk import child: $@\n" if $@;
1969 sub volume_export_start
{
1970 my ($cfg, $volid, $format, $log, $opts) = @_;
1972 my $known_format = [ grep { $_ eq $format } $KNOWN_EXPORT_FORMATS->@* ];
1973 if (!$known_format->@*) {
1974 die "Cannot export '$volid' using unknown export format '$format'\n";
1976 $format = $known_format->[0];
1978 my $run_command_params = delete $opts->{cmd
} // {};
1980 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1982 PVE
::Tools
::run_command
($cmds, %$run_command_params);
1985 # bash completion helper
1987 sub complete_storage
{
1988 my ($cmdname, $pname, $cvalue) = @_;
1990 my $cfg = PVE
::Storage
::config
();
1992 return $cmdname eq 'add' ?
[] : [ PVE
::Storage
::storage_ids
($cfg) ];
1995 sub complete_storage_enabled
{
1996 my ($cmdname, $pname, $cvalue) = @_;
2000 my $cfg = PVE
::Storage
::config
();
2001 foreach my $sid (keys %{$cfg->{ids
}}) {
2002 next if !storage_check_enabled
($cfg, $sid, undef, 1);
2008 sub complete_content_type
{
2009 my ($cmdname, $pname, $cvalue) = @_;
2011 return [qw(rootdir images vztmpl iso backup snippets)];
2014 sub complete_volume
{
2015 my ($cmdname, $pname, $cvalue) = @_;
2019 my $storage_list = complete_storage_enabled
();
2021 if ($cvalue =~ m/^([^:]+):/) {
2022 $storage_list = [ $1 ];
2024 if (scalar(@$storage_list) > 1) {
2025 # only list storage IDs to avoid large listings
2027 foreach my $storeid (@$storage_list) {
2028 # Hack: simply return 2 artificial values, so that
2029 # completions does not finish
2030 push @$res, "$storeid:volname", "$storeid:...";
2037 foreach my $storeid (@$storage_list) {
2038 my $vollist = PVE
::Storage
::volume_list
($cfg, $storeid);
2040 foreach my $item (@$vollist) {
2041 push @$res, $item->{volid
};
2049 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
2051 die "no source volid provided\n" if !$source_volid;
2052 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
2054 my ($storeid, $source_volname) = parse_volume_id
($source_volid);
2056 activate_storage
($cfg, $storeid);
2058 my $scfg = storage_config
($cfg, $storeid);
2059 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
2061 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
2063 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
2064 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
2068 # Various io-heavy operations require io/bandwidth limits which can be
2069 # configured on multiple levels: The global defaults in datacenter.cfg, and
2070 # per-storage overrides. When we want to do a restore from storage A to storage
2071 # B, we should take the smaller limit defined for storages A and B, and if no
2072 # such limit was specified, use the one from datacenter.cfg.
2073 sub get_bandwidth_limit
{
2074 my ($operation, $storage_list, $override) = @_;
2076 # called for each limit (global, per-storage) with the 'default' and the
2077 # $operation limit and should update $override for every limit affecting
2079 my $use_global_limits = 0;
2080 my $apply_limit = sub {
2082 if (defined($bwlimit)) {
2083 my $limits = PVE
::JSONSchema
::parse_property_string
('bwlimit', $bwlimit);
2084 my $limit = $limits->{$operation} // $limits->{default};
2085 if (defined($limit)) {
2086 if (!$override || $limit < $override) {
2092 # If there was no applicable limit, try to apply the global ones.
2093 $use_global_limits = 1;
2096 my ($rpcenv, $authuser);
2097 if (defined($override)) {
2098 $rpcenv = PVE
::RPCEnvironment-
>get();
2099 $authuser = $rpcenv->get_user();
2102 # Apply per-storage limits - if there are storages involved.
2103 if (defined($storage_list) && grep { defined($_) } $storage_list->@*) {
2104 my $config = config
();
2106 # The Datastore.Allocate permission allows us to modify the per-storage
2107 # limits, therefore it also allows us to override them.
2108 # Since we have most likely multiple storages to check, do a quick check on
2109 # the general '/storage' path to see if we can skip the checks entirely:
2110 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
2113 foreach my $storage (@$storage_list) {
2114 next if !defined($storage);
2115 # Avoid duplicate checks:
2116 next if $done{$storage};
2117 $done{$storage} = 1;
2119 # Otherwise we may still have individual /storage/$ID permissions:
2120 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
2121 # And if not: apply the limits.
2122 my $storecfg = storage_config
($config, $storage);
2123 $apply_limit->($storecfg->{bwlimit
});
2127 # Storage limits take precedence over the datacenter defaults, so if
2128 # a limit was applied:
2129 return $override if !$use_global_limits;
2132 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2133 # global default limits.
2134 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
2135 # So if we cannot modify global limits, apply them to our currently
2136 # requested override.
2137 my $dc = cfs_read_file
('datacenter.cfg');
2138 $apply_limit->($dc->{bwlimit
});
2144 # checks if the storage id is available and dies if not
2145 sub assert_sid_unused
{
2149 if (my $scfg = storage_config
($cfg, $sid, 1)) {
2150 die "storage ID '$sid' already defined\n";
2156 # removes leading/trailing spaces and (back)slashes completely
2157 # substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2158 sub normalize_content_filename
{
2159 my ($filename) = @_;
2162 $filename =~ s/^.*[\/\\]//;
2163 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;