16 use Time
::Local
qw(timelocal);
18 use PVE
::Tools
qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
19 use PVE
::Cluster
qw(cfs_read_file cfs_write_file cfs_lock_file);
20 use PVE
::DataCenterConfig
;
21 use PVE
::Exception
qw(raise_param_exc raise);
24 use PVE
::RPCEnvironment
;
27 use PVE
::Storage
::Plugin
;
28 use PVE
::Storage
::DirPlugin
;
29 use PVE
::Storage
::LVMPlugin
;
30 use PVE
::Storage
::LvmThinPlugin
;
31 use PVE
::Storage
::NFSPlugin
;
32 use PVE
::Storage
::CIFSPlugin
;
33 use PVE
::Storage
::ISCSIPlugin
;
34 use PVE
::Storage
::RBDPlugin
;
35 use PVE
::Storage
::CephFSPlugin
;
36 use PVE
::Storage
::ISCSIDirectPlugin
;
37 use PVE
::Storage
::GlusterfsPlugin
;
38 use PVE
::Storage
::ZFSPoolPlugin
;
39 use PVE
::Storage
::ZFSPlugin
;
40 use PVE
::Storage
::PBSPlugin
;
41 use PVE
::Storage
::BTRFSPlugin
;
43 # Storage API version. Increment it on changes in storage API interface.
44 use constant APIVER
=> 10;
45 # Age is the number of versions we're backward compatible with.
46 # This is like having 'current=APIVER' and age='APIAGE' in libtool,
47 # see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
48 use constant APIAGE
=> 1;
50 # load standard plugins
51 PVE
::Storage
::DirPlugin-
>register();
52 PVE
::Storage
::LVMPlugin-
>register();
53 PVE
::Storage
::LvmThinPlugin-
>register();
54 PVE
::Storage
::NFSPlugin-
>register();
55 PVE
::Storage
::CIFSPlugin-
>register();
56 PVE
::Storage
::ISCSIPlugin-
>register();
57 PVE
::Storage
::RBDPlugin-
>register();
58 PVE
::Storage
::CephFSPlugin-
>register();
59 PVE
::Storage
::ISCSIDirectPlugin-
>register();
60 PVE
::Storage
::GlusterfsPlugin-
>register();
61 PVE
::Storage
::ZFSPoolPlugin-
>register();
62 PVE
::Storage
::ZFSPlugin-
>register();
63 PVE
::Storage
::PBSPlugin-
>register();
64 PVE
::Storage
::BTRFSPlugin-
>register();
66 # load third-party plugins
67 if ( -d
'/usr/share/perl5/PVE/Storage/Custom' ) {
68 dir_glob_foreach
('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
70 my $modname = 'PVE::Storage::Custom::' . $file;
71 $modname =~ s!\.pm$!!;
72 $file = 'PVE/Storage/Custom/' . $file;
77 # Check perl interface:
78 die "not derived from PVE::Storage::Plugin\n" if !$modname->isa('PVE::Storage::Plugin');
79 die "does not provide an api() method\n" if !$modname->can('api');
80 # Check storage API version and that file is really storage plugin.
81 my $version = $modname->api();
82 die "implements an API version newer than current ($version > " . APIVER
. ")\n"
84 my $min_version = (APIVER
- APIAGE
);
85 die "API version too old, please update the plugin ($version < $min_version)\n"
86 if $version < $min_version;
87 # all OK, do import and register (i.e., "use")
91 # If we got this far and the API version is not the same, make some noise:
92 warn "Plugin \"$modname\" is implementing an older storage API
, an upgrade
is recommended
\n"
93 if $version != APIVER;
96 warn "Error loading storage plugin
\"$modname\": $@";
101 # initialize all plugins
102 PVE
::Storage
::Plugin-
>init();
104 # the following REs indicate the number or capture groups via the trailing digit
105 # CAUTION don't forget to update the digits accordingly after messing with the capture groups
107 our $ISO_EXT_RE_0 = qr/\.(?:iso|img)/i;
109 our $VZTMPL_EXT_RE_1 = qr/\.tar\.(gz|xz|zst)/i;
111 our $BACKUP_EXT_RE_2 = qr/\.(tgz|(?:tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)/;
113 # FIXME remove with PVE 8.0, add versioned breaks for pve-manager
114 our $vztmpl_extension_re = $VZTMPL_EXT_RE_1;
116 # PVE::Storage utility functions
119 return cfs_read_file
("storage.cfg");
125 cfs_write_file
('storage.cfg', $cfg);
128 sub lock_storage_config
{
129 my ($code, $errmsg) = @_;
131 cfs_lock_file
("storage.cfg", undef, $code);
134 $errmsg ?
die "$errmsg: $err" : die $err;
138 # FIXME remove maxfiles for PVE 8.0 or PVE 9.0
139 my $convert_maxfiles_to_prune_backups = sub {
144 my $maxfiles = delete $scfg->{maxfiles
};
146 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
149 $prune_backups = { 'keep-last' => $maxfiles };
150 } else { # maxfiles 0 means no limit
151 $prune_backups = { 'keep-all' => 1 };
153 $scfg->{'prune-backups'} = PVE
::JSONSchema
::print_property_string
(
161 my ($cfg, $storeid, $noerr) = @_;
163 die "no storage ID specified\n" if !$storeid;
165 my $scfg = $cfg->{ids
}->{$storeid};
167 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
169 $convert_maxfiles_to_prune_backups->($scfg);
174 sub storage_check_node
{
175 my ($cfg, $storeid, $node, $noerr) = @_;
177 my $scfg = storage_config
($cfg, $storeid);
179 if ($scfg->{nodes
}) {
180 $node = PVE
::INotify
::nodename
() if !$node || ($node eq 'localhost');
181 if (!$scfg->{nodes
}->{$node}) {
182 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
190 sub storage_check_enabled
{
191 my ($cfg, $storeid, $node, $noerr) = @_;
193 my $scfg = storage_config
($cfg, $storeid);
195 if ($scfg->{disable
}) {
196 die "storage '$storeid' is disabled\n" if !$noerr;
200 return storage_check_node
($cfg, $storeid, $node, $noerr);
203 # storage_can_replicate:
204 # return true if storage supports replication
205 # (volumes allocated with vdisk_alloc() has replication feature)
206 sub storage_can_replicate
{
207 my ($cfg, $storeid, $format) = @_;
209 my $scfg = storage_config
($cfg, $storeid);
210 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
211 return $plugin->storage_can_replicate($scfg, $storeid, $format);
217 return keys %{$cfg->{ids
}};
221 my ($filename, $timeout) = @_;
223 return PVE
::Storage
::Plugin
::file_size_info
($filename, $timeout);
226 sub get_volume_attribute
{
227 my ($cfg, $volid, $attribute) = @_;
229 my ($storeid, $volname) = parse_volume_id
($volid);
230 my $scfg = storage_config
($cfg, $storeid);
231 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
233 return $plugin->get_volume_attribute($scfg, $storeid, $volname, $attribute);
236 sub update_volume_attribute
{
237 my ($cfg, $volid, $attribute, $value) = @_;
239 my ($storeid, $volname) = parse_volume_id
($volid);
240 my $scfg = storage_config
($cfg, $storeid);
241 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
243 return $plugin->update_volume_attribute($scfg, $storeid, $volname, $attribute, $value);
246 sub volume_size_info
{
247 my ($cfg, $volid, $timeout) = @_;
249 my ($storeid, $volname) = parse_volume_id
($volid, 1);
251 my $scfg = storage_config
($cfg, $storeid);
252 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
253 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
254 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
255 return file_size_info
($volid, $timeout);
262 my ($cfg, $volid, $size, $running) = @_;
264 my $padding = (1024 - $size % 1024) % 1024;
265 $size = $size + $padding;
267 my ($storeid, $volname) = parse_volume_id
($volid, 1);
269 my $scfg = storage_config
($cfg, $storeid);
270 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
271 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
272 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
273 die "resize file/device '$volid' is not possible\n";
275 die "unable to parse volume ID '$volid'\n";
279 sub volume_rollback_is_possible
{
280 my ($cfg, $volid, $snap, $blockers) = @_;
282 my ($storeid, $volname) = parse_volume_id
($volid, 1);
284 my $scfg = storage_config
($cfg, $storeid);
285 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
286 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap, $blockers);
287 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
288 die "snapshot rollback file/device '$volid' is not possible\n";
290 die "unable to parse volume ID '$volid'\n";
294 sub volume_snapshot
{
295 my ($cfg, $volid, $snap) = @_;
297 my ($storeid, $volname) = parse_volume_id
($volid, 1);
299 my $scfg = storage_config
($cfg, $storeid);
300 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
301 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
302 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
303 die "snapshot file/device '$volid' is not possible\n";
305 die "unable to parse volume ID '$volid'\n";
309 sub volume_snapshot_rollback
{
310 my ($cfg, $volid, $snap) = @_;
312 my ($storeid, $volname) = parse_volume_id
($volid, 1);
314 my $scfg = storage_config
($cfg, $storeid);
315 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
316 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
317 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
318 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
319 die "snapshot rollback file/device '$volid' is not possible\n";
321 die "unable to parse volume ID '$volid'\n";
325 sub volume_snapshot_delete
{
326 my ($cfg, $volid, $snap, $running) = @_;
328 my ($storeid, $volname) = parse_volume_id
($volid, 1);
330 my $scfg = storage_config
($cfg, $storeid);
331 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
332 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
333 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
334 die "snapshot delete file/device '$volid' is not possible\n";
336 die "unable to parse volume ID '$volid'\n";
340 # check if a filesystem on top of a volume needs to flush its journal for
341 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
342 # container mountpoints
343 sub volume_snapshot_needs_fsfreeze
{
344 my ($cfg, $volid) = @_;
346 my ($storeid, $volname) = parse_volume_id
($volid);
347 my $scfg = storage_config
($cfg, $storeid);
348 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
349 return $plugin->volume_snapshot_needs_fsfreeze();
352 # check if a volume or snapshot supports a given feature
354 # clone - linked clone is possible
355 # copy - full clone is possible
356 # replicate - replication is possible
357 # snapshot - taking a snapshot is possible
358 # sparseinit - volume is sparsely initialized
359 # template - conversion to base image is possible
360 # rename - renaming volumes is possible
361 # $snap - check if the feature is supported for a given snapshot
362 # $running - if the guest owning the volume is running
363 # $opts - hash with further options:
364 # valid_target_formats - list of formats for the target of a copy/clone
365 # operation that the caller could work with. The
366 # format of $volid is always considered valid and if
367 # no list is specified, all formats are considered valid.
368 sub volume_has_feature
{
369 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
371 my ($storeid, $volname) = parse_volume_id
($volid, 1);
373 my $scfg = storage_config
($cfg, $storeid);
374 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
375 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
376 } elsif ($volid =~ m
|^(/.+)$| && -e
$volid) {
383 sub volume_snapshot_info
{
384 my ($cfg, $volid) = @_;
386 my ($storeid, $volname) = parse_volume_id
($volid);
387 my $scfg = storage_config
($cfg, $storeid);
388 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
389 return $plugin->volume_snapshot_info($scfg, $storeid, $volname);
393 my ($cfg, $storeid, $vmid) = @_;
395 my $scfg = storage_config
($cfg, $storeid);
396 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
398 my $path = $plugin->get_subdir($scfg, 'images');
400 return $vmid ?
"$path/$vmid" : $path;
403 sub get_private_dir
{
404 my ($cfg, $storeid, $vmid) = @_;
406 my $scfg = storage_config
($cfg, $storeid);
407 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
409 my $path = $plugin->get_subdir($scfg, 'rootdir');
411 return $vmid ?
"$path/$vmid" : $path;
415 my ($cfg, $storeid) = @_;
417 my $scfg = storage_config
($cfg, $storeid);
418 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
420 return $plugin->get_subdir($scfg, 'iso');
424 my ($cfg, $storeid) = @_;
426 my $scfg = storage_config
($cfg, $storeid);
427 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
429 return $plugin->get_subdir($scfg, 'vztmpl');
433 my ($cfg, $storeid) = @_;
435 my $scfg = storage_config
($cfg, $storeid);
436 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
438 return $plugin->get_subdir($scfg, 'backup');
441 # library implementation
446 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
451 # NOTE: basename and basevmid are always undef for LVM-thin, where the
452 # clone -> base reference is not encoded in the volume ID.
453 # see note in PVE::Storage::LvmThinPlugin for details.
455 my ($cfg, $volid) = @_;
457 my ($storeid, $volname) = parse_volume_id
($volid);
459 my $scfg = storage_config
($cfg, $storeid);
461 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
463 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
465 return $plugin->parse_volname($volname);
468 sub parse_volume_id
{
469 my ($volid, $noerr) = @_;
471 return PVE
::Storage
::Plugin
::parse_volume_id
($volid, $noerr);
474 # test if we have read access to volid
475 sub check_volume_access
{
476 my ($rpcenv, $user, $cfg, $vmid, $volid, $type) = @_;
478 my ($sid, $volname) = parse_volume_id
($volid, 1);
480 my ($vtype, undef, $ownervm) = parse_volname
($cfg, $volid);
482 # Need to allow 'images' when expecting 'rootdir' too - not cleanly separated in plugins.
483 die "unable to use volume $volid - content type needs to be '$type'\n"
484 if defined($type) && $vtype ne $type && ($type ne 'rootdir' || $vtype ne 'images');
486 return if $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate'], 1);
488 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
489 # require at least read access to storage, (custom) templates/ISOs could be sensitive
490 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
491 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
492 # we are owner - allow access
493 } elsif ($vtype eq 'backup' && $ownervm) {
494 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
495 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
496 } elsif (($vtype eq 'images' || $vtype eq 'rootdir') && $ownervm) {
497 $rpcenv->check($user, "/storage/$sid", ['Datastore.Audit']);
498 $rpcenv->check($user, "/vms/$ownervm", ['VM.Config.Disk']);
500 die "missing privileges to access $volid\n";
503 die "Only root can pass arbitrary filesystem paths."
504 if $user ne 'root@pam';
510 # NOTE: this check does not work for LVM-thin, where the clone -> base
511 # reference is not encoded in the volume ID.
512 # see note in PVE::Storage::LvmThinPlugin for details.
513 sub volume_is_base_and_used
{
514 my ($cfg, $volid) = @_;
516 my ($storeid, $volname) = parse_volume_id
($volid);
517 my $scfg = storage_config
($cfg, $storeid);
518 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
520 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
521 $plugin->parse_volname($volname);
524 my $vollist = $plugin->list_images($storeid, $scfg);
525 foreach my $info (@$vollist) {
526 my (undef, $tmpvolname) = parse_volume_id
($info->{volid
});
527 my $basename = undef;
528 my $basevmid = undef;
531 (undef, undef, undef, $basename, $basevmid) =
532 $plugin->parse_volname($tmpvolname);
535 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
543 # try to map a filesystem path to a volume identifier
544 sub path_to_volume_id
{
545 my ($cfg, $path) = @_;
547 my $ids = $cfg->{ids
};
549 my ($sid, $volname) = parse_volume_id
($path, 1);
551 if (my $scfg = $ids->{$sid}) {
553 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
554 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
555 return ($vtype, $path);
561 # Note: abs_path() return undef if $path doesn not exist
562 # for example when nfs storage is not mounted
563 $path = abs_path
($path) || $path;
565 foreach my $sid (keys %$ids) {
566 my $scfg = $ids->{$sid};
567 next if !$scfg->{path
};
568 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
569 my $imagedir = $plugin->get_subdir($scfg, 'images');
570 my $isodir = $plugin->get_subdir($scfg, 'iso');
571 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
572 my $backupdir = $plugin->get_subdir($scfg, 'backup');
573 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
574 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
576 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
580 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
581 foreach my $info (@$vollist) {
582 my ($storeid, $volname) = parse_volume_id
($info->{volid
});
583 my $volpath = $plugin->path($scfg, $volname, $storeid);
584 if ($volpath eq $path) {
585 return ('images', $info->{volid
});
588 } elsif ($path =~ m!^$isodir/([^/]+$ISO_EXT_RE_0)$!) {
590 return ('iso', "$sid:iso/$name");
591 } elsif ($path =~ m!^$tmpldir/([^/]+$VZTMPL_EXT_RE_1)$!) {
593 return ('vztmpl', "$sid:vztmpl/$name");
594 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
596 return ('rootdir', "$sid:rootdir/$vmid");
597 } elsif ($path =~ m!^$backupdir/([^/]+$BACKUP_EXT_RE_2)$!) {
599 return ('backup', "$sid:backup/$name");
600 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
602 return ('snippets', "$sid:snippets/$name");
606 # can't map path to volume id
611 my ($cfg, $volid, $snapname) = @_;
613 my ($storeid, $volname) = parse_volume_id
($volid);
615 my $scfg = storage_config
($cfg, $storeid);
617 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
618 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
619 return wantarray ?
($path, $owner, $vtype) : $path;
622 sub abs_filesystem_path
{
623 my ($cfg, $volid, $allow_blockdev) = @_;
626 if (parse_volume_id
($volid, 1)) {
627 activate_volumes
($cfg, [ $volid ]);
628 $path = PVE
::Storage
::path
($cfg, $volid);
630 if (-f
$volid || ($allow_blockdev && -b
$volid)) {
631 my $abspath = abs_path
($volid);
632 if ($abspath && $abspath =~ m
|^(/.+)$|) {
633 $path = $1; # untaint any path
637 die "can't find file '$volid'\n"
638 if !($path && (-f
$path || ($allow_blockdev && -b
$path)));
643 # used as last resort to adapt volnames when migrating
644 my $volname_for_storage = sub {
645 my ($cfg, $storeid, $name, $vmid, $format) = @_;
647 my $scfg = storage_config
($cfg, $storeid);
649 my (undef, $valid_formats) = PVE
::Storage
::Plugin
::default_format
($scfg);
650 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
651 die "unsupported format '$format' for storage type $scfg->{type}\n"
652 if !$format_is_valid;
654 (my $name_without_extension = $name) =~ s/\.$format$//;
657 return "$vmid/$name_without_extension.$format";
659 return "$name_without_extension";
663 # whether a migration snapshot is needed for a given storage
664 sub storage_migrate_snapshot
{
665 my ($cfg, $storeid, $existing_snapshots) = @_;
666 my $scfg = storage_config
($cfg, $storeid);
668 return $scfg->{type
} eq 'zfspool' || ($scfg->{type
} eq 'btrfs' && $existing_snapshots);
671 my $volume_import_prepare = sub {
672 my ($volid, $format, $path, $apiver, $opts) = @_;
674 my $base_snapshot = $opts->{base_snapshot
};
675 my $snapshot = $opts->{snapshot
};
676 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
677 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
678 my $allow_rename = $opts->{allow_rename
} ?
1 : 0;
680 my $recv = ['pvesm', 'import', $volid, $format, $path, '-with-snapshots', $with_snapshots];
681 if (defined($snapshot)) {
682 push @$recv, '-snapshot', $snapshot;
684 if ($migration_snapshot) {
685 push @$recv, '-delete-snapshot', $snapshot;
687 push @$recv, '-allow-rename', $allow_rename if $apiver >= 5;
689 if (defined($base_snapshot)) {
690 # Check if the snapshot exists on the remote side:
691 push @$recv, '-base', $base_snapshot if $apiver >= 9;
697 my $volume_export_prepare = sub {
698 my ($cfg, $volid, $format, $logfunc, $opts) = @_;
699 my $base_snapshot = $opts->{base_snapshot
};
700 my $snapshot = $opts->{snapshot
};
701 my $with_snapshots = $opts->{with_snapshots
} ?
1 : 0;
702 my $migration_snapshot = $opts->{migration_snapshot
} ?
1 : 0;
703 my $ratelimit_bps = $opts->{ratelimit_bps
};
705 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
706 if (defined($snapshot)) {
707 push @$send, '-snapshot', $snapshot;
709 if (defined($base_snapshot)) {
710 push @$send, '-base', $base_snapshot;
714 if (defined($ratelimit_bps)) {
715 $cstream = [ '/usr/bin/cstream', '-t', $ratelimit_bps ];
716 $logfunc->("using a bandwidth limit of $ratelimit_bps bps for transferring '$volid'") if $logfunc;
719 volume_snapshot
($cfg, $volid, $snapshot) if $migration_snapshot;
721 if (defined($snapshot)) {
722 activate_volumes
($cfg, [$volid], $snapshot);
724 activate_volumes
($cfg, [$volid]);
727 return $cstream ?
[ $send, $cstream ] : [ $send ];
730 sub storage_migrate
{
731 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
733 my $insecure = $opts->{insecure
};
735 my ($storeid, $volname) = parse_volume_id
($volid);
737 my $scfg = storage_config
($cfg, $storeid);
739 # no need to migrate shared content
740 return $volid if $storeid eq $target_storeid && $scfg->{shared
};
742 my $tcfg = storage_config
($cfg, $target_storeid);
745 if ($opts->{target_volname
}) {
746 $target_volname = $opts->{target_volname
};
747 } elsif ($scfg->{type
} eq $tcfg->{type
}) {
748 $target_volname = $volname;
750 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname
($cfg, $volid);
751 $target_volname = $volname_for_storage->($cfg, $target_storeid, $name, $vmid, $format);
754 my $target_volid = "${target_storeid}:${target_volname}";
756 my $target_ip = $target_sshinfo->{ip
};
758 my $ssh = PVE
::SSHInfo
::ssh_info_to_command
($target_sshinfo);
759 my $ssh_base = PVE
::SSHInfo
::ssh_info_to_command_base
($target_sshinfo);
760 local $ENV{RSYNC_RSH
} = PVE
::Tools
::cmd2string
($ssh_base);
762 if (!defined($opts->{snapshot
})) {
763 $opts->{migration_snapshot
} = storage_migrate_snapshot
($cfg, $storeid, $opts->{with_snapshots
});
764 $opts->{snapshot
} = '__migration__' if $opts->{migration_snapshot
};
767 my @formats = volume_transfer_formats
($cfg, $volid, $target_volid, $opts->{snapshot
}, $opts->{base_snapshot
}, $opts->{with_snapshots
});
768 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
769 my $format = $formats[0];
771 my $import_fn = '-'; # let pvesm import read from stdin per default
773 my $net = $target_sshinfo->{network
} // $target_sshinfo->{ip
};
774 $import_fn = "tcp://$net";
777 my $target_apiver = 1; # if there is no apiinfo call, assume 1
778 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
779 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
780 eval { run_command
($get_api_version, logfunc
=> $match_api_version); };
782 my $recv = [ @$ssh, '--', $volume_import_prepare->($target_volid, $format, $import_fn, $target_apiver, $opts)->@* ];
785 my $pattern = volume_imported_message
(undef, 1);
786 my $match_volid_and_log = sub {
789 $new_volid = $1 if ($line =~ $pattern);
797 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
801 my $input = IO
::File-
>new();
802 my $info = IO
::File-
>new();
803 open3
($input, $info, $info, @$recv)
804 or die "receive command failed: $!\n";
807 my $try_ip = <$info> // '';
808 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
809 or die "no tunnel IP received, got '$try_ip'\n";
811 my $try_port = <$info> // '';
812 my ($port) = $try_port =~ /^(\d+)$/ # untaint
813 or die "no tunnel port received, got '$try_port'\n";
815 my $socket = IO
::Socket
::IP-
>new(PeerHost
=> $ip, PeerPort
=> $port, Type
=> SOCK_STREAM
)
816 or die "failed to connect to tunnel at $ip:$port\n";
817 # we won't be reading from the socket
818 shutdown($socket, 0);
820 eval { run_command
($cmds, output
=> '>&'.fileno($socket), errfunc
=> $logfunc); };
823 # don't close the connection entirely otherwise the receiving end
824 # might not get all buffered data (and fails with 'connection reset by peer')
825 shutdown($socket, 1);
827 # wait for the remote process to finish
828 while (my $line = <$info>) {
829 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
832 # now close the socket
834 if (!close($info)) { # does waitpid()
835 die "import failed: $!\n" if $!;
836 die "import failed: exit code ".($?>>8)."\n";
839 die $send_error if $send_error;
842 run_command
($cmds, logfunc
=> $match_volid_and_log);
845 die "unable to get ID of the migrated volume\n"
846 if !defined($new_volid) && $target_apiver >= 5;
849 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
850 if ($opts->{migration_snapshot
}) {
851 eval { volume_snapshot_delete
($cfg, $volid, $opts->{snapshot
}, 0) };
852 warn "could not remove source snapshot: $@\n" if $@;
856 return $new_volid // $target_volid;
860 my ($cfg, $volid, $vmid, $snap) = @_;
862 my ($storeid, $volname) = parse_volume_id
($volid);
864 my $scfg = storage_config
($cfg, $storeid);
866 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
868 activate_storage
($cfg, $storeid);
870 # lock shared storage
871 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
872 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
873 return "$storeid:$volname";
877 sub vdisk_create_base
{
878 my ($cfg, $volid) = @_;
880 my ($storeid, $volname) = parse_volume_id
($volid);
882 my $scfg = storage_config
($cfg, $storeid);
884 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
886 activate_storage
($cfg, $storeid);
888 # lock shared storage
889 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
890 my $volname = $plugin->create_base($storeid, $scfg, $volname);
891 return "$storeid:$volname";
896 my ($cfg, $volid, $snapname) = @_;
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 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
908 my ($cfg, $volid, $snapname) = @_;
910 my ($storeid, $volname) = parse_volume_id
($volid);
912 my $scfg = storage_config
($cfg, $storeid);
914 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
916 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
920 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
922 die "no storage ID specified\n" if !$storeid;
924 PVE
::JSONSchema
::parse_storage_id
($storeid);
926 my $scfg = storage_config
($cfg, $storeid);
928 die "no VMID specified\n" if !$vmid;
930 $vmid = parse_vmid
($vmid);
932 my $defformat = PVE
::Storage
::Plugin
::default_format
($scfg);
934 $fmt = $defformat if !$fmt;
936 activate_storage
($cfg, $storeid);
938 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
940 # lock shared storage
941 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
942 my $old_umask = umask(umask|0037);
943 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
947 return "$storeid:$volname";
952 my ($cfg, $volid) = @_;
954 my ($storeid, $volname) = parse_volume_id
($volid);
955 my $scfg = storage_config
($cfg, $storeid);
956 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
958 activate_storage
($cfg, $storeid);
962 # lock shared storage
963 $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
964 # LVM-thin allows deletion of still referenced base volumes!
965 die "base volume '$volname' is still in use by linked clones\n"
966 if volume_is_base_and_used
($cfg, $volid);
968 my (undef, undef, undef, undef, undef, $isBase, $format) =
969 $plugin->parse_volname($volname);
970 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
973 return if !$cleanup_worker;
975 my $rpcenv = PVE
::RPCEnvironment
::get
();
976 my $authuser = $rpcenv->get_user();
978 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
982 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
984 my $ids = $cfg->{ids
};
986 storage_check_enabled
($cfg, $storeid) if ($storeid);
988 my $res = $storeid ?
{ $storeid => [] } : {};
990 # prepare/activate/refresh all storages
992 my $storage_list = [];
994 foreach my $volid (@$vollist) {
995 my ($sid, undef) = parse_volume_id
($volid);
996 next if !defined($ids->{$sid});
997 next if !storage_check_enabled
($cfg, $sid, undef, 1);
998 push @$storage_list, $sid;
1001 foreach my $sid (keys %$ids) {
1002 next if $storeid && $storeid ne $sid;
1003 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1004 my $content = $ids->{$sid}->{content
};
1005 next if defined($ctype) && !$content->{$ctype};
1006 next if !($content->{rootdir
} || $content->{images
});
1007 push @$storage_list, $sid;
1013 activate_storage_list
($cfg, $storage_list, $cache);
1015 for my $sid ($storage_list->@*) {
1016 next if $storeid && $storeid ne $sid;
1018 my $scfg = $ids->{$sid};
1019 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1020 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
1021 @{$res->{$sid}} = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @{$res->{$sid}} if $res->{$sid};
1028 my ($cfg, $storeid, $tt) = @_;
1030 die "unknown template type '$tt'\n"
1031 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1033 my $ids = $cfg->{ids
};
1035 storage_check_enabled
($cfg, $storeid) if ($storeid);
1040 foreach my $sid (keys %$ids) {
1041 next if $storeid && $storeid ne $sid;
1043 my $scfg = $ids->{$sid};
1044 my $type = $scfg->{type
};
1046 next if !$scfg->{content
}->{$tt};
1048 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1050 $res->{$sid} = volume_list
($cfg, $sid, undef, $tt);
1057 my ($cfg, $storeid, $vmid, $content) = @_;
1059 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
1061 my $cts = $content ?
[ $content ] : [ @ctypes ];
1063 my $scfg = PVE
::Storage
::storage_config
($cfg, $storeid);
1065 $cts = [ grep { defined($scfg->{content
}->{$_}) } @$cts ];
1067 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1069 activate_storage
($cfg, $storeid);
1071 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1073 @$res = sort {lc($a->{volid
}) cmp lc ($b->{volid
}) } @$res;
1080 my $filename = "/sys/kernel/uevent_seqnum";
1083 if (my $fh = IO
::File-
>new($filename, "r")) {
1085 if ($line =~ m/^(\d+)$/) {
1093 sub activate_storage
{
1094 my ($cfg, $storeid, $cache) = @_;
1096 $cache = {} if !$cache;
1098 my $scfg = storage_check_enabled
($cfg, $storeid);
1100 return if $cache->{activated
}->{$storeid};
1102 $cache->{uevent_seqnum
} = uevent_seqnum
() if !$cache->{uevent_seqnum
};
1104 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1106 if ($scfg->{base
}) {
1107 my ($baseid, undef) = parse_volume_id
($scfg->{base
});
1108 activate_storage
($cfg, $baseid, $cache);
1111 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1112 die "connection check for storage '$storeid' failed - $@\n" if $@;
1113 die "storage '$storeid' is not online\n";
1116 $plugin->activate_storage($storeid, $scfg, $cache);
1118 my $newseq = uevent_seqnum
();
1120 # only call udevsettle if there are events
1121 if ($newseq > $cache->{uevent_seqnum
}) {
1122 system ("udevadm settle --timeout=30"); # ignore errors
1123 $cache->{uevent_seqnum
} = $newseq;
1126 $cache->{activated
}->{$storeid} = 1;
1129 sub activate_storage_list
{
1130 my ($cfg, $storeid_list, $cache) = @_;
1132 $cache = {} if !$cache;
1134 foreach my $storeid (@$storeid_list) {
1135 activate_storage
($cfg, $storeid, $cache);
1139 sub deactivate_storage
{
1140 my ($cfg, $storeid) = @_;
1142 my $scfg = storage_config
($cfg, $storeid);
1143 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1146 $plugin->deactivate_storage($storeid, $scfg, $cache);
1149 sub activate_volumes
{
1150 my ($cfg, $vollist, $snapname) = @_;
1152 return if !($vollist && scalar(@$vollist));
1154 my $storagehash = {};
1155 foreach my $volid (@$vollist) {
1156 my ($storeid, undef) = parse_volume_id
($volid);
1157 $storagehash->{$storeid} = 1;
1162 activate_storage_list
($cfg, [keys %$storagehash], $cache);
1164 foreach my $volid (@$vollist) {
1165 my ($storeid, $volname) = parse_volume_id
($volid);
1166 my $scfg = storage_config
($cfg, $storeid);
1167 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1168 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1172 sub deactivate_volumes
{
1173 my ($cfg, $vollist, $snapname) = @_;
1175 return if !($vollist && scalar(@$vollist));
1180 foreach my $volid (@$vollist) {
1181 my ($storeid, $volname) = parse_volume_id
($volid);
1183 my $scfg = storage_config
($cfg, $storeid);
1184 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1187 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1191 push @errlist, $volid;
1195 die "volume deactivation failed: " . join(' ', @errlist)
1196 if scalar(@errlist);
1200 my ($cfg, $content, $includeformat) = @_;
1202 my $ids = $cfg->{ids
};
1206 my @ctypes = PVE
::Tools
::split_list
($content);
1209 foreach my $storeid (keys %$ids) {
1210 my $storage_enabled = defined(storage_check_enabled
($cfg, $storeid, undef, 1));
1212 if (defined($content)) {
1214 foreach my $ctype (@ctypes) {
1215 if ($ids->{$storeid}->{content
}->{$ctype}) {
1220 next if !$want_ctype || !$storage_enabled;
1223 my $type = $ids->{$storeid}->{type
};
1225 $info->{$storeid} = {
1230 shared
=> $ids->{$storeid}->{shared
} ?
1 : 0,
1231 content
=> PVE
::Storage
::Plugin
::content_hash_to_string
($ids->{$storeid}->{content
}),
1233 enabled
=> $storage_enabled ?
1 : 0,
1236 push @$slist, $storeid;
1241 foreach my $storeid (keys %$ids) {
1242 my $scfg = $ids->{$storeid};
1244 next if !$info->{$storeid};
1245 next if !$info->{$storeid}->{enabled
};
1247 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1248 if ($includeformat) {
1249 my $pd = $plugin->plugindata();
1250 $info->{$storeid}->{format
} = $pd->{format
}
1252 $info->{$storeid}->{select_existing
} = $pd->{select_existing
}
1253 if $pd->{select_existing
};
1256 eval { activate_storage
($cfg, $storeid, $cache); };
1262 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1265 $info->{$storeid}->{total
} = int($total);
1266 $info->{$storeid}->{avail
} = int($avail);
1267 $info->{$storeid}->{used
} = int($used);
1268 $info->{$storeid}->{active
} = $active;
1277 my ($packed_ip, $family);
1279 my @res = PVE
::Tools
::getaddrinfo_all
($server);
1280 $family = $res[0]->{family
};
1281 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
1283 if (defined $packed_ip) {
1284 return Socket
::inet_ntop
($family, $packed_ip);
1290 my ($server_in) = @_;
1293 if (!($server = resolv_server
($server_in))) {
1294 die "unable to resolve address for server '${server_in}'\n";
1297 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1300 run_command
($cmd, outfunc
=> sub {
1303 # note: howto handle white spaces in export path??
1304 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1313 my ($server_in, $user, $password, $domain) = @_;
1315 my $server = resolv_server
($server_in);
1316 die "unable to resolve address for server '${server_in}'\n" if !$server;
1318 # we only support Windows 2012 and newer, so just use smb3
1319 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1320 push @$cmd, '-W', $domain if defined($domain);
1322 push @$cmd, '-N' if !defined($password);
1323 local $ENV{USER
} = $user if defined($user);
1324 local $ENV{PASSWD
} = $password if defined($password);
1335 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1337 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1339 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1343 # only die if we got no share, else it's just some followup check error
1344 # (like workgroup querying)
1345 raise
($err) if $err && !%$res;
1352 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1355 run_command
($cmd, outfunc
=> sub {
1358 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1359 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1360 my $size = $size_str + 0;
1361 my $used = $used_str + 0;
1362 # ignore subvolumes generated by our ZFSPoolPlugin
1363 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1364 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1365 push @$res, { pool
=> $pool, size
=> $size, free
=> $size-$used };
1373 my ($portal, $noerr) = @_;
1375 my ($server, $port) = PVE
::Tools
::parse_host_and_port
($portal);
1377 if (my $ip = resolv_server
($server)) {
1379 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1380 return $port ?
"$server:$port" : $server;
1383 return undef if $noerr;
1385 raise_param_exc
({ portal
=> "unable to resolve portal address '$portal'" });
1390 my ($portal_in) = @_;
1393 if (!($portal = resolv_portal
($portal_in))) {
1394 die "unable to parse/resolve portal address '${portal_in}'\n";
1397 return PVE
::Storage
::ISCSIPlugin
::iscsi_discovery
($portal);
1400 sub storage_default_format
{
1401 my ($cfg, $storeid) = @_;
1403 my $scfg = storage_config
($cfg, $storeid);
1405 return PVE
::Storage
::Plugin
::default_format
($scfg);
1408 sub vgroup_is_used
{
1409 my ($cfg, $vgname) = @_;
1411 foreach my $storeid (keys %{$cfg->{ids
}}) {
1412 my $scfg = storage_config
($cfg, $storeid);
1413 if ($scfg->{type
} eq 'lvm' && $scfg->{vgname
} eq $vgname) {
1421 sub target_is_used
{
1422 my ($cfg, $target) = @_;
1424 foreach my $storeid (keys %{$cfg->{ids
}}) {
1425 my $scfg = storage_config
($cfg, $storeid);
1426 if ($scfg->{type
} eq 'iscsi' && $scfg->{target
} eq $target) {
1434 sub volume_is_used
{
1435 my ($cfg, $volid) = @_;
1437 foreach my $storeid (keys %{$cfg->{ids
}}) {
1438 my $scfg = storage_config
($cfg, $storeid);
1439 if ($scfg->{base
} && $scfg->{base
} eq $volid) {
1447 sub storage_is_used
{
1448 my ($cfg, $storeid) = @_;
1450 foreach my $sid (keys %{$cfg->{ids
}}) {
1451 my $scfg = storage_config
($cfg, $sid);
1452 next if !$scfg->{base
};
1453 my ($st) = parse_volume_id
($scfg->{base
});
1454 return 1 if $st && $st eq $storeid;
1461 my ($list, $func) = @_;
1465 foreach my $sid (keys %$list) {
1466 foreach my $info (@{$list->{$sid}}) {
1467 my $volid = $info->{volid
};
1468 my ($sid1, $volname) = parse_volume_id
($volid, 1);
1469 if ($sid1 && $sid1 eq $sid) {
1470 &$func ($volid, $sid, $info);
1472 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1478 sub decompressor_info
{
1479 my ($format, $comp) = @_;
1481 if ($format eq 'tgz' && !defined($comp)) {
1482 ($format, $comp) = ('tar', 'gz');
1485 my $decompressor = {
1487 gz
=> ['tar', '-z'],
1488 lzo
=> ['tar', '--lzop'],
1489 zst
=> ['tar', '--zstd'],
1493 lzo
=> ['lzop', '-d', '-c'],
1494 zst
=> ['zstd', '-q', '-d', '-c'],
1498 die "ERROR: archive format not defined\n"
1499 if !defined($decompressor->{$format});
1502 $decomp = $decompressor->{$format}->{$comp} if $comp;
1506 compression
=> $comp,
1507 decompressor
=> $decomp,
1513 sub protection_file_path
{
1516 return "${path}.protected";
1520 my ($archive) = shift;
1523 my $volid = basename
($archive);
1524 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
1525 my $filename = "$1"; # untaint
1526 my ($type, $extension, $comp) = ($2, $3, $4);
1527 (my $format = $extension) =~ s/\..*//;
1528 $info = decompressor_info
($format, $comp);
1529 $info->{filename
} = $filename;
1530 $info->{type
} = $type;
1532 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${extension}$/) {
1533 $info->{logfilename
} = "$1.log";
1534 $info->{vmid
} = int($2);
1535 $info->{ctime
} = timelocal
($8, $7, $6, $5, $4 - 1, $3);
1536 $info->{is_std_name
} = 1;
1538 $info->{is_std_name
} = 0;
1541 die "ERROR: couldn't determine archive info from '$archive'\n";
1547 sub archive_remove
{
1548 my ($archive_path) = @_;
1550 die "cannot remove protected archive '$archive_path'\n"
1551 if -e protection_file_path
($archive_path);
1553 my $dirname = dirname
($archive_path);
1554 my $archive_info = eval { archive_info
($archive_path) } // {};
1555 my $logfn = $archive_info->{logfilename
};
1557 unlink $archive_path or die "removing archive $archive_path failed: $!\n";
1559 if (defined($logfn)) {
1560 my $logpath = "$dirname/$logfn";
1562 unlink $logpath or warn "removing log file $logpath failed: $!\n";
1567 sub extract_vzdump_config_tar
{
1568 my ($archive, $conf_re) = @_;
1570 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
1572 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1573 die "unable to open file '$archive'\n";
1576 while (defined($file = <$fh>)) {
1577 if ($file =~ $conf_re) {
1578 $file = $1; # untaint
1587 die "ERROR: archive contains no configuration file\n" if !$file;
1593 $raw .= "$output\n";
1596 run_command
(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc
=> $out);
1598 return wantarray ?
($raw, $file) : $raw;
1601 sub extract_vzdump_config_vma
{
1602 my ($archive, $comp) = @_;
1605 my $out = sub { $raw .= "$_[0]\n"; };
1607 my $info = archive_info
($archive);
1608 $comp //= $info->{compression
};
1609 my $decompressor = $info->{decompressor
};
1612 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1614 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1619 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
1621 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1622 $errstring = "Failed to extract config from VMA archive: $output\n";
1626 my $rc = eval { run_command
($cmd, outfunc
=> $out, errfunc
=> $err, noerr
=> 1) };
1629 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1631 if (!$errstring && !$broken_pipe && $rc != 0) {
1632 die "$rerr\n" if $rerr;
1633 die "config extraction failed with exit code $rc\n";
1635 die "$errstring\n" if $errstring;
1637 run_command
(["vma", "config", $archive], outfunc
=> $out);
1640 return wantarray ?
($raw, undef) : $raw;
1643 sub extract_vzdump_config
{
1644 my ($cfg, $volid) = @_;
1646 my ($storeid, $volname) = parse_volume_id
($volid);
1647 if (defined($storeid)) {
1648 my $scfg = storage_config
($cfg, $storeid);
1649 if ($scfg->{type
} eq 'pbs') {
1650 storage_check_enabled
($cfg, $storeid);
1651 return PVE
::Storage
::PBSPlugin-
>extract_vzdump_config($scfg, $volname, $storeid);
1655 my $archive = abs_filesystem_path
($cfg, $volid);
1656 my $info = archive_info
($archive);
1657 my $format = $info->{format
};
1658 my $comp = $info->{compression
};
1659 my $type = $info->{type
};
1661 if ($type eq 'lxc' || $type eq 'openvz') {
1662 return extract_vzdump_config_tar
($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1663 } elsif ($type eq 'qemu') {
1664 if ($format eq 'tar') {
1665 return extract_vzdump_config_tar
($archive, qr!\(\./qemu-server\.conf\)!);
1667 return extract_vzdump_config_vma
($archive, $comp);
1670 die "cannot determine backup guest type for backup archive '$volid'\n";
1675 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1677 my $scfg = storage_config
($cfg, $storeid);
1678 die "storage '$storeid' does not support backups\n" if !$scfg->{content
}->{backup
};
1680 if (!defined($keep)) {
1681 die "no prune-backups options configured for storage '$storeid'\n"
1682 if !defined($scfg->{'prune-backups'});
1683 $keep = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'});
1686 activate_storage
($cfg, $storeid);
1688 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1689 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1692 my $prune_mark = sub {
1693 my ($prune_entries, $keep_count, $id_func) = @_;
1695 return if !$keep_count;
1697 my $already_included = {};
1698 my $newly_included = {};
1700 foreach my $prune_entry (@{$prune_entries}) {
1701 my $mark = $prune_entry->{mark
};
1702 my $id = $id_func->($prune_entry->{ctime
});
1703 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1706 foreach my $prune_entry (@{$prune_entries}) {
1707 my $mark = $prune_entry->{mark
};
1708 my $id = $id_func->($prune_entry->{ctime
});
1710 next if defined($mark) || $already_included->{$id};
1712 if (!$newly_included->{$id}) {
1713 last if scalar(keys %{$newly_included}) >= $keep_count;
1714 $newly_included->{$id} = 1;
1715 $prune_entry->{mark
} = 'keep';
1717 $prune_entry->{mark
} = 'remove';
1722 sub prune_mark_backup_group
{
1723 my ($backup_group, $keep) = @_;
1725 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1727 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
1728 foreach my $prune_entry (@{$backup_group}) {
1729 # preserve additional information like 'protected'
1730 next if $prune_entry->{mark
} && $prune_entry->{mark
} ne 'remove';
1731 $prune_entry->{mark
} = 'keep';
1736 my $prune_list = [ sort { $b->{ctime
} <=> $a->{ctime
} } @{$backup_group} ];
1738 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1742 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1744 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1745 return "$hour/$day/$month/$year";
1747 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1749 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1750 return "$day/$month/$year";
1752 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1754 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1755 my $iso_week = int(strftime
("%V", $sec, $min, $hour, $day, $month, $year));
1756 my $iso_week_year = int(strftime
("%G", $sec, $min, $hour, $day, $month, $year));
1757 return "$iso_week/$iso_week_year";
1759 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1761 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1762 return "$month/$year";
1764 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1766 my $year = (localtime($ctime))[5];
1770 foreach my $prune_entry (@{$prune_list}) {
1771 $prune_entry->{mark
} //= 'remove';
1775 sub volume_export
: prototype($$$$$$$) {
1776 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1778 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1779 die "cannot export volume '$volid'\n" if !$storeid;
1780 my $scfg = storage_config
($cfg, $storeid);
1781 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1782 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1783 $snapshot, $base_snapshot, $with_snapshots);
1786 sub volume_import
: prototype($$$$$$$$) {
1787 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1789 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1790 die "cannot import into volume '$volid'\n" if !$storeid;
1791 my $scfg = storage_config
($cfg, $storeid);
1792 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1793 return $plugin->volume_import(
1806 sub volume_export_formats
: prototype($$$$$) {
1807 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1809 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1810 return if !$storeid;
1811 my $scfg = storage_config
($cfg, $storeid);
1812 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1813 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1814 $snapshot, $base_snapshot,
1818 sub volume_import_formats
: prototype($$$$$) {
1819 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1821 my ($storeid, $volname) = parse_volume_id
($volid, 1);
1822 return if !$storeid;
1823 my $scfg = storage_config
($cfg, $storeid);
1824 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1825 return $plugin->volume_import_formats(
1835 sub volume_transfer_formats
{
1836 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1837 my @export_formats = volume_export_formats
($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1838 my @import_formats = volume_import_formats
($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
1839 my %import_hash = map { $_ => 1 } @import_formats;
1840 my @common = grep { $import_hash{$_} } @export_formats;
1844 sub volume_imported_message
{
1845 my ($volid, $want_pattern) = @_;
1847 if ($want_pattern) {
1848 return qr/successfully imported '([^']*)'$/;
1850 return "successfully imported '$volid'\n";
1854 # $format and $volname are requests and might be overruled depending on $opts
1856 # - with_snapshots: passed to `pvesm import` and used to select import format
1857 # - allow_rename: passed to `pvesm import`
1858 # - export_formats: used to select common transport format
1859 # - unix: unix socket path
1860 sub volume_import_start
{
1861 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1863 my $with_snapshots = $opts->{'with_snapshots'} ?
1 : 0;
1865 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1867 my $volid = "$storeid:$volname";
1869 # find common import/export format, like volume_transfer_formats
1870 my @import_formats = PVE
::Storage
::volume_import_formats
($cfg, $volid, $opts->{snapshot
}, undef, $with_snapshots);
1871 my @export_formats = PVE
::Tools
::split_list
($opts->{export_formats
});
1872 my %import_hash = map { $_ => 1 } @import_formats;
1873 my @common = grep { $import_hash{$_} } @export_formats;
1874 die "no matching import/export format found for storage '$storeid'\n"
1876 $format = $common[0];
1878 my $input = IO
::File-
>new();
1879 my $info = IO
::File-
>new();
1881 my $unix = $opts->{unix
} // "/run/pve/storage-migrate-$vmid.$$.unix";
1882 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER
, $opts);
1885 my $cpid = open3
($input, $info, $info, @$import)
1886 or die "failed to spawn disk-import child - $!\n";
1890 PVE
::Tools
::run_with_timeout
(5, sub { $ready = <$info>; });
1893 die "failed to read readyness from disk import child: $@\n" if $@;
1905 sub volume_export_start
{
1906 my ($cfg, $volid, $format, $log, $opts) = @_;
1908 my $run_command_params = delete $opts->{cmd
} // {};
1910 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1912 PVE
::Tools
::run_command
($cmds, %$run_command_params);
1915 # bash completion helper
1917 sub complete_storage
{
1918 my ($cmdname, $pname, $cvalue) = @_;
1920 my $cfg = PVE
::Storage
::config
();
1922 return $cmdname eq 'add' ?
[] : [ PVE
::Storage
::storage_ids
($cfg) ];
1925 sub complete_storage_enabled
{
1926 my ($cmdname, $pname, $cvalue) = @_;
1930 my $cfg = PVE
::Storage
::config
();
1931 foreach my $sid (keys %{$cfg->{ids
}}) {
1932 next if !storage_check_enabled
($cfg, $sid, undef, 1);
1938 sub complete_content_type
{
1939 my ($cmdname, $pname, $cvalue) = @_;
1941 return [qw(rootdir images vztmpl iso backup snippets)];
1944 sub complete_volume
{
1945 my ($cmdname, $pname, $cvalue) = @_;
1949 my $storage_list = complete_storage_enabled
();
1951 if ($cvalue =~ m/^([^:]+):/) {
1952 $storage_list = [ $1 ];
1954 if (scalar(@$storage_list) > 1) {
1955 # only list storage IDs to avoid large listings
1957 foreach my $storeid (@$storage_list) {
1958 # Hack: simply return 2 artificial values, so that
1959 # completions does not finish
1960 push @$res, "$storeid:volname", "$storeid:...";
1967 foreach my $storeid (@$storage_list) {
1968 my $vollist = PVE
::Storage
::volume_list
($cfg, $storeid);
1970 foreach my $item (@$vollist) {
1971 push @$res, $item->{volid
};
1979 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
1981 die "no source volid provided\n" if !$source_volid;
1982 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
1984 my ($storeid, $source_volname) = parse_volume_id
($source_volid);
1986 activate_storage
($cfg, $storeid);
1988 my $scfg = storage_config
($cfg, $storeid);
1989 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
1991 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
1993 return $plugin->cluster_lock_storage($storeid, $scfg->{shared
}, undef, sub {
1994 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
1998 # Various io-heavy operations require io/bandwidth limits which can be
1999 # configured on multiple levels: The global defaults in datacenter.cfg, and
2000 # per-storage overrides. When we want to do a restore from storage A to storage
2001 # B, we should take the smaller limit defined for storages A and B, and if no
2002 # such limit was specified, use the one from datacenter.cfg.
2003 sub get_bandwidth_limit
{
2004 my ($operation, $storage_list, $override) = @_;
2006 # called for each limit (global, per-storage) with the 'default' and the
2007 # $operation limit and should update $override for every limit affecting
2009 my $use_global_limits = 0;
2010 my $apply_limit = sub {
2012 if (defined($bwlimit)) {
2013 my $limits = PVE
::JSONSchema
::parse_property_string
('bwlimit', $bwlimit);
2014 my $limit = $limits->{$operation} // $limits->{default};
2015 if (defined($limit)) {
2016 if (!$override || $limit < $override) {
2022 # If there was no applicable limit, try to apply the global ones.
2023 $use_global_limits = 1;
2026 my ($rpcenv, $authuser);
2027 if (defined($override)) {
2028 $rpcenv = PVE
::RPCEnvironment-
>get();
2029 $authuser = $rpcenv->get_user();
2032 # Apply per-storage limits - if there are storages involved.
2033 if (defined($storage_list) && @$storage_list) {
2034 my $config = config
();
2036 # The Datastore.Allocate permission allows us to modify the per-storage
2037 # limits, therefore it also allows us to override them.
2038 # Since we have most likely multiple storages to check, do a quick check on
2039 # the general '/storage' path to see if we can skip the checks entirely:
2040 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
2043 foreach my $storage (@$storage_list) {
2044 next if !defined($storage);
2045 # Avoid duplicate checks:
2046 next if $done{$storage};
2047 $done{$storage} = 1;
2049 # Otherwise we may still have individual /storage/$ID permissions:
2050 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
2051 # And if not: apply the limits.
2052 my $storecfg = storage_config
($config, $storage);
2053 $apply_limit->($storecfg->{bwlimit
});
2057 # Storage limits take precedence over the datacenter defaults, so if
2058 # a limit was applied:
2059 return $override if !$use_global_limits;
2062 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2063 # global default limits.
2064 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
2065 # So if we cannot modify global limits, apply them to our currently
2066 # requested override.
2067 my $dc = cfs_read_file
('datacenter.cfg');
2068 $apply_limit->($dc->{bwlimit
});
2074 # checks if the storage id is available and dies if not
2075 sub assert_sid_unused
{
2079 if (my $scfg = storage_config
($cfg, $sid, 1)) {
2080 die "storage ID '$sid' already defined\n";
2086 # removes leading/trailing spaces and (back)slashes completely
2087 # substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2088 sub normalize_content_filename
{
2089 my ($filename) = @_;
2092 $filename =~ s/^.*[\/\\]//;
2093 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;