]> git.proxmox.com Git - pve-storage.git/blame - src/PVE/Storage.pm
offline migration: use telling variable for capture group
[pve-storage.git] / src / PVE / Storage.pm
CommitLineData
b6cf0a66
DM
1package PVE::Storage;
2
3use strict;
ffd6f2f3
DM
4use warnings;
5
b6cf0a66
DM
6use POSIX;
7use IO::Select;
b6cf0a66 8use IO::File;
7ba34faa 9use IO::Socket::IP;
57acd6a1 10use IPC::Open3;
b6cf0a66
DM
11use File::Basename;
12use File::Path;
b6cf0a66 13use Cwd 'abs_path';
7a2d5c1a 14use Socket;
fb821c18 15use Time::Local qw(timelocal);
b6cf0a66 16
4dee23d3 17use PVE::Tools qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
83d7192f 18use PVE::Cluster qw(cfs_read_file cfs_write_file cfs_lock_file);
2f08fb4b 19use PVE::DataCenterConfig;
be18d6da 20use PVE::Exception qw(raise_param_exc raise);
b6cf0a66
DM
21use PVE::JSONSchema;
22use PVE::INotify;
88c3abaf 23use PVE::RPCEnvironment;
65bb9859 24use PVE::SSHInfo;
3048641b 25use PVE::RESTEnvironment qw(log_warn);
b6cf0a66 26
1dc01b9f
DM
27use PVE::Storage::Plugin;
28use PVE::Storage::DirPlugin;
29use PVE::Storage::LVMPlugin;
610798bc 30use PVE::Storage::LvmThinPlugin;
1dc01b9f 31use PVE::Storage::NFSPlugin;
d7875239 32use PVE::Storage::CIFSPlugin;
1dc01b9f 33use PVE::Storage::ISCSIPlugin;
0509010d 34use PVE::Storage::RBDPlugin;
e34ce144 35use PVE::Storage::CephFSPlugin;
86616554 36use PVE::Storage::ISCSIDirectPlugin;
f4648aef 37use PVE::Storage::GlusterfsPlugin;
85fda4dd 38use PVE::Storage::ZFSPoolPlugin;
4f914e6e 39use PVE::Storage::ZFSPlugin;
271fe394 40use PVE::Storage::PBSPlugin;
af50c2e6 41use PVE::Storage::BTRFSPlugin;
b6cf0a66 42
af2dd59e 43# Storage API version. Increment it on changes in storage API interface.
a799f752 44use constant APIVER => 10;
042dd4be
WB
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
a799f752 48use constant APIAGE => 1;
4dee23d3 49
71460c8a
FG
50our $KNOWN_EXPORT_FORMATS = ['raw+size', 'tar+size', 'qcow2+size', 'vmdk+size', 'zfs', 'btrfs'];
51
4dee23d3 52# load standard plugins
1dc01b9f
DM
53PVE::Storage::DirPlugin->register();
54PVE::Storage::LVMPlugin->register();
610798bc 55PVE::Storage::LvmThinPlugin->register();
1dc01b9f 56PVE::Storage::NFSPlugin->register();
d7875239 57PVE::Storage::CIFSPlugin->register();
1dc01b9f 58PVE::Storage::ISCSIPlugin->register();
0509010d 59PVE::Storage::RBDPlugin->register();
e34ce144 60PVE::Storage::CephFSPlugin->register();
86616554 61PVE::Storage::ISCSIDirectPlugin->register();
f4648aef 62PVE::Storage::GlusterfsPlugin->register();
85fda4dd 63PVE::Storage::ZFSPoolPlugin->register();
4f914e6e 64PVE::Storage::ZFSPlugin->register();
271fe394 65PVE::Storage::PBSPlugin->register();
af50c2e6 66PVE::Storage::BTRFSPlugin->register();
4dee23d3
DP
67
68# load third-party plugins
69if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
70 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
71 my ($file) = @_;
72 my $modname = 'PVE::Storage::Custom::' . $file;
73 $modname =~ s!\.pm$!!;
74 $file = 'PVE/Storage/Custom/' . $file;
75
76 eval {
77 require $file;
042dd4be
WB
78
79 # Check perl interface:
823e8afe
TL
80 die "not derived from PVE::Storage::Plugin\n" if !$modname->isa('PVE::Storage::Plugin');
81 die "does not provide an api() method\n" if !$modname->can('api');
042dd4be
WB
82 # Check storage API version and that file is really storage plugin.
83 my $version = $modname->api();
a0908caa 84 die "implements an API version newer than current ($version > " . APIVER . ")\n"
042dd4be 85 if $version > APIVER;
a0908caa
TL
86 my $min_version = (APIVER - APIAGE);
87 die "API version too old, please update the plugin ($version < $min_version)\n"
88 if $version < $min_version;
823e8afe 89 # all OK, do import and register (i.e., "use")
042dd4be
WB
90 import $file;
91 $modname->register();
92
823e8afe 93 # If we got this far and the API version is not the same, make some noise:
042dd4be
WB
94 warn "Plugin \"$modname\" is implementing an older storage API, an upgrade is recommended\n"
95 if $version != APIVER;
4dee23d3
DP
96 };
97 if ($@) {
042dd4be 98 warn "Error loading storage plugin \"$modname\": $@";
4dee23d3
DP
99 }
100 });
101}
102
103# initialize all plugins
1dc01b9f 104PVE::Storage::Plugin->init();
b6cf0a66 105
cd461a50
LS
106# the following REs indicate the number or capture groups via the trailing digit
107# CAUTION don't forget to update the digits accordingly after messing with the capture groups
4c693491 108
cd461a50
LS
109our $ISO_EXT_RE_0 = qr/\.(?:iso|img)/i;
110
111our $VZTMPL_EXT_RE_1 = qr/\.tar\.(gz|xz|zst)/i;
112
18bf2e59
LS
113our $BACKUP_EXT_RE_2 = qr/\.(tgz|(?:tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)/;
114
cd461a50
LS
115# FIXME remove with PVE 8.0, add versioned breaks for pve-manager
116our $vztmpl_extension_re = $VZTMPL_EXT_RE_1;
bba10cf4 117
1dc01b9f 118# PVE::Storage utility functions
b6cf0a66
DM
119
120sub config {
121 return cfs_read_file("storage.cfg");
122}
123
83d7192f
FG
124sub write_config {
125 my ($cfg) = @_;
126
127 cfs_write_file('storage.cfg', $cfg);
128}
129
b6cf0a66
DM
130sub lock_storage_config {
131 my ($code, $errmsg) = @_;
132
133 cfs_lock_file("storage.cfg", undef, $code);
134 my $err = $@;
135 if ($err) {
136 $errmsg ? die "$errmsg: $err" : die $err;
137 }
138}
139
bbadd165 140# FIXME remove maxfiles for PVE 8.0 or PVE 9.0
d4e8a1f2
FE
141my $convert_maxfiles_to_prune_backups = sub {
142 my ($scfg) = @_;
143
144 return if !$scfg;
145
146 my $maxfiles = delete $scfg->{maxfiles};
147
148 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
149 my $prune_backups;
150 if ($maxfiles) {
151 $prune_backups = { 'keep-last' => $maxfiles };
152 } else { # maxfiles 0 means no limit
153 $prune_backups = { 'keep-all' => 1 };
154 }
155 $scfg->{'prune-backups'} = PVE::JSONSchema::print_property_string(
156 $prune_backups,
157 'prune-backups'
158 );
159 }
160};
161
b6cf0a66
DM
162sub storage_config {
163 my ($cfg, $storeid, $noerr) = @_;
164
82fc923f 165 die "no storage ID specified\n" if !$storeid;
1a3459ac 166
b6cf0a66
DM
167 my $scfg = $cfg->{ids}->{$storeid};
168
481f6177 169 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
b6cf0a66 170
d4e8a1f2
FE
171 $convert_maxfiles_to_prune_backups->($scfg);
172
b6cf0a66
DM
173 return $scfg;
174}
175
176sub storage_check_node {
177 my ($cfg, $storeid, $node, $noerr) = @_;
178
1dc01b9f 179 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
180
181 if ($scfg->{nodes}) {
182 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
183 if (!$scfg->{nodes}->{$node}) {
da156fb3 184 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
b6cf0a66
DM
185 return undef;
186 }
187 }
188
189 return $scfg;
190}
191
192sub storage_check_enabled {
193 my ($cfg, $storeid, $node, $noerr) = @_;
194
1dc01b9f 195 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
196
197 if ($scfg->{disable}) {
198 die "storage '$storeid' is disabled\n" if !$noerr;
199 return undef;
200 }
201
202 return storage_check_node($cfg, $storeid, $node, $noerr);
203}
204
7118dd91
DM
205# storage_can_replicate:
206# return true if storage supports replication
ffc31266 207# (volumes allocated with vdisk_alloc() has replication feature)
7118dd91
DM
208sub storage_can_replicate {
209 my ($cfg, $storeid, $format) = @_;
210
211 my $scfg = storage_config($cfg, $storeid);
212 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
213 return $plugin->storage_can_replicate($scfg, $storeid, $format);
214}
215
8009417d
FE
216sub get_max_protected_backups {
217 my ($scfg, $storeid) = @_;
218
219 return $scfg->{'max-protected-backups'} if defined($scfg->{'max-protected-backups'});
220
221 my $rpcenv = PVE::RPCEnvironment::get();
222 my $authuser = $rpcenv->get_user();
223
224 return $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.Allocate'], 1) ? -1 : 5;
225}
226
b6cf0a66
DM
227sub storage_ids {
228 my ($cfg) = @_;
229
1dc01b9f 230 return keys %{$cfg->{ids}};
b6cf0a66
DM
231}
232
1dc01b9f
DM
233sub file_size_info {
234 my ($filename, $timeout) = @_;
b6cf0a66 235
1dc01b9f 236 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
b6cf0a66
DM
237}
238
f1de8281
FE
239sub get_volume_attribute {
240 my ($cfg, $volid, $attribute) = @_;
e9991d26
DC
241
242 my ($storeid, $volname) = parse_volume_id($volid);
243 my $scfg = storage_config($cfg, $storeid);
244 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
245
f1de8281 246 return $plugin->get_volume_attribute($scfg, $storeid, $volname, $attribute);
e9991d26
DC
247}
248
f1de8281
FE
249sub update_volume_attribute {
250 my ($cfg, $volid, $attribute, $value) = @_;
e9991d26
DC
251
252 my ($storeid, $volname) = parse_volume_id($volid);
253 my $scfg = storage_config($cfg, $storeid);
254 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
255
8009417d
FE
256 my ($vtype, undef, $vmid) = $plugin->parse_volname($volname);
257 my $max_protected_backups = get_max_protected_backups($scfg, $storeid);
258
259 if (
260 $vtype eq 'backup'
261 && $vmid
262 && $attribute eq 'protected'
263 && $value
264 && !$plugin->get_volume_attribute($scfg, $storeid, $volname, 'protected')
265 && $max_protected_backups > -1 # -1 is unlimited
266 ) {
267 my $backups = $plugin->list_volumes($storeid, $scfg, $vmid, ['backup']);
268 my ($backup_type) = map { $_->{subtype} } grep { $_->{volid} eq $volid } $backups->@*;
269
270 my $protected_count = grep {
271 $_->{protected} && (!$backup_type || ($_->{subtype} && $_->{subtype} eq $backup_type))
272 } $backups->@*;
273
274 if ($max_protected_backups <= $protected_count) {
275 die "The number of protected backups per guest is limited to $max_protected_backups ".
276 "on storage '$storeid'\n";
277 }
278 }
279
f1de8281 280 return $plugin->update_volume_attribute($scfg, $storeid, $volname, $attribute, $value);
e9991d26
DC
281}
282
20ccac1b
AD
283sub volume_size_info {
284 my ($cfg, $volid, $timeout) = @_;
285
f18199e5
DM
286 my ($storeid, $volname) = parse_volume_id($volid, 1);
287 if ($storeid) {
288 my $scfg = storage_config($cfg, $storeid);
289 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
290 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
291 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
292 return file_size_info($volid, $timeout);
293 } else {
294 return 0;
295 }
20ccac1b
AD
296}
297
7e6c05dc
AD
298sub volume_resize {
299 my ($cfg, $volid, $size, $running) = @_;
300
c7215573
FE
301 my $padding = (1024 - $size % 1024) % 1024;
302 $size = $size + $padding;
303
7e6c05dc
AD
304 my ($storeid, $volname) = parse_volume_id($volid, 1);
305 if ($storeid) {
618bdfd9
PH
306 my $scfg = storage_config($cfg, $storeid);
307 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
308 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
7e6c05dc 309 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
618bdfd9 310 die "resize file/device '$volid' is not possible\n";
7e6c05dc 311 } else {
f824c722 312 die "unable to parse volume ID '$volid'\n";
7e6c05dc
AD
313 }
314}
315
1597f1f9 316sub volume_rollback_is_possible {
9a5d5095 317 my ($cfg, $volid, $snap, $blockers) = @_;
e0852ba7 318
1597f1f9
WL
319 my ($storeid, $volname) = parse_volume_id($volid, 1);
320 if ($storeid) {
618bdfd9
PH
321 my $scfg = storage_config($cfg, $storeid);
322 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
323 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap, $blockers);
1597f1f9 324 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
618bdfd9 325 die "snapshot rollback file/device '$volid' is not possible\n";
1597f1f9 326 } else {
f824c722 327 die "unable to parse volume ID '$volid'\n";
1597f1f9
WL
328 }
329}
330
db60719c 331sub volume_snapshot {
f5640e7d 332 my ($cfg, $volid, $snap) = @_;
db60719c
AD
333
334 my ($storeid, $volname) = parse_volume_id($volid, 1);
335 if ($storeid) {
618bdfd9
PH
336 my $scfg = storage_config($cfg, $storeid);
337 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
338 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
db60719c 339 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
618bdfd9 340 die "snapshot file/device '$volid' is not possible\n";
db60719c 341 } else {
f824c722 342 die "unable to parse volume ID '$volid'\n";
db60719c
AD
343 }
344}
345
22a2a633
AD
346sub volume_snapshot_rollback {
347 my ($cfg, $volid, $snap) = @_;
348
349 my ($storeid, $volname) = parse_volume_id($volid, 1);
350 if ($storeid) {
618bdfd9
PH
351 my $scfg = storage_config($cfg, $storeid);
352 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b3f302c6 353 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
618bdfd9 354 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
22a2a633 355 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
618bdfd9 356 die "snapshot rollback file/device '$volid' is not possible\n";
22a2a633 357 } else {
f824c722 358 die "unable to parse volume ID '$volid'\n";
22a2a633
AD
359 }
360}
361
eaff3616 362# FIXME PVE 8.x remove $running parameter (needs APIAGE reset)
5753c9d1
AD
363sub volume_snapshot_delete {
364 my ($cfg, $volid, $snap, $running) = @_;
365
366 my ($storeid, $volname) = parse_volume_id($volid, 1);
367 if ($storeid) {
618bdfd9
PH
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);
5753c9d1 371 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
618bdfd9 372 die "snapshot delete file/device '$volid' is not possible\n";
5753c9d1 373 } else {
f824c722 374 die "unable to parse volume ID '$volid'\n";
5753c9d1
AD
375 }
376}
377
2c036838
SI
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
381sub volume_snapshot_needs_fsfreeze {
382 my ($cfg, $volid) = @_;
383
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();
388}
389
2668adce
FE
390# check if a volume or snapshot supports a given feature
391# $feature - one of:
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
95dfa44c 398# rename - renaming volumes is possible
2668adce
FE
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.
99473759 406sub volume_has_feature {
e6f4eed4 407 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
99473759
AD
408
409 my ($storeid, $volname) = parse_volume_id($volid, 1);
410 if ($storeid) {
618bdfd9
PH
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);
99473759
AD
414 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
415 return undef;
416 } else {
417 return undef;
418 }
419}
420
8c20d8af
FE
421sub volume_snapshot_info {
422 my ($cfg, $volid) = @_;
423
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);
428}
429
1dc01b9f
DM
430sub get_image_dir {
431 my ($cfg, $storeid, $vmid) = @_;
b6cf0a66 432
1dc01b9f
DM
433 my $scfg = storage_config($cfg, $storeid);
434 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 435
1dc01b9f 436 my $path = $plugin->get_subdir($scfg, 'images');
b6cf0a66 437
1dc01b9f 438 return $vmid ? "$path/$vmid" : $path;
b6cf0a66
DM
439}
440
1dc01b9f 441sub get_private_dir {
b6cf0a66
DM
442 my ($cfg, $storeid, $vmid) = @_;
443
1dc01b9f
DM
444 my $scfg = storage_config($cfg, $storeid);
445 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 446
1dc01b9f 447 my $path = $plugin->get_subdir($scfg, 'rootdir');
d22a6133 448
1dc01b9f 449 return $vmid ? "$path/$vmid" : $path;
d22a6133
DM
450}
451
b6cf0a66
DM
452sub get_iso_dir {
453 my ($cfg, $storeid) = @_;
454
1dc01b9f
DM
455 my $scfg = storage_config($cfg, $storeid);
456 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 457
1dc01b9f 458 return $plugin->get_subdir($scfg, 'iso');
b6cf0a66
DM
459}
460
461sub get_vztmpl_dir {
462 my ($cfg, $storeid) = @_;
463
1dc01b9f
DM
464 my $scfg = storage_config($cfg, $storeid);
465 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 466
1dc01b9f 467 return $plugin->get_subdir($scfg, 'vztmpl');
b6cf0a66
DM
468}
469
568de3d1
DM
470sub get_backup_dir {
471 my ($cfg, $storeid) = @_;
472
1dc01b9f
DM
473 my $scfg = storage_config($cfg, $storeid);
474 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 475
1dc01b9f 476 return $plugin->get_subdir($scfg, 'backup');
b6cf0a66
DM
477}
478
479# library implementation
480
b6cf0a66
DM
481sub parse_vmid {
482 my $vmid = shift;
483
484 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
485
486 return int($vmid);
487}
488
787624df
FG
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.
ec4b0dc7
AD
492sub parse_volname {
493 my ($cfg, $volid) = @_;
494
495 my ($storeid, $volname) = parse_volume_id($volid);
496
497 my $scfg = storage_config($cfg, $storeid);
498
499 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
a6f12626
DM
500
501 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
502
ec4b0dc7
AD
503 return $plugin->parse_volname($volname);
504}
505
b6cf0a66
DM
506sub parse_volume_id {
507 my ($volid, $noerr) = @_;
508
a7f3d909 509 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
b6cf0a66
DM
510}
511
04a13668
DM
512# test if we have read access to volid
513sub check_volume_access {
21c7b546 514 my ($rpcenv, $user, $cfg, $vmid, $volid, $type) = @_;
04a13668
DM
515
516 my ($sid, $volname) = parse_volume_id($volid, 1);
517 if ($sid) {
21c7b546
FE
518 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
519
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');
523
3e1a618e
FE
524 return if $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate'], 1);
525
04a13668 526 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
775fdc69 527 # require at least read access to storage, (custom) templates/ISOs could be sensitive
061b9ca6 528 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
04a13668
DM
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']);
42352a49
FE
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']);
04a13668 537 } else {
3e1a618e 538 die "missing privileges to access $volid\n";
04a13668
DM
539 }
540 } else {
541 die "Only root can pass arbitrary filesystem paths."
542 if $user ne 'root@pam';
543 }
544
545 return undef;
546}
547
50853be2
FE
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.
551sub volume_is_base_and_used {
552 my ($cfg, $volid) = @_;
553
554 my ($storeid, $volname) = parse_volume_id($volid);
555 my $scfg = storage_config($cfg, $storeid);
556 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
17fb7e42
FG
557
558 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
559 $plugin->parse_volname($volname);
560
561 if ($isBase) {
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;
567
568 eval{
569 (undef, undef, undef, $basename, $basevmid) =
570 $plugin->parse_volname($tmpvolname);
571 };
572
573 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
574 return 1;
575 }
576 }
577 }
578 return 0;
17fb7e42
FG
579}
580
b6cf0a66
DM
581# try to map a filesystem path to a volume identifier
582sub path_to_volume_id {
583 my ($cfg, $path) = @_;
584
585 my $ids = $cfg->{ids};
586
1dc01b9f 587 my ($sid, $volname) = parse_volume_id($path, 1);
b6cf0a66 588 if ($sid) {
1dc01b9f 589 if (my $scfg = $ids->{$sid}) {
188aca38 590 if ($scfg->{path}) {
1dc01b9f
DM
591 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
592 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
b6cf0a66
DM
593 return ($vtype, $path);
594 }
595 }
596 return ('');
597 }
598
1a3459ac 599 # Note: abs_path() return undef if $path doesn not exist
75d75990
DM
600 # for example when nfs storage is not mounted
601 $path = abs_path($path) || $path;
b6cf0a66
DM
602
603 foreach my $sid (keys %$ids) {
1dc01b9f
DM
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');
73fcb7bf 612 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
b6cf0a66
DM
613
614 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
615 my $vmid = $1;
616 my $name = $2;
fcbec654
DM
617
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});
624 }
625 }
cd461a50 626 } elsif ($path =~ m!^$isodir/([^/]+$ISO_EXT_RE_0)$!) {
b6cf0a66 627 my $name = $1;
1a3459ac 628 return ('iso', "$sid:iso/$name");
cd461a50 629 } elsif ($path =~ m!^$tmpldir/([^/]+$VZTMPL_EXT_RE_1)$!) {
b6cf0a66
DM
630 my $name = $1;
631 return ('vztmpl', "$sid:vztmpl/$name");
1ac17c74
DM
632 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
633 my $vmid = $1;
634 return ('rootdir', "$sid:rootdir/$vmid");
18bf2e59 635 } elsif ($path =~ m!^$backupdir/([^/]+$BACKUP_EXT_RE_2)$!) {
568de3d1 636 my $name = $1;
892dc992 637 return ('backup', "$sid:backup/$name");
73fcb7bf
AA
638 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
639 my $name = $1;
640 return ('snippets', "$sid:snippets/$name");
b6cf0a66
DM
641 }
642 }
643
644 # can't map path to volume id
645 return ('');
646}
647
648sub path {
207ea852 649 my ($cfg, $volid, $snapname) = @_;
b6cf0a66 650
1dc01b9f 651 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 652
1dc01b9f 653 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 654
1dc01b9f 655 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
207ea852 656 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
2494896a 657 return wantarray ? ($path, $owner, $vtype) : $path;
b6cf0a66
DM
658}
659
35fbb2e6 660sub abs_filesystem_path {
4b84ad5e 661 my ($cfg, $volid, $allow_blockdev) = @_;
35fbb2e6
DM
662
663 my $path;
6ed43d81
TL
664 if (parse_volume_id ($volid, 1)) {
665 activate_volumes($cfg, [ $volid ]);
35fbb2e6
DM
666 $path = PVE::Storage::path($cfg, $volid);
667 } else {
4b84ad5e 668 if (-f $volid || ($allow_blockdev && -b $volid)) {
35fbb2e6
DM
669 my $abspath = abs_path($volid);
670 if ($abspath && $abspath =~ m|^(/.+)$|) {
671 $path = $1; # untaint any path
672 }
673 }
674 }
4b84ad5e
DJ
675 die "can't find file '$volid'\n"
676 if !($path && (-f $path || ($allow_blockdev && -b $path)));
35fbb2e6
DM
677
678 return $path;
679}
680
f78f26ae 681# used as last resort to adapt volnames when migrating
683a3f46 682my $volname_for_storage = sub {
f78f26ae 683 my ($cfg, $storeid, $name, $vmid, $format) = @_;
683a3f46 684
f78f26ae 685 my $scfg = storage_config($cfg, $storeid);
683a3f46 686
f78f26ae 687 my (undef, $valid_formats) = PVE::Storage::Plugin::default_format($scfg);
683a3f46 688 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
f78f26ae
FG
689 die "unsupported format '$format' for storage type $scfg->{type}\n"
690 if !$format_is_valid;
683a3f46
FE
691
692 (my $name_without_extension = $name) =~ s/\.$format$//;
693
f78f26ae 694 if ($scfg->{path}) {
683a3f46
FE
695 return "$vmid/$name_without_extension.$format";
696 } else {
697 return "$name_without_extension";
698 }
699};
700
05b07a67
FG
701# whether a migration snapshot is needed for a given storage
702sub storage_migrate_snapshot {
686b0737 703 my ($cfg, $storeid, $existing_snapshots) = @_;
05b07a67
FG
704 my $scfg = storage_config($cfg, $storeid);
705
686b0737 706 return $scfg->{type} eq 'zfspool' || ($scfg->{type} eq 'btrfs' && $existing_snapshots);
05b07a67
FG
707}
708
7a158d0b
FG
709my $volume_import_prepare = sub {
710 my ($volid, $format, $path, $apiver, $opts) = @_;
dc3655a1
FE
711
712 my $base_snapshot = $opts->{base_snapshot};
713 my $snapshot = $opts->{snapshot};
dc3655a1 714 my $with_snapshots = $opts->{with_snapshots} ? 1 : 0;
7a158d0b 715 my $migration_snapshot = $opts->{migration_snapshot} ? 1 : 0;
dc3655a1 716 my $allow_rename = $opts->{allow_rename} ? 1 : 0;
b6cf0a66 717
7a158d0b
FG
718 my $recv = ['pvesm', 'import', $volid, $format, $path, '-with-snapshots', $with_snapshots];
719 if (defined($snapshot)) {
720 push @$recv, '-snapshot', $snapshot;
721 }
722 if ($migration_snapshot) {
723 push @$recv, '-delete-snapshot', $snapshot;
724 }
725 push @$recv, '-allow-rename', $allow_rename if $apiver >= 5;
726
727 if (defined($base_snapshot)) {
728 # Check if the snapshot exists on the remote side:
729 push @$recv, '-base', $base_snapshot if $apiver >= 9;
730 }
731
732 return $recv;
733};
734
735my $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};
742
743 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
744 if (defined($snapshot)) {
745 push @$send, '-snapshot', $snapshot;
746 }
747 if (defined($base_snapshot)) {
748 push @$send, '-base', $base_snapshot;
749 }
750
751 my $cstream;
752 if (defined($ratelimit_bps)) {
753 $cstream = [ '/usr/bin/cstream', '-t', $ratelimit_bps ];
0bbb358c 754 $logfunc->("using a bandwidth limit of $ratelimit_bps bytes per second for transferring '$volid'") if $logfunc;
7a158d0b
FG
755 }
756
757 volume_snapshot($cfg, $volid, $snapshot) if $migration_snapshot;
758
759 if (defined($snapshot)) {
760 activate_volumes($cfg, [$volid], $snapshot);
761 } else {
762 activate_volumes($cfg, [$volid]);
763 }
764
765 return $cstream ? [ $send, $cstream ] : [ $send ];
766};
767
768sub storage_migrate {
769 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
770
771 my $insecure = $opts->{insecure};
772
6bf56298 773 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 774
6bf56298 775 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
776
777 # no need to migrate shared content
a97d3ee4 778 return $volid if $storeid eq $target_storeid && $scfg->{shared};
b6cf0a66 779
6bf56298 780 my $tcfg = storage_config($cfg, $target_storeid);
b6cf0a66 781
683a3f46
FE
782 my $target_volname;
783 if ($opts->{target_volname}) {
784 $target_volname = $opts->{target_volname};
785 } elsif ($scfg->{type} eq $tcfg->{type}) {
786 $target_volname = $volname;
787 } else {
f78f26ae
FG
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);
683a3f46
FE
790 }
791
b6cf0a66
DM
792 my $target_volid = "${target_storeid}:${target_volname}";
793
4b4c580d 794 my $target_ip = $target_sshinfo->{ip};
b6cf0a66 795
65bb9859
FG
796 my $ssh = PVE::SSHInfo::ssh_info_to_command($target_sshinfo);
797 my $ssh_base = PVE::SSHInfo::ssh_info_to_command_base($target_sshinfo);
47cea194 798 local $ENV{RSYNC_RSH} = PVE::Tools::cmd2string($ssh_base);
b6cf0a66 799
7a158d0b
FG
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};
93d1812e 803 }
01f7e902 804
7a158d0b 805 my @formats = volume_transfer_formats($cfg, $volid, $target_volid, $opts->{snapshot}, $opts->{base_snapshot}, $opts->{with_snapshots});
da72898c
WB
806 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
807 my $format = $formats[0];
7459cb3d 808
228e5be9 809 my $import_fn = '-'; # let pvesm import read from stdin per default
da72898c 810 if ($insecure) {
228e5be9
TL
811 my $net = $target_sshinfo->{network} // $target_sshinfo->{ip};
812 $import_fn = "tcp://$net";
da72898c 813 }
7ba34faa 814
a97d3ee4
FE
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); };
819
7a158d0b 820 my $recv = [ @$ssh, '--', $volume_import_prepare->($target_volid, $format, $import_fn, $target_apiver, $opts)->@* ];
ac191ec7 821
a97d3ee4
FE
822 my $new_volid;
823 my $pattern = volume_imported_message(undef, 1);
aa82ad5c 824 # Matches new volid and rate-limits dd output
a97d3ee4
FE
825 my $match_volid_and_log = sub {
826 my $line = shift;
aa82ad5c
LN
827 my $show = 1;
828
9bd1c95a
TL
829 if ($line =~ /(?:\d+ bytes)(?:.+?copied, )(\d+) s/) { # rate-limit dd logs
830 my $elapsed = int($1);
831 if ($elapsed < 60) {
aa82ad5c 832 $show = !($1 % 3);
9bd1c95a 833 } elsif ($elapsed < 600) {
aa82ad5c 834 $show = !($1 % 10);
9bd1c95a 835 } else {
aa82ad5c
LN
836 $show = !($1 % 30);
837 }
838 }
a97d3ee4
FE
839
840 $new_volid = $1 if ($line =~ $pattern);
841
aa82ad5c 842 if ($logfunc && $show) {
a97d3ee4
FE
843 chomp($line);
844 $logfunc->($line);
845 }
846 };
847
7a158d0b 848 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
5324ceff 849
da72898c
WB
850 eval {
851 if ($insecure) {
57acd6a1
FE
852 my $input = IO::File->new();
853 my $info = IO::File->new();
7a158d0b 854 open3($input, $info, $info, @$recv)
da72898c 855 or die "receive command failed: $!\n";
57acd6a1
FE
856 close($input);
857
7cdc75a2
FE
858 my $try_ip = <$info> // '';
859 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
860 or die "no tunnel IP received, got '$try_ip'\n";
861
862 my $try_port = <$info> // '';
863 my ($port) = $try_port =~ /^(\d+)$/ # untaint
864 or die "no tunnel port received, got '$try_port'\n";
865
da72898c
WB
866 my $socket = IO::Socket::IP->new(PeerHost => $ip, PeerPort => $port, Type => SOCK_STREAM)
867 or die "failed to connect to tunnel at $ip:$port\n";
868 # we won't be reading from the socket
869 shutdown($socket, 0);
57acd6a1 870
aa82ad5c 871 eval { run_command($cmds, output => '>&'.fileno($socket), errfunc => $match_volid_and_log); };
57acd6a1
FE
872 my $send_error = $@;
873
da72898c
WB
874 # don't close the connection entirely otherwise the receiving end
875 # might not get all buffered data (and fails with 'connection reset by peer')
876 shutdown($socket, 1);
aca83310
FE
877
878 # wait for the remote process to finish
a97d3ee4
FE
879 while (my $line = <$info>) {
880 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
aca83310
FE
881 }
882
da72898c
WB
883 # now close the socket
884 close($socket);
885 if (!close($info)) { # does waitpid()
886 die "import failed: $!\n" if $!;
887 die "import failed: exit code ".($?>>8)."\n";
0a29ad61 888 }
57acd6a1
FE
889
890 die $send_error if $send_error;
0a29ad61 891 } else {
7a158d0b
FG
892 push @$cmds, $recv;
893 run_command($cmds, logfunc => $match_volid_and_log);
0a29ad61 894 }
a97d3ee4
FE
895
896 die "unable to get ID of the migrated volume\n"
897 if !defined($new_volid) && $target_apiver >= 5;
da72898c
WB
898 };
899 my $err = $@;
900 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
7a158d0b
FG
901 if ($opts->{migration_snapshot}) {
902 eval { volume_snapshot_delete($cfg, $volid, $opts->{snapshot}, 0) };
da72898c 903 warn "could not remove source snapshot: $@\n" if $@;
b6cf0a66 904 }
da72898c 905 die $err if $err;
a97d3ee4
FE
906
907 return $new_volid // $target_volid;
b6cf0a66
DM
908}
909
2502b33b 910sub vdisk_clone {
7bbc4004 911 my ($cfg, $volid, $vmid, $snap) = @_;
1a3459ac 912
2502b33b
DM
913 my ($storeid, $volname) = parse_volume_id($volid);
914
915 my $scfg = storage_config($cfg, $storeid);
916
917 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 918
2502b33b
DM
919 activate_storage($cfg, $storeid);
920
921 # lock shared storage
922 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
7bbc4004 923 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
2502b33b
DM
924 return "$storeid:$volname";
925 });
926}
927
928sub vdisk_create_base {
929 my ($cfg, $volid) = @_;
930
931 my ($storeid, $volname) = parse_volume_id($volid);
932
933 my $scfg = storage_config($cfg, $storeid);
934
935 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 936
2502b33b
DM
937 activate_storage($cfg, $storeid);
938
939 # lock shared storage
940 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
941 my $volname = $plugin->create_base($storeid, $scfg, $volname);
942 return "$storeid:$volname";
943 });
944}
945
40d69893
DM
946sub map_volume {
947 my ($cfg, $volid, $snapname) = @_;
948
949 my ($storeid, $volname) = parse_volume_id($volid);
950
951 my $scfg = storage_config($cfg, $storeid);
952
953 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
954
955 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
956}
957
958sub unmap_volume {
959 my ($cfg, $volid, $snapname) = @_;
960
961 my ($storeid, $volname) = parse_volume_id($volid);
962
963 my $scfg = storage_config($cfg, $storeid);
964
965 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
966
967 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
968}
969
1dc01b9f
DM
970sub vdisk_alloc {
971 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
b6cf0a66 972
82fc923f 973 die "no storage ID specified\n" if !$storeid;
b6cf0a66 974
1dc01b9f 975 PVE::JSONSchema::parse_storage_id($storeid);
b6cf0a66 976
1dc01b9f 977 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 978
1dc01b9f 979 die "no VMID specified\n" if !$vmid;
b6cf0a66 980
1dc01b9f 981 $vmid = parse_vmid($vmid);
b6cf0a66 982
1dc01b9f 983 my $defformat = PVE::Storage::Plugin::default_format($scfg);
b6cf0a66 984
1dc01b9f 985 $fmt = $defformat if !$fmt;
b6cf0a66 986
1dc01b9f 987 activate_storage($cfg, $storeid);
3af60e62 988
1dc01b9f 989 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 990
1dc01b9f
DM
991 # lock shared storage
992 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
afdfbe55
WB
993 my $old_umask = umask(umask|0037);
994 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
995 my $err = $@;
996 umask $old_umask;
997 die $err if $err;
1dc01b9f
DM
998 return "$storeid:$volname";
999 });
b6cf0a66
DM
1000}
1001
1dc01b9f
DM
1002sub vdisk_free {
1003 my ($cfg, $volid) = @_;
b6cf0a66 1004
1dc01b9f 1005 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f 1006 my $scfg = storage_config($cfg, $storeid);
1dc01b9f 1007 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 1008
1dc01b9f 1009 activate_storage($cfg, $storeid);
b6cf0a66 1010
1dc01b9f 1011 my $cleanup_worker;
b6cf0a66 1012
1dc01b9f
DM
1013 # lock shared storage
1014 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
787624df 1015 # LVM-thin allows deletion of still referenced base volumes!
17fb7e42 1016 die "base volume '$volname' is still in use by linked clones\n"
50853be2 1017 if volume_is_base_and_used($cfg, $volid);
32437ed2 1018
17fb7e42 1019 my (undef, undef, undef, undef, undef, $isBase, $format) =
32437ed2 1020 $plugin->parse_volname($volname);
35533c68 1021 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1dc01b9f 1022 });
b6cf0a66 1023
1dc01b9f 1024 return if !$cleanup_worker;
b6cf0a66 1025
1dc01b9f
DM
1026 my $rpcenv = PVE::RPCEnvironment::get();
1027 my $authuser = $rpcenv->get_user();
b6cf0a66 1028
1dc01b9f 1029 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
b6cf0a66
DM
1030}
1031
b6cf0a66 1032sub vdisk_list {
2c5246e1 1033 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
b6cf0a66
DM
1034
1035 my $ids = $cfg->{ids};
1036
1037 storage_check_enabled($cfg, $storeid) if ($storeid);
1038
d96b789a 1039 my $res = $storeid ? { $storeid => [] } : {};
b6cf0a66
DM
1040
1041 # prepare/activate/refresh all storages
1042
b6cf0a66
DM
1043 my $storage_list = [];
1044 if ($vollist) {
1045 foreach my $volid (@$vollist) {
1dc01b9f
DM
1046 my ($sid, undef) = parse_volume_id($volid);
1047 next if !defined($ids->{$sid});
b6cf0a66
DM
1048 next if !storage_check_enabled($cfg, $sid, undef, 1);
1049 push @$storage_list, $sid;
b6cf0a66
DM
1050 }
1051 } else {
1052 foreach my $sid (keys %$ids) {
1053 next if $storeid && $storeid ne $sid;
1054 next if !storage_check_enabled($cfg, $sid, undef, 1);
c43655d2 1055 my $content = $ids->{$sid}->{content};
2c5246e1 1056 next if defined($ctype) && !$content->{$ctype};
c43655d2 1057 next if !($content->{rootdir} || $content->{images});
b6cf0a66 1058 push @$storage_list, $sid;
b6cf0a66
DM
1059 }
1060 }
1061
1dc01b9f 1062 my $cache = {};
b6cf0a66 1063
1dc01b9f 1064 activate_storage_list($cfg, $storage_list, $cache);
b6cf0a66 1065
d96b789a 1066 for my $sid ($storage_list->@*) {
1dc01b9f 1067 next if $storeid && $storeid ne $sid;
b6cf0a66 1068
1dc01b9f
DM
1069 my $scfg = $ids->{$sid};
1070 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1071 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
b6cf0a66
DM
1072 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
1073 }
1074
1075 return $res;
1076}
1077
c2fc9fbe
DM
1078sub template_list {
1079 my ($cfg, $storeid, $tt) = @_;
1080
1081 die "unknown template type '$tt'\n"
1082 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1083
1084 my $ids = $cfg->{ids};
1085
1086 storage_check_enabled($cfg, $storeid) if ($storeid);
1087
1088 my $res = {};
1089
1090 # query the storage
1091 foreach my $sid (keys %$ids) {
1092 next if $storeid && $storeid ne $sid;
1093
1094 my $scfg = $ids->{$sid};
1095 my $type = $scfg->{type};
1096
1097 next if !$scfg->{content}->{$tt};
1098
1099 next if !storage_check_enabled($cfg, $sid, undef, 1);
1100
1101 $res->{$sid} = volume_list($cfg, $sid, undef, $tt);
1102 }
1103
1104 return $res;
1105}
1106
37ba0aea
DM
1107sub volume_list {
1108 my ($cfg, $storeid, $vmid, $content) = @_;
1109
be785439 1110 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
37ba0aea
DM
1111
1112 my $cts = $content ? [ $content ] : [ @ctypes ];
1113
1114 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
1115
c2fc9fbe 1116 $cts = [ grep { defined($scfg->{content}->{$_}) } @$cts ];
37ba0aea 1117
c2fc9fbe 1118 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
37ba0aea 1119
c2fc9fbe
DM
1120 activate_storage($cfg, $storeid);
1121
1122 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1123
1124 @$res = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @$res;
37ba0aea
DM
1125
1126 return $res;
1127}
1128
b6cf0a66
DM
1129sub uevent_seqnum {
1130
1131 my $filename = "/sys/kernel/uevent_seqnum";
1132
1133 my $seqnum = 0;
1dc01b9f 1134 if (my $fh = IO::File->new($filename, "r")) {
b6cf0a66
DM
1135 my $line = <$fh>;
1136 if ($line =~ m/^(\d+)$/) {
1dc01b9f 1137 $seqnum = int($1);
b6cf0a66
DM
1138 }
1139 close ($fh);
1140 }
1141 return $seqnum;
1142}
1143
f3d4ef46 1144sub activate_storage {
1dc01b9f 1145 my ($cfg, $storeid, $cache) = @_;
b6cf0a66 1146
f3d4ef46
DM
1147 $cache = {} if !$cache;
1148
b6cf0a66
DM
1149 my $scfg = storage_check_enabled($cfg, $storeid);
1150
1dc01b9f 1151 return if $cache->{activated}->{$storeid};
b6cf0a66 1152
1dc01b9f 1153 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
b6cf0a66 1154
1dc01b9f 1155 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 1156
1dc01b9f
DM
1157 if ($scfg->{base}) {
1158 my ($baseid, undef) = parse_volume_id ($scfg->{base});
f3d4ef46
DM
1159 activate_storage($cfg, $baseid, $cache);
1160 }
1161
38431808
FE
1162 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1163 die "connection check for storage '$storeid' failed - $@\n" if $@;
f3d4ef46 1164 die "storage '$storeid' is not online\n";
b6cf0a66
DM
1165 }
1166
1dc01b9f
DM
1167 $plugin->activate_storage($storeid, $scfg, $cache);
1168
b6cf0a66
DM
1169 my $newseq = uevent_seqnum ();
1170
1171 # only call udevsettle if there are events
1dc01b9f 1172 if ($newseq > $cache->{uevent_seqnum}) {
d3a5e309 1173 system ("udevadm settle --timeout=30"); # ignore errors
1dc01b9f 1174 $cache->{uevent_seqnum} = $newseq;
b6cf0a66
DM
1175 }
1176
1dc01b9f 1177 $cache->{activated}->{$storeid} = 1;
b6cf0a66
DM
1178}
1179
1180sub activate_storage_list {
1dc01b9f 1181 my ($cfg, $storeid_list, $cache) = @_;
b6cf0a66 1182
1dc01b9f 1183 $cache = {} if !$cache;
b6cf0a66
DM
1184
1185 foreach my $storeid (@$storeid_list) {
f3d4ef46 1186 activate_storage($cfg, $storeid, $cache);
b6cf0a66
DM
1187 }
1188}
1189
1dc01b9f
DM
1190sub deactivate_storage {
1191 my ($cfg, $storeid) = @_;
1192
1193 my $scfg = storage_config ($cfg, $storeid);
1194 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 1195
1dc01b9f
DM
1196 my $cache = {};
1197 $plugin->deactivate_storage($storeid, $scfg, $cache);
b6cf0a66
DM
1198}
1199
1200sub activate_volumes {
02e797b8 1201 my ($cfg, $vollist, $snapname) = @_;
6703353b
DM
1202
1203 return if !($vollist && scalar(@$vollist));
1204
b6cf0a66
DM
1205 my $storagehash = {};
1206 foreach my $volid (@$vollist) {
1dc01b9f 1207 my ($storeid, undef) = parse_volume_id($volid);
b6cf0a66
DM
1208 $storagehash->{$storeid} = 1;
1209 }
1210
1dc01b9f
DM
1211 my $cache = {};
1212
1213 activate_storage_list($cfg, [keys %$storagehash], $cache);
b6cf0a66
DM
1214
1215 foreach my $volid (@$vollist) {
5521b580 1216 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f
DM
1217 my $scfg = storage_config($cfg, $storeid);
1218 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
02e797b8 1219 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
b6cf0a66
DM
1220 }
1221}
1222
1223sub deactivate_volumes {
02e797b8 1224 my ($cfg, $vollist, $snapname) = @_;
b6cf0a66 1225
6703353b
DM
1226 return if !($vollist && scalar(@$vollist));
1227
1dc01b9f
DM
1228 my $cache = {};
1229
6703353b 1230 my @errlist = ();
b6cf0a66 1231 foreach my $volid (@$vollist) {
1dc01b9f 1232 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 1233
1dc01b9f
DM
1234 my $scfg = storage_config($cfg, $storeid);
1235 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 1236
1dc01b9f 1237 eval {
02e797b8 1238 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1dc01b9f
DM
1239 };
1240 if (my $err = $@) {
1241 warn $err;
1242 push @errlist, $volid;
b6cf0a66
DM
1243 }
1244 }
6703353b 1245
82fc923f 1246 die "volume deactivation failed: " . join(' ', @errlist)
6703353b 1247 if scalar(@errlist);
b6cf0a66
DM
1248}
1249
1a3459ac 1250sub storage_info {
856c54bd 1251 my ($cfg, $content, $includeformat) = @_;
b6cf0a66
DM
1252
1253 my $ids = $cfg->{ids};
1254
1255 my $info = {};
ff3badd8 1256
583c2802 1257 my @ctypes = PVE::Tools::split_list($content);
ff3badd8 1258
b6cf0a66
DM
1259 my $slist = [];
1260 foreach my $storeid (keys %$ids) {
6ce4f724 1261 my $storage_enabled = defined(storage_check_enabled($cfg, $storeid, undef, 1));
b6cf0a66 1262
d73060be
DM
1263 if (defined($content)) {
1264 my $want_ctype = 0;
1265 foreach my $ctype (@ctypes) {
1266 if ($ids->{$storeid}->{content}->{$ctype}) {
1267 $want_ctype = 1;
1268 last;
1269 }
583c2802 1270 }
6ce4f724 1271 next if !$want_ctype || !$storage_enabled;
583c2802 1272 }
ff3badd8 1273
b6cf0a66
DM
1274 my $type = $ids->{$storeid}->{type};
1275
1a3459ac 1276 $info->{$storeid} = {
b6cf0a66 1277 type => $type,
1a3459ac
DM
1278 total => 0,
1279 avail => 0,
1280 used => 0,
04a2e4f3 1281 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1dc01b9f 1282 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
b6cf0a66 1283 active => 0,
6ce4f724 1284 enabled => $storage_enabled ? 1 : 0,
b6cf0a66
DM
1285 };
1286
b6cf0a66
DM
1287 push @$slist, $storeid;
1288 }
1289
1dc01b9f 1290 my $cache = {};
b6cf0a66 1291
b6cf0a66
DM
1292 foreach my $storeid (keys %$ids) {
1293 my $scfg = $ids->{$storeid};
b43b073b 1294
b6cf0a66 1295 next if !$info->{$storeid};
b43b073b 1296 next if !$info->{$storeid}->{enabled};
b6cf0a66 1297
856c54bd
DC
1298 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1299 if ($includeformat) {
1300 my $pd = $plugin->plugindata();
1301 $info->{$storeid}->{format} = $pd->{format}
1302 if $pd->{format};
1303 $info->{$storeid}->{select_existing} = $pd->{select_existing}
1304 if $pd->{select_existing};
1305 }
1306
f3d4ef46
DM
1307 eval { activate_storage($cfg, $storeid, $cache); };
1308 if (my $err = $@) {
1309 warn $err;
1310 next;
1311 }
1312
41aacc6c 1313 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
7028645e 1314 warn $@ if $@;
1dc01b9f 1315 next if !$active;
ff3badd8
DM
1316 $info->{$storeid}->{total} = int($total);
1317 $info->{$storeid}->{avail} = int($avail);
1318 $info->{$storeid}->{used} = int($used);
1dc01b9f 1319 $info->{$storeid}->{active} = $active;
b6cf0a66
DM
1320 }
1321
1322 return $info;
1323}
1324
1325sub resolv_server {
1326 my ($server) = @_;
1a3459ac 1327
c67daeac
WB
1328 my ($packed_ip, $family);
1329 eval {
1330 my @res = PVE::Tools::getaddrinfo_all($server);
1331 $family = $res[0]->{family};
1332 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1333 };
b6cf0a66 1334 if (defined $packed_ip) {
ee302b1c 1335 return Socket::inet_ntop($family, $packed_ip);
b6cf0a66
DM
1336 }
1337 return undef;
1338}
1339
1340sub scan_nfs {
1341 my ($server_in) = @_;
1342
1343 my $server;
1344 if (!($server = resolv_server ($server_in))) {
1345 die "unable to resolve address for server '${server_in}'\n";
1346 }
1347
1348 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1349
1350 my $res = {};
f81372ac 1351 run_command($cmd, outfunc => sub {
b6cf0a66
DM
1352 my $line = shift;
1353
1354 # note: howto handle white spaces in export path??
1355 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1356 $res->{$1} = $2;
1357 }
1358 });
1359
1360 return $res;
1361}
1362
4cab0acd
WL
1363sub scan_cifs {
1364 my ($server_in, $user, $password, $domain) = @_;
1365
436773fd
TL
1366 my $server = resolv_server($server_in);
1367 die "unable to resolve address for server '${server_in}'\n" if !$server;
4cab0acd 1368
436773fd 1369 # we only support Windows 2012 and newer, so just use smb3
4cab0acd 1370 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
fd55f51e 1371 push @$cmd, '-W', $domain if defined($domain);
afaa98f1 1372
8594155a 1373 push @$cmd, '-N' if !defined($password);
afaa98f1
TL
1374 local $ENV{USER} = $user if defined($user);
1375 local $ENV{PASSWD} = $password if defined($password);
4cab0acd
WL
1376
1377 my $res = {};
be18d6da 1378 my $err = '';
4cab0acd 1379 run_command($cmd,
436773fd 1380 noerr => 1,
be18d6da
TL
1381 errfunc => sub {
1382 $err .= "$_[0]\n"
1383 },
436773fd
TL
1384 outfunc => sub {
1385 my $line = shift;
1386 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1387 $res->{$1} = $2;
c42d8655
TL
1388 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1389 my $status = $1;
1390 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
436773fd
TL
1391 }
1392 },
4cab0acd 1393 );
d37729b9
TL
1394 # only die if we got no share, else it's just some followup check error
1395 # (like workgroup querying)
1396 raise($err) if $err && !%$res;
4cab0acd
WL
1397
1398 return $res;
1399}
1400
584d97f6
DM
1401sub scan_zfs {
1402
3881e680 1403 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
584d97f6
DM
1404
1405 my $res = [];
1406 run_command($cmd, outfunc => sub {
1407 my $line = shift;
1408
1409 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
3932390b 1410 my ($pool, $size_str, $used_str) = ($1, $2, $3);
3881e680
AL
1411 my $size = $size_str + 0;
1412 my $used = $used_str + 0;
48e27f79 1413 # ignore subvolumes generated by our ZFSPoolPlugin
851658c3
WL
1414 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1415 return if $pool =~ m!/basevol-\d+-[^/]+$!;
3932390b 1416 push @$res, { pool => $pool, size => $size, free => $size-$used };
584d97f6
DM
1417 }
1418 });
1419
1420 return $res;
1421}
1422
b6cf0a66
DM
1423sub resolv_portal {
1424 my ($portal, $noerr) = @_;
1425
1689e627
WB
1426 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1427 if ($server) {
b6cf0a66
DM
1428 if (my $ip = resolv_server($server)) {
1429 $server = $ip;
1689e627 1430 $server = "[$server]" if $server =~ /^$IPV6RE$/;
b6cf0a66
DM
1431 return $port ? "$server:$port" : $server;
1432 }
1433 }
1434 return undef if $noerr;
1435
1436 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1437}
1438
b6cf0a66
DM
1439
1440sub scan_iscsi {
1441 my ($portal_in) = @_;
1442
1443 my $portal;
1dc01b9f 1444 if (!($portal = resolv_portal($portal_in))) {
b6cf0a66
DM
1445 die "unable to parse/resolve portal address '${portal_in}'\n";
1446 }
1447
1dc01b9f 1448 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
b6cf0a66
DM
1449}
1450
1451sub storage_default_format {
1452 my ($cfg, $storeid) = @_;
1453
1454 my $scfg = storage_config ($cfg, $storeid);
1455
1dc01b9f 1456 return PVE::Storage::Plugin::default_format($scfg);
b6cf0a66
DM
1457}
1458
1459sub vgroup_is_used {
1460 my ($cfg, $vgname) = @_;
1461
1462 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1463 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1464 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1465 return 1;
1466 }
1467 }
1468
1469 return undef;
1470}
1471
1472sub target_is_used {
1473 my ($cfg, $target) = @_;
1474
1475 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1476 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1477 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1478 return 1;
1479 }
1480 }
1481
1482 return undef;
1483}
1484
1485sub volume_is_used {
1486 my ($cfg, $volid) = @_;
1487
1488 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1489 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1490 if ($scfg->{base} && $scfg->{base} eq $volid) {
1491 return 1;
1492 }
1493 }
1494
1495 return undef;
1496}
1497
1498sub storage_is_used {
1499 my ($cfg, $storeid) = @_;
1500
1501 foreach my $sid (keys %{$cfg->{ids}}) {
1dc01b9f 1502 my $scfg = storage_config($cfg, $sid);
b6cf0a66 1503 next if !$scfg->{base};
1dc01b9f 1504 my ($st) = parse_volume_id($scfg->{base});
b6cf0a66
DM
1505 return 1 if $st && $st eq $storeid;
1506 }
1507
1508 return undef;
1509}
1510
1511sub foreach_volid {
1512 my ($list, $func) = @_;
1513
1514 return if !$list;
1515
1516 foreach my $sid (keys %$list) {
1517 foreach my $info (@{$list->{$sid}}) {
618bdfd9 1518 my $volid = $info->{volid};
1dc01b9f 1519 my ($sid1, $volname) = parse_volume_id($volid, 1);
b6cf0a66
DM
1520 if ($sid1 && $sid1 eq $sid) {
1521 &$func ($volid, $sid, $info);
1522 } else {
1523 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1524 }
1525 }
1526 }
1527}
1528
cd554b79
AA
1529sub decompressor_info {
1530 my ($format, $comp) = @_;
1531
1532 if ($format eq 'tgz' && !defined($comp)) {
1533 ($format, $comp) = ('tar', 'gz');
1534 }
1535
1536 my $decompressor = {
1537 tar => {
1538 gz => ['tar', '-z'],
1539 lzo => ['tar', '--lzop'],
014d36db 1540 zst => ['tar', '--zstd'],
cd554b79
AA
1541 },
1542 vma => {
1543 gz => ['zcat'],
1544 lzo => ['lzop', '-d', '-c'],
014d36db 1545 zst => ['zstd', '-q', '-d', '-c'],
2197ff97
PH
1546 },
1547 iso => {
2197ff97
PH
1548 gz => ['zcat'],
1549 lzo => ['lzop', '-d', '-c'],
1550 zst => ['zstd', '-q', '-d', '-c'],
cd554b79
AA
1551 },
1552 };
1553
1554 die "ERROR: archive format not defined\n"
1555 if !defined($decompressor->{$format});
1556
1207620c
TL
1557 my $decomp;
1558 $decomp = $decompressor->{$format}->{$comp} if $comp;
cd554b79
AA
1559
1560 my $info = {
1561 format => $format,
1562 compression => $comp,
1563 decompressor => $decomp,
1564 };
1565
1566 return $info;
1567}
1568
56897a92
FE
1569sub protection_file_path {
1570 my ($path) = @_;
1571
1572 return "${path}.protected";
1573}
1574
cd554b79
AA
1575sub archive_info {
1576 my ($archive) = shift;
1577 my $info;
1578
1579 my $volid = basename($archive);
18bf2e59 1580 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
e34afeb1 1581 my $filename = "$1"; # untaint
18bf2e59
LS
1582 my ($type, $extension, $comp) = ($2, $3, $4);
1583 (my $format = $extension) =~ s/\..*//;
fb821c18 1584 $info = decompressor_info($format, $comp);
e34afeb1 1585 $info->{filename} = $filename;
fb821c18
FE
1586 $info->{type} = $type;
1587
18bf2e59 1588 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${extension}$/) {
90778f7c
DT
1589 $info->{logfilename} = "$1".PVE::Storage::Plugin::LOG_EXT;
1590 $info->{notesfilename} = "$filename".PVE::Storage::Plugin::NOTES_EXT;
e34afeb1 1591 $info->{vmid} = int($2);
b1ddc54a 1592 $info->{ctime} = timelocal($8, $7, $6, $5, $4 - 1, $3);
fb821c18
FE
1593 $info->{is_std_name} = 1;
1594 } else {
1595 $info->{is_std_name} = 0;
1596 }
cd554b79 1597 } else {
bf5af0fb 1598 die "ERROR: couldn't determine archive info from '$archive'\n";
cd554b79
AA
1599 }
1600
1601 return $info;
1602}
1603
35a39532
FE
1604sub archive_remove {
1605 my ($archive_path) = @_;
1606
56897a92
FE
1607 die "cannot remove protected archive '$archive_path'\n"
1608 if -e protection_file_path($archive_path);
1609
e573445e 1610 unlink $archive_path or $! == ENOENT or die "removing archive $archive_path failed: $!\n";
c3e2ff80
DT
1611
1612 archive_auxiliaries_remove($archive_path);
1613}
1614
1615sub archive_auxiliaries_remove {
1616 my ($archive_path) = @_;
1617
35a39532
FE
1618 my $dirname = dirname($archive_path);
1619 my $archive_info = eval { archive_info($archive_path) } // {};
35a39532 1620
c3e2ff80
DT
1621 for my $type (qw(log notes)) {
1622 my $filename = $archive_info->{"${type}filename"} or next;
1623 my $path = "$dirname/$filename";
35a39532 1624
c3e2ff80 1625 if (-e $path) {
3048641b 1626 unlink $path or $! == ENOENT or log_warn("Removing $type file failed: $!");
35a39532
FE
1627 }
1628 }
1629}
1630
8898dd7b
FG
1631sub extract_vzdump_config_tar {
1632 my ($archive, $conf_re) = @_;
1633
1634 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1635
1636 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1637 die "unable to open file '$archive'\n";
1638
1639 my $file;
1640 while (defined($file = <$fh>)) {
086c4bf1 1641 if ($file =~ $conf_re) {
8898dd7b
FG
1642 $file = $1; # untaint
1643 last;
1644 }
1645 }
1646
1647 kill 15, $pid;
1648 waitpid $pid, 0;
1649 close $fh;
1650
1651 die "ERROR: archive contains no configuration file\n" if !$file;
1652 chomp $file;
1653
1654 my $raw = '';
1655 my $out = sub {
1656 my $output = shift;
1657 $raw .= "$output\n";
1658 };
1659
63e89295 1660 run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
8898dd7b
FG
1661
1662 return wantarray ? ($raw, $file) : $raw;
1663}
1664
1665sub extract_vzdump_config_vma {
1666 my ($archive, $comp) = @_;
1667
8898dd7b 1668 my $raw = '';
63e89295 1669 my $out = sub { $raw .= "$_[0]\n"; };
8898dd7b 1670
cd554b79
AA
1671 my $info = archive_info($archive);
1672 $comp //= $info->{compression};
1673 my $decompressor = $info->{decompressor};
1674
8898dd7b 1675 if ($comp) {
63e89295 1676 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
8898dd7b 1677
63e89295 1678 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
8898dd7b
FG
1679 my $broken_pipe;
1680 my $errstring;
1681 my $err = sub {
1682 my $output = shift;
576e560d 1683 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
8898dd7b
FG
1684 $broken_pipe = 1;
1685 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1686 $errstring = "Failed to extract config from VMA archive: $output\n";
1687 }
1688 };
1689
63e89295 1690 my $rc = eval { run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1) };
8898dd7b
FG
1691 my $rerr = $@;
1692
63e89295
TL
1693 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1694
1695 if (!$errstring && !$broken_pipe && $rc != 0) {
8898dd7b
FG
1696 die "$rerr\n" if $rerr;
1697 die "config extraction failed with exit code $rc\n";
1698 }
1699 die "$errstring\n" if $errstring;
1700 } else {
63e89295 1701 run_command(["vma", "config", $archive], outfunc => $out);
8898dd7b
FG
1702 }
1703
1704 return wantarray ? ($raw, undef) : $raw;
1705}
1706
1707sub extract_vzdump_config {
1708 my ($cfg, $volid) = @_;
1709
c855ac15
DM
1710 my ($storeid, $volname) = parse_volume_id($volid);
1711 if (defined($storeid)) {
1712 my $scfg = storage_config($cfg, $storeid);
1713 if ($scfg->{type} eq 'pbs') {
1714 storage_check_enabled($cfg, $storeid);
1715 return PVE::Storage::PBSPlugin->extract_vzdump_config($scfg, $volname, $storeid);
1716 }
1717 }
1718
8898dd7b 1719 my $archive = abs_filesystem_path($cfg, $volid);
cd554b79
AA
1720 my $info = archive_info($archive);
1721 my $format = $info->{format};
1722 my $comp = $info->{compression};
1723 my $type = $info->{type};
8898dd7b 1724
cd554b79 1725 if ($type eq 'lxc' || $type eq 'openvz') {
086c4bf1 1726 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
cd554b79 1727 } elsif ($type eq 'qemu') {
8898dd7b
FG
1728 if ($format eq 'tar') {
1729 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1730 } else {
1731 return extract_vzdump_config_vma($archive, $comp);
1732 }
1733 } else {
1734 die "cannot determine backup guest type for backup archive '$volid'\n";
1735 }
1736}
1737
8f26b391
FE
1738sub prune_backups {
1739 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1740
1741 my $scfg = storage_config($cfg, $storeid);
1742 die "storage '$storeid' does not support backups\n" if !$scfg->{content}->{backup};
1743
1744 if (!defined($keep)) {
1745 die "no prune-backups options configured for storage '$storeid'\n"
1746 if !defined($scfg->{'prune-backups'});
1747 $keep = PVE::JSONSchema::parse_property_string('prune-backups', $scfg->{'prune-backups'});
1748 }
1749
883c811f
FE
1750 activate_storage($cfg, $storeid);
1751
8f26b391
FE
1752 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1753 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1754}
1755
1756my $prune_mark = sub {
1757 my ($prune_entries, $keep_count, $id_func) = @_;
1758
1759 return if !$keep_count;
1760
1761 my $already_included = {};
1762 my $newly_included = {};
1763
1764 foreach my $prune_entry (@{$prune_entries}) {
1765 my $mark = $prune_entry->{mark};
1766 my $id = $id_func->($prune_entry->{ctime});
10dfeb9e
FE
1767 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1768 }
8f26b391 1769
10dfeb9e
FE
1770 foreach my $prune_entry (@{$prune_entries}) {
1771 my $mark = $prune_entry->{mark};
1772 my $id = $id_func->($prune_entry->{ctime});
8f26b391 1773
10dfeb9e 1774 next if defined($mark) || $already_included->{$id};
8f26b391
FE
1775
1776 if (!$newly_included->{$id}) {
1777 last if scalar(keys %{$newly_included}) >= $keep_count;
1778 $newly_included->{$id} = 1;
1779 $prune_entry->{mark} = 'keep';
1780 } else {
1781 $prune_entry->{mark} = 'remove';
1782 }
1783 }
1784};
1785
1786sub prune_mark_backup_group {
1787 my ($backup_group, $keep) = @_;
1788
a000e26c 1789 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1b87f013 1790
a000e26c 1791 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
f514181d 1792 foreach my $prune_entry (@{$backup_group}) {
9a4c0e84
FE
1793 # preserve additional information like 'protected'
1794 next if $prune_entry->{mark} && $prune_entry->{mark} ne 'remove';
f514181d
FE
1795 $prune_entry->{mark} = 'keep';
1796 }
1797 return;
1798 }
1799
8f26b391
FE
1800 my $prune_list = [ sort { $b->{ctime} <=> $a->{ctime} } @{$backup_group} ];
1801
1802 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1803 my ($ctime) = @_;
1804 return $ctime;
1805 });
1806 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1807 my ($ctime) = @_;
1808 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1809 return "$hour/$day/$month/$year";
1810 });
1811 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1812 my ($ctime) = @_;
1813 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1814 return "$day/$month/$year";
1815 });
1816 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1817 my ($ctime) = @_;
1818 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
189e67ff
FE
1819 my $iso_week = int(strftime("%V", $sec, $min, $hour, $day, $month, $year));
1820 my $iso_week_year = int(strftime("%G", $sec, $min, $hour, $day, $month, $year));
8f26b391
FE
1821 return "$iso_week/$iso_week_year";
1822 });
1823 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1824 my ($ctime) = @_;
1825 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1826 return "$month/$year";
1827 });
1828 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1829 my ($ctime) = @_;
1830 my $year = (localtime($ctime))[5];
1831 return "$year";
1832 });
1833
1834 foreach my $prune_entry (@{$prune_list}) {
1835 $prune_entry->{mark} //= 'remove';
1836 }
1837}
1838
3cc29a04 1839sub volume_export : prototype($$$$$$$) {
47f37b53
WB
1840 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1841
1842 my ($storeid, $volname) = parse_volume_id($volid, 1);
1843 die "cannot export volume '$volid'\n" if !$storeid;
1844 my $scfg = storage_config($cfg, $storeid);
1845 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1846 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
618bdfd9 1847 $snapshot, $base_snapshot, $with_snapshots);
47f37b53
WB
1848}
1849
3cc29a04
WB
1850sub volume_import : prototype($$$$$$$$) {
1851 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
47f37b53
WB
1852
1853 my ($storeid, $volname) = parse_volume_id($volid, 1);
1854 die "cannot import into volume '$volid'\n" if !$storeid;
1855 my $scfg = storage_config($cfg, $storeid);
1856 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
3cc29a04
WB
1857 return $plugin->volume_import(
1858 $scfg,
1859 $storeid,
1860 $fh,
1861 $volname,
1862 $format,
1863 $snapshot,
1864 $base_snapshot,
1865 $with_snapshots,
1866 $allow_rename,
1867 ) // $volid;
1868}
1869
1870sub volume_export_formats : prototype($$$$$) {
d390328b
WB
1871 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1872
1873 my ($storeid, $volname) = parse_volume_id($volid, 1);
1874 return if !$storeid;
1875 my $scfg = storage_config($cfg, $storeid);
1876 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1877 return $plugin->volume_export_formats($scfg, $storeid, $volname,
618bdfd9
PH
1878 $snapshot, $base_snapshot,
1879 $with_snapshots);
d390328b
WB
1880}
1881
3cc29a04
WB
1882sub volume_import_formats : prototype($$$$$) {
1883 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
d390328b
WB
1884
1885 my ($storeid, $volname) = parse_volume_id($volid, 1);
1886 return if !$storeid;
1887 my $scfg = storage_config($cfg, $storeid);
1888 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
3cc29a04
WB
1889 return $plugin->volume_import_formats(
1890 $scfg,
1891 $storeid,
1892 $volname,
1893 $snapshot,
1894 $base_snapshot,
1895 $with_snapshots,
1896 );
d390328b
WB
1897}
1898
1899sub volume_transfer_formats {
1900 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1901 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
3cc29a04 1902 my @import_formats = volume_import_formats($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
d390328b
WB
1903 my %import_hash = map { $_ => 1 } @import_formats;
1904 my @common = grep { $import_hash{$_} } @export_formats;
1905 return @common;
1906}
1907
a97d3ee4
FE
1908sub volume_imported_message {
1909 my ($volid, $want_pattern) = @_;
1910
1911 if ($want_pattern) {
1912 return qr/successfully imported '([^']*)'$/;
1913 } else {
1914 return "successfully imported '$volid'\n";
1915 }
1916}
1917
3363fcf6
FG
1918# $format and $volname are requests and might be overruled depending on $opts
1919# $opts:
1920# - with_snapshots: passed to `pvesm import` and used to select import format
1921# - allow_rename: passed to `pvesm import`
1922# - export_formats: used to select common transport format
1923# - unix: unix socket path
1924sub volume_import_start {
1925 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1926
1927 my $with_snapshots = $opts->{'with_snapshots'} ? 1 : 0;
1928
1929 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1930
1931 my $volid = "$storeid:$volname";
1932
1933 # find common import/export format, like volume_transfer_formats
1934 my @import_formats = PVE::Storage::volume_import_formats($cfg, $volid, $opts->{snapshot}, undef, $with_snapshots);
1935 my @export_formats = PVE::Tools::split_list($opts->{export_formats});
1936 my %import_hash = map { $_ => 1 } @import_formats;
1937 my @common = grep { $import_hash{$_} } @export_formats;
1938 die "no matching import/export format found for storage '$storeid'\n"
1939 if !@common;
1940 $format = $common[0];
1941
1942 my $input = IO::File->new();
1943 my $info = IO::File->new();
1944
1945 my $unix = $opts->{unix} // "/run/pve/storage-migrate-$vmid.$$.unix";
1946 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER, $opts);
1947
1948 unlink $unix;
1949 my $cpid = open3($input, $info, $info, @$import)
1950 or die "failed to spawn disk-import child - $!\n";
1951
1952 my $ready;
1953 eval {
1954 PVE::Tools::run_with_timeout(5, sub { $ready = <$info>; });
1955 };
1956
1957 die "failed to read readyness from disk import child: $@\n" if $@;
1958
1959 print "$ready\n";
1960
1961 return {
1962 fh => $info,
1963 pid => $cpid,
1964 socket => $unix,
1965 format => $format,
1966 };
1967}
1968
1969sub volume_export_start {
1970 my ($cfg, $volid, $format, $log, $opts) = @_;
1971
71460c8a
FG
1972 my $known_format = [ grep { $_ eq $format } $KNOWN_EXPORT_FORMATS->@* ];
1973 if (!$known_format->@*) {
1974 die "Cannot export '$volid' using unknown export format '$format'\n";
1975 }
1976 $format = $known_format->[0];
1977
3363fcf6
FG
1978 my $run_command_params = delete $opts->{cmd} // {};
1979
1980 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1981
1982 PVE::Tools::run_command($cmds, %$run_command_params);
1983}
1984
f7621c01
DM
1985# bash completion helper
1986
1987sub complete_storage {
746e530f 1988 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1989
746e530f 1990 my $cfg = PVE::Storage::config();
180c8b02 1991
746e530f 1992 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
f7621c01
DM
1993}
1994
1995sub complete_storage_enabled {
746e530f 1996 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1997
746e530f 1998 my $res = [];
f7621c01 1999
746e530f
DM
2000 my $cfg = PVE::Storage::config();
2001 foreach my $sid (keys %{$cfg->{ids}}) {
2002 next if !storage_check_enabled($cfg, $sid, undef, 1);
2003 push @$res, $sid;
2004 }
2005 return $res;
f7621c01
DM
2006}
2007
98437f4c
DM
2008sub complete_content_type {
2009 my ($cmdname, $pname, $cvalue) = @_;
2010
7c7ae12f 2011 return [qw(rootdir images vztmpl iso backup snippets)];
98437f4c
DM
2012}
2013
bf7aed26
DM
2014sub complete_volume {
2015 my ($cmdname, $pname, $cvalue) = @_;
2016
2017 my $cfg = config();
2018
2019 my $storage_list = complete_storage_enabled();
2020
b70b0c58
DM
2021 if ($cvalue =~ m/^([^:]+):/) {
2022 $storage_list = [ $1 ];
2023 } else {
2024 if (scalar(@$storage_list) > 1) {
2025 # only list storage IDs to avoid large listings
2026 my $res = [];
2027 foreach my $storeid (@$storage_list) {
2028 # Hack: simply return 2 artificial values, so that
2029 # completions does not finish
2030 push @$res, "$storeid:volname", "$storeid:...";
2031 }
2032 return $res;
2033 }
2034 }
2035
bf7aed26
DM
2036 my $res = [];
2037 foreach my $storeid (@$storage_list) {
2038 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
2039
2040 foreach my $item (@$vollist) {
2041 push @$res, $item->{volid};
2042 }
2043 }
2044
2045 return $res;
2046}
2047
95dfa44c
AL
2048sub rename_volume {
2049 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
2050
2051 die "no source volid provided\n" if !$source_volid;
2052 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
2053
2054 my ($storeid, $source_volname) = parse_volume_id($source_volid);
2055
2056 activate_storage($cfg, $storeid);
2057
2058 my $scfg = storage_config($cfg, $storeid);
2059 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
2060
2061 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
2062
2063 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
2064 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
2065 });
2066}
2067
9edb99a5
WB
2068# Various io-heavy operations require io/bandwidth limits which can be
2069# configured on multiple levels: The global defaults in datacenter.cfg, and
2070# per-storage overrides. When we want to do a restore from storage A to storage
2071# B, we should take the smaller limit defined for storages A and B, and if no
2072# such limit was specified, use the one from datacenter.cfg.
2073sub get_bandwidth_limit {
2074 my ($operation, $storage_list, $override) = @_;
2075
2076 # called for each limit (global, per-storage) with the 'default' and the
ffc31266 2077 # $operation limit and should update $override for every limit affecting
9edb99a5
WB
2078 # us.
2079 my $use_global_limits = 0;
2080 my $apply_limit = sub {
2081 my ($bwlimit) = @_;
2082 if (defined($bwlimit)) {
2083 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
2084 my $limit = $limits->{$operation} // $limits->{default};
2085 if (defined($limit)) {
2086 if (!$override || $limit < $override) {
2087 $override = $limit;
2088 }
2089 return;
2090 }
2091 }
2092 # If there was no applicable limit, try to apply the global ones.
2093 $use_global_limits = 1;
2094 };
2095
77445e9b
WB
2096 my ($rpcenv, $authuser);
2097 if (defined($override)) {
2098 $rpcenv = PVE::RPCEnvironment->get();
2099 $authuser = $rpcenv->get_user();
2100 }
9edb99a5
WB
2101
2102 # Apply per-storage limits - if there are storages involved.
0227e28e 2103 if (defined($storage_list) && grep { defined($_) } $storage_list->@*) {
9edb99a5
WB
2104 my $config = config();
2105
2106 # The Datastore.Allocate permission allows us to modify the per-storage
2107 # limits, therefore it also allows us to override them.
2108 # Since we have most likely multiple storages to check, do a quick check on
2109 # the general '/storage' path to see if we can skip the checks entirely:
77445e9b 2110 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
9edb99a5
WB
2111
2112 my %done;
2113 foreach my $storage (@$storage_list) {
396aedff 2114 next if !defined($storage);
9edb99a5
WB
2115 # Avoid duplicate checks:
2116 next if $done{$storage};
2117 $done{$storage} = 1;
2118
2119 # Otherwise we may still have individual /storage/$ID permissions:
77445e9b 2120 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
9edb99a5
WB
2121 # And if not: apply the limits.
2122 my $storecfg = storage_config($config, $storage);
2123 $apply_limit->($storecfg->{bwlimit});
2124 }
2125 }
2126
2127 # Storage limits take precedence over the datacenter defaults, so if
2128 # a limit was applied:
2129 return $override if !$use_global_limits;
2130 }
2131
2132 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2133 # global default limits.
77445e9b 2134 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
9edb99a5
WB
2135 # So if we cannot modify global limits, apply them to our currently
2136 # requested override.
2137 my $dc = cfs_read_file('datacenter.cfg');
2138 $apply_limit->($dc->{bwlimit});
2139 }
2140
2141 return $override;
2142}
2143
76c1e57b 2144# checks if the storage id is available and dies if not
9280153e
TL
2145sub assert_sid_unused {
2146 my ($sid) = @_;
76c1e57b
DC
2147
2148 my $cfg = config();
9280153e
TL
2149 if (my $scfg = storage_config($cfg, $sid, 1)) {
2150 die "storage ID '$sid' already defined\n";
76c1e57b
DC
2151 }
2152
2153 return undef;
2154}
2155
edda43ed
LS
2156# removes leading/trailing spaces and (back)slashes completely
2157# substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2158sub normalize_content_filename {
2159 my ($filename) = @_;
2160
2161 chomp $filename;
2162 $filename =~ s/^.*[\/\\]//;
2163 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;
2164
2165 return $filename;
2166}
2167
b6cf0a66 21681;