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
;
26 use PVE
::RESTEnvironment
qw(log_warn);
28 use PVE
::Storage
::Plugin
;
29 use PVE
::Storage
::DirPlugin
;
30 use PVE
::Storage
::LVMPlugin
;
31 use PVE
::Storage
::LvmThinPlugin
;
32 use PVE
::Storage
::NFSPlugin
;
33 use PVE
::Storage
::CIFSPlugin
;
34 use PVE
::Storage
::ISCSIPlugin
;
35 use PVE
::Storage
::RBDPlugin
;
36 use PVE
::Storage
::CephFSPlugin
;
37 use PVE
::Storage
::ISCSIDirectPlugin
;
38 use PVE
::Storage
::GlusterfsPlugin
;
39 use PVE
::Storage
::ZFSPoolPlugin
;
40 use PVE
::Storage
::ZFSPlugin
;
41 use PVE
::Storage
::PBSPlugin
;
42 use PVE
::Storage
::BTRFSPlugin
;
44 # Storage API version. Increment it on changes in storage API interface.
45 use constant APIVER
=> 10;
46 # Age is the number of versions we're backward compatible with.
47 # This is like having 'current=APIVER' and age='APIAGE' in libtool,
48 # see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
49 use constant APIAGE
=> 1;
51 # load standard plugins
52 PVE
::Storage
::DirPlugin-
>register();
53 PVE
::Storage
::LVMPlugin-
>register();
54 PVE
::Storage
::LvmThinPlugin-
>register();
55 PVE
::Storage
::NFSPlugin-
>register();
56 PVE
::Storage
::CIFSPlugin-
>register();
57 PVE
::Storage
::ISCSIPlugin-
>register();
58 PVE
::Storage
::RBDPlugin-
>register();
59 PVE
::Storage
::CephFSPlugin-
>register();
60 PVE
::Storage
::ISCSIDirectPlugin-
>register();
61 PVE
::Storage
::GlusterfsPlugin-
>register();
62 PVE
::Storage
::ZFSPoolPlugin-
>register();
63 PVE
::Storage
::ZFSPlugin-
>register();
64 PVE
::Storage
::PBSPlugin-
>register();
65 PVE
::Storage
::BTRFSPlugin-
>register();
67 # load third-party plugins
68 if ( -d
'/usr/share/perl5/PVE/Storage/Custom' ) {
69 dir_glob_foreach
('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
71 my $modname = 'PVE::Storage::Custom::' . $file;
72 $modname =~ s!\.pm$!!;
73 $file = 'PVE/Storage/Custom/' . $file;
78 # Check perl interface:
79 die "not derived from PVE::Storage::Plugin\n" if !$modname->isa('PVE::Storage::Plugin');
80 die "does not provide an api() method\n" if !$modname->can('api');
81 # Check storage API version and that file is really storage plugin.
82 my $version = $modname->api();
83 die "implements an API version newer than current ($version > " . APIVER
. ")\n"
85 my $min_version = (APIVER
- APIAGE
);
86 die "API version too old, please update the plugin ($version < $min_version)\n"
87 if $version < $min_version;
88 # all OK, do import and register (i.e., "use")
92 # If we got this far and the API version is not the same, make some noise:
93 warn "Plugin \"$modname\" is implementing an older storage API
, an upgrade
is recommended
\n"
94 if $version != APIVER;
97 warn "Error loading storage plugin
\"$modname\": $@";
102 # initialize all plugins
103 PVE
::Storage
::Plugin-
>init();
105 # the following REs indicate the number or capture groups via the trailing digit
106 # CAUTION don't forget to update the digits accordingly after messing with the capture groups
108 our $ISO_EXT_RE_0 = qr/\.(?:iso|img)/i;
110 our $VZTMPL_EXT_RE_1 = qr/\.tar\.(gz|xz|zst)/i;
112 our $BACKUP_EXT_RE_2 = qr/\.(tgz|(?:tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)/;
114 # FIXME remove with PVE 8.0, add versioned breaks for pve-manager
115 our $vztmpl_extension_re = $VZTMPL_EXT_RE_1;
117 # PVE::Storage utility functions
120 return cfs_read_file
("storage.cfg");
126 cfs_write_file
('storage.cfg', $cfg);
129 sub lock_storage_config
{
130 my ($code, $errmsg) = @_;
132 cfs_lock_file
("storage.cfg", undef, $code);
135 $errmsg ?
die "$errmsg: $err" : die $err;
139 # FIXME remove maxfiles for PVE 8.0 or PVE 9.0
140 my $convert_maxfiles_to_prune_backups = sub {
145 my $maxfiles = delete $scfg->{maxfiles
};
147 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
150 $prune_backups = { 'keep-last' => $maxfiles };
151 } else { # maxfiles 0 means no limit
152 $prune_backups = { 'keep-all' => 1 };
154 $scfg->{'prune-backups'} = PVE
::JSONSchema
::print_property_string
(
162 my ($cfg, $storeid, $noerr) = @_;
164 die "no storage ID specified\n" if !$storeid;
166 my $scfg = $cfg->{ids
}->{$storeid};
168 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
170 $convert_maxfiles_to_prune_backups->($scfg);
175 sub storage_check_node
{
176 my ($cfg, $storeid, $node, $noerr) = @_;
178 my $scfg = storage_config
($cfg, $storeid);
180 if ($scfg->{nodes
}) {
181 $node = PVE
::INotify
::nodename
() if !$node || ($node eq 'localhost');
182 if (!$scfg->{nodes
}->{$node}) {
183 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
191 sub storage_check_enabled
{
192 my ($cfg, $storeid, $node, $noerr) = @_;
194 my $scfg = storage_config
($cfg, $storeid);
196 if ($scfg->{disable
}) {
197 die "storage '$storeid' is disabled\n" if !$noerr;
201 return storage_check_node
($cfg, $storeid, $node, $noerr);
204 # storage_can_replicate:
205 # return true if storage supports replication
206 # (volumes allocated with vdisk_alloc() has replication feature)
207 sub storage_can_replicate
{
208 my ($cfg, $storeid, $format) = @_;
210 my $scfg = storage_config
($cfg, $storeid);
211 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
212 return $plugin->storage_can_replicate($scfg, $storeid, $format);
215 sub get_max_protected_backups
{
216 my ($scfg, $storeid) = @_;
218 return $scfg->{'max-protected-backups'} if defined($scfg->{'max-protected-backups'});
220 my $rpcenv = PVE
::RPCEnvironment
::get
();
221 my $authuser = $rpcenv->get_user();
223 return $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.Allocate'], 1) ?
-1 : 5;
229 return keys %{$cfg->{ids
}};
233 my ($filename, $timeout) = @_;
235 return PVE
::Storage
::Plugin
::file_size_info
($filename, $timeout);
238 sub get_volume_attribute
{
239 my ($cfg, $volid, $attribute) = @_;
241 my ($storeid, $volname) = parse_volume_id
($volid);
242 my $scfg = storage_config
($cfg, $storeid);
243 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
245 return $plugin->get_volume_attribute($scfg, $storeid, $volname, $attribute);
248 sub update_volume_attribute
{
249 my ($cfg, $volid, $attribute, $value) = @_;
251 my ($storeid, $volname) = parse_volume_id
($volid);
252 my $scfg = storage_config
($cfg, $storeid);
253 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
255 my ($vtype, undef, $vmid) = $plugin->parse_volname($volname);
256 my $max_protected_backups = get_max_protected_backups
($scfg, $storeid);
261 && $attribute eq 'protected'
263 && !$plugin->get_volume_attribute($scfg, $storeid, $volname, 'protected')
264 && $max_protected_backups > -1 # -1 is unlimited
266 my $backups = $plugin->list_volumes($storeid, $scfg, $vmid, ['backup']);
267 my ($backup_type) = map { $_->{subtype
} } grep { $_->{volid
} eq $volid } $backups->@*;
269 my $protected_count = grep {
270 $_->{protected
} && (!$backup_type || ($_->{subtype
} && $_->{subtype
} eq $backup_type))
273 if ($max_protected_backups <= $protected_count) {
274 die "The number of protected backups per guest is limited to $max_protected_backups ".
275 "on storage '$storeid'\n";
279 return $plugin->update_volume_attribute($scfg, $storeid, $volname, $attribute, $value);
282 sub volume_size_info
{
283 my ($cfg, $volid, $timeout) = @_;
285 my ($storeid, $volname) = parse_volume_id
($volid, 1);
287 my $scfg = storage_config
($cfg, $storeid);
288 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
289 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
290 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
291 return file_size_info
($volid, $timeout);
298 my ($cfg, $volid, $size, $running) = @_;
300 my $padding = (1024 - $size % 1024) % 1024;
301 $size = $size + $padding;
303 my ($storeid, $volname) = parse_volume_id
($volid, 1);
305 my $scfg = storage_config
($cfg, $storeid);
306 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
307 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
308 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
309 die "resize file/device '$volid' is not possible\n";
311 die "unable to parse volume ID '$volid'\n";
315 sub volume_rollback_is_possible
{
316 my ($cfg, $volid, $snap, $blockers) = @_;
318 my ($storeid, $volname) = parse_volume_id
($volid, 1);
320 my $scfg = storage_config
($cfg, $storeid);
321 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
322 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap, $blockers);
323 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
324 die "snapshot rollback file/device '$volid' is not possible\n";
326 die "unable to parse volume ID '$volid'\n";
330 sub volume_snapshot
{
331 my ($cfg, $volid, $snap) = @_;
333 my ($storeid, $volname) = parse_volume_id
($volid, 1);
335 my $scfg = storage_config
($cfg, $storeid);
336 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
337 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
338 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
339 die "snapshot file/device '$volid' is not possible\n";
341 die "unable to parse volume ID '$volid'\n";
345 sub volume_snapshot_rollback
{
346 my ($cfg, $volid, $snap) = @_;
348 my ($storeid, $volname) = parse_volume_id
($volid, 1);
350 my $scfg = storage_config
($cfg, $storeid);
351 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
352 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
353 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
354 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
355 die "snapshot rollback file/device '$volid' is not possible\n";
357 die "unable to parse volume ID '$volid'\n";
361 sub volume_snapshot_delete
{
362 my ($cfg, $volid, $snap, $running) = @_;
364 my ($storeid, $volname) = parse_volume_id
($volid, 1);
366 my $scfg = storage_config
($cfg, $storeid);
367 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
368 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
369 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
370 die "snapshot delete file/device '$volid' is not possible\n";
372 die "unable to parse volume ID '$volid'\n";
376 # check if a filesystem on top of a volume needs to flush its journal for
377 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
378 # container mountpoints
379 sub volume_snapshot_needs_fsfreeze
{
380 my ($cfg, $volid) = @_;
382 my ($storeid, $volname) = parse_volume_id
($volid);
383 my $scfg = storage_config
($cfg, $storeid);
384 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
385 return $plugin->volume_snapshot_needs_fsfreeze();
388 # check if a volume or snapshot supports a given feature
390 # clone - linked clone is possible
391 # copy - full clone is possible
392 # replicate - replication is possible
393 # snapshot - taking a snapshot is possible
394 # sparseinit - volume is sparsely initialized
395 # template - conversion to base image is possible
396 # rename - renaming volumes is possible
397 # $snap - check if the feature is supported for a given snapshot
398 # $running - if the guest owning the volume is running
399 # $opts - hash with further options:
400 # valid_target_formats - list of formats for the target of a copy/clone
401 # operation that the caller could work with. The
402 # format of $volid is always considered valid and if
403 # no list is specified, all formats are considered valid.
404 sub volume_has_feature
{
405 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
407 my ($storeid, $volname) = parse_volume_id
($volid, 1);
409 my $scfg = storage_config
($cfg, $storeid);
410 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
411 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
412 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
419 sub volume_snapshot_info
{
420 my ($cfg, $volid) = @_;
422 my ($storeid, $volname) = parse_volume_id
($volid);
423 my $scfg = storage_config
($cfg, $storeid);
424 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
425 return $plugin->volume_snapshot_info($scfg, $storeid, $volname);
429 my ($cfg, $storeid, $vmid) = @_;
431 my $scfg = storage_config
($cfg, $storeid);
432 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
434 my $path = $plugin->get_subdir($scfg, 'images');
436 return $vmid ?
"$path/$vmid" : $path;
439 sub get_private_dir
{
440 my ($cfg, $storeid, $vmid) = @_;
442 my $scfg = storage_config
($cfg, $storeid);
443 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
445 my $path = $plugin->get_subdir($scfg, 'rootdir');
447 return $vmid ?
"$path/$vmid" : $path;
451 my ($cfg, $storeid) = @_;
453 my $scfg = storage_config
($cfg, $storeid);
454 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
456 return $plugin->get_subdir($scfg, 'iso');
460 my ($cfg, $storeid) = @_;
462 my $scfg = storage_config
($cfg, $storeid);
463 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
465 return $plugin->get_subdir($scfg, 'vztmpl');
469 my ($cfg, $storeid) = @_;
471 my $scfg = storage_config
($cfg, $storeid);
472 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
474 return $plugin->get_subdir($scfg, 'backup');
477 # library implementation
482 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
487 # NOTE: basename and basevmid are always undef for LVM-thin, where the
488 # clone -> base reference is not encoded in the volume ID.
489 # see note in PVE::Storage::LvmThinPlugin for details.
491 my ($cfg, $volid) = @_;
493 my ($storeid, $volname) = parse_volume_id
($volid);
495 my $scfg = storage_config
($cfg, $storeid);
497 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
499 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
501 return $plugin->parse_volname($volname);
504 sub parse_volume_id
{
505 my ($volid, $noerr) = @_;
507 return PVE
::Storage
::Plugin
::parse_volume_id
($volid, $noerr);
510 # test if we have read access to volid
511 sub check_volume_access
{
512 my ($rpcenv, $user, $cfg, $vmid, $volid, $type) = @_;
514 my ($sid, $volname) = parse_volume_id
($volid, 1);
516 my ($vtype, undef, $ownervm) = parse_volname
($cfg, $volid);
518 # Need to allow 'images' when expecting 'rootdir' too - not cleanly separated in plugins.
519 die "unable to use volume $volid - content type needs to be '$type'\n"
520 if defined($type) && $vtype ne $type && ($type ne 'rootdir' || $vtype ne 'images');
522 return if $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate'], 1);
524 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
525 # require at least read access to storage, (custom) templates/ISOs could be sensitive
526 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
527 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
528 # we are owner - allow access
529 } elsif ($vtype eq 'backup' && $ownervm) {
530 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
531 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
532 } elsif (($vtype eq 'images' || $vtype eq 'rootdir') && $ownervm) {
533 $rpcenv->check($user, "/storage/$sid", ['Datastore.Audit']);
534 $rpcenv->check($user, "/vms/$ownervm", ['VM.Config.Disk']);
536 die "missing privileges to access $volid\n";
539 die "Only root can pass arbitrary filesystem paths."
540 if $user ne 'root@pam';
546 # NOTE: this check does not work for LVM-thin, where the clone -> base
547 # reference is not encoded in the volume ID.
548 # see note in PVE::Storage::LvmThinPlugin for details.
549 sub volume_is_base_and_used
{
550 my ($cfg, $volid) = @_;
552 my ($storeid, $volname) = parse_volume_id
($volid);
553 my $scfg = storage_config
($cfg, $storeid);
554 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
556 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
557 $plugin->parse_volname($volname);
560 my $vollist = $plugin->list_images($storeid, $scfg);
561 foreach my $info (@$vollist) {
562 my (undef, $tmpvolname) = parse_volume_id
($info->{volid
});
563 my $basename = undef;
564 my $basevmid = undef;
567 (undef, undef, undef, $basename, $basevmid) =
568 $plugin->parse_volname($tmpvolname);
571 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
579 # try to map a filesystem path to a volume identifier
580 sub path_to_volume_id
{
581 my ($cfg, $path) = @_;
583 my $ids = $cfg->{ids
};
585 my ($sid, $volname) = parse_volume_id
($path, 1);
587 if (my $scfg = $ids->{$sid}) {
589 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
590 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
591 return ($vtype, $path);
597 # Note: abs_path() return undef if $path doesn not exist
598 # for example when nfs storage is not mounted
599 $path = abs_path
($path) || $path;
601 foreach my $sid (keys %$ids) {
602 my $scfg = $ids->{$sid};
603 next if !$scfg->{path
};
604 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
605 my $imagedir = $plugin->get_subdir($scfg, 'images');
606 my $isodir = $plugin->get_subdir($scfg, 'iso');
607 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
608 my $backupdir = $plugin->get_subdir($scfg, 'backup');
609 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
610 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
612 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
616 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
617 foreach my $info (@$vollist) {
618 my ($storeid, $volname) = parse_volume_id
($info->{volid
});
619 my $volpath = $plugin->path($scfg, $volname, $storeid);
620 if ($volpath eq $path) {
621 return ('images', $info->{volid
});
624 } elsif ($path =~ m!^$isodir/([^/]+$ISO_EXT_RE_0)$!) {
626 return ('iso', "$sid:iso/$name");
627 } elsif ($path =~ m!^$tmpldir/([^/]+$VZTMPL_EXT_RE_1)$!) {
629 return ('vztmpl', "$sid:vztmpl/$name");
630 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
632 return ('rootdir', "$sid:rootdir/$vmid");
633 } elsif ($path =~ m!^$backupdir/([^/]+$BACKUP_EXT_RE_2)$!) {
635 return ('backup', "$sid:backup/$name");
636 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
638 return ('snippets', "$sid:snippets/$name");
642 # can't map path to volume id
647 my ($cfg, $volid, $snapname) = @_;
649 my ($storeid, $volname) = parse_volume_id
($volid);
651 my $scfg = storage_config
($cfg, $storeid);
653 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
654 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
655 return wantarray ?
($path, $owner, $vtype) : $path;
658 sub abs_filesystem_path
{
659 my ($cfg, $volid, $allow_blockdev) = @_;
662 if (parse_volume_id
($volid, 1)) {
663 activate_volumes
($cfg, [ $volid ]);
664 $path = PVE
::Storage
::path
($cfg, $volid);
666 if (-f
$volid || ($allow_blockdev && -b
$volid)) {
667 my $abspath = abs_path
($volid);
668 if ($abspath && $abspath =~ m
|^(/.+)$|) {
669 $path = $1; # untaint any path
673 die "can't find file '$volid'\n"
674 if !($path && (-f
$path || ($allow_blockdev && -b
$path)));
679 # used as last resort to adapt volnames when migrating
680 my $volname_for_storage = sub {
681 my ($cfg, $storeid, $name, $vmid, $format) = @_;
683 my $scfg = storage_config
($cfg, $storeid);
685 my (undef, $valid_formats) = PVE
::Storage
::Plugin
::default_format
($scfg);
686 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
687 die "unsupported format '$format' for storage type $scfg->{type}\n"
688 if !$format_is_valid;
690 (my $name_without_extension = $name) =~ s/\.$format$//;
693 return "$vmid/$name_without_extension.$format";
695 return "$name_without_extension";
699 # whether a migration snapshot is needed for a given storage
700 sub storage_migrate_snapshot
{
701 my ($cfg, $storeid, $existing_snapshots) = @_;
702 my $scfg = storage_config
($cfg, $storeid);
704 return $scfg->{type
} eq 'zfspool' || ($scfg->{type
} eq 'btrfs' && $existing_snapshots);
707 my $volume_import_prepare = sub {
708 my ($volid, $format, $path, $apiver, $opts) = @_;
710 my $base_snapshot = $opts->{base_snapshot
};
711 my $snapshot = $opts->{snapshot
};
712 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
713 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
714 my $allow_rename = $opts->{allow_rename
} ?
1 : 0;
716 my $recv = ['pvesm', 'import', $volid, $format, $path, '-with-snapshots', $with_snapshots];
717 if (defined($snapshot)) {
718 push @$recv, '-snapshot', $snapshot;
720 if ($migration_snapshot) {
721 push @$recv, '-delete-snapshot', $snapshot;
723 push @$recv, '-allow-rename', $allow_rename if $apiver >= 5;
725 if (defined($base_snapshot)) {
726 # Check if the snapshot exists on the remote side:
727 push @$recv, '-base', $base_snapshot if $apiver >= 9;
733 my $volume_export_prepare = sub {
734 my ($cfg, $volid, $format, $logfunc, $opts) = @_;
735 my $base_snapshot = $opts->{base_snapshot
};
736 my $snapshot = $opts->{snapshot
};
737 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
738 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
739 my $ratelimit_bps = $opts->{ratelimit_bps
};
741 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
742 if (defined($snapshot)) {
743 push @$send, '-snapshot', $snapshot;
745 if (defined($base_snapshot)) {
746 push @$send, '-base', $base_snapshot;
750 if (defined($ratelimit_bps)) {
751 $cstream = [ '/usr/bin/cstream', '-t', $ratelimit_bps ];
752 $logfunc->("using a bandwidth limit of $ratelimit_bps bps for transferring '$volid'") if $logfunc;
755 volume_snapshot
($cfg, $volid, $snapshot) if $migration_snapshot;
757 if (defined($snapshot)) {
758 activate_volumes
($cfg, [$volid], $snapshot);
760 activate_volumes
($cfg, [$volid]);
763 return $cstream ?
[ $send, $cstream ] : [ $send ];
766 sub storage_migrate
{
767 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
769 my $insecure = $opts->{insecure
};
771 my ($storeid, $volname) = parse_volume_id
($volid);
773 my $scfg = storage_config
($cfg, $storeid);
775 # no need to migrate shared content
776 return $volid if $storeid eq $target_storeid && $scfg->{shared
};
778 my $tcfg = storage_config
($cfg, $target_storeid);
781 if ($opts->{target_volname
}) {
782 $target_volname = $opts->{target_volname
};
783 } elsif ($scfg->{type
} eq $tcfg->{type
}) {
784 $target_volname = $volname;
786 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname
($cfg, $volid);
787 $target_volname = $volname_for_storage->($cfg, $target_storeid, $name, $vmid, $format);
790 my $target_volid = "${target_storeid}:${target_volname}";
792 my $target_ip = $target_sshinfo->{ip
};
794 my $ssh = PVE
::SSHInfo
::ssh_info_to_command
($target_sshinfo);
795 my $ssh_base = PVE
::SSHInfo
::ssh_info_to_command_base
($target_sshinfo);
796 local $ENV{RSYNC_RSH
} = PVE
::Tools
::cmd2string
($ssh_base);
798 if (!defined($opts->{snapshot
})) {
799 $opts->{migration_snapshot
} = storage_migrate_snapshot
($cfg, $storeid, $opts->{with_snapshots
});
800 $opts->{snapshot
} = '__migration__' if $opts->{migration_snapshot
};
803 my @formats = volume_transfer_formats
($cfg, $volid, $target_volid, $opts->{snapshot
}, $opts->{base_snapshot
}, $opts->{with_snapshots
});
804 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
805 my $format = $formats[0];
807 my $import_fn = '-'; # let pvesm import read from stdin per default
809 my $net = $target_sshinfo->{network
} // $target_sshinfo->{ip
};
810 $import_fn = "tcp://$net";
813 my $target_apiver = 1; # if there is no apiinfo call, assume 1
814 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
815 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
816 eval { run_command
($get_api_version, logfunc
=> $match_api_version); };
818 my $recv = [ @$ssh, '--', $volume_import_prepare->($target_volid, $format, $import_fn, $target_apiver, $opts)->@* ];
821 my $pattern = volume_imported_message
(undef, 1);
822 my $match_volid_and_log = sub {
825 $new_volid = $1 if ($line =~ $pattern);
833 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
837 my $input = IO
::File-
>new();
838 my $info = IO
::File-
>new();
839 open3
($input, $info, $info, @$recv)
840 or die "receive command failed: $!\n";
843 my $try_ip = <$info> // '';
844 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
845 or die "no tunnel IP received, got '$try_ip'\n";
847 my $try_port = <$info> // '';
848 my ($port) = $try_port =~ /^(\d+)$/ # untaint
849 or die "no tunnel port received, got '$try_port'\n";
851 my $socket = IO
::Socket
::IP-
>new(PeerHost
=> $ip, PeerPort
=> $port, Type
=> SOCK_STREAM
)
852 or die "failed to connect to tunnel at $ip:$port\n";
853 # we won't be reading from the socket
854 shutdown($socket, 0);
856 eval { run_command
($cmds, output
=> '>&'.fileno($socket), errfunc
=> $logfunc); };
859 # don't close the connection entirely otherwise the receiving end
860 # might not get all buffered data (and fails with 'connection reset by peer')
861 shutdown($socket, 1);
863 # wait for the remote process to finish
864 while (my $line = <$info>) {
865 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
868 # now close the socket
870 if (!close($info)) { # does waitpid()
871 die "import failed: $!\n" if $!;
872 die "import failed: exit code ".($?>>8)."\n";
875 die $send_error if $send_error;
878 run_command
($cmds, logfunc
=> $match_volid_and_log);
881 die "unable to get ID of the migrated volume\n"
882 if !defined($new_volid) && $target_apiver >= 5;
885 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
886 if ($opts->{migration_snapshot
}) {
887 eval { volume_snapshot_delete
($cfg, $volid, $opts->{snapshot
}, 0) };
888 warn "could not remove source snapshot: $@\n" if $@;
892 return $new_volid // $target_volid;
896 my ($cfg, $volid, $vmid, $snap) = @_;
898 my ($storeid, $volname) = parse_volume_id
($volid);
900 my $scfg = storage_config
($cfg, $storeid);
902 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
904 activate_storage
($cfg, $storeid);
906 # lock shared storage
907 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
908 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
909 return "$storeid:$volname";
913 sub vdisk_create_base
{
914 my ($cfg, $volid) = @_;
916 my ($storeid, $volname) = parse_volume_id
($volid);
918 my $scfg = storage_config
($cfg, $storeid);
920 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
922 activate_storage
($cfg, $storeid);
924 # lock shared storage
925 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
926 my $volname = $plugin->create_base($storeid, $scfg, $volname);
927 return "$storeid:$volname";
932 my ($cfg, $volid, $snapname) = @_;
934 my ($storeid, $volname) = parse_volume_id
($volid);
936 my $scfg = storage_config
($cfg, $storeid);
938 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
940 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
944 my ($cfg, $volid, $snapname) = @_;
946 my ($storeid, $volname) = parse_volume_id
($volid);
948 my $scfg = storage_config
($cfg, $storeid);
950 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
952 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
956 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
958 die "no storage ID specified\n" if !$storeid;
960 PVE
::JSONSchema
::parse_storage_id
($storeid);
962 my $scfg = storage_config
($cfg, $storeid);
964 die "no VMID specified\n" if !$vmid;
966 $vmid = parse_vmid
($vmid);
968 my $defformat = PVE
::Storage
::Plugin
::default_format
($scfg);
970 $fmt = $defformat if !$fmt;
972 activate_storage
($cfg, $storeid);
974 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
976 # lock shared storage
977 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
978 my $old_umask = umask(umask|0037);
979 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
983 return "$storeid:$volname";
988 my ($cfg, $volid) = @_;
990 my ($storeid, $volname) = parse_volume_id
($volid);
991 my $scfg = storage_config
($cfg, $storeid);
992 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
994 activate_storage
($cfg, $storeid);
998 # lock shared storage
999 $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
1000 # LVM-thin allows deletion of still referenced base volumes!
1001 die "base volume '$volname' is still in use by linked clones\n"
1002 if volume_is_base_and_used
($cfg, $volid);
1004 my (undef, undef, undef, undef, undef, $isBase, $format) =
1005 $plugin->parse_volname($volname);
1006 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1009 return if !$cleanup_worker;
1011 my $rpcenv = PVE
::RPCEnvironment
::get
();
1012 my $authuser = $rpcenv->get_user();
1014 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
1018 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
1020 my $ids = $cfg->{ids
};
1022 storage_check_enabled
($cfg, $storeid) if ($storeid);
1024 my $res = $storeid ?
{ $storeid => [] } : {};
1026 # prepare/activate/refresh all storages
1028 my $storage_list = [];
1030 foreach my $volid (@$vollist) {
1031 my ($sid, undef) = parse_volume_id
($volid);
1032 next if !defined($ids->{$sid});
1033 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1034 push @$storage_list, $sid;
1037 foreach my $sid (keys %$ids) {
1038 next if $storeid && $storeid ne $sid;
1039 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1040 my $content = $ids->{$sid}->{content
};
1041 next if defined($ctype) && !$content->{$ctype};
1042 next if !($content->{rootdir
} || $content->{images
});
1043 push @$storage_list, $sid;
1049 activate_storage_list
($cfg, $storage_list, $cache);
1051 for my $sid ($storage_list->@*) {
1052 next if $storeid && $storeid ne $sid;
1054 my $scfg = $ids->{$sid};
1055 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1056 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
1057 @{$res->{$sid}} = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @{$res->{$sid}} if $res->{$sid};
1064 my ($cfg, $storeid, $tt) = @_;
1066 die "unknown template type '$tt'\n"
1067 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1069 my $ids = $cfg->{ids
};
1071 storage_check_enabled
($cfg, $storeid) if ($storeid);
1076 foreach my $sid (keys %$ids) {
1077 next if $storeid && $storeid ne $sid;
1079 my $scfg = $ids->{$sid};
1080 my $type = $scfg->{type
};
1082 next if !$scfg->{content
}->{$tt};
1084 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1086 $res->{$sid} = volume_list
($cfg, $sid, undef, $tt);
1093 my ($cfg, $storeid, $vmid, $content) = @_;
1095 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
1097 my $cts = $content ?
[ $content ] : [ @ctypes ];
1099 my $scfg = PVE
::Storage
::storage_config
($cfg, $storeid);
1101 $cts = [ grep { defined($scfg->{content
}->{$_}) } @$cts ];
1103 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1105 activate_storage
($cfg, $storeid);
1107 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1109 @$res = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @$res;
1116 my $filename = "/sys/kernel/uevent_seqnum";
1119 if (my $fh = IO
::File-
>new($filename, "r")) {
1121 if ($line =~ m/^(\d+)$/) {
1129 sub activate_storage
{
1130 my ($cfg, $storeid, $cache) = @_;
1132 $cache = {} if !$cache;
1134 my $scfg = storage_check_enabled
($cfg, $storeid);
1136 return if $cache->{activated
}->{$storeid};
1138 $cache->{uevent_seqnum
} = uevent_seqnum
() if !$cache->{uevent_seqnum
};
1140 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1142 if ($scfg->{base
}) {
1143 my ($baseid, undef) = parse_volume_id
($scfg->{base
});
1144 activate_storage
($cfg, $baseid, $cache);
1147 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1148 die "connection check for storage '$storeid' failed - $@\n" if $@;
1149 die "storage '$storeid' is not online\n";
1152 $plugin->activate_storage($storeid, $scfg, $cache);
1154 my $newseq = uevent_seqnum
();
1156 # only call udevsettle if there are events
1157 if ($newseq > $cache->{uevent_seqnum
}) {
1158 system ("udevadm settle --timeout=30"); # ignore errors
1159 $cache->{uevent_seqnum
} = $newseq;
1162 $cache->{activated
}->{$storeid} = 1;
1165 sub activate_storage_list
{
1166 my ($cfg, $storeid_list, $cache) = @_;
1168 $cache = {} if !$cache;
1170 foreach my $storeid (@$storeid_list) {
1171 activate_storage
($cfg, $storeid, $cache);
1175 sub deactivate_storage
{
1176 my ($cfg, $storeid) = @_;
1178 my $scfg = storage_config
($cfg, $storeid);
1179 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1182 $plugin->deactivate_storage($storeid, $scfg, $cache);
1185 sub activate_volumes
{
1186 my ($cfg, $vollist, $snapname) = @_;
1188 return if !($vollist && scalar(@$vollist));
1190 my $storagehash = {};
1191 foreach my $volid (@$vollist) {
1192 my ($storeid, undef) = parse_volume_id
($volid);
1193 $storagehash->{$storeid} = 1;
1198 activate_storage_list
($cfg, [keys %$storagehash], $cache);
1200 foreach my $volid (@$vollist) {
1201 my ($storeid, $volname) = parse_volume_id
($volid);
1202 my $scfg = storage_config
($cfg, $storeid);
1203 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1204 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1208 sub deactivate_volumes
{
1209 my ($cfg, $vollist, $snapname) = @_;
1211 return if !($vollist && scalar(@$vollist));
1216 foreach my $volid (@$vollist) {
1217 my ($storeid, $volname) = parse_volume_id
($volid);
1219 my $scfg = storage_config
($cfg, $storeid);
1220 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1223 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1227 push @errlist, $volid;
1231 die "volume deactivation failed: " . join(' ', @errlist)
1232 if scalar(@errlist);
1236 my ($cfg, $content, $includeformat) = @_;
1238 my $ids = $cfg->{ids
};
1242 my @ctypes = PVE
::Tools
::split_list
($content);
1245 foreach my $storeid (keys %$ids) {
1246 my $storage_enabled = defined(storage_check_enabled
($cfg, $storeid, undef, 1));
1248 if (defined($content)) {
1250 foreach my $ctype (@ctypes) {
1251 if ($ids->{$storeid}->{content
}->{$ctype}) {
1256 next if !$want_ctype || !$storage_enabled;
1259 my $type = $ids->{$storeid}->{type
};
1261 $info->{$storeid} = {
1266 shared
=> $ids->{$storeid}->{shared
} ?
1 : 0,
1267 content
=> PVE
::Storage
::Plugin
::content_hash_to_string
($ids->{$storeid}->{content
}),
1269 enabled
=> $storage_enabled ?
1 : 0,
1272 push @$slist, $storeid;
1277 foreach my $storeid (keys %$ids) {
1278 my $scfg = $ids->{$storeid};
1280 next if !$info->{$storeid};
1281 next if !$info->{$storeid}->{enabled
};
1283 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1284 if ($includeformat) {
1285 my $pd = $plugin->plugindata();
1286 $info->{$storeid}->{format
} = $pd->{format
}
1288 $info->{$storeid}->{select_existing
} = $pd->{select_existing
}
1289 if $pd->{select_existing
};
1292 eval { activate_storage
($cfg, $storeid, $cache); };
1298 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1301 $info->{$storeid}->{total
} = int($total);
1302 $info->{$storeid}->{avail
} = int($avail);
1303 $info->{$storeid}->{used
} = int($used);
1304 $info->{$storeid}->{active
} = $active;
1313 my ($packed_ip, $family);
1315 my @res = PVE
::Tools
::getaddrinfo_all
($server);
1316 $family = $res[0]->{family
};
1317 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
1319 if (defined $packed_ip) {
1320 return Socket
::inet_ntop
($family, $packed_ip);
1326 my ($server_in) = @_;
1329 if (!($server = resolv_server
($server_in))) {
1330 die "unable to resolve address for server '${server_in}'\n";
1333 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1336 run_command
($cmd, outfunc
=> sub {
1339 # note: howto handle white spaces in export path??
1340 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1349 my ($server_in, $user, $password, $domain) = @_;
1351 my $server = resolv_server
($server_in);
1352 die "unable to resolve address for server '${server_in}'\n" if !$server;
1354 # we only support Windows 2012 and newer, so just use smb3
1355 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1356 push @$cmd, '-W', $domain if defined($domain);
1358 push @$cmd, '-N' if !defined($password);
1359 local $ENV{USER
} = $user if defined($user);
1360 local $ENV{PASSWD
} = $password if defined($password);
1371 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1373 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1375 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1379 # only die if we got no share, else it's just some followup check error
1380 # (like workgroup querying)
1381 raise
($err) if $err && !%$res;
1388 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1391 run_command
($cmd, outfunc
=> sub {
1394 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1395 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1396 my $size = $size_str + 0;
1397 my $used = $used_str + 0;
1398 # ignore subvolumes generated by our ZFSPoolPlugin
1399 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1400 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1401 push @$res, { pool
=> $pool, size
=> $size, free
=> $size-$used };
1409 my ($portal, $noerr) = @_;
1411 my ($server, $port) = PVE
::Tools
::parse_host_and_port
($portal);
1413 if (my $ip = resolv_server
($server)) {
1415 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1416 return $port ?
"$server:$port" : $server;
1419 return undef if $noerr;
1421 raise_param_exc
({ portal
=> "unable to resolve portal address '$portal'" });
1426 my ($portal_in) = @_;
1429 if (!($portal = resolv_portal
($portal_in))) {
1430 die "unable to parse/resolve portal address '${portal_in}'\n";
1433 return PVE
::Storage
::ISCSIPlugin
::iscsi_discovery
($portal);
1436 sub storage_default_format
{
1437 my ($cfg, $storeid) = @_;
1439 my $scfg = storage_config
($cfg, $storeid);
1441 return PVE
::Storage
::Plugin
::default_format
($scfg);
1444 sub vgroup_is_used
{
1445 my ($cfg, $vgname) = @_;
1447 foreach my $storeid (keys %{$cfg->{ids
}}) {
1448 my $scfg = storage_config
($cfg, $storeid);
1449 if ($scfg->{type
} eq 'lvm' && $scfg->{vgname
} eq $vgname) {
1457 sub target_is_used
{
1458 my ($cfg, $target) = @_;
1460 foreach my $storeid (keys %{$cfg->{ids
}}) {
1461 my $scfg = storage_config
($cfg, $storeid);
1462 if ($scfg->{type
} eq 'iscsi' && $scfg->{target
} eq $target) {
1470 sub volume_is_used
{
1471 my ($cfg, $volid) = @_;
1473 foreach my $storeid (keys %{$cfg->{ids
}}) {
1474 my $scfg = storage_config
($cfg, $storeid);
1475 if ($scfg->{base
} && $scfg->{base
} eq $volid) {
1483 sub storage_is_used
{
1484 my ($cfg, $storeid) = @_;
1486 foreach my $sid (keys %{$cfg->{ids
}}) {
1487 my $scfg = storage_config
($cfg, $sid);
1488 next if !$scfg->{base
};
1489 my ($st) = parse_volume_id
($scfg->{base
});
1490 return 1 if $st && $st eq $storeid;
1497 my ($list, $func) = @_;
1501 foreach my $sid (keys %$list) {
1502 foreach my $info (@{$list->{$sid}}) {
1503 my $volid = $info->{volid
};
1504 my ($sid1, $volname) = parse_volume_id
($volid, 1);
1505 if ($sid1 && $sid1 eq $sid) {
1506 &$func ($volid, $sid, $info);
1508 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1514 sub decompressor_info
{
1515 my ($format, $comp) = @_;
1517 if ($format eq 'tgz' && !defined($comp)) {
1518 ($format, $comp) = ('tar', 'gz');
1521 my $decompressor = {
1523 gz
=> ['tar', '-z'],
1524 lzo
=> ['tar', '--lzop'],
1525 zst
=> ['tar', '--zstd'],
1529 lzo
=> ['lzop', '-d', '-c'],
1530 zst
=> ['zstd', '-q', '-d', '-c'],
1534 die "ERROR: archive format not defined\n"
1535 if !defined($decompressor->{$format});
1538 $decomp = $decompressor->{$format}->{$comp} if $comp;
1542 compression
=> $comp,
1543 decompressor
=> $decomp,
1549 sub protection_file_path
{
1552 return "${path}.protected";
1556 my ($archive) = shift;
1559 my $volid = basename
($archive);
1560 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
1561 my $filename = "$1"; # untaint
1562 my ($type, $extension, $comp) = ($2, $3, $4);
1563 (my $format = $extension) =~ s/\..*//;
1564 $info = decompressor_info
($format, $comp);
1565 $info->{filename
} = $filename;
1566 $info->{type
} = $type;
1568 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${extension}$/) {
1569 $info->{logfilename
} = "$1".PVE
::Storage
::Plugin
::LOG_EXT
;
1570 $info->{notesfilename
} = "$filename".PVE
::Storage
::Plugin
::NOTES_EXT
;
1571 $info->{vmid
} = int($2);
1572 $info->{ctime
} = timelocal
($8, $7, $6, $5, $4 - 1, $3);
1573 $info->{is_std_name
} = 1;
1575 $info->{is_std_name
} = 0;
1578 die "ERROR: couldn't determine archive info from '$archive'\n";
1584 sub archive_remove
{
1585 my ($archive_path) = @_;
1587 die "cannot remove protected archive '$archive_path'\n"
1588 if -e protection_file_path
($archive_path);
1590 unlink $archive_path or $! == ENOENT
or die "removing archive $archive_path failed: $!\n";
1592 archive_auxiliaries_remove
($archive_path);
1595 sub archive_auxiliaries_remove
{
1596 my ($archive_path) = @_;
1598 my $dirname = dirname
($archive_path);
1599 my $archive_info = eval { archive_info
($archive_path) } // {};
1601 for my $type (qw(log notes)) {
1602 my $filename = $archive_info->{"${type}filename"} or next;
1603 my $path = "$dirname/$filename";
1606 unlink $path or $! == ENOENT
or log_warn
("Removing $type file failed: $!");
1611 sub extract_vzdump_config_tar
{
1612 my ($archive, $conf_re) = @_;
1614 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
1616 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1617 die "unable to open file '$archive'\n";
1620 while (defined($file = <$fh>)) {
1621 if ($file =~ $conf_re) {
1622 $file = $1; # untaint
1631 die "ERROR: archive contains no configuration file\n" if !$file;
1637 $raw .= "$output\n";
1640 run_command
(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc
=> $out);
1642 return wantarray ?
($raw, $file) : $raw;
1645 sub extract_vzdump_config_vma
{
1646 my ($archive, $comp) = @_;
1649 my $out = sub { $raw .= "$_[0]\n"; };
1651 my $info = archive_info
($archive);
1652 $comp //= $info->{compression
};
1653 my $decompressor = $info->{decompressor
};
1656 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1658 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1663 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
1665 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1666 $errstring = "Failed to extract config from VMA archive: $output\n";
1670 my $rc = eval { run_command
($cmd, outfunc
=> $out, errfunc
=> $err, noerr
=> 1) };
1673 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1675 if (!$errstring && !$broken_pipe && $rc != 0) {
1676 die "$rerr\n" if $rerr;
1677 die "config extraction failed with exit code $rc\n";
1679 die "$errstring\n" if $errstring;
1681 run_command
(["vma", "config", $archive], outfunc
=> $out);
1684 return wantarray ?
($raw, undef) : $raw;
1687 sub extract_vzdump_config
{
1688 my ($cfg, $volid) = @_;
1690 my ($storeid, $volname) = parse_volume_id
($volid);
1691 if (defined($storeid)) {
1692 my $scfg = storage_config
($cfg, $storeid);
1693 if ($scfg->{type
} eq 'pbs') {
1694 storage_check_enabled
($cfg, $storeid);
1695 return PVE
::Storage
::PBSPlugin-
>extract_vzdump_config($scfg, $volname, $storeid);
1699 my $archive = abs_filesystem_path
($cfg, $volid);
1700 my $info = archive_info
($archive);
1701 my $format = $info->{format
};
1702 my $comp = $info->{compression
};
1703 my $type = $info->{type
};
1705 if ($type eq 'lxc' || $type eq 'openvz') {
1706 return extract_vzdump_config_tar
($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1707 } elsif ($type eq 'qemu') {
1708 if ($format eq 'tar') {
1709 return extract_vzdump_config_tar
($archive, qr!\(\./qemu-server\.conf\)!);
1711 return extract_vzdump_config_vma
($archive, $comp);
1714 die "cannot determine backup guest type for backup archive '$volid'\n";
1719 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1721 my $scfg = storage_config
($cfg, $storeid);
1722 die "storage '$storeid' does not support backups\n" if !$scfg->{content
}->{backup
};
1724 if (!defined($keep)) {
1725 die "no prune-backups options configured for storage '$storeid'\n"
1726 if !defined($scfg->{'prune-backups'});
1727 $keep = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'});
1730 activate_storage
($cfg, $storeid);
1732 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1733 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1736 my $prune_mark = sub {
1737 my ($prune_entries, $keep_count, $id_func) = @_;
1739 return if !$keep_count;
1741 my $already_included = {};
1742 my $newly_included = {};
1744 foreach my $prune_entry (@{$prune_entries}) {
1745 my $mark = $prune_entry->{mark
};
1746 my $id = $id_func->($prune_entry->{ctime
});
1747 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1750 foreach my $prune_entry (@{$prune_entries}) {
1751 my $mark = $prune_entry->{mark
};
1752 my $id = $id_func->($prune_entry->{ctime
});
1754 next if defined($mark) || $already_included->{$id};
1756 if (!$newly_included->{$id}) {
1757 last if scalar(keys %{$newly_included}) >= $keep_count;
1758 $newly_included->{$id} = 1;
1759 $prune_entry->{mark
} = 'keep';
1761 $prune_entry->{mark
} = 'remove';
1766 sub prune_mark_backup_group
{
1767 my ($backup_group, $keep) = @_;
1769 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1771 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
1772 foreach my $prune_entry (@{$backup_group}) {
1773 # preserve additional information like 'protected'
1774 next if $prune_entry->{mark
} && $prune_entry->{mark
} ne 'remove';
1775 $prune_entry->{mark
} = 'keep';
1780 my $prune_list = [ sort { $b->{ctime
} <=> $a->{ctime
} } @{$backup_group} ];
1782 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1786 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1788 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1789 return "$hour/$day/$month/$year";
1791 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1793 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1794 return "$day/$month/$year";
1796 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1798 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1799 my $iso_week = int(strftime
("%V", $sec, $min, $hour, $day, $month, $year));
1800 my $iso_week_year = int(strftime
("%G", $sec, $min, $hour, $day, $month, $year));
1801 return "$iso_week/$iso_week_year";
1803 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1805 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1806 return "$month/$year";
1808 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1810 my $year = (localtime($ctime))[5];
1814 foreach my $prune_entry (@{$prune_list}) {
1815 $prune_entry->{mark
} //= 'remove';
1819 sub volume_export
: prototype($$$$$$$) {
1820 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1822 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1823 die "cannot export volume '$volid'\n" if !$storeid;
1824 my $scfg = storage_config
($cfg, $storeid);
1825 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1826 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1827 $snapshot, $base_snapshot, $with_snapshots);
1830 sub volume_import
: prototype($$$$$$$$) {
1831 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1833 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1834 die "cannot import into volume '$volid'\n" if !$storeid;
1835 my $scfg = storage_config
($cfg, $storeid);
1836 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1837 return $plugin->volume_import(
1850 sub volume_export_formats
: prototype($$$$$) {
1851 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1853 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1854 return if !$storeid;
1855 my $scfg = storage_config
($cfg, $storeid);
1856 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1857 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1858 $snapshot, $base_snapshot,
1862 sub volume_import_formats
: prototype($$$$$) {
1863 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1865 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1866 return if !$storeid;
1867 my $scfg = storage_config
($cfg, $storeid);
1868 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1869 return $plugin->volume_import_formats(
1879 sub volume_transfer_formats
{
1880 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1881 my @export_formats = volume_export_formats
($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1882 my @import_formats = volume_import_formats
($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
1883 my %import_hash = map { $_ => 1 } @import_formats;
1884 my @common = grep { $import_hash{$_} } @export_formats;
1888 sub volume_imported_message
{
1889 my ($volid, $want_pattern) = @_;
1891 if ($want_pattern) {
1892 return qr/successfully imported '([^']*)'$/;
1894 return "successfully imported '$volid'\n";
1898 # $format and $volname are requests and might be overruled depending on $opts
1900 # - with_snapshots: passed to `pvesm import` and used to select import format
1901 # - allow_rename: passed to `pvesm import`
1902 # - export_formats: used to select common transport format
1903 # - unix: unix socket path
1904 sub volume_import_start
{
1905 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1907 my $with_snapshots = $opts->{'with_snapshots'} ?
1 : 0;
1909 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1911 my $volid = "$storeid:$volname";
1913 # find common import/export format, like volume_transfer_formats
1914 my @import_formats = PVE
::Storage
::volume_import_formats
($cfg, $volid, $opts->{snapshot
}, undef, $with_snapshots);
1915 my @export_formats = PVE
::Tools
::split_list
($opts->{export_formats
});
1916 my %import_hash = map { $_ => 1 } @import_formats;
1917 my @common = grep { $import_hash{$_} } @export_formats;
1918 die "no matching import/export format found for storage '$storeid'\n"
1920 $format = $common[0];
1922 my $input = IO
::File-
>new();
1923 my $info = IO
::File-
>new();
1925 my $unix = $opts->{unix
} // "/run/pve/storage-migrate-$vmid.$$.unix";
1926 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER
, $opts);
1929 my $cpid = open3
($input, $info, $info, @$import)
1930 or die "failed to spawn disk-import child - $!\n";
1934 PVE
::Tools
::run_with_timeout
(5, sub { $ready = <$info>; });
1937 die "failed to read readyness from disk import child: $@\n" if $@;
1949 sub volume_export_start
{
1950 my ($cfg, $volid, $format, $log, $opts) = @_;
1952 my $run_command_params = delete $opts->{cmd
} // {};
1954 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1956 PVE
::Tools
::run_command
($cmds, %$run_command_params);
1959 # bash completion helper
1961 sub complete_storage
{
1962 my ($cmdname, $pname, $cvalue) = @_;
1964 my $cfg = PVE
::Storage
::config
();
1966 return $cmdname eq 'add' ?
[] : [ PVE
::Storage
::storage_ids
($cfg) ];
1969 sub complete_storage_enabled
{
1970 my ($cmdname, $pname, $cvalue) = @_;
1974 my $cfg = PVE
::Storage
::config
();
1975 foreach my $sid (keys %{$cfg->{ids
}}) {
1976 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1982 sub complete_content_type
{
1983 my ($cmdname, $pname, $cvalue) = @_;
1985 return [qw(rootdir images vztmpl iso backup snippets)];
1988 sub complete_volume
{
1989 my ($cmdname, $pname, $cvalue) = @_;
1993 my $storage_list = complete_storage_enabled
();
1995 if ($cvalue =~ m/^([^:]+):/) {
1996 $storage_list = [ $1 ];
1998 if (scalar(@$storage_list) > 1) {
1999 # only list storage IDs to avoid large listings
2001 foreach my $storeid (@$storage_list) {
2002 # Hack: simply return 2 artificial values, so that
2003 # completions does not finish
2004 push @$res, "$storeid:volname", "$storeid:...";
2011 foreach my $storeid (@$storage_list) {
2012 my $vollist = PVE
::Storage
::volume_list
($cfg, $storeid);
2014 foreach my $item (@$vollist) {
2015 push @$res, $item->{volid
};
2023 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
2025 die "no source volid provided\n" if !$source_volid;
2026 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
2028 my ($storeid, $source_volname) = parse_volume_id
($source_volid);
2030 activate_storage
($cfg, $storeid);
2032 my $scfg = storage_config
($cfg, $storeid);
2033 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
2035 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
2037 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
2038 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
2042 # Various io-heavy operations require io/bandwidth limits which can be
2043 # configured on multiple levels: The global defaults in datacenter.cfg, and
2044 # per-storage overrides. When we want to do a restore from storage A to storage
2045 # B, we should take the smaller limit defined for storages A and B, and if no
2046 # such limit was specified, use the one from datacenter.cfg.
2047 sub get_bandwidth_limit
{
2048 my ($operation, $storage_list, $override) = @_;
2050 # called for each limit (global, per-storage) with the 'default' and the
2051 # $operation limit and should update $override for every limit affecting
2053 my $use_global_limits = 0;
2054 my $apply_limit = sub {
2056 if (defined($bwlimit)) {
2057 my $limits = PVE
::JSONSchema
::parse_property_string
('bwlimit', $bwlimit);
2058 my $limit = $limits->{$operation} // $limits->{default};
2059 if (defined($limit)) {
2060 if (!$override || $limit < $override) {
2066 # If there was no applicable limit, try to apply the global ones.
2067 $use_global_limits = 1;
2070 my ($rpcenv, $authuser);
2071 if (defined($override)) {
2072 $rpcenv = PVE
::RPCEnvironment-
>get();
2073 $authuser = $rpcenv->get_user();
2076 # Apply per-storage limits - if there are storages involved.
2077 if (defined($storage_list) && @$storage_list) {
2078 my $config = config
();
2080 # The Datastore.Allocate permission allows us to modify the per-storage
2081 # limits, therefore it also allows us to override them.
2082 # Since we have most likely multiple storages to check, do a quick check on
2083 # the general '/storage' path to see if we can skip the checks entirely:
2084 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
2087 foreach my $storage (@$storage_list) {
2088 next if !defined($storage);
2089 # Avoid duplicate checks:
2090 next if $done{$storage};
2091 $done{$storage} = 1;
2093 # Otherwise we may still have individual /storage/$ID permissions:
2094 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
2095 # And if not: apply the limits.
2096 my $storecfg = storage_config
($config, $storage);
2097 $apply_limit->($storecfg->{bwlimit
});
2101 # Storage limits take precedence over the datacenter defaults, so if
2102 # a limit was applied:
2103 return $override if !$use_global_limits;
2106 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2107 # global default limits.
2108 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
2109 # So if we cannot modify global limits, apply them to our currently
2110 # requested override.
2111 my $dc = cfs_read_file
('datacenter.cfg');
2112 $apply_limit->($dc->{bwlimit
});
2118 # checks if the storage id is available and dies if not
2119 sub assert_sid_unused
{
2123 if (my $scfg = storage_config
($cfg, $sid, 1)) {
2124 die "storage ID '$sid' already defined\n";
2130 # removes leading/trailing spaces and (back)slashes completely
2131 # substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2132 sub normalize_content_filename
{
2133 my ($filename) = @_;
2136 $filename =~ s/^.*[\/\\]//;
2137 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;