16 use Time
::Local
qw(timelocal);
18 use PVE
::Tools
qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
19 use PVE
::Cluster
qw(cfs_read_file cfs_write_file cfs_lock_file);
20 use PVE
::DataCenterConfig
;
21 use PVE
::Exception
qw(raise_param_exc raise);
24 use PVE
::RPCEnvironment
;
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 # load standard plugins
51 PVE
::Storage
::DirPlugin-
>register();
52 PVE
::Storage
::LVMPlugin-
>register();
53 PVE
::Storage
::LvmThinPlugin-
>register();
54 PVE
::Storage
::NFSPlugin-
>register();
55 PVE
::Storage
::CIFSPlugin-
>register();
56 PVE
::Storage
::ISCSIPlugin-
>register();
57 PVE
::Storage
::RBDPlugin-
>register();
58 PVE
::Storage
::CephFSPlugin-
>register();
59 PVE
::Storage
::ISCSIDirectPlugin-
>register();
60 PVE
::Storage
::GlusterfsPlugin-
>register();
61 PVE
::Storage
::ZFSPoolPlugin-
>register();
62 PVE
::Storage
::ZFSPlugin-
>register();
63 PVE
::Storage
::PBSPlugin-
>register();
64 PVE
::Storage
::BTRFSPlugin-
>register();
66 # load third-party plugins
67 if ( -d
'/usr/share/perl5/PVE/Storage/Custom' ) {
68 dir_glob_foreach
('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
70 my $modname = 'PVE::Storage::Custom::' . $file;
71 $modname =~ s!\.pm$!!;
72 $file = 'PVE/Storage/Custom/' . $file;
77 # Check perl interface:
78 die "not derived from PVE::Storage::Plugin\n" if !$modname->isa('PVE::Storage::Plugin');
79 die "does not provide an api() method\n" if !$modname->can('api');
80 # Check storage API version and that file is really storage plugin.
81 my $version = $modname->api();
82 die "implements an API version newer than current ($version > " . APIVER
. ")\n"
84 my $min_version = (APIVER
- APIAGE
);
85 die "API version too old, please update the plugin ($version < $min_version)\n"
86 if $version < $min_version;
87 # all OK, do import and register (i.e., "use")
91 # If we got this far and the API version is not the same, make some noise:
92 warn "Plugin \"$modname\" is implementing an older storage API
, an upgrade
is recommended
\n"
93 if $version != APIVER;
96 warn "Error loading storage plugin
\"$modname\": $@";
101 # initialize all plugins
102 PVE
::Storage
::Plugin-
>init();
104 # the following REs indicate the number or capture groups via the trailing digit
105 # CAUTION don't forget to update the digits accordingly after messing with the capture groups
107 our $ISO_EXT_RE_0 = qr/\.(?:iso|img)/i;
109 our $VZTMPL_EXT_RE_1 = qr/\.tar\.(gz|xz|zst)/i;
111 our $BACKUP_EXT_RE_2 = qr/\.(tgz|(?:tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)/;
113 # FIXME remove with PVE 8.0, add versioned breaks for pve-manager
114 our $vztmpl_extension_re = $VZTMPL_EXT_RE_1;
116 # PVE::Storage utility functions
119 return cfs_read_file
("storage.cfg");
125 cfs_write_file
('storage.cfg', $cfg);
128 sub lock_storage_config
{
129 my ($code, $errmsg) = @_;
131 cfs_lock_file
("storage.cfg", undef, $code);
134 $errmsg ?
die "$errmsg: $err" : die $err;
138 # FIXME remove maxfiles for PVE 8.0 or PVE 9.0
139 my $convert_maxfiles_to_prune_backups = sub {
144 my $maxfiles = delete $scfg->{maxfiles
};
146 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
149 $prune_backups = { 'keep-last' => $maxfiles };
150 } else { # maxfiles 0 means no limit
151 $prune_backups = { 'keep-all' => 1 };
153 $scfg->{'prune-backups'} = PVE
::JSONSchema
::print_property_string
(
161 my ($cfg, $storeid, $noerr) = @_;
163 die "no storage ID specified\n" if !$storeid;
165 my $scfg = $cfg->{ids
}->{$storeid};
167 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
169 $convert_maxfiles_to_prune_backups->($scfg);
174 sub storage_check_node
{
175 my ($cfg, $storeid, $node, $noerr) = @_;
177 my $scfg = storage_config
($cfg, $storeid);
179 if ($scfg->{nodes
}) {
180 $node = PVE
::INotify
::nodename
() if !$node || ($node eq 'localhost');
181 if (!$scfg->{nodes
}->{$node}) {
182 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
190 sub storage_check_enabled
{
191 my ($cfg, $storeid, $node, $noerr) = @_;
193 my $scfg = storage_config
($cfg, $storeid);
195 if ($scfg->{disable
}) {
196 die "storage '$storeid' is disabled\n" if !$noerr;
200 return storage_check_node
($cfg, $storeid, $node, $noerr);
203 # storage_can_replicate:
204 # return true if storage supports replication
205 # (volumes allocated with vdisk_alloc() has replication feature)
206 sub storage_can_replicate
{
207 my ($cfg, $storeid, $format) = @_;
209 my $scfg = storage_config
($cfg, $storeid);
210 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
211 return $plugin->storage_can_replicate($scfg, $storeid, $format);
214 sub get_max_protected_backups
{
215 my ($scfg, $storeid) = @_;
217 return $scfg->{'max-protected-backups'} if defined($scfg->{'max-protected-backups'});
219 my $rpcenv = PVE
::RPCEnvironment
::get
();
220 my $authuser = $rpcenv->get_user();
222 return $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.Allocate'], 1) ?
-1 : 5;
228 return keys %{$cfg->{ids
}};
232 my ($filename, $timeout) = @_;
234 return PVE
::Storage
::Plugin
::file_size_info
($filename, $timeout);
237 sub get_volume_attribute
{
238 my ($cfg, $volid, $attribute) = @_;
240 my ($storeid, $volname) = parse_volume_id
($volid);
241 my $scfg = storage_config
($cfg, $storeid);
242 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
244 return $plugin->get_volume_attribute($scfg, $storeid, $volname, $attribute);
247 sub update_volume_attribute
{
248 my ($cfg, $volid, $attribute, $value) = @_;
250 my ($storeid, $volname) = parse_volume_id
($volid);
251 my $scfg = storage_config
($cfg, $storeid);
252 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
254 my ($vtype, undef, $vmid) = $plugin->parse_volname($volname);
255 my $max_protected_backups = get_max_protected_backups
($scfg, $storeid);
260 && $attribute eq 'protected'
262 && !$plugin->get_volume_attribute($scfg, $storeid, $volname, 'protected')
263 && $max_protected_backups > -1 # -1 is unlimited
265 my $backups = $plugin->list_volumes($storeid, $scfg, $vmid, ['backup']);
266 my ($backup_type) = map { $_->{subtype
} } grep { $_->{volid
} eq $volid } $backups->@*;
268 my $protected_count = grep {
269 $_->{protected
} && (!$backup_type || ($_->{subtype
} && $_->{subtype
} eq $backup_type))
272 if ($max_protected_backups <= $protected_count) {
273 die "The number of protected backups per guest is limited to $max_protected_backups ".
274 "on storage '$storeid'\n";
278 return $plugin->update_volume_attribute($scfg, $storeid, $volname, $attribute, $value);
281 sub volume_size_info
{
282 my ($cfg, $volid, $timeout) = @_;
284 my ($storeid, $volname) = parse_volume_id
($volid, 1);
286 my $scfg = storage_config
($cfg, $storeid);
287 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
288 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
289 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
290 return file_size_info
($volid, $timeout);
297 my ($cfg, $volid, $size, $running) = @_;
299 my $padding = (1024 - $size % 1024) % 1024;
300 $size = $size + $padding;
302 my ($storeid, $volname) = parse_volume_id
($volid, 1);
304 my $scfg = storage_config
($cfg, $storeid);
305 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
306 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
307 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
308 die "resize file/device '$volid' is not possible\n";
310 die "unable to parse volume ID '$volid'\n";
314 sub volume_rollback_is_possible
{
315 my ($cfg, $volid, $snap, $blockers) = @_;
317 my ($storeid, $volname) = parse_volume_id
($volid, 1);
319 my $scfg = storage_config
($cfg, $storeid);
320 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
321 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap, $blockers);
322 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
323 die "snapshot rollback file/device '$volid' is not possible\n";
325 die "unable to parse volume ID '$volid'\n";
329 sub volume_snapshot
{
330 my ($cfg, $volid, $snap) = @_;
332 my ($storeid, $volname) = parse_volume_id
($volid, 1);
334 my $scfg = storage_config
($cfg, $storeid);
335 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
336 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
337 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
338 die "snapshot file/device '$volid' is not possible\n";
340 die "unable to parse volume ID '$volid'\n";
344 sub volume_snapshot_rollback
{
345 my ($cfg, $volid, $snap) = @_;
347 my ($storeid, $volname) = parse_volume_id
($volid, 1);
349 my $scfg = storage_config
($cfg, $storeid);
350 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
351 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
352 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
353 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
354 die "snapshot rollback file/device '$volid' is not possible\n";
356 die "unable to parse volume ID '$volid'\n";
360 sub volume_snapshot_delete
{
361 my ($cfg, $volid, $snap, $running) = @_;
363 my ($storeid, $volname) = parse_volume_id
($volid, 1);
365 my $scfg = storage_config
($cfg, $storeid);
366 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
367 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
368 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
369 die "snapshot delete file/device '$volid' is not possible\n";
371 die "unable to parse volume ID '$volid'\n";
375 # check if a filesystem on top of a volume needs to flush its journal for
376 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
377 # container mountpoints
378 sub volume_snapshot_needs_fsfreeze
{
379 my ($cfg, $volid) = @_;
381 my ($storeid, $volname) = parse_volume_id
($volid);
382 my $scfg = storage_config
($cfg, $storeid);
383 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
384 return $plugin->volume_snapshot_needs_fsfreeze();
387 # check if a volume or snapshot supports a given feature
389 # clone - linked clone is possible
390 # copy - full clone is possible
391 # replicate - replication is possible
392 # snapshot - taking a snapshot is possible
393 # sparseinit - volume is sparsely initialized
394 # template - conversion to base image is possible
395 # rename - renaming volumes is possible
396 # $snap - check if the feature is supported for a given snapshot
397 # $running - if the guest owning the volume is running
398 # $opts - hash with further options:
399 # valid_target_formats - list of formats for the target of a copy/clone
400 # operation that the caller could work with. The
401 # format of $volid is always considered valid and if
402 # no list is specified, all formats are considered valid.
403 sub volume_has_feature
{
404 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
406 my ($storeid, $volname) = parse_volume_id
($volid, 1);
408 my $scfg = storage_config
($cfg, $storeid);
409 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
410 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
411 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
418 sub volume_snapshot_info
{
419 my ($cfg, $volid) = @_;
421 my ($storeid, $volname) = parse_volume_id
($volid);
422 my $scfg = storage_config
($cfg, $storeid);
423 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
424 return $plugin->volume_snapshot_info($scfg, $storeid, $volname);
428 my ($cfg, $storeid, $vmid) = @_;
430 my $scfg = storage_config
($cfg, $storeid);
431 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
433 my $path = $plugin->get_subdir($scfg, 'images');
435 return $vmid ?
"$path/$vmid" : $path;
438 sub get_private_dir
{
439 my ($cfg, $storeid, $vmid) = @_;
441 my $scfg = storage_config
($cfg, $storeid);
442 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
444 my $path = $plugin->get_subdir($scfg, 'rootdir');
446 return $vmid ?
"$path/$vmid" : $path;
450 my ($cfg, $storeid) = @_;
452 my $scfg = storage_config
($cfg, $storeid);
453 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
455 return $plugin->get_subdir($scfg, 'iso');
459 my ($cfg, $storeid) = @_;
461 my $scfg = storage_config
($cfg, $storeid);
462 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
464 return $plugin->get_subdir($scfg, 'vztmpl');
468 my ($cfg, $storeid) = @_;
470 my $scfg = storage_config
($cfg, $storeid);
471 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
473 return $plugin->get_subdir($scfg, 'backup');
476 # library implementation
481 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
486 # NOTE: basename and basevmid are always undef for LVM-thin, where the
487 # clone -> base reference is not encoded in the volume ID.
488 # see note in PVE::Storage::LvmThinPlugin for details.
490 my ($cfg, $volid) = @_;
492 my ($storeid, $volname) = parse_volume_id
($volid);
494 my $scfg = storage_config
($cfg, $storeid);
496 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
498 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
500 return $plugin->parse_volname($volname);
503 sub parse_volume_id
{
504 my ($volid, $noerr) = @_;
506 return PVE
::Storage
::Plugin
::parse_volume_id
($volid, $noerr);
509 # test if we have read access to volid
510 sub check_volume_access
{
511 my ($rpcenv, $user, $cfg, $vmid, $volid, $type) = @_;
513 my ($sid, $volname) = parse_volume_id
($volid, 1);
515 my ($vtype, undef, $ownervm) = parse_volname
($cfg, $volid);
517 # Need to allow 'images' when expecting 'rootdir' too - not cleanly separated in plugins.
518 die "unable to use volume $volid - content type needs to be '$type'\n"
519 if defined($type) && $vtype ne $type && ($type ne 'rootdir' || $vtype ne 'images');
521 return if $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate'], 1);
523 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
524 # require at least read access to storage, (custom) templates/ISOs could be sensitive
525 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
526 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
527 # we are owner - allow access
528 } elsif ($vtype eq 'backup' && $ownervm) {
529 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
530 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
531 } elsif (($vtype eq 'images' || $vtype eq 'rootdir') && $ownervm) {
532 $rpcenv->check($user, "/storage/$sid", ['Datastore.Audit']);
533 $rpcenv->check($user, "/vms/$ownervm", ['VM.Config.Disk']);
535 die "missing privileges to access $volid\n";
538 die "Only root can pass arbitrary filesystem paths."
539 if $user ne 'root@pam';
545 # NOTE: this check does not work for LVM-thin, where the clone -> base
546 # reference is not encoded in the volume ID.
547 # see note in PVE::Storage::LvmThinPlugin for details.
548 sub volume_is_base_and_used
{
549 my ($cfg, $volid) = @_;
551 my ($storeid, $volname) = parse_volume_id
($volid);
552 my $scfg = storage_config
($cfg, $storeid);
553 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
555 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
556 $plugin->parse_volname($volname);
559 my $vollist = $plugin->list_images($storeid, $scfg);
560 foreach my $info (@$vollist) {
561 my (undef, $tmpvolname) = parse_volume_id
($info->{volid
});
562 my $basename = undef;
563 my $basevmid = undef;
566 (undef, undef, undef, $basename, $basevmid) =
567 $plugin->parse_volname($tmpvolname);
570 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
578 # try to map a filesystem path to a volume identifier
579 sub path_to_volume_id
{
580 my ($cfg, $path) = @_;
582 my $ids = $cfg->{ids
};
584 my ($sid, $volname) = parse_volume_id
($path, 1);
586 if (my $scfg = $ids->{$sid}) {
588 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
589 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
590 return ($vtype, $path);
596 # Note: abs_path() return undef if $path doesn not exist
597 # for example when nfs storage is not mounted
598 $path = abs_path
($path) || $path;
600 foreach my $sid (keys %$ids) {
601 my $scfg = $ids->{$sid};
602 next if !$scfg->{path
};
603 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
604 my $imagedir = $plugin->get_subdir($scfg, 'images');
605 my $isodir = $plugin->get_subdir($scfg, 'iso');
606 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
607 my $backupdir = $plugin->get_subdir($scfg, 'backup');
608 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
609 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
611 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
615 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
616 foreach my $info (@$vollist) {
617 my ($storeid, $volname) = parse_volume_id
($info->{volid
});
618 my $volpath = $plugin->path($scfg, $volname, $storeid);
619 if ($volpath eq $path) {
620 return ('images', $info->{volid
});
623 } elsif ($path =~ m!^$isodir/([^/]+$ISO_EXT_RE_0)$!) {
625 return ('iso', "$sid:iso/$name");
626 } elsif ($path =~ m!^$tmpldir/([^/]+$VZTMPL_EXT_RE_1)$!) {
628 return ('vztmpl', "$sid:vztmpl/$name");
629 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
631 return ('rootdir', "$sid:rootdir/$vmid");
632 } elsif ($path =~ m!^$backupdir/([^/]+$BACKUP_EXT_RE_2)$!) {
634 return ('backup', "$sid:backup/$name");
635 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
637 return ('snippets', "$sid:snippets/$name");
641 # can't map path to volume id
646 my ($cfg, $volid, $snapname) = @_;
648 my ($storeid, $volname) = parse_volume_id
($volid);
650 my $scfg = storage_config
($cfg, $storeid);
652 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
653 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
654 return wantarray ?
($path, $owner, $vtype) : $path;
657 sub abs_filesystem_path
{
658 my ($cfg, $volid, $allow_blockdev) = @_;
661 if (parse_volume_id
($volid, 1)) {
662 activate_volumes
($cfg, [ $volid ]);
663 $path = PVE
::Storage
::path
($cfg, $volid);
665 if (-f
$volid || ($allow_blockdev && -b
$volid)) {
666 my $abspath = abs_path
($volid);
667 if ($abspath && $abspath =~ m
|^(/.+)$|) {
668 $path = $1; # untaint any path
672 die "can't find file '$volid'\n"
673 if !($path && (-f
$path || ($allow_blockdev && -b
$path)));
678 # used as last resort to adapt volnames when migrating
679 my $volname_for_storage = sub {
680 my ($cfg, $storeid, $name, $vmid, $format) = @_;
682 my $scfg = storage_config
($cfg, $storeid);
684 my (undef, $valid_formats) = PVE
::Storage
::Plugin
::default_format
($scfg);
685 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
686 die "unsupported format '$format' for storage type $scfg->{type}\n"
687 if !$format_is_valid;
689 (my $name_without_extension = $name) =~ s/\.$format$//;
692 return "$vmid/$name_without_extension.$format";
694 return "$name_without_extension";
698 # whether a migration snapshot is needed for a given storage
699 sub storage_migrate_snapshot
{
700 my ($cfg, $storeid, $existing_snapshots) = @_;
701 my $scfg = storage_config
($cfg, $storeid);
703 return $scfg->{type
} eq 'zfspool' || ($scfg->{type
} eq 'btrfs' && $existing_snapshots);
706 my $volume_import_prepare = sub {
707 my ($volid, $format, $path, $apiver, $opts) = @_;
709 my $base_snapshot = $opts->{base_snapshot
};
710 my $snapshot = $opts->{snapshot
};
711 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
712 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
713 my $allow_rename = $opts->{allow_rename
} ?
1 : 0;
715 my $recv = ['pvesm', 'import', $volid, $format, $path, '-with-snapshots', $with_snapshots];
716 if (defined($snapshot)) {
717 push @$recv, '-snapshot', $snapshot;
719 if ($migration_snapshot) {
720 push @$recv, '-delete-snapshot', $snapshot;
722 push @$recv, '-allow-rename', $allow_rename if $apiver >= 5;
724 if (defined($base_snapshot)) {
725 # Check if the snapshot exists on the remote side:
726 push @$recv, '-base', $base_snapshot if $apiver >= 9;
732 my $volume_export_prepare = sub {
733 my ($cfg, $volid, $format, $logfunc, $opts) = @_;
734 my $base_snapshot = $opts->{base_snapshot
};
735 my $snapshot = $opts->{snapshot
};
736 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
737 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
738 my $ratelimit_bps = $opts->{ratelimit_bps
};
740 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
741 if (defined($snapshot)) {
742 push @$send, '-snapshot', $snapshot;
744 if (defined($base_snapshot)) {
745 push @$send, '-base', $base_snapshot;
749 if (defined($ratelimit_bps)) {
750 $cstream = [ '/usr/bin/cstream', '-t', $ratelimit_bps ];
751 $logfunc->("using a bandwidth limit of $ratelimit_bps bps for transferring '$volid'") if $logfunc;
754 volume_snapshot
($cfg, $volid, $snapshot) if $migration_snapshot;
756 if (defined($snapshot)) {
757 activate_volumes
($cfg, [$volid], $snapshot);
759 activate_volumes
($cfg, [$volid]);
762 return $cstream ?
[ $send, $cstream ] : [ $send ];
765 sub storage_migrate
{
766 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
768 my $insecure = $opts->{insecure
};
770 my ($storeid, $volname) = parse_volume_id
($volid);
772 my $scfg = storage_config
($cfg, $storeid);
774 # no need to migrate shared content
775 return $volid if $storeid eq $target_storeid && $scfg->{shared
};
777 my $tcfg = storage_config
($cfg, $target_storeid);
780 if ($opts->{target_volname
}) {
781 $target_volname = $opts->{target_volname
};
782 } elsif ($scfg->{type
} eq $tcfg->{type
}) {
783 $target_volname = $volname;
785 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname
($cfg, $volid);
786 $target_volname = $volname_for_storage->($cfg, $target_storeid, $name, $vmid, $format);
789 my $target_volid = "${target_storeid}:${target_volname}";
791 my $target_ip = $target_sshinfo->{ip
};
793 my $ssh = PVE
::SSHInfo
::ssh_info_to_command
($target_sshinfo);
794 my $ssh_base = PVE
::SSHInfo
::ssh_info_to_command_base
($target_sshinfo);
795 local $ENV{RSYNC_RSH
} = PVE
::Tools
::cmd2string
($ssh_base);
797 if (!defined($opts->{snapshot
})) {
798 $opts->{migration_snapshot
} = storage_migrate_snapshot
($cfg, $storeid, $opts->{with_snapshots
});
799 $opts->{snapshot
} = '__migration__' if $opts->{migration_snapshot
};
802 my @formats = volume_transfer_formats
($cfg, $volid, $target_volid, $opts->{snapshot
}, $opts->{base_snapshot
}, $opts->{with_snapshots
});
803 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
804 my $format = $formats[0];
806 my $import_fn = '-'; # let pvesm import read from stdin per default
808 my $net = $target_sshinfo->{network
} // $target_sshinfo->{ip
};
809 $import_fn = "tcp://$net";
812 my $target_apiver = 1; # if there is no apiinfo call, assume 1
813 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
814 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
815 eval { run_command
($get_api_version, logfunc
=> $match_api_version); };
817 my $recv = [ @$ssh, '--', $volume_import_prepare->($target_volid, $format, $import_fn, $target_apiver, $opts)->@* ];
820 my $pattern = volume_imported_message
(undef, 1);
821 my $match_volid_and_log = sub {
824 $new_volid = $1 if ($line =~ $pattern);
832 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
836 my $input = IO
::File-
>new();
837 my $info = IO
::File-
>new();
838 open3
($input, $info, $info, @$recv)
839 or die "receive command failed: $!\n";
842 my $try_ip = <$info> // '';
843 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
844 or die "no tunnel IP received, got '$try_ip'\n";
846 my $try_port = <$info> // '';
847 my ($port) = $try_port =~ /^(\d+)$/ # untaint
848 or die "no tunnel port received, got '$try_port'\n";
850 my $socket = IO
::Socket
::IP-
>new(PeerHost
=> $ip, PeerPort
=> $port, Type
=> SOCK_STREAM
)
851 or die "failed to connect to tunnel at $ip:$port\n";
852 # we won't be reading from the socket
853 shutdown($socket, 0);
855 eval { run_command
($cmds, output
=> '>&'.fileno($socket), errfunc
=> $logfunc); };
858 # don't close the connection entirely otherwise the receiving end
859 # might not get all buffered data (and fails with 'connection reset by peer')
860 shutdown($socket, 1);
862 # wait for the remote process to finish
863 while (my $line = <$info>) {
864 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
867 # now close the socket
869 if (!close($info)) { # does waitpid()
870 die "import failed: $!\n" if $!;
871 die "import failed: exit code ".($?>>8)."\n";
874 die $send_error if $send_error;
877 run_command
($cmds, logfunc
=> $match_volid_and_log);
880 die "unable to get ID of the migrated volume\n"
881 if !defined($new_volid) && $target_apiver >= 5;
884 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
885 if ($opts->{migration_snapshot
}) {
886 eval { volume_snapshot_delete
($cfg, $volid, $opts->{snapshot
}, 0) };
887 warn "could not remove source snapshot: $@\n" if $@;
891 return $new_volid // $target_volid;
895 my ($cfg, $volid, $vmid, $snap) = @_;
897 my ($storeid, $volname) = parse_volume_id
($volid);
899 my $scfg = storage_config
($cfg, $storeid);
901 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
903 activate_storage
($cfg, $storeid);
905 # lock shared storage
906 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
907 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
908 return "$storeid:$volname";
912 sub vdisk_create_base
{
913 my ($cfg, $volid) = @_;
915 my ($storeid, $volname) = parse_volume_id
($volid);
917 my $scfg = storage_config
($cfg, $storeid);
919 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
921 activate_storage
($cfg, $storeid);
923 # lock shared storage
924 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
925 my $volname = $plugin->create_base($storeid, $scfg, $volname);
926 return "$storeid:$volname";
931 my ($cfg, $volid, $snapname) = @_;
933 my ($storeid, $volname) = parse_volume_id
($volid);
935 my $scfg = storage_config
($cfg, $storeid);
937 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
939 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
943 my ($cfg, $volid, $snapname) = @_;
945 my ($storeid, $volname) = parse_volume_id
($volid);
947 my $scfg = storage_config
($cfg, $storeid);
949 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
951 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
955 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
957 die "no storage ID specified\n" if !$storeid;
959 PVE
::JSONSchema
::parse_storage_id
($storeid);
961 my $scfg = storage_config
($cfg, $storeid);
963 die "no VMID specified\n" if !$vmid;
965 $vmid = parse_vmid
($vmid);
967 my $defformat = PVE
::Storage
::Plugin
::default_format
($scfg);
969 $fmt = $defformat if !$fmt;
971 activate_storage
($cfg, $storeid);
973 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
975 # lock shared storage
976 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
977 my $old_umask = umask(umask|0037);
978 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
982 return "$storeid:$volname";
987 my ($cfg, $volid) = @_;
989 my ($storeid, $volname) = parse_volume_id
($volid);
990 my $scfg = storage_config
($cfg, $storeid);
991 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
993 activate_storage
($cfg, $storeid);
997 # lock shared storage
998 $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
999 # LVM-thin allows deletion of still referenced base volumes!
1000 die "base volume '$volname' is still in use by linked clones\n"
1001 if volume_is_base_and_used
($cfg, $volid);
1003 my (undef, undef, undef, undef, undef, $isBase, $format) =
1004 $plugin->parse_volname($volname);
1005 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1008 return if !$cleanup_worker;
1010 my $rpcenv = PVE
::RPCEnvironment
::get
();
1011 my $authuser = $rpcenv->get_user();
1013 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
1017 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
1019 my $ids = $cfg->{ids
};
1021 storage_check_enabled
($cfg, $storeid) if ($storeid);
1023 my $res = $storeid ?
{ $storeid => [] } : {};
1025 # prepare/activate/refresh all storages
1027 my $storage_list = [];
1029 foreach my $volid (@$vollist) {
1030 my ($sid, undef) = parse_volume_id
($volid);
1031 next if !defined($ids->{$sid});
1032 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1033 push @$storage_list, $sid;
1036 foreach my $sid (keys %$ids) {
1037 next if $storeid && $storeid ne $sid;
1038 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1039 my $content = $ids->{$sid}->{content
};
1040 next if defined($ctype) && !$content->{$ctype};
1041 next if !($content->{rootdir
} || $content->{images
});
1042 push @$storage_list, $sid;
1048 activate_storage_list
($cfg, $storage_list, $cache);
1050 for my $sid ($storage_list->@*) {
1051 next if $storeid && $storeid ne $sid;
1053 my $scfg = $ids->{$sid};
1054 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1055 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
1056 @{$res->{$sid}} = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @{$res->{$sid}} if $res->{$sid};
1063 my ($cfg, $storeid, $tt) = @_;
1065 die "unknown template type '$tt'\n"
1066 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1068 my $ids = $cfg->{ids
};
1070 storage_check_enabled
($cfg, $storeid) if ($storeid);
1075 foreach my $sid (keys %$ids) {
1076 next if $storeid && $storeid ne $sid;
1078 my $scfg = $ids->{$sid};
1079 my $type = $scfg->{type
};
1081 next if !$scfg->{content
}->{$tt};
1083 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1085 $res->{$sid} = volume_list
($cfg, $sid, undef, $tt);
1092 my ($cfg, $storeid, $vmid, $content) = @_;
1094 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
1096 my $cts = $content ?
[ $content ] : [ @ctypes ];
1098 my $scfg = PVE
::Storage
::storage_config
($cfg, $storeid);
1100 $cts = [ grep { defined($scfg->{content
}->{$_}) } @$cts ];
1102 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1104 activate_storage
($cfg, $storeid);
1106 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1108 @$res = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @$res;
1115 my $filename = "/sys/kernel/uevent_seqnum";
1118 if (my $fh = IO
::File-
>new($filename, "r")) {
1120 if ($line =~ m/^(\d+)$/) {
1128 sub activate_storage
{
1129 my ($cfg, $storeid, $cache) = @_;
1131 $cache = {} if !$cache;
1133 my $scfg = storage_check_enabled
($cfg, $storeid);
1135 return if $cache->{activated
}->{$storeid};
1137 $cache->{uevent_seqnum
} = uevent_seqnum
() if !$cache->{uevent_seqnum
};
1139 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1141 if ($scfg->{base
}) {
1142 my ($baseid, undef) = parse_volume_id
($scfg->{base
});
1143 activate_storage
($cfg, $baseid, $cache);
1146 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1147 die "connection check for storage '$storeid' failed - $@\n" if $@;
1148 die "storage '$storeid' is not online\n";
1151 $plugin->activate_storage($storeid, $scfg, $cache);
1153 my $newseq = uevent_seqnum
();
1155 # only call udevsettle if there are events
1156 if ($newseq > $cache->{uevent_seqnum
}) {
1157 system ("udevadm settle --timeout=30"); # ignore errors
1158 $cache->{uevent_seqnum
} = $newseq;
1161 $cache->{activated
}->{$storeid} = 1;
1164 sub activate_storage_list
{
1165 my ($cfg, $storeid_list, $cache) = @_;
1167 $cache = {} if !$cache;
1169 foreach my $storeid (@$storeid_list) {
1170 activate_storage
($cfg, $storeid, $cache);
1174 sub deactivate_storage
{
1175 my ($cfg, $storeid) = @_;
1177 my $scfg = storage_config
($cfg, $storeid);
1178 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1181 $plugin->deactivate_storage($storeid, $scfg, $cache);
1184 sub activate_volumes
{
1185 my ($cfg, $vollist, $snapname) = @_;
1187 return if !($vollist && scalar(@$vollist));
1189 my $storagehash = {};
1190 foreach my $volid (@$vollist) {
1191 my ($storeid, undef) = parse_volume_id
($volid);
1192 $storagehash->{$storeid} = 1;
1197 activate_storage_list
($cfg, [keys %$storagehash], $cache);
1199 foreach my $volid (@$vollist) {
1200 my ($storeid, $volname) = parse_volume_id
($volid);
1201 my $scfg = storage_config
($cfg, $storeid);
1202 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1203 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1207 sub deactivate_volumes
{
1208 my ($cfg, $vollist, $snapname) = @_;
1210 return if !($vollist && scalar(@$vollist));
1215 foreach my $volid (@$vollist) {
1216 my ($storeid, $volname) = parse_volume_id
($volid);
1218 my $scfg = storage_config
($cfg, $storeid);
1219 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1222 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1226 push @errlist, $volid;
1230 die "volume deactivation failed: " . join(' ', @errlist)
1231 if scalar(@errlist);
1235 my ($cfg, $content, $includeformat) = @_;
1237 my $ids = $cfg->{ids
};
1241 my @ctypes = PVE
::Tools
::split_list
($content);
1244 foreach my $storeid (keys %$ids) {
1245 my $storage_enabled = defined(storage_check_enabled
($cfg, $storeid, undef, 1));
1247 if (defined($content)) {
1249 foreach my $ctype (@ctypes) {
1250 if ($ids->{$storeid}->{content
}->{$ctype}) {
1255 next if !$want_ctype || !$storage_enabled;
1258 my $type = $ids->{$storeid}->{type
};
1260 $info->{$storeid} = {
1265 shared
=> $ids->{$storeid}->{shared
} ?
1 : 0,
1266 content
=> PVE
::Storage
::Plugin
::content_hash_to_string
($ids->{$storeid}->{content
}),
1268 enabled
=> $storage_enabled ?
1 : 0,
1271 push @$slist, $storeid;
1276 foreach my $storeid (keys %$ids) {
1277 my $scfg = $ids->{$storeid};
1279 next if !$info->{$storeid};
1280 next if !$info->{$storeid}->{enabled
};
1282 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1283 if ($includeformat) {
1284 my $pd = $plugin->plugindata();
1285 $info->{$storeid}->{format
} = $pd->{format
}
1287 $info->{$storeid}->{select_existing
} = $pd->{select_existing
}
1288 if $pd->{select_existing
};
1291 eval { activate_storage
($cfg, $storeid, $cache); };
1297 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1300 $info->{$storeid}->{total
} = int($total);
1301 $info->{$storeid}->{avail
} = int($avail);
1302 $info->{$storeid}->{used
} = int($used);
1303 $info->{$storeid}->{active
} = $active;
1312 my ($packed_ip, $family);
1314 my @res = PVE
::Tools
::getaddrinfo_all
($server);
1315 $family = $res[0]->{family
};
1316 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
1318 if (defined $packed_ip) {
1319 return Socket
::inet_ntop
($family, $packed_ip);
1325 my ($server_in) = @_;
1328 if (!($server = resolv_server
($server_in))) {
1329 die "unable to resolve address for server '${server_in}'\n";
1332 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1335 run_command
($cmd, outfunc
=> sub {
1338 # note: howto handle white spaces in export path??
1339 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1348 my ($server_in, $user, $password, $domain) = @_;
1350 my $server = resolv_server
($server_in);
1351 die "unable to resolve address for server '${server_in}'\n" if !$server;
1353 # we only support Windows 2012 and newer, so just use smb3
1354 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1355 push @$cmd, '-W', $domain if defined($domain);
1357 push @$cmd, '-N' if !defined($password);
1358 local $ENV{USER
} = $user if defined($user);
1359 local $ENV{PASSWD
} = $password if defined($password);
1370 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1372 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1374 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1378 # only die if we got no share, else it's just some followup check error
1379 # (like workgroup querying)
1380 raise
($err) if $err && !%$res;
1387 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1390 run_command
($cmd, outfunc
=> sub {
1393 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1394 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1395 my $size = $size_str + 0;
1396 my $used = $used_str + 0;
1397 # ignore subvolumes generated by our ZFSPoolPlugin
1398 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1399 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1400 push @$res, { pool
=> $pool, size
=> $size, free
=> $size-$used };
1408 my ($portal, $noerr) = @_;
1410 my ($server, $port) = PVE
::Tools
::parse_host_and_port
($portal);
1412 if (my $ip = resolv_server
($server)) {
1414 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1415 return $port ?
"$server:$port" : $server;
1418 return undef if $noerr;
1420 raise_param_exc
({ portal
=> "unable to resolve portal address '$portal'" });
1425 my ($portal_in) = @_;
1428 if (!($portal = resolv_portal
($portal_in))) {
1429 die "unable to parse/resolve portal address '${portal_in}'\n";
1432 return PVE
::Storage
::ISCSIPlugin
::iscsi_discovery
($portal);
1435 sub storage_default_format
{
1436 my ($cfg, $storeid) = @_;
1438 my $scfg = storage_config
($cfg, $storeid);
1440 return PVE
::Storage
::Plugin
::default_format
($scfg);
1443 sub vgroup_is_used
{
1444 my ($cfg, $vgname) = @_;
1446 foreach my $storeid (keys %{$cfg->{ids
}}) {
1447 my $scfg = storage_config
($cfg, $storeid);
1448 if ($scfg->{type
} eq 'lvm' && $scfg->{vgname
} eq $vgname) {
1456 sub target_is_used
{
1457 my ($cfg, $target) = @_;
1459 foreach my $storeid (keys %{$cfg->{ids
}}) {
1460 my $scfg = storage_config
($cfg, $storeid);
1461 if ($scfg->{type
} eq 'iscsi' && $scfg->{target
} eq $target) {
1469 sub volume_is_used
{
1470 my ($cfg, $volid) = @_;
1472 foreach my $storeid (keys %{$cfg->{ids
}}) {
1473 my $scfg = storage_config
($cfg, $storeid);
1474 if ($scfg->{base
} && $scfg->{base
} eq $volid) {
1482 sub storage_is_used
{
1483 my ($cfg, $storeid) = @_;
1485 foreach my $sid (keys %{$cfg->{ids
}}) {
1486 my $scfg = storage_config
($cfg, $sid);
1487 next if !$scfg->{base
};
1488 my ($st) = parse_volume_id
($scfg->{base
});
1489 return 1 if $st && $st eq $storeid;
1496 my ($list, $func) = @_;
1500 foreach my $sid (keys %$list) {
1501 foreach my $info (@{$list->{$sid}}) {
1502 my $volid = $info->{volid
};
1503 my ($sid1, $volname) = parse_volume_id
($volid, 1);
1504 if ($sid1 && $sid1 eq $sid) {
1505 &$func ($volid, $sid, $info);
1507 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1513 sub decompressor_info
{
1514 my ($format, $comp) = @_;
1516 if ($format eq 'tgz' && !defined($comp)) {
1517 ($format, $comp) = ('tar', 'gz');
1520 my $decompressor = {
1522 gz
=> ['tar', '-z'],
1523 lzo
=> ['tar', '--lzop'],
1524 zst
=> ['tar', '--zstd'],
1528 lzo
=> ['lzop', '-d', '-c'],
1529 zst
=> ['zstd', '-q', '-d', '-c'],
1533 die "ERROR: archive format not defined\n"
1534 if !defined($decompressor->{$format});
1537 $decomp = $decompressor->{$format}->{$comp} if $comp;
1541 compression
=> $comp,
1542 decompressor
=> $decomp,
1548 sub protection_file_path
{
1551 return "${path}.protected";
1555 my ($archive) = shift;
1558 my $volid = basename
($archive);
1559 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
1560 my $filename = "$1"; # untaint
1561 my ($type, $extension, $comp) = ($2, $3, $4);
1562 (my $format = $extension) =~ s/\..*//;
1563 $info = decompressor_info
($format, $comp);
1564 $info->{filename
} = $filename;
1565 $info->{type
} = $type;
1567 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${extension}$/) {
1568 $info->{logfilename
} = "$1.log";
1569 $info->{notesfilename
} = "$filename.notes";
1570 $info->{vmid
} = int($2);
1571 $info->{ctime
} = timelocal
($8, $7, $6, $5, $4 - 1, $3);
1572 $info->{is_std_name
} = 1;
1574 $info->{is_std_name
} = 0;
1577 die "ERROR: couldn't determine archive info from '$archive'\n";
1583 sub archive_remove
{
1584 my ($archive_path) = @_;
1586 die "cannot remove protected archive '$archive_path'\n"
1587 if -e protection_file_path
($archive_path);
1589 unlink $archive_path or die "removing archive $archive_path failed: $!\n";
1591 archive_auxiliaries_remove
($archive_path);
1594 sub archive_auxiliaries_remove
{
1595 my ($archive_path) = @_;
1597 my $dirname = dirname
($archive_path);
1598 my $archive_info = eval { archive_info
($archive_path) } // {};
1600 for my $type (qw(log notes)) {
1601 my $filename = $archive_info->{"${type}filename"} or next;
1602 my $path = "$dirname/$filename";
1605 unlink $path or warn "Removing $type file failed: $!\n";
1610 sub extract_vzdump_config_tar
{
1611 my ($archive, $conf_re) = @_;
1613 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
1615 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1616 die "unable to open file '$archive'\n";
1619 while (defined($file = <$fh>)) {
1620 if ($file =~ $conf_re) {
1621 $file = $1; # untaint
1630 die "ERROR: archive contains no configuration file\n" if !$file;
1636 $raw .= "$output\n";
1639 run_command
(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc
=> $out);
1641 return wantarray ?
($raw, $file) : $raw;
1644 sub extract_vzdump_config_vma
{
1645 my ($archive, $comp) = @_;
1648 my $out = sub { $raw .= "$_[0]\n"; };
1650 my $info = archive_info
($archive);
1651 $comp //= $info->{compression
};
1652 my $decompressor = $info->{decompressor
};
1655 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1657 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1662 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
1664 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1665 $errstring = "Failed to extract config from VMA archive: $output\n";
1669 my $rc = eval { run_command
($cmd, outfunc
=> $out, errfunc
=> $err, noerr
=> 1) };
1672 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1674 if (!$errstring && !$broken_pipe && $rc != 0) {
1675 die "$rerr\n" if $rerr;
1676 die "config extraction failed with exit code $rc\n";
1678 die "$errstring\n" if $errstring;
1680 run_command
(["vma", "config", $archive], outfunc
=> $out);
1683 return wantarray ?
($raw, undef) : $raw;
1686 sub extract_vzdump_config
{
1687 my ($cfg, $volid) = @_;
1689 my ($storeid, $volname) = parse_volume_id
($volid);
1690 if (defined($storeid)) {
1691 my $scfg = storage_config
($cfg, $storeid);
1692 if ($scfg->{type
} eq 'pbs') {
1693 storage_check_enabled
($cfg, $storeid);
1694 return PVE
::Storage
::PBSPlugin-
>extract_vzdump_config($scfg, $volname, $storeid);
1698 my $archive = abs_filesystem_path
($cfg, $volid);
1699 my $info = archive_info
($archive);
1700 my $format = $info->{format
};
1701 my $comp = $info->{compression
};
1702 my $type = $info->{type
};
1704 if ($type eq 'lxc' || $type eq 'openvz') {
1705 return extract_vzdump_config_tar
($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1706 } elsif ($type eq 'qemu') {
1707 if ($format eq 'tar') {
1708 return extract_vzdump_config_tar
($archive, qr!\(\./qemu-server\.conf\)!);
1710 return extract_vzdump_config_vma
($archive, $comp);
1713 die "cannot determine backup guest type for backup archive '$volid'\n";
1718 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1720 my $scfg = storage_config
($cfg, $storeid);
1721 die "storage '$storeid' does not support backups\n" if !$scfg->{content
}->{backup
};
1723 if (!defined($keep)) {
1724 die "no prune-backups options configured for storage '$storeid'\n"
1725 if !defined($scfg->{'prune-backups'});
1726 $keep = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'});
1729 activate_storage
($cfg, $storeid);
1731 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1732 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1735 my $prune_mark = sub {
1736 my ($prune_entries, $keep_count, $id_func) = @_;
1738 return if !$keep_count;
1740 my $already_included = {};
1741 my $newly_included = {};
1743 foreach my $prune_entry (@{$prune_entries}) {
1744 my $mark = $prune_entry->{mark
};
1745 my $id = $id_func->($prune_entry->{ctime
});
1746 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1749 foreach my $prune_entry (@{$prune_entries}) {
1750 my $mark = $prune_entry->{mark
};
1751 my $id = $id_func->($prune_entry->{ctime
});
1753 next if defined($mark) || $already_included->{$id};
1755 if (!$newly_included->{$id}) {
1756 last if scalar(keys %{$newly_included}) >= $keep_count;
1757 $newly_included->{$id} = 1;
1758 $prune_entry->{mark
} = 'keep';
1760 $prune_entry->{mark
} = 'remove';
1765 sub prune_mark_backup_group
{
1766 my ($backup_group, $keep) = @_;
1768 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1770 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
1771 foreach my $prune_entry (@{$backup_group}) {
1772 # preserve additional information like 'protected'
1773 next if $prune_entry->{mark
} && $prune_entry->{mark
} ne 'remove';
1774 $prune_entry->{mark
} = 'keep';
1779 my $prune_list = [ sort { $b->{ctime
} <=> $a->{ctime
} } @{$backup_group} ];
1781 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1785 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1787 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1788 return "$hour/$day/$month/$year";
1790 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1792 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1793 return "$day/$month/$year";
1795 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1797 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1798 my $iso_week = int(strftime
("%V", $sec, $min, $hour, $day, $month, $year));
1799 my $iso_week_year = int(strftime
("%G", $sec, $min, $hour, $day, $month, $year));
1800 return "$iso_week/$iso_week_year";
1802 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1804 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1805 return "$month/$year";
1807 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1809 my $year = (localtime($ctime))[5];
1813 foreach my $prune_entry (@{$prune_list}) {
1814 $prune_entry->{mark
} //= 'remove';
1818 sub volume_export
: prototype($$$$$$$) {
1819 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1821 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1822 die "cannot export volume '$volid'\n" if !$storeid;
1823 my $scfg = storage_config
($cfg, $storeid);
1824 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1825 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1826 $snapshot, $base_snapshot, $with_snapshots);
1829 sub volume_import
: prototype($$$$$$$$) {
1830 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1832 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1833 die "cannot import into volume '$volid'\n" if !$storeid;
1834 my $scfg = storage_config
($cfg, $storeid);
1835 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1836 return $plugin->volume_import(
1849 sub volume_export_formats
: prototype($$$$$) {
1850 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1852 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1853 return if !$storeid;
1854 my $scfg = storage_config
($cfg, $storeid);
1855 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1856 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1857 $snapshot, $base_snapshot,
1861 sub volume_import_formats
: prototype($$$$$) {
1862 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1864 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1865 return if !$storeid;
1866 my $scfg = storage_config
($cfg, $storeid);
1867 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1868 return $plugin->volume_import_formats(
1878 sub volume_transfer_formats
{
1879 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1880 my @export_formats = volume_export_formats
($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1881 my @import_formats = volume_import_formats
($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
1882 my %import_hash = map { $_ => 1 } @import_formats;
1883 my @common = grep { $import_hash{$_} } @export_formats;
1887 sub volume_imported_message
{
1888 my ($volid, $want_pattern) = @_;
1890 if ($want_pattern) {
1891 return qr/successfully imported '([^']*)'$/;
1893 return "successfully imported '$volid'\n";
1897 # $format and $volname are requests and might be overruled depending on $opts
1899 # - with_snapshots: passed to `pvesm import` and used to select import format
1900 # - allow_rename: passed to `pvesm import`
1901 # - export_formats: used to select common transport format
1902 # - unix: unix socket path
1903 sub volume_import_start
{
1904 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1906 my $with_snapshots = $opts->{'with_snapshots'} ?
1 : 0;
1908 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1910 my $volid = "$storeid:$volname";
1912 # find common import/export format, like volume_transfer_formats
1913 my @import_formats = PVE
::Storage
::volume_import_formats
($cfg, $volid, $opts->{snapshot
}, undef, $with_snapshots);
1914 my @export_formats = PVE
::Tools
::split_list
($opts->{export_formats
});
1915 my %import_hash = map { $_ => 1 } @import_formats;
1916 my @common = grep { $import_hash{$_} } @export_formats;
1917 die "no matching import/export format found for storage '$storeid'\n"
1919 $format = $common[0];
1921 my $input = IO
::File-
>new();
1922 my $info = IO
::File-
>new();
1924 my $unix = $opts->{unix
} // "/run/pve/storage-migrate-$vmid.$$.unix";
1925 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER
, $opts);
1928 my $cpid = open3
($input, $info, $info, @$import)
1929 or die "failed to spawn disk-import child - $!\n";
1933 PVE
::Tools
::run_with_timeout
(5, sub { $ready = <$info>; });
1936 die "failed to read readyness from disk import child: $@\n" if $@;
1948 sub volume_export_start
{
1949 my ($cfg, $volid, $format, $log, $opts) = @_;
1951 my $run_command_params = delete $opts->{cmd
} // {};
1953 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1955 PVE
::Tools
::run_command
($cmds, %$run_command_params);
1958 # bash completion helper
1960 sub complete_storage
{
1961 my ($cmdname, $pname, $cvalue) = @_;
1963 my $cfg = PVE
::Storage
::config
();
1965 return $cmdname eq 'add' ?
[] : [ PVE
::Storage
::storage_ids
($cfg) ];
1968 sub complete_storage_enabled
{
1969 my ($cmdname, $pname, $cvalue) = @_;
1973 my $cfg = PVE
::Storage
::config
();
1974 foreach my $sid (keys %{$cfg->{ids
}}) {
1975 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1981 sub complete_content_type
{
1982 my ($cmdname, $pname, $cvalue) = @_;
1984 return [qw(rootdir images vztmpl iso backup snippets)];
1987 sub complete_volume
{
1988 my ($cmdname, $pname, $cvalue) = @_;
1992 my $storage_list = complete_storage_enabled
();
1994 if ($cvalue =~ m/^([^:]+):/) {
1995 $storage_list = [ $1 ];
1997 if (scalar(@$storage_list) > 1) {
1998 # only list storage IDs to avoid large listings
2000 foreach my $storeid (@$storage_list) {
2001 # Hack: simply return 2 artificial values, so that
2002 # completions does not finish
2003 push @$res, "$storeid:volname", "$storeid:...";
2010 foreach my $storeid (@$storage_list) {
2011 my $vollist = PVE
::Storage
::volume_list
($cfg, $storeid);
2013 foreach my $item (@$vollist) {
2014 push @$res, $item->{volid
};
2022 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
2024 die "no source volid provided\n" if !$source_volid;
2025 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
2027 my ($storeid, $source_volname) = parse_volume_id
($source_volid);
2029 activate_storage
($cfg, $storeid);
2031 my $scfg = storage_config
($cfg, $storeid);
2032 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
2034 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
2036 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
2037 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
2041 # Various io-heavy operations require io/bandwidth limits which can be
2042 # configured on multiple levels: The global defaults in datacenter.cfg, and
2043 # per-storage overrides. When we want to do a restore from storage A to storage
2044 # B, we should take the smaller limit defined for storages A and B, and if no
2045 # such limit was specified, use the one from datacenter.cfg.
2046 sub get_bandwidth_limit
{
2047 my ($operation, $storage_list, $override) = @_;
2049 # called for each limit (global, per-storage) with the 'default' and the
2050 # $operation limit and should update $override for every limit affecting
2052 my $use_global_limits = 0;
2053 my $apply_limit = sub {
2055 if (defined($bwlimit)) {
2056 my $limits = PVE
::JSONSchema
::parse_property_string
('bwlimit', $bwlimit);
2057 my $limit = $limits->{$operation} // $limits->{default};
2058 if (defined($limit)) {
2059 if (!$override || $limit < $override) {
2065 # If there was no applicable limit, try to apply the global ones.
2066 $use_global_limits = 1;
2069 my ($rpcenv, $authuser);
2070 if (defined($override)) {
2071 $rpcenv = PVE
::RPCEnvironment-
>get();
2072 $authuser = $rpcenv->get_user();
2075 # Apply per-storage limits - if there are storages involved.
2076 if (defined($storage_list) && @$storage_list) {
2077 my $config = config
();
2079 # The Datastore.Allocate permission allows us to modify the per-storage
2080 # limits, therefore it also allows us to override them.
2081 # Since we have most likely multiple storages to check, do a quick check on
2082 # the general '/storage' path to see if we can skip the checks entirely:
2083 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
2086 foreach my $storage (@$storage_list) {
2087 next if !defined($storage);
2088 # Avoid duplicate checks:
2089 next if $done{$storage};
2090 $done{$storage} = 1;
2092 # Otherwise we may still have individual /storage/$ID permissions:
2093 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
2094 # And if not: apply the limits.
2095 my $storecfg = storage_config
($config, $storage);
2096 $apply_limit->($storecfg->{bwlimit
});
2100 # Storage limits take precedence over the datacenter defaults, so if
2101 # a limit was applied:
2102 return $override if !$use_global_limits;
2105 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2106 # global default limits.
2107 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
2108 # So if we cannot modify global limits, apply them to our currently
2109 # requested override.
2110 my $dc = cfs_read_file
('datacenter.cfg');
2111 $apply_limit->($dc->{bwlimit
});
2117 # checks if the storage id is available and dies if not
2118 sub assert_sid_unused
{
2122 if (my $scfg = storage_config
($cfg, $sid, 1)) {
2123 die "storage ID '$sid' already defined\n";
2129 # removes leading/trailing spaces and (back)slashes completely
2130 # substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2131 sub normalize_content_filename
{
2132 my ($filename) = @_;
2135 $filename =~ s/^.*[\/\\]//;
2136 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;