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 our $KNOWN_EXPORT_FORMATS = ['raw+size', 'tar+size', 'qcow2+size', 'vmdk+size', 'zfs', 'btrfs'];
53 # load standard plugins
54 PVE
::Storage
::DirPlugin-
>register();
55 PVE
::Storage
::LVMPlugin-
>register();
56 PVE
::Storage
::LvmThinPlugin-
>register();
57 PVE
::Storage
::NFSPlugin-
>register();
58 PVE
::Storage
::CIFSPlugin-
>register();
59 PVE
::Storage
::ISCSIPlugin-
>register();
60 PVE
::Storage
::RBDPlugin-
>register();
61 PVE
::Storage
::CephFSPlugin-
>register();
62 PVE
::Storage
::ISCSIDirectPlugin-
>register();
63 PVE
::Storage
::GlusterfsPlugin-
>register();
64 PVE
::Storage
::ZFSPoolPlugin-
>register();
65 PVE
::Storage
::ZFSPlugin-
>register();
66 PVE
::Storage
::PBSPlugin-
>register();
67 PVE
::Storage
::BTRFSPlugin-
>register();
69 # load third-party plugins
70 if ( -d
'/usr/share/perl5/PVE/Storage/Custom' ) {
71 dir_glob_foreach
('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
73 my $modname = 'PVE::Storage::Custom::' . $file;
74 $modname =~ s!\.pm$!!;
75 $file = 'PVE/Storage/Custom/' . $file;
80 # Check perl interface:
81 die "not derived from PVE::Storage::Plugin\n" if !$modname->isa('PVE::Storage::Plugin');
82 die "does not provide an api() method\n" if !$modname->can('api');
83 # Check storage API version and that file is really storage plugin.
84 my $version = $modname->api();
85 die "implements an API version newer than current ($version > " . APIVER
. ")\n"
87 my $min_version = (APIVER
- APIAGE
);
88 die "API version too old, please update the plugin ($version < $min_version)\n"
89 if $version < $min_version;
90 # all OK, do import and register (i.e., "use")
94 # If we got this far and the API version is not the same, make some noise:
95 warn "Plugin \"$modname\" is implementing an older storage API
, an upgrade
is recommended
\n"
96 if $version != APIVER;
99 warn "Error loading storage plugin
\"$modname\": $@";
104 # initialize all plugins
105 PVE
::Storage
::Plugin-
>init();
107 # the following REs indicate the number or capture groups via the trailing digit
108 # CAUTION don't forget to update the digits accordingly after messing with the capture groups
110 our $ISO_EXT_RE_0 = qr/\.(?:iso|img)/i;
112 our $VZTMPL_EXT_RE_1 = qr/\.tar\.(gz|xz|zst)/i;
114 our $BACKUP_EXT_RE_2 = qr/\.(tgz|(?:tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)/;
116 # FIXME remove with PVE 8.0, add versioned breaks for pve-manager
117 our $vztmpl_extension_re = $VZTMPL_EXT_RE_1;
119 # PVE::Storage utility functions
122 return cfs_read_file
("storage.cfg");
128 cfs_write_file
('storage.cfg', $cfg);
131 sub lock_storage_config
{
132 my ($code, $errmsg) = @_;
134 cfs_lock_file
("storage.cfg", undef, $code);
137 $errmsg ?
die "$errmsg: $err" : die $err;
141 # FIXME remove maxfiles for PVE 8.0 or PVE 9.0
142 my $convert_maxfiles_to_prune_backups = sub {
147 my $maxfiles = delete $scfg->{maxfiles
};
149 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
152 $prune_backups = { 'keep-last' => $maxfiles };
153 } else { # maxfiles 0 means no limit
154 $prune_backups = { 'keep-all' => 1 };
156 $scfg->{'prune-backups'} = PVE
::JSONSchema
::print_property_string
(
164 my ($cfg, $storeid, $noerr) = @_;
166 die "no storage ID specified\n" if !$storeid;
168 my $scfg = $cfg->{ids
}->{$storeid};
170 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
172 $convert_maxfiles_to_prune_backups->($scfg);
177 sub storage_check_node
{
178 my ($cfg, $storeid, $node, $noerr) = @_;
180 my $scfg = storage_config
($cfg, $storeid);
182 if ($scfg->{nodes
}) {
183 $node = PVE
::INotify
::nodename
() if !$node || ($node eq 'localhost');
184 if (!$scfg->{nodes
}->{$node}) {
185 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
193 sub storage_check_enabled
{
194 my ($cfg, $storeid, $node, $noerr) = @_;
196 my $scfg = storage_config
($cfg, $storeid);
198 if ($scfg->{disable
}) {
199 die "storage '$storeid' is disabled\n" if !$noerr;
203 return storage_check_node
($cfg, $storeid, $node, $noerr);
206 # storage_can_replicate:
207 # return true if storage supports replication
208 # (volumes allocated with vdisk_alloc() has replication feature)
209 sub storage_can_replicate
{
210 my ($cfg, $storeid, $format) = @_;
212 my $scfg = storage_config
($cfg, $storeid);
213 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
214 return $plugin->storage_can_replicate($scfg, $storeid, $format);
217 sub get_max_protected_backups
{
218 my ($scfg, $storeid) = @_;
220 return $scfg->{'max-protected-backups'} if defined($scfg->{'max-protected-backups'});
222 my $rpcenv = PVE
::RPCEnvironment
::get
();
223 my $authuser = $rpcenv->get_user();
225 return $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.Allocate'], 1) ?
-1 : 5;
231 return keys %{$cfg->{ids
}};
235 my ($filename, $timeout) = @_;
237 return PVE
::Storage
::Plugin
::file_size_info
($filename, $timeout);
240 sub get_volume_attribute
{
241 my ($cfg, $volid, $attribute) = @_;
243 my ($storeid, $volname) = parse_volume_id
($volid);
244 my $scfg = storage_config
($cfg, $storeid);
245 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
247 return $plugin->get_volume_attribute($scfg, $storeid, $volname, $attribute);
250 sub update_volume_attribute
{
251 my ($cfg, $volid, $attribute, $value) = @_;
253 my ($storeid, $volname) = parse_volume_id
($volid);
254 my $scfg = storage_config
($cfg, $storeid);
255 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
257 my ($vtype, undef, $vmid) = $plugin->parse_volname($volname);
258 my $max_protected_backups = get_max_protected_backups
($scfg, $storeid);
263 && $attribute eq 'protected'
265 && !$plugin->get_volume_attribute($scfg, $storeid, $volname, 'protected')
266 && $max_protected_backups > -1 # -1 is unlimited
268 my $backups = $plugin->list_volumes($storeid, $scfg, $vmid, ['backup']);
269 my ($backup_type) = map { $_->{subtype
} } grep { $_->{volid
} eq $volid } $backups->@*;
271 my $protected_count = grep {
272 $_->{protected
} && (!$backup_type || ($_->{subtype
} && $_->{subtype
} eq $backup_type))
275 if ($max_protected_backups <= $protected_count) {
276 die "The number of protected backups per guest is limited to $max_protected_backups ".
277 "on storage '$storeid'\n";
281 return $plugin->update_volume_attribute($scfg, $storeid, $volname, $attribute, $value);
284 sub volume_size_info
{
285 my ($cfg, $volid, $timeout) = @_;
287 my ($storeid, $volname) = parse_volume_id
($volid, 1);
289 my $scfg = storage_config
($cfg, $storeid);
290 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
291 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
292 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
293 return file_size_info
($volid, $timeout);
300 my ($cfg, $volid, $size, $running) = @_;
302 my $padding = (1024 - $size % 1024) % 1024;
303 $size = $size + $padding;
305 my ($storeid, $volname) = parse_volume_id
($volid, 1);
307 my $scfg = storage_config
($cfg, $storeid);
308 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
309 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
310 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
311 die "resize file/device '$volid' is not possible\n";
313 die "unable to parse volume ID '$volid'\n";
317 sub volume_rollback_is_possible
{
318 my ($cfg, $volid, $snap, $blockers) = @_;
320 my ($storeid, $volname) = parse_volume_id
($volid, 1);
322 my $scfg = storage_config
($cfg, $storeid);
323 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
324 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap, $blockers);
325 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
326 die "snapshot rollback file/device '$volid' is not possible\n";
328 die "unable to parse volume ID '$volid'\n";
332 sub volume_snapshot
{
333 my ($cfg, $volid, $snap) = @_;
335 my ($storeid, $volname) = parse_volume_id
($volid, 1);
337 my $scfg = storage_config
($cfg, $storeid);
338 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
339 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
340 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
341 die "snapshot file/device '$volid' is not possible\n";
343 die "unable to parse volume ID '$volid'\n";
347 sub volume_snapshot_rollback
{
348 my ($cfg, $volid, $snap) = @_;
350 my ($storeid, $volname) = parse_volume_id
($volid, 1);
352 my $scfg = storage_config
($cfg, $storeid);
353 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
354 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
355 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
356 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
357 die "snapshot rollback file/device '$volid' is not possible\n";
359 die "unable to parse volume ID '$volid'\n";
363 sub volume_snapshot_delete
{
364 my ($cfg, $volid, $snap, $running) = @_;
366 my ($storeid, $volname) = parse_volume_id
($volid, 1);
368 my $scfg = storage_config
($cfg, $storeid);
369 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
370 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
371 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
372 die "snapshot delete file/device '$volid' is not possible\n";
374 die "unable to parse volume ID '$volid'\n";
378 # check if a filesystem on top of a volume needs to flush its journal for
379 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
380 # container mountpoints
381 sub volume_snapshot_needs_fsfreeze
{
382 my ($cfg, $volid) = @_;
384 my ($storeid, $volname) = parse_volume_id
($volid);
385 my $scfg = storage_config
($cfg, $storeid);
386 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
387 return $plugin->volume_snapshot_needs_fsfreeze();
390 # check if a volume or snapshot supports a given feature
392 # clone - linked clone is possible
393 # copy - full clone is possible
394 # replicate - replication is possible
395 # snapshot - taking a snapshot is possible
396 # sparseinit - volume is sparsely initialized
397 # template - conversion to base image is possible
398 # rename - renaming volumes is possible
399 # $snap - check if the feature is supported for a given snapshot
400 # $running - if the guest owning the volume is running
401 # $opts - hash with further options:
402 # valid_target_formats - list of formats for the target of a copy/clone
403 # operation that the caller could work with. The
404 # format of $volid is always considered valid and if
405 # no list is specified, all formats are considered valid.
406 sub volume_has_feature
{
407 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
409 my ($storeid, $volname) = parse_volume_id
($volid, 1);
411 my $scfg = storage_config
($cfg, $storeid);
412 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
413 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
414 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
421 sub volume_snapshot_info
{
422 my ($cfg, $volid) = @_;
424 my ($storeid, $volname) = parse_volume_id
($volid);
425 my $scfg = storage_config
($cfg, $storeid);
426 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
427 return $plugin->volume_snapshot_info($scfg, $storeid, $volname);
431 my ($cfg, $storeid, $vmid) = @_;
433 my $scfg = storage_config
($cfg, $storeid);
434 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
436 my $path = $plugin->get_subdir($scfg, 'images');
438 return $vmid ?
"$path/$vmid" : $path;
441 sub get_private_dir
{
442 my ($cfg, $storeid, $vmid) = @_;
444 my $scfg = storage_config
($cfg, $storeid);
445 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
447 my $path = $plugin->get_subdir($scfg, 'rootdir');
449 return $vmid ?
"$path/$vmid" : $path;
453 my ($cfg, $storeid) = @_;
455 my $scfg = storage_config
($cfg, $storeid);
456 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
458 return $plugin->get_subdir($scfg, 'iso');
462 my ($cfg, $storeid) = @_;
464 my $scfg = storage_config
($cfg, $storeid);
465 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
467 return $plugin->get_subdir($scfg, 'vztmpl');
471 my ($cfg, $storeid) = @_;
473 my $scfg = storage_config
($cfg, $storeid);
474 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
476 return $plugin->get_subdir($scfg, 'backup');
479 # library implementation
484 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
489 # NOTE: basename and basevmid are always undef for LVM-thin, where the
490 # clone -> base reference is not encoded in the volume ID.
491 # see note in PVE::Storage::LvmThinPlugin for details.
493 my ($cfg, $volid) = @_;
495 my ($storeid, $volname) = parse_volume_id
($volid);
497 my $scfg = storage_config
($cfg, $storeid);
499 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
501 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
503 return $plugin->parse_volname($volname);
506 sub parse_volume_id
{
507 my ($volid, $noerr) = @_;
509 return PVE
::Storage
::Plugin
::parse_volume_id
($volid, $noerr);
512 # test if we have read access to volid
513 sub check_volume_access
{
514 my ($rpcenv, $user, $cfg, $vmid, $volid, $type) = @_;
516 my ($sid, $volname) = parse_volume_id
($volid, 1);
518 my ($vtype, undef, $ownervm) = parse_volname
($cfg, $volid);
520 # Need to allow 'images' when expecting 'rootdir' too - not cleanly separated in plugins.
521 die "unable to use volume $volid - content type needs to be '$type'\n"
522 if defined($type) && $vtype ne $type && ($type ne 'rootdir' || $vtype ne 'images');
524 return if $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate'], 1);
526 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
527 # require at least read access to storage, (custom) templates/ISOs could be sensitive
528 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
529 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
530 # we are owner - allow access
531 } elsif ($vtype eq 'backup' && $ownervm) {
532 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
533 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
534 } elsif (($vtype eq 'images' || $vtype eq 'rootdir') && $ownervm) {
535 $rpcenv->check($user, "/storage/$sid", ['Datastore.Audit']);
536 $rpcenv->check($user, "/vms/$ownervm", ['VM.Config.Disk']);
538 die "missing privileges to access $volid\n";
541 die "Only root can pass arbitrary filesystem paths."
542 if $user ne 'root@pam';
548 # NOTE: this check does not work for LVM-thin, where the clone -> base
549 # reference is not encoded in the volume ID.
550 # see note in PVE::Storage::LvmThinPlugin for details.
551 sub volume_is_base_and_used
{
552 my ($cfg, $volid) = @_;
554 my ($storeid, $volname) = parse_volume_id
($volid);
555 my $scfg = storage_config
($cfg, $storeid);
556 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
558 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
559 $plugin->parse_volname($volname);
562 my $vollist = $plugin->list_images($storeid, $scfg);
563 foreach my $info (@$vollist) {
564 my (undef, $tmpvolname) = parse_volume_id
($info->{volid
});
565 my $basename = undef;
566 my $basevmid = undef;
569 (undef, undef, undef, $basename, $basevmid) =
570 $plugin->parse_volname($tmpvolname);
573 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
581 # try to map a filesystem path to a volume identifier
582 sub path_to_volume_id
{
583 my ($cfg, $path) = @_;
585 my $ids = $cfg->{ids
};
587 my ($sid, $volname) = parse_volume_id
($path, 1);
589 if (my $scfg = $ids->{$sid}) {
591 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
592 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
593 return ($vtype, $path);
599 # Note: abs_path() return undef if $path doesn not exist
600 # for example when nfs storage is not mounted
601 $path = abs_path
($path) || $path;
603 foreach my $sid (keys %$ids) {
604 my $scfg = $ids->{$sid};
605 next if !$scfg->{path
};
606 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
607 my $imagedir = $plugin->get_subdir($scfg, 'images');
608 my $isodir = $plugin->get_subdir($scfg, 'iso');
609 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
610 my $backupdir = $plugin->get_subdir($scfg, 'backup');
611 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
612 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
614 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
618 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
619 foreach my $info (@$vollist) {
620 my ($storeid, $volname) = parse_volume_id
($info->{volid
});
621 my $volpath = $plugin->path($scfg, $volname, $storeid);
622 if ($volpath eq $path) {
623 return ('images', $info->{volid
});
626 } elsif ($path =~ m!^$isodir/([^/]+$ISO_EXT_RE_0)$!) {
628 return ('iso', "$sid:iso/$name");
629 } elsif ($path =~ m!^$tmpldir/([^/]+$VZTMPL_EXT_RE_1)$!) {
631 return ('vztmpl', "$sid:vztmpl/$name");
632 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
634 return ('rootdir', "$sid:rootdir/$vmid");
635 } elsif ($path =~ m!^$backupdir/([^/]+$BACKUP_EXT_RE_2)$!) {
637 return ('backup', "$sid:backup/$name");
638 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
640 return ('snippets', "$sid:snippets/$name");
644 # can't map path to volume id
649 my ($cfg, $volid, $snapname) = @_;
651 my ($storeid, $volname) = parse_volume_id
($volid);
653 my $scfg = storage_config
($cfg, $storeid);
655 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
656 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
657 return wantarray ?
($path, $owner, $vtype) : $path;
660 sub abs_filesystem_path
{
661 my ($cfg, $volid, $allow_blockdev) = @_;
664 if (parse_volume_id
($volid, 1)) {
665 activate_volumes
($cfg, [ $volid ]);
666 $path = PVE
::Storage
::path
($cfg, $volid);
668 if (-f
$volid || ($allow_blockdev && -b
$volid)) {
669 my $abspath = abs_path
($volid);
670 if ($abspath && $abspath =~ m
|^(/.+)$|) {
671 $path = $1; # untaint any path
675 die "can't find file '$volid'\n"
676 if !($path && (-f
$path || ($allow_blockdev && -b
$path)));
681 # used as last resort to adapt volnames when migrating
682 my $volname_for_storage = sub {
683 my ($cfg, $storeid, $name, $vmid, $format) = @_;
685 my $scfg = storage_config
($cfg, $storeid);
687 my (undef, $valid_formats) = PVE
::Storage
::Plugin
::default_format
($scfg);
688 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
689 die "unsupported format '$format' for storage type $scfg->{type}\n"
690 if !$format_is_valid;
692 (my $name_without_extension = $name) =~ s/\.$format$//;
695 return "$vmid/$name_without_extension.$format";
697 return "$name_without_extension";
701 # whether a migration snapshot is needed for a given storage
702 sub storage_migrate_snapshot
{
703 my ($cfg, $storeid, $existing_snapshots) = @_;
704 my $scfg = storage_config
($cfg, $storeid);
706 return $scfg->{type
} eq 'zfspool' || ($scfg->{type
} eq 'btrfs' && $existing_snapshots);
709 my $volume_import_prepare = sub {
710 my ($volid, $format, $path, $apiver, $opts) = @_;
712 my $base_snapshot = $opts->{base_snapshot
};
713 my $snapshot = $opts->{snapshot
};
714 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
715 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
716 my $allow_rename = $opts->{allow_rename
} ?
1 : 0;
718 my $recv = ['pvesm', 'import', $volid, $format, $path, '-with-snapshots', $with_snapshots];
719 if (defined($snapshot)) {
720 push @$recv, '-snapshot', $snapshot;
722 if ($migration_snapshot) {
723 push @$recv, '-delete-snapshot', $snapshot;
725 push @$recv, '-allow-rename', $allow_rename if $apiver >= 5;
727 if (defined($base_snapshot)) {
728 # Check if the snapshot exists on the remote side:
729 push @$recv, '-base', $base_snapshot if $apiver >= 9;
735 my $volume_export_prepare = sub {
736 my ($cfg, $volid, $format, $logfunc, $opts) = @_;
737 my $base_snapshot = $opts->{base_snapshot
};
738 my $snapshot = $opts->{snapshot
};
739 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
740 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
741 my $ratelimit_bps = $opts->{ratelimit_bps
};
743 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
744 if (defined($snapshot)) {
745 push @$send, '-snapshot', $snapshot;
747 if (defined($base_snapshot)) {
748 push @$send, '-base', $base_snapshot;
752 if (defined($ratelimit_bps)) {
753 $cstream = [ '/usr/bin/cstream', '-t', $ratelimit_bps ];
754 $logfunc->("using a bandwidth limit of $ratelimit_bps bps for transferring '$volid'") if $logfunc;
757 volume_snapshot
($cfg, $volid, $snapshot) if $migration_snapshot;
759 if (defined($snapshot)) {
760 activate_volumes
($cfg, [$volid], $snapshot);
762 activate_volumes
($cfg, [$volid]);
765 return $cstream ?
[ $send, $cstream ] : [ $send ];
768 sub storage_migrate
{
769 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
771 my $insecure = $opts->{insecure
};
773 my ($storeid, $volname) = parse_volume_id
($volid);
775 my $scfg = storage_config
($cfg, $storeid);
777 # no need to migrate shared content
778 return $volid if $storeid eq $target_storeid && $scfg->{shared
};
780 my $tcfg = storage_config
($cfg, $target_storeid);
783 if ($opts->{target_volname
}) {
784 $target_volname = $opts->{target_volname
};
785 } elsif ($scfg->{type
} eq $tcfg->{type
}) {
786 $target_volname = $volname;
788 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname
($cfg, $volid);
789 $target_volname = $volname_for_storage->($cfg, $target_storeid, $name, $vmid, $format);
792 my $target_volid = "${target_storeid}:${target_volname}";
794 my $target_ip = $target_sshinfo->{ip
};
796 my $ssh = PVE
::SSHInfo
::ssh_info_to_command
($target_sshinfo);
797 my $ssh_base = PVE
::SSHInfo
::ssh_info_to_command_base
($target_sshinfo);
798 local $ENV{RSYNC_RSH
} = PVE
::Tools
::cmd2string
($ssh_base);
800 if (!defined($opts->{snapshot
})) {
801 $opts->{migration_snapshot
} = storage_migrate_snapshot
($cfg, $storeid, $opts->{with_snapshots
});
802 $opts->{snapshot
} = '__migration__' if $opts->{migration_snapshot
};
805 my @formats = volume_transfer_formats
($cfg, $volid, $target_volid, $opts->{snapshot
}, $opts->{base_snapshot
}, $opts->{with_snapshots
});
806 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
807 my $format = $formats[0];
809 my $import_fn = '-'; # let pvesm import read from stdin per default
811 my $net = $target_sshinfo->{network
} // $target_sshinfo->{ip
};
812 $import_fn = "tcp://$net";
815 my $target_apiver = 1; # if there is no apiinfo call, assume 1
816 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
817 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
818 eval { run_command
($get_api_version, logfunc
=> $match_api_version); };
820 my $recv = [ @$ssh, '--', $volume_import_prepare->($target_volid, $format, $import_fn, $target_apiver, $opts)->@* ];
823 my $pattern = volume_imported_message
(undef, 1);
824 my $match_volid_and_log = sub {
827 $new_volid = $1 if ($line =~ $pattern);
835 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
839 my $input = IO
::File-
>new();
840 my $info = IO
::File-
>new();
841 open3
($input, $info, $info, @$recv)
842 or die "receive command failed: $!\n";
845 my $try_ip = <$info> // '';
846 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
847 or die "no tunnel IP received, got '$try_ip'\n";
849 my $try_port = <$info> // '';
850 my ($port) = $try_port =~ /^(\d+)$/ # untaint
851 or die "no tunnel port received, got '$try_port'\n";
853 my $socket = IO
::Socket
::IP-
>new(PeerHost
=> $ip, PeerPort
=> $port, Type
=> SOCK_STREAM
)
854 or die "failed to connect to tunnel at $ip:$port\n";
855 # we won't be reading from the socket
856 shutdown($socket, 0);
858 eval { run_command
($cmds, output
=> '>&'.fileno($socket), errfunc
=> $logfunc); };
861 # don't close the connection entirely otherwise the receiving end
862 # might not get all buffered data (and fails with 'connection reset by peer')
863 shutdown($socket, 1);
865 # wait for the remote process to finish
866 while (my $line = <$info>) {
867 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
870 # now close the socket
872 if (!close($info)) { # does waitpid()
873 die "import failed: $!\n" if $!;
874 die "import failed: exit code ".($?>>8)."\n";
877 die $send_error if $send_error;
880 run_command
($cmds, logfunc
=> $match_volid_and_log);
883 die "unable to get ID of the migrated volume\n"
884 if !defined($new_volid) && $target_apiver >= 5;
887 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
888 if ($opts->{migration_snapshot
}) {
889 eval { volume_snapshot_delete
($cfg, $volid, $opts->{snapshot
}, 0) };
890 warn "could not remove source snapshot: $@\n" if $@;
894 return $new_volid // $target_volid;
898 my ($cfg, $volid, $vmid, $snap) = @_;
900 my ($storeid, $volname) = parse_volume_id
($volid);
902 my $scfg = storage_config
($cfg, $storeid);
904 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
906 activate_storage
($cfg, $storeid);
908 # lock shared storage
909 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
910 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
911 return "$storeid:$volname";
915 sub vdisk_create_base
{
916 my ($cfg, $volid) = @_;
918 my ($storeid, $volname) = parse_volume_id
($volid);
920 my $scfg = storage_config
($cfg, $storeid);
922 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
924 activate_storage
($cfg, $storeid);
926 # lock shared storage
927 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
928 my $volname = $plugin->create_base($storeid, $scfg, $volname);
929 return "$storeid:$volname";
934 my ($cfg, $volid, $snapname) = @_;
936 my ($storeid, $volname) = parse_volume_id
($volid);
938 my $scfg = storage_config
($cfg, $storeid);
940 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
942 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
946 my ($cfg, $volid, $snapname) = @_;
948 my ($storeid, $volname) = parse_volume_id
($volid);
950 my $scfg = storage_config
($cfg, $storeid);
952 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
954 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
958 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
960 die "no storage ID specified\n" if !$storeid;
962 PVE
::JSONSchema
::parse_storage_id
($storeid);
964 my $scfg = storage_config
($cfg, $storeid);
966 die "no VMID specified\n" if !$vmid;
968 $vmid = parse_vmid
($vmid);
970 my $defformat = PVE
::Storage
::Plugin
::default_format
($scfg);
972 $fmt = $defformat if !$fmt;
974 activate_storage
($cfg, $storeid);
976 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
978 # lock shared storage
979 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
980 my $old_umask = umask(umask|0037);
981 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
985 return "$storeid:$volname";
990 my ($cfg, $volid) = @_;
992 my ($storeid, $volname) = parse_volume_id
($volid);
993 my $scfg = storage_config
($cfg, $storeid);
994 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
996 activate_storage
($cfg, $storeid);
1000 # lock shared storage
1001 $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
1002 # LVM-thin allows deletion of still referenced base volumes!
1003 die "base volume '$volname' is still in use by linked clones\n"
1004 if volume_is_base_and_used
($cfg, $volid);
1006 my (undef, undef, undef, undef, undef, $isBase, $format) =
1007 $plugin->parse_volname($volname);
1008 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1011 return if !$cleanup_worker;
1013 my $rpcenv = PVE
::RPCEnvironment
::get
();
1014 my $authuser = $rpcenv->get_user();
1016 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
1020 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
1022 my $ids = $cfg->{ids
};
1024 storage_check_enabled
($cfg, $storeid) if ($storeid);
1026 my $res = $storeid ?
{ $storeid => [] } : {};
1028 # prepare/activate/refresh all storages
1030 my $storage_list = [];
1032 foreach my $volid (@$vollist) {
1033 my ($sid, undef) = parse_volume_id
($volid);
1034 next if !defined($ids->{$sid});
1035 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1036 push @$storage_list, $sid;
1039 foreach my $sid (keys %$ids) {
1040 next if $storeid && $storeid ne $sid;
1041 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1042 my $content = $ids->{$sid}->{content
};
1043 next if defined($ctype) && !$content->{$ctype};
1044 next if !($content->{rootdir
} || $content->{images
});
1045 push @$storage_list, $sid;
1051 activate_storage_list
($cfg, $storage_list, $cache);
1053 for my $sid ($storage_list->@*) {
1054 next if $storeid && $storeid ne $sid;
1056 my $scfg = $ids->{$sid};
1057 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1058 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
1059 @{$res->{$sid}} = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @{$res->{$sid}} if $res->{$sid};
1066 my ($cfg, $storeid, $tt) = @_;
1068 die "unknown template type '$tt'\n"
1069 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1071 my $ids = $cfg->{ids
};
1073 storage_check_enabled
($cfg, $storeid) if ($storeid);
1078 foreach my $sid (keys %$ids) {
1079 next if $storeid && $storeid ne $sid;
1081 my $scfg = $ids->{$sid};
1082 my $type = $scfg->{type
};
1084 next if !$scfg->{content
}->{$tt};
1086 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1088 $res->{$sid} = volume_list
($cfg, $sid, undef, $tt);
1095 my ($cfg, $storeid, $vmid, $content) = @_;
1097 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
1099 my $cts = $content ?
[ $content ] : [ @ctypes ];
1101 my $scfg = PVE
::Storage
::storage_config
($cfg, $storeid);
1103 $cts = [ grep { defined($scfg->{content
}->{$_}) } @$cts ];
1105 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1107 activate_storage
($cfg, $storeid);
1109 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1111 @$res = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @$res;
1118 my $filename = "/sys/kernel/uevent_seqnum";
1121 if (my $fh = IO
::File-
>new($filename, "r")) {
1123 if ($line =~ m/^(\d+)$/) {
1131 sub activate_storage
{
1132 my ($cfg, $storeid, $cache) = @_;
1134 $cache = {} if !$cache;
1136 my $scfg = storage_check_enabled
($cfg, $storeid);
1138 return if $cache->{activated
}->{$storeid};
1140 $cache->{uevent_seqnum
} = uevent_seqnum
() if !$cache->{uevent_seqnum
};
1142 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1144 if ($scfg->{base
}) {
1145 my ($baseid, undef) = parse_volume_id
($scfg->{base
});
1146 activate_storage
($cfg, $baseid, $cache);
1149 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1150 die "connection check for storage '$storeid' failed - $@\n" if $@;
1151 die "storage '$storeid' is not online\n";
1154 $plugin->activate_storage($storeid, $scfg, $cache);
1156 my $newseq = uevent_seqnum
();
1158 # only call udevsettle if there are events
1159 if ($newseq > $cache->{uevent_seqnum
}) {
1160 system ("udevadm settle --timeout=30"); # ignore errors
1161 $cache->{uevent_seqnum
} = $newseq;
1164 $cache->{activated
}->{$storeid} = 1;
1167 sub activate_storage_list
{
1168 my ($cfg, $storeid_list, $cache) = @_;
1170 $cache = {} if !$cache;
1172 foreach my $storeid (@$storeid_list) {
1173 activate_storage
($cfg, $storeid, $cache);
1177 sub deactivate_storage
{
1178 my ($cfg, $storeid) = @_;
1180 my $scfg = storage_config
($cfg, $storeid);
1181 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1184 $plugin->deactivate_storage($storeid, $scfg, $cache);
1187 sub activate_volumes
{
1188 my ($cfg, $vollist, $snapname) = @_;
1190 return if !($vollist && scalar(@$vollist));
1192 my $storagehash = {};
1193 foreach my $volid (@$vollist) {
1194 my ($storeid, undef) = parse_volume_id
($volid);
1195 $storagehash->{$storeid} = 1;
1200 activate_storage_list
($cfg, [keys %$storagehash], $cache);
1202 foreach my $volid (@$vollist) {
1203 my ($storeid, $volname) = parse_volume_id
($volid);
1204 my $scfg = storage_config
($cfg, $storeid);
1205 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1206 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1210 sub deactivate_volumes
{
1211 my ($cfg, $vollist, $snapname) = @_;
1213 return if !($vollist && scalar(@$vollist));
1218 foreach my $volid (@$vollist) {
1219 my ($storeid, $volname) = parse_volume_id
($volid);
1221 my $scfg = storage_config
($cfg, $storeid);
1222 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1225 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1229 push @errlist, $volid;
1233 die "volume deactivation failed: " . join(' ', @errlist)
1234 if scalar(@errlist);
1238 my ($cfg, $content, $includeformat) = @_;
1240 my $ids = $cfg->{ids
};
1244 my @ctypes = PVE
::Tools
::split_list
($content);
1247 foreach my $storeid (keys %$ids) {
1248 my $storage_enabled = defined(storage_check_enabled
($cfg, $storeid, undef, 1));
1250 if (defined($content)) {
1252 foreach my $ctype (@ctypes) {
1253 if ($ids->{$storeid}->{content
}->{$ctype}) {
1258 next if !$want_ctype || !$storage_enabled;
1261 my $type = $ids->{$storeid}->{type
};
1263 $info->{$storeid} = {
1268 shared
=> $ids->{$storeid}->{shared
} ?
1 : 0,
1269 content
=> PVE
::Storage
::Plugin
::content_hash_to_string
($ids->{$storeid}->{content
}),
1271 enabled
=> $storage_enabled ?
1 : 0,
1274 push @$slist, $storeid;
1279 foreach my $storeid (keys %$ids) {
1280 my $scfg = $ids->{$storeid};
1282 next if !$info->{$storeid};
1283 next if !$info->{$storeid}->{enabled
};
1285 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1286 if ($includeformat) {
1287 my $pd = $plugin->plugindata();
1288 $info->{$storeid}->{format
} = $pd->{format
}
1290 $info->{$storeid}->{select_existing
} = $pd->{select_existing
}
1291 if $pd->{select_existing
};
1294 eval { activate_storage
($cfg, $storeid, $cache); };
1300 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1303 $info->{$storeid}->{total
} = int($total);
1304 $info->{$storeid}->{avail
} = int($avail);
1305 $info->{$storeid}->{used
} = int($used);
1306 $info->{$storeid}->{active
} = $active;
1315 my ($packed_ip, $family);
1317 my @res = PVE
::Tools
::getaddrinfo_all
($server);
1318 $family = $res[0]->{family
};
1319 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
1321 if (defined $packed_ip) {
1322 return Socket
::inet_ntop
($family, $packed_ip);
1328 my ($server_in) = @_;
1331 if (!($server = resolv_server
($server_in))) {
1332 die "unable to resolve address for server '${server_in}'\n";
1335 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1338 run_command
($cmd, outfunc
=> sub {
1341 # note: howto handle white spaces in export path??
1342 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1351 my ($server_in, $user, $password, $domain) = @_;
1353 my $server = resolv_server
($server_in);
1354 die "unable to resolve address for server '${server_in}'\n" if !$server;
1356 # we only support Windows 2012 and newer, so just use smb3
1357 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1358 push @$cmd, '-W', $domain if defined($domain);
1360 push @$cmd, '-N' if !defined($password);
1361 local $ENV{USER
} = $user if defined($user);
1362 local $ENV{PASSWD
} = $password if defined($password);
1373 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1375 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1377 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1381 # only die if we got no share, else it's just some followup check error
1382 # (like workgroup querying)
1383 raise
($err) if $err && !%$res;
1390 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1393 run_command
($cmd, outfunc
=> sub {
1396 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1397 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1398 my $size = $size_str + 0;
1399 my $used = $used_str + 0;
1400 # ignore subvolumes generated by our ZFSPoolPlugin
1401 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1402 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1403 push @$res, { pool
=> $pool, size
=> $size, free
=> $size-$used };
1411 my ($portal, $noerr) = @_;
1413 my ($server, $port) = PVE
::Tools
::parse_host_and_port
($portal);
1415 if (my $ip = resolv_server
($server)) {
1417 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1418 return $port ?
"$server:$port" : $server;
1421 return undef if $noerr;
1423 raise_param_exc
({ portal
=> "unable to resolve portal address '$portal'" });
1428 my ($portal_in) = @_;
1431 if (!($portal = resolv_portal
($portal_in))) {
1432 die "unable to parse/resolve portal address '${portal_in}'\n";
1435 return PVE
::Storage
::ISCSIPlugin
::iscsi_discovery
($portal);
1438 sub storage_default_format
{
1439 my ($cfg, $storeid) = @_;
1441 my $scfg = storage_config
($cfg, $storeid);
1443 return PVE
::Storage
::Plugin
::default_format
($scfg);
1446 sub vgroup_is_used
{
1447 my ($cfg, $vgname) = @_;
1449 foreach my $storeid (keys %{$cfg->{ids
}}) {
1450 my $scfg = storage_config
($cfg, $storeid);
1451 if ($scfg->{type
} eq 'lvm' && $scfg->{vgname
} eq $vgname) {
1459 sub target_is_used
{
1460 my ($cfg, $target) = @_;
1462 foreach my $storeid (keys %{$cfg->{ids
}}) {
1463 my $scfg = storage_config
($cfg, $storeid);
1464 if ($scfg->{type
} eq 'iscsi' && $scfg->{target
} eq $target) {
1472 sub volume_is_used
{
1473 my ($cfg, $volid) = @_;
1475 foreach my $storeid (keys %{$cfg->{ids
}}) {
1476 my $scfg = storage_config
($cfg, $storeid);
1477 if ($scfg->{base
} && $scfg->{base
} eq $volid) {
1485 sub storage_is_used
{
1486 my ($cfg, $storeid) = @_;
1488 foreach my $sid (keys %{$cfg->{ids
}}) {
1489 my $scfg = storage_config
($cfg, $sid);
1490 next if !$scfg->{base
};
1491 my ($st) = parse_volume_id
($scfg->{base
});
1492 return 1 if $st && $st eq $storeid;
1499 my ($list, $func) = @_;
1503 foreach my $sid (keys %$list) {
1504 foreach my $info (@{$list->{$sid}}) {
1505 my $volid = $info->{volid
};
1506 my ($sid1, $volname) = parse_volume_id
($volid, 1);
1507 if ($sid1 && $sid1 eq $sid) {
1508 &$func ($volid, $sid, $info);
1510 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1516 sub decompressor_info
{
1517 my ($format, $comp) = @_;
1519 if ($format eq 'tgz' && !defined($comp)) {
1520 ($format, $comp) = ('tar', 'gz');
1523 my $decompressor = {
1525 gz
=> ['tar', '-z'],
1526 lzo
=> ['tar', '--lzop'],
1527 zst
=> ['tar', '--zstd'],
1531 lzo
=> ['lzop', '-d', '-c'],
1532 zst
=> ['zstd', '-q', '-d', '-c'],
1536 die "ERROR: archive format not defined\n"
1537 if !defined($decompressor->{$format});
1540 $decomp = $decompressor->{$format}->{$comp} if $comp;
1544 compression
=> $comp,
1545 decompressor
=> $decomp,
1551 sub protection_file_path
{
1554 return "${path}.protected";
1558 my ($archive) = shift;
1561 my $volid = basename
($archive);
1562 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
1563 my $filename = "$1"; # untaint
1564 my ($type, $extension, $comp) = ($2, $3, $4);
1565 (my $format = $extension) =~ s/\..*//;
1566 $info = decompressor_info
($format, $comp);
1567 $info->{filename
} = $filename;
1568 $info->{type
} = $type;
1570 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${extension}$/) {
1571 $info->{logfilename
} = "$1".PVE
::Storage
::Plugin
::LOG_EXT
;
1572 $info->{notesfilename
} = "$filename".PVE
::Storage
::Plugin
::NOTES_EXT
;
1573 $info->{vmid
} = int($2);
1574 $info->{ctime
} = timelocal
($8, $7, $6, $5, $4 - 1, $3);
1575 $info->{is_std_name
} = 1;
1577 $info->{is_std_name
} = 0;
1580 die "ERROR: couldn't determine archive info from '$archive'\n";
1586 sub archive_remove
{
1587 my ($archive_path) = @_;
1589 die "cannot remove protected archive '$archive_path'\n"
1590 if -e protection_file_path
($archive_path);
1592 unlink $archive_path or $! == ENOENT
or die "removing archive $archive_path failed: $!\n";
1594 archive_auxiliaries_remove
($archive_path);
1597 sub archive_auxiliaries_remove
{
1598 my ($archive_path) = @_;
1600 my $dirname = dirname
($archive_path);
1601 my $archive_info = eval { archive_info
($archive_path) } // {};
1603 for my $type (qw(log notes)) {
1604 my $filename = $archive_info->{"${type}filename"} or next;
1605 my $path = "$dirname/$filename";
1608 unlink $path or $! == ENOENT
or log_warn
("Removing $type file failed: $!");
1613 sub extract_vzdump_config_tar
{
1614 my ($archive, $conf_re) = @_;
1616 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
1618 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1619 die "unable to open file '$archive'\n";
1622 while (defined($file = <$fh>)) {
1623 if ($file =~ $conf_re) {
1624 $file = $1; # untaint
1633 die "ERROR: archive contains no configuration file\n" if !$file;
1639 $raw .= "$output\n";
1642 run_command
(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc
=> $out);
1644 return wantarray ?
($raw, $file) : $raw;
1647 sub extract_vzdump_config_vma
{
1648 my ($archive, $comp) = @_;
1651 my $out = sub { $raw .= "$_[0]\n"; };
1653 my $info = archive_info
($archive);
1654 $comp //= $info->{compression
};
1655 my $decompressor = $info->{decompressor
};
1658 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1660 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1665 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
1667 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1668 $errstring = "Failed to extract config from VMA archive: $output\n";
1672 my $rc = eval { run_command
($cmd, outfunc
=> $out, errfunc
=> $err, noerr
=> 1) };
1675 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1677 if (!$errstring && !$broken_pipe && $rc != 0) {
1678 die "$rerr\n" if $rerr;
1679 die "config extraction failed with exit code $rc\n";
1681 die "$errstring\n" if $errstring;
1683 run_command
(["vma", "config", $archive], outfunc
=> $out);
1686 return wantarray ?
($raw, undef) : $raw;
1689 sub extract_vzdump_config
{
1690 my ($cfg, $volid) = @_;
1692 my ($storeid, $volname) = parse_volume_id
($volid);
1693 if (defined($storeid)) {
1694 my $scfg = storage_config
($cfg, $storeid);
1695 if ($scfg->{type
} eq 'pbs') {
1696 storage_check_enabled
($cfg, $storeid);
1697 return PVE
::Storage
::PBSPlugin-
>extract_vzdump_config($scfg, $volname, $storeid);
1701 my $archive = abs_filesystem_path
($cfg, $volid);
1702 my $info = archive_info
($archive);
1703 my $format = $info->{format
};
1704 my $comp = $info->{compression
};
1705 my $type = $info->{type
};
1707 if ($type eq 'lxc' || $type eq 'openvz') {
1708 return extract_vzdump_config_tar
($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1709 } elsif ($type eq 'qemu') {
1710 if ($format eq 'tar') {
1711 return extract_vzdump_config_tar
($archive, qr!\(\./qemu-server\.conf\)!);
1713 return extract_vzdump_config_vma
($archive, $comp);
1716 die "cannot determine backup guest type for backup archive '$volid'\n";
1721 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1723 my $scfg = storage_config
($cfg, $storeid);
1724 die "storage '$storeid' does not support backups\n" if !$scfg->{content
}->{backup
};
1726 if (!defined($keep)) {
1727 die "no prune-backups options configured for storage '$storeid'\n"
1728 if !defined($scfg->{'prune-backups'});
1729 $keep = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'});
1732 activate_storage
($cfg, $storeid);
1734 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1735 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1738 my $prune_mark = sub {
1739 my ($prune_entries, $keep_count, $id_func) = @_;
1741 return if !$keep_count;
1743 my $already_included = {};
1744 my $newly_included = {};
1746 foreach my $prune_entry (@{$prune_entries}) {
1747 my $mark = $prune_entry->{mark
};
1748 my $id = $id_func->($prune_entry->{ctime
});
1749 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1752 foreach my $prune_entry (@{$prune_entries}) {
1753 my $mark = $prune_entry->{mark
};
1754 my $id = $id_func->($prune_entry->{ctime
});
1756 next if defined($mark) || $already_included->{$id};
1758 if (!$newly_included->{$id}) {
1759 last if scalar(keys %{$newly_included}) >= $keep_count;
1760 $newly_included->{$id} = 1;
1761 $prune_entry->{mark
} = 'keep';
1763 $prune_entry->{mark
} = 'remove';
1768 sub prune_mark_backup_group
{
1769 my ($backup_group, $keep) = @_;
1771 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1773 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
1774 foreach my $prune_entry (@{$backup_group}) {
1775 # preserve additional information like 'protected'
1776 next if $prune_entry->{mark
} && $prune_entry->{mark
} ne 'remove';
1777 $prune_entry->{mark
} = 'keep';
1782 my $prune_list = [ sort { $b->{ctime
} <=> $a->{ctime
} } @{$backup_group} ];
1784 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1788 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1790 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1791 return "$hour/$day/$month/$year";
1793 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1795 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1796 return "$day/$month/$year";
1798 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1800 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1801 my $iso_week = int(strftime
("%V", $sec, $min, $hour, $day, $month, $year));
1802 my $iso_week_year = int(strftime
("%G", $sec, $min, $hour, $day, $month, $year));
1803 return "$iso_week/$iso_week_year";
1805 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1807 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1808 return "$month/$year";
1810 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1812 my $year = (localtime($ctime))[5];
1816 foreach my $prune_entry (@{$prune_list}) {
1817 $prune_entry->{mark
} //= 'remove';
1821 sub volume_export
: prototype($$$$$$$) {
1822 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1824 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1825 die "cannot export volume '$volid'\n" if !$storeid;
1826 my $scfg = storage_config
($cfg, $storeid);
1827 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1828 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1829 $snapshot, $base_snapshot, $with_snapshots);
1832 sub volume_import
: prototype($$$$$$$$) {
1833 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1835 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1836 die "cannot import into volume '$volid'\n" if !$storeid;
1837 my $scfg = storage_config
($cfg, $storeid);
1838 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1839 return $plugin->volume_import(
1852 sub volume_export_formats
: prototype($$$$$) {
1853 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1855 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1856 return if !$storeid;
1857 my $scfg = storage_config
($cfg, $storeid);
1858 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1859 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1860 $snapshot, $base_snapshot,
1864 sub volume_import_formats
: prototype($$$$$) {
1865 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1867 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1868 return if !$storeid;
1869 my $scfg = storage_config
($cfg, $storeid);
1870 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1871 return $plugin->volume_import_formats(
1881 sub volume_transfer_formats
{
1882 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1883 my @export_formats = volume_export_formats
($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1884 my @import_formats = volume_import_formats
($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
1885 my %import_hash = map { $_ => 1 } @import_formats;
1886 my @common = grep { $import_hash{$_} } @export_formats;
1890 sub volume_imported_message
{
1891 my ($volid, $want_pattern) = @_;
1893 if ($want_pattern) {
1894 return qr/successfully imported '([^']*)'$/;
1896 return "successfully imported '$volid'\n";
1900 # $format and $volname are requests and might be overruled depending on $opts
1902 # - with_snapshots: passed to `pvesm import` and used to select import format
1903 # - allow_rename: passed to `pvesm import`
1904 # - export_formats: used to select common transport format
1905 # - unix: unix socket path
1906 sub volume_import_start
{
1907 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1909 my $with_snapshots = $opts->{'with_snapshots'} ?
1 : 0;
1911 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1913 my $volid = "$storeid:$volname";
1915 # find common import/export format, like volume_transfer_formats
1916 my @import_formats = PVE
::Storage
::volume_import_formats
($cfg, $volid, $opts->{snapshot
}, undef, $with_snapshots);
1917 my @export_formats = PVE
::Tools
::split_list
($opts->{export_formats
});
1918 my %import_hash = map { $_ => 1 } @import_formats;
1919 my @common = grep { $import_hash{$_} } @export_formats;
1920 die "no matching import/export format found for storage '$storeid'\n"
1922 $format = $common[0];
1924 my $input = IO
::File-
>new();
1925 my $info = IO
::File-
>new();
1927 my $unix = $opts->{unix
} // "/run/pve/storage-migrate-$vmid.$$.unix";
1928 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER
, $opts);
1931 my $cpid = open3
($input, $info, $info, @$import)
1932 or die "failed to spawn disk-import child - $!\n";
1936 PVE
::Tools
::run_with_timeout
(5, sub { $ready = <$info>; });
1939 die "failed to read readyness from disk import child: $@\n" if $@;
1951 sub volume_export_start
{
1952 my ($cfg, $volid, $format, $log, $opts) = @_;
1954 my $known_format = [ grep { $_ eq $format } $KNOWN_EXPORT_FORMATS->@* ];
1955 if (!$known_format->@*) {
1956 die "Cannot export '$volid' using unknown export format '$format'\n";
1958 $format = $known_format->[0];
1960 my $run_command_params = delete $opts->{cmd
} // {};
1962 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1964 PVE
::Tools
::run_command
($cmds, %$run_command_params);
1967 # bash completion helper
1969 sub complete_storage
{
1970 my ($cmdname, $pname, $cvalue) = @_;
1972 my $cfg = PVE
::Storage
::config
();
1974 return $cmdname eq 'add' ?
[] : [ PVE
::Storage
::storage_ids
($cfg) ];
1977 sub complete_storage_enabled
{
1978 my ($cmdname, $pname, $cvalue) = @_;
1982 my $cfg = PVE
::Storage
::config
();
1983 foreach my $sid (keys %{$cfg->{ids
}}) {
1984 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1990 sub complete_content_type
{
1991 my ($cmdname, $pname, $cvalue) = @_;
1993 return [qw(rootdir images vztmpl iso backup snippets)];
1996 sub complete_volume
{
1997 my ($cmdname, $pname, $cvalue) = @_;
2001 my $storage_list = complete_storage_enabled
();
2003 if ($cvalue =~ m/^([^:]+):/) {
2004 $storage_list = [ $1 ];
2006 if (scalar(@$storage_list) > 1) {
2007 # only list storage IDs to avoid large listings
2009 foreach my $storeid (@$storage_list) {
2010 # Hack: simply return 2 artificial values, so that
2011 # completions does not finish
2012 push @$res, "$storeid:volname", "$storeid:...";
2019 foreach my $storeid (@$storage_list) {
2020 my $vollist = PVE
::Storage
::volume_list
($cfg, $storeid);
2022 foreach my $item (@$vollist) {
2023 push @$res, $item->{volid
};
2031 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
2033 die "no source volid provided\n" if !$source_volid;
2034 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
2036 my ($storeid, $source_volname) = parse_volume_id
($source_volid);
2038 activate_storage
($cfg, $storeid);
2040 my $scfg = storage_config
($cfg, $storeid);
2041 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
2043 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
2045 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
2046 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
2050 # Various io-heavy operations require io/bandwidth limits which can be
2051 # configured on multiple levels: The global defaults in datacenter.cfg, and
2052 # per-storage overrides. When we want to do a restore from storage A to storage
2053 # B, we should take the smaller limit defined for storages A and B, and if no
2054 # such limit was specified, use the one from datacenter.cfg.
2055 sub get_bandwidth_limit
{
2056 my ($operation, $storage_list, $override) = @_;
2058 # called for each limit (global, per-storage) with the 'default' and the
2059 # $operation limit and should update $override for every limit affecting
2061 my $use_global_limits = 0;
2062 my $apply_limit = sub {
2064 if (defined($bwlimit)) {
2065 my $limits = PVE
::JSONSchema
::parse_property_string
('bwlimit', $bwlimit);
2066 my $limit = $limits->{$operation} // $limits->{default};
2067 if (defined($limit)) {
2068 if (!$override || $limit < $override) {
2074 # If there was no applicable limit, try to apply the global ones.
2075 $use_global_limits = 1;
2078 my ($rpcenv, $authuser);
2079 if (defined($override)) {
2080 $rpcenv = PVE
::RPCEnvironment-
>get();
2081 $authuser = $rpcenv->get_user();
2084 # Apply per-storage limits - if there are storages involved.
2085 if (defined($storage_list) && grep { defined($_) } $storage_list->@*) {
2086 my $config = config
();
2088 # The Datastore.Allocate permission allows us to modify the per-storage
2089 # limits, therefore it also allows us to override them.
2090 # Since we have most likely multiple storages to check, do a quick check on
2091 # the general '/storage' path to see if we can skip the checks entirely:
2092 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
2095 foreach my $storage (@$storage_list) {
2096 next if !defined($storage);
2097 # Avoid duplicate checks:
2098 next if $done{$storage};
2099 $done{$storage} = 1;
2101 # Otherwise we may still have individual /storage/$ID permissions:
2102 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
2103 # And if not: apply the limits.
2104 my $storecfg = storage_config
($config, $storage);
2105 $apply_limit->($storecfg->{bwlimit
});
2109 # Storage limits take precedence over the datacenter defaults, so if
2110 # a limit was applied:
2111 return $override if !$use_global_limits;
2114 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2115 # global default limits.
2116 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
2117 # So if we cannot modify global limits, apply them to our currently
2118 # requested override.
2119 my $dc = cfs_read_file
('datacenter.cfg');
2120 $apply_limit->($dc->{bwlimit
});
2126 # checks if the storage id is available and dies if not
2127 sub assert_sid_unused
{
2131 if (my $scfg = storage_config
($cfg, $sid, 1)) {
2132 die "storage ID '$sid' already defined\n";
2138 # removes leading/trailing spaces and (back)slashes completely
2139 # substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2140 sub normalize_content_filename
{
2141 my ($filename) = @_;
2144 $filename =~ s/^.*[\/\\]//;
2145 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;