]> git.proxmox.com Git - pve-storage.git/blame - src/PVE/Storage.pm
fix whitespace
[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);
824 my $match_volid_and_log = sub {
825 my $line = shift;
826
827 $new_volid = $1 if ($line =~ $pattern);
828
829 if ($logfunc) {
830 chomp($line);
831 $logfunc->($line);
832 }
833 };
834
7a158d0b 835 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $logfunc, $opts);
5324ceff 836
da72898c
WB
837 eval {
838 if ($insecure) {
57acd6a1
FE
839 my $input = IO::File->new();
840 my $info = IO::File->new();
7a158d0b 841 open3($input, $info, $info, @$recv)
da72898c 842 or die "receive command failed: $!\n";
57acd6a1
FE
843 close($input);
844
7cdc75a2
FE
845 my $try_ip = <$info> // '';
846 my ($ip) = $try_ip =~ /^($PVE::Tools::IPRE)$/ # untaint
847 or die "no tunnel IP received, got '$try_ip'\n";
848
849 my $try_port = <$info> // '';
850 my ($port) = $try_port =~ /^(\d+)$/ # untaint
851 or die "no tunnel port received, got '$try_port'\n";
852
da72898c
WB
853 my $socket = IO::Socket::IP->new(PeerHost => $ip, PeerPort => $port, Type => SOCK_STREAM)
854 or die "failed to connect to tunnel at $ip:$port\n";
855 # we won't be reading from the socket
856 shutdown($socket, 0);
57acd6a1 857
7a158d0b 858 eval { run_command($cmds, output => '>&'.fileno($socket), errfunc => $logfunc); };
57acd6a1
FE
859 my $send_error = $@;
860
da72898c
WB
861 # don't close the connection entirely otherwise the receiving end
862 # might not get all buffered data (and fails with 'connection reset by peer')
863 shutdown($socket, 1);
aca83310
FE
864
865 # wait for the remote process to finish
a97d3ee4
FE
866 while (my $line = <$info>) {
867 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
aca83310
FE
868 }
869
da72898c
WB
870 # now close the socket
871 close($socket);
872 if (!close($info)) { # does waitpid()
873 die "import failed: $!\n" if $!;
874 die "import failed: exit code ".($?>>8)."\n";
0a29ad61 875 }
57acd6a1
FE
876
877 die $send_error if $send_error;
0a29ad61 878 } else {
7a158d0b
FG
879 push @$cmds, $recv;
880 run_command($cmds, logfunc => $match_volid_and_log);
0a29ad61 881 }
a97d3ee4
FE
882
883 die "unable to get ID of the migrated volume\n"
884 if !defined($new_volid) && $target_apiver >= 5;
da72898c
WB
885 };
886 my $err = $@;
887 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
7a158d0b
FG
888 if ($opts->{migration_snapshot}) {
889 eval { volume_snapshot_delete($cfg, $volid, $opts->{snapshot}, 0) };
da72898c 890 warn "could not remove source snapshot: $@\n" if $@;
b6cf0a66 891 }
da72898c 892 die $err if $err;
a97d3ee4
FE
893
894 return $new_volid // $target_volid;
b6cf0a66
DM
895}
896
2502b33b 897sub vdisk_clone {
7bbc4004 898 my ($cfg, $volid, $vmid, $snap) = @_;
1a3459ac 899
2502b33b
DM
900 my ($storeid, $volname) = parse_volume_id($volid);
901
902 my $scfg = storage_config($cfg, $storeid);
903
904 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 905
2502b33b
DM
906 activate_storage($cfg, $storeid);
907
908 # lock shared storage
909 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
7bbc4004 910 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
2502b33b
DM
911 return "$storeid:$volname";
912 });
913}
914
915sub vdisk_create_base {
916 my ($cfg, $volid) = @_;
917
918 my ($storeid, $volname) = parse_volume_id($volid);
919
920 my $scfg = storage_config($cfg, $storeid);
921
922 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 923
2502b33b
DM
924 activate_storage($cfg, $storeid);
925
926 # lock shared storage
927 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
928 my $volname = $plugin->create_base($storeid, $scfg, $volname);
929 return "$storeid:$volname";
930 });
931}
932
40d69893
DM
933sub map_volume {
934 my ($cfg, $volid, $snapname) = @_;
935
936 my ($storeid, $volname) = parse_volume_id($volid);
937
938 my $scfg = storage_config($cfg, $storeid);
939
940 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
941
942 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
943}
944
945sub unmap_volume {
946 my ($cfg, $volid, $snapname) = @_;
947
948 my ($storeid, $volname) = parse_volume_id($volid);
949
950 my $scfg = storage_config($cfg, $storeid);
951
952 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
953
954 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
955}
956
1dc01b9f
DM
957sub vdisk_alloc {
958 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
b6cf0a66 959
82fc923f 960 die "no storage ID specified\n" if !$storeid;
b6cf0a66 961
1dc01b9f 962 PVE::JSONSchema::parse_storage_id($storeid);
b6cf0a66 963
1dc01b9f 964 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 965
1dc01b9f 966 die "no VMID specified\n" if !$vmid;
b6cf0a66 967
1dc01b9f 968 $vmid = parse_vmid($vmid);
b6cf0a66 969
1dc01b9f 970 my $defformat = PVE::Storage::Plugin::default_format($scfg);
b6cf0a66 971
1dc01b9f 972 $fmt = $defformat if !$fmt;
b6cf0a66 973
1dc01b9f 974 activate_storage($cfg, $storeid);
3af60e62 975
1dc01b9f 976 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 977
1dc01b9f
DM
978 # lock shared storage
979 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
afdfbe55
WB
980 my $old_umask = umask(umask|0037);
981 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
982 my $err = $@;
983 umask $old_umask;
984 die $err if $err;
1dc01b9f
DM
985 return "$storeid:$volname";
986 });
b6cf0a66
DM
987}
988
1dc01b9f
DM
989sub vdisk_free {
990 my ($cfg, $volid) = @_;
b6cf0a66 991
1dc01b9f 992 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f 993 my $scfg = storage_config($cfg, $storeid);
1dc01b9f 994 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 995
1dc01b9f 996 activate_storage($cfg, $storeid);
b6cf0a66 997
1dc01b9f 998 my $cleanup_worker;
b6cf0a66 999
1dc01b9f
DM
1000 # lock shared storage
1001 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
787624df 1002 # LVM-thin allows deletion of still referenced base volumes!
17fb7e42 1003 die "base volume '$volname' is still in use by linked clones\n"
50853be2 1004 if volume_is_base_and_used($cfg, $volid);
32437ed2 1005
17fb7e42 1006 my (undef, undef, undef, undef, undef, $isBase, $format) =
32437ed2 1007 $plugin->parse_volname($volname);
35533c68 1008 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1dc01b9f 1009 });
b6cf0a66 1010
1dc01b9f 1011 return if !$cleanup_worker;
b6cf0a66 1012
1dc01b9f
DM
1013 my $rpcenv = PVE::RPCEnvironment::get();
1014 my $authuser = $rpcenv->get_user();
b6cf0a66 1015
1dc01b9f 1016 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
b6cf0a66
DM
1017}
1018
b6cf0a66 1019sub vdisk_list {
2c5246e1 1020 my ($cfg, $storeid, $vmid, $vollist, $ctype) = @_;
b6cf0a66
DM
1021
1022 my $ids = $cfg->{ids};
1023
1024 storage_check_enabled($cfg, $storeid) if ($storeid);
1025
d96b789a 1026 my $res = $storeid ? { $storeid => [] } : {};
b6cf0a66
DM
1027
1028 # prepare/activate/refresh all storages
1029
b6cf0a66
DM
1030 my $storage_list = [];
1031 if ($vollist) {
1032 foreach my $volid (@$vollist) {
1dc01b9f
DM
1033 my ($sid, undef) = parse_volume_id($volid);
1034 next if !defined($ids->{$sid});
b6cf0a66
DM
1035 next if !storage_check_enabled($cfg, $sid, undef, 1);
1036 push @$storage_list, $sid;
b6cf0a66
DM
1037 }
1038 } else {
1039 foreach my $sid (keys %$ids) {
1040 next if $storeid && $storeid ne $sid;
1041 next if !storage_check_enabled($cfg, $sid, undef, 1);
c43655d2 1042 my $content = $ids->{$sid}->{content};
2c5246e1 1043 next if defined($ctype) && !$content->{$ctype};
c43655d2 1044 next if !($content->{rootdir} || $content->{images});
b6cf0a66 1045 push @$storage_list, $sid;
b6cf0a66
DM
1046 }
1047 }
1048
1dc01b9f 1049 my $cache = {};
b6cf0a66 1050
1dc01b9f 1051 activate_storage_list($cfg, $storage_list, $cache);
b6cf0a66 1052
d96b789a 1053 for my $sid ($storage_list->@*) {
1dc01b9f 1054 next if $storeid && $storeid ne $sid;
b6cf0a66 1055
1dc01b9f
DM
1056 my $scfg = $ids->{$sid};
1057 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1058 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
b6cf0a66
DM
1059 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
1060 }
1061
1062 return $res;
1063}
1064
c2fc9fbe
DM
1065sub template_list {
1066 my ($cfg, $storeid, $tt) = @_;
1067
1068 die "unknown template type '$tt'\n"
1069 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
1070
1071 my $ids = $cfg->{ids};
1072
1073 storage_check_enabled($cfg, $storeid) if ($storeid);
1074
1075 my $res = {};
1076
1077 # query the storage
1078 foreach my $sid (keys %$ids) {
1079 next if $storeid && $storeid ne $sid;
1080
1081 my $scfg = $ids->{$sid};
1082 my $type = $scfg->{type};
1083
1084 next if !$scfg->{content}->{$tt};
1085
1086 next if !storage_check_enabled($cfg, $sid, undef, 1);
1087
1088 $res->{$sid} = volume_list($cfg, $sid, undef, $tt);
1089 }
1090
1091 return $res;
1092}
1093
37ba0aea
DM
1094sub volume_list {
1095 my ($cfg, $storeid, $vmid, $content) = @_;
1096
be785439 1097 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
37ba0aea
DM
1098
1099 my $cts = $content ? [ $content ] : [ @ctypes ];
1100
1101 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
1102
c2fc9fbe 1103 $cts = [ grep { defined($scfg->{content}->{$_}) } @$cts ];
37ba0aea 1104
c2fc9fbe 1105 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
37ba0aea 1106
c2fc9fbe
DM
1107 activate_storage($cfg, $storeid);
1108
1109 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1110
1111 @$res = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @$res;
37ba0aea
DM
1112
1113 return $res;
1114}
1115
b6cf0a66
DM
1116sub uevent_seqnum {
1117
1118 my $filename = "/sys/kernel/uevent_seqnum";
1119
1120 my $seqnum = 0;
1dc01b9f 1121 if (my $fh = IO::File->new($filename, "r")) {
b6cf0a66
DM
1122 my $line = <$fh>;
1123 if ($line =~ m/^(\d+)$/) {
1dc01b9f 1124 $seqnum = int($1);
b6cf0a66
DM
1125 }
1126 close ($fh);
1127 }
1128 return $seqnum;
1129}
1130
f3d4ef46 1131sub activate_storage {
1dc01b9f 1132 my ($cfg, $storeid, $cache) = @_;
b6cf0a66 1133
f3d4ef46
DM
1134 $cache = {} if !$cache;
1135
b6cf0a66
DM
1136 my $scfg = storage_check_enabled($cfg, $storeid);
1137
1dc01b9f 1138 return if $cache->{activated}->{$storeid};
b6cf0a66 1139
1dc01b9f 1140 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
b6cf0a66 1141
1dc01b9f 1142 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 1143
1dc01b9f
DM
1144 if ($scfg->{base}) {
1145 my ($baseid, undef) = parse_volume_id ($scfg->{base});
f3d4ef46
DM
1146 activate_storage($cfg, $baseid, $cache);
1147 }
1148
38431808
FE
1149 if (! eval { $plugin->check_connection($storeid, $scfg) }) {
1150 die "connection check for storage '$storeid' failed - $@\n" if $@;
f3d4ef46 1151 die "storage '$storeid' is not online\n";
b6cf0a66
DM
1152 }
1153
1dc01b9f
DM
1154 $plugin->activate_storage($storeid, $scfg, $cache);
1155
b6cf0a66
DM
1156 my $newseq = uevent_seqnum ();
1157
1158 # only call udevsettle if there are events
1dc01b9f 1159 if ($newseq > $cache->{uevent_seqnum}) {
d3a5e309 1160 system ("udevadm settle --timeout=30"); # ignore errors
1dc01b9f 1161 $cache->{uevent_seqnum} = $newseq;
b6cf0a66
DM
1162 }
1163
1dc01b9f 1164 $cache->{activated}->{$storeid} = 1;
b6cf0a66
DM
1165}
1166
1167sub activate_storage_list {
1dc01b9f 1168 my ($cfg, $storeid_list, $cache) = @_;
b6cf0a66 1169
1dc01b9f 1170 $cache = {} if !$cache;
b6cf0a66
DM
1171
1172 foreach my $storeid (@$storeid_list) {
f3d4ef46 1173 activate_storage($cfg, $storeid, $cache);
b6cf0a66
DM
1174 }
1175}
1176
1dc01b9f
DM
1177sub deactivate_storage {
1178 my ($cfg, $storeid) = @_;
1179
1180 my $scfg = storage_config ($cfg, $storeid);
1181 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 1182
1dc01b9f
DM
1183 my $cache = {};
1184 $plugin->deactivate_storage($storeid, $scfg, $cache);
b6cf0a66
DM
1185}
1186
1187sub activate_volumes {
02e797b8 1188 my ($cfg, $vollist, $snapname) = @_;
6703353b
DM
1189
1190 return if !($vollist && scalar(@$vollist));
1191
b6cf0a66
DM
1192 my $storagehash = {};
1193 foreach my $volid (@$vollist) {
1dc01b9f 1194 my ($storeid, undef) = parse_volume_id($volid);
b6cf0a66
DM
1195 $storagehash->{$storeid} = 1;
1196 }
1197
1dc01b9f
DM
1198 my $cache = {};
1199
1200 activate_storage_list($cfg, [keys %$storagehash], $cache);
b6cf0a66
DM
1201
1202 foreach my $volid (@$vollist) {
5521b580 1203 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f
DM
1204 my $scfg = storage_config($cfg, $storeid);
1205 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
02e797b8 1206 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
b6cf0a66
DM
1207 }
1208}
1209
1210sub deactivate_volumes {
02e797b8 1211 my ($cfg, $vollist, $snapname) = @_;
b6cf0a66 1212
6703353b
DM
1213 return if !($vollist && scalar(@$vollist));
1214
1dc01b9f
DM
1215 my $cache = {};
1216
6703353b 1217 my @errlist = ();
b6cf0a66 1218 foreach my $volid (@$vollist) {
1dc01b9f 1219 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 1220
1dc01b9f
DM
1221 my $scfg = storage_config($cfg, $storeid);
1222 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 1223
1dc01b9f 1224 eval {
02e797b8 1225 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1dc01b9f
DM
1226 };
1227 if (my $err = $@) {
1228 warn $err;
1229 push @errlist, $volid;
b6cf0a66
DM
1230 }
1231 }
6703353b 1232
82fc923f 1233 die "volume deactivation failed: " . join(' ', @errlist)
6703353b 1234 if scalar(@errlist);
b6cf0a66
DM
1235}
1236
1a3459ac 1237sub storage_info {
856c54bd 1238 my ($cfg, $content, $includeformat) = @_;
b6cf0a66
DM
1239
1240 my $ids = $cfg->{ids};
1241
1242 my $info = {};
ff3badd8 1243
583c2802 1244 my @ctypes = PVE::Tools::split_list($content);
ff3badd8 1245
b6cf0a66
DM
1246 my $slist = [];
1247 foreach my $storeid (keys %$ids) {
6ce4f724 1248 my $storage_enabled = defined(storage_check_enabled($cfg, $storeid, undef, 1));
b6cf0a66 1249
d73060be
DM
1250 if (defined($content)) {
1251 my $want_ctype = 0;
1252 foreach my $ctype (@ctypes) {
1253 if ($ids->{$storeid}->{content}->{$ctype}) {
1254 $want_ctype = 1;
1255 last;
1256 }
583c2802 1257 }
6ce4f724 1258 next if !$want_ctype || !$storage_enabled;
583c2802 1259 }
ff3badd8 1260
b6cf0a66
DM
1261 my $type = $ids->{$storeid}->{type};
1262
1a3459ac 1263 $info->{$storeid} = {
b6cf0a66 1264 type => $type,
1a3459ac
DM
1265 total => 0,
1266 avail => 0,
1267 used => 0,
04a2e4f3 1268 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1dc01b9f 1269 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
b6cf0a66 1270 active => 0,
6ce4f724 1271 enabled => $storage_enabled ? 1 : 0,
b6cf0a66
DM
1272 };
1273
b6cf0a66
DM
1274 push @$slist, $storeid;
1275 }
1276
1dc01b9f 1277 my $cache = {};
b6cf0a66 1278
b6cf0a66
DM
1279 foreach my $storeid (keys %$ids) {
1280 my $scfg = $ids->{$storeid};
b43b073b 1281
b6cf0a66 1282 next if !$info->{$storeid};
b43b073b 1283 next if !$info->{$storeid}->{enabled};
b6cf0a66 1284
856c54bd
DC
1285 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1286 if ($includeformat) {
1287 my $pd = $plugin->plugindata();
1288 $info->{$storeid}->{format} = $pd->{format}
1289 if $pd->{format};
1290 $info->{$storeid}->{select_existing} = $pd->{select_existing}
1291 if $pd->{select_existing};
1292 }
1293
f3d4ef46
DM
1294 eval { activate_storage($cfg, $storeid, $cache); };
1295 if (my $err = $@) {
1296 warn $err;
1297 next;
1298 }
1299
41aacc6c 1300 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
7028645e 1301 warn $@ if $@;
1dc01b9f 1302 next if !$active;
ff3badd8
DM
1303 $info->{$storeid}->{total} = int($total);
1304 $info->{$storeid}->{avail} = int($avail);
1305 $info->{$storeid}->{used} = int($used);
1dc01b9f 1306 $info->{$storeid}->{active} = $active;
b6cf0a66
DM
1307 }
1308
1309 return $info;
1310}
1311
1312sub resolv_server {
1313 my ($server) = @_;
1a3459ac 1314
c67daeac
WB
1315 my ($packed_ip, $family);
1316 eval {
1317 my @res = PVE::Tools::getaddrinfo_all($server);
1318 $family = $res[0]->{family};
1319 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1320 };
b6cf0a66 1321 if (defined $packed_ip) {
ee302b1c 1322 return Socket::inet_ntop($family, $packed_ip);
b6cf0a66
DM
1323 }
1324 return undef;
1325}
1326
1327sub scan_nfs {
1328 my ($server_in) = @_;
1329
1330 my $server;
1331 if (!($server = resolv_server ($server_in))) {
1332 die "unable to resolve address for server '${server_in}'\n";
1333 }
1334
1335 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1336
1337 my $res = {};
f81372ac 1338 run_command($cmd, outfunc => sub {
b6cf0a66
DM
1339 my $line = shift;
1340
1341 # note: howto handle white spaces in export path??
1342 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1343 $res->{$1} = $2;
1344 }
1345 });
1346
1347 return $res;
1348}
1349
4cab0acd
WL
1350sub scan_cifs {
1351 my ($server_in, $user, $password, $domain) = @_;
1352
436773fd
TL
1353 my $server = resolv_server($server_in);
1354 die "unable to resolve address for server '${server_in}'\n" if !$server;
4cab0acd 1355
436773fd 1356 # we only support Windows 2012 and newer, so just use smb3
4cab0acd 1357 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
fd55f51e 1358 push @$cmd, '-W', $domain if defined($domain);
afaa98f1 1359
8594155a 1360 push @$cmd, '-N' if !defined($password);
afaa98f1
TL
1361 local $ENV{USER} = $user if defined($user);
1362 local $ENV{PASSWD} = $password if defined($password);
4cab0acd
WL
1363
1364 my $res = {};
be18d6da 1365 my $err = '';
4cab0acd 1366 run_command($cmd,
436773fd 1367 noerr => 1,
be18d6da
TL
1368 errfunc => sub {
1369 $err .= "$_[0]\n"
1370 },
436773fd
TL
1371 outfunc => sub {
1372 my $line = shift;
1373 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1374 $res->{$1} = $2;
c42d8655
TL
1375 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1376 my $status = $1;
1377 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
436773fd
TL
1378 }
1379 },
4cab0acd 1380 );
d37729b9
TL
1381 # only die if we got no share, else it's just some followup check error
1382 # (like workgroup querying)
1383 raise($err) if $err && !%$res;
4cab0acd
WL
1384
1385 return $res;
1386}
1387
584d97f6
DM
1388sub scan_zfs {
1389
3881e680 1390 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
584d97f6
DM
1391
1392 my $res = [];
1393 run_command($cmd, outfunc => sub {
1394 my $line = shift;
1395
1396 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
3932390b 1397 my ($pool, $size_str, $used_str) = ($1, $2, $3);
3881e680
AL
1398 my $size = $size_str + 0;
1399 my $used = $used_str + 0;
48e27f79 1400 # ignore subvolumes generated by our ZFSPoolPlugin
851658c3
WL
1401 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1402 return if $pool =~ m!/basevol-\d+-[^/]+$!;
3932390b 1403 push @$res, { pool => $pool, size => $size, free => $size-$used };
584d97f6
DM
1404 }
1405 });
1406
1407 return $res;
1408}
1409
b6cf0a66
DM
1410sub resolv_portal {
1411 my ($portal, $noerr) = @_;
1412
1689e627
WB
1413 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1414 if ($server) {
b6cf0a66
DM
1415 if (my $ip = resolv_server($server)) {
1416 $server = $ip;
1689e627 1417 $server = "[$server]" if $server =~ /^$IPV6RE$/;
b6cf0a66
DM
1418 return $port ? "$server:$port" : $server;
1419 }
1420 }
1421 return undef if $noerr;
1422
1423 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1424}
1425
b6cf0a66
DM
1426
1427sub scan_iscsi {
1428 my ($portal_in) = @_;
1429
1430 my $portal;
1dc01b9f 1431 if (!($portal = resolv_portal($portal_in))) {
b6cf0a66
DM
1432 die "unable to parse/resolve portal address '${portal_in}'\n";
1433 }
1434
1dc01b9f 1435 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
b6cf0a66
DM
1436}
1437
1438sub storage_default_format {
1439 my ($cfg, $storeid) = @_;
1440
1441 my $scfg = storage_config ($cfg, $storeid);
1442
1dc01b9f 1443 return PVE::Storage::Plugin::default_format($scfg);
b6cf0a66
DM
1444}
1445
1446sub vgroup_is_used {
1447 my ($cfg, $vgname) = @_;
1448
1449 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1450 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1451 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1452 return 1;
1453 }
1454 }
1455
1456 return undef;
1457}
1458
1459sub target_is_used {
1460 my ($cfg, $target) = @_;
1461
1462 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1463 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1464 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1465 return 1;
1466 }
1467 }
1468
1469 return undef;
1470}
1471
1472sub volume_is_used {
1473 my ($cfg, $volid) = @_;
1474
1475 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1476 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1477 if ($scfg->{base} && $scfg->{base} eq $volid) {
1478 return 1;
1479 }
1480 }
1481
1482 return undef;
1483}
1484
1485sub storage_is_used {
1486 my ($cfg, $storeid) = @_;
1487
1488 foreach my $sid (keys %{$cfg->{ids}}) {
1dc01b9f 1489 my $scfg = storage_config($cfg, $sid);
b6cf0a66 1490 next if !$scfg->{base};
1dc01b9f 1491 my ($st) = parse_volume_id($scfg->{base});
b6cf0a66
DM
1492 return 1 if $st && $st eq $storeid;
1493 }
1494
1495 return undef;
1496}
1497
1498sub foreach_volid {
1499 my ($list, $func) = @_;
1500
1501 return if !$list;
1502
1503 foreach my $sid (keys %$list) {
1504 foreach my $info (@{$list->{$sid}}) {
618bdfd9 1505 my $volid = $info->{volid};
1dc01b9f 1506 my ($sid1, $volname) = parse_volume_id($volid, 1);
b6cf0a66
DM
1507 if ($sid1 && $sid1 eq $sid) {
1508 &$func ($volid, $sid, $info);
1509 } else {
1510 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1511 }
1512 }
1513 }
1514}
1515
cd554b79
AA
1516sub decompressor_info {
1517 my ($format, $comp) = @_;
1518
1519 if ($format eq 'tgz' && !defined($comp)) {
1520 ($format, $comp) = ('tar', 'gz');
1521 }
1522
1523 my $decompressor = {
1524 tar => {
1525 gz => ['tar', '-z'],
1526 lzo => ['tar', '--lzop'],
014d36db 1527 zst => ['tar', '--zstd'],
cd554b79
AA
1528 },
1529 vma => {
1530 gz => ['zcat'],
1531 lzo => ['lzop', '-d', '-c'],
014d36db 1532 zst => ['zstd', '-q', '-d', '-c'],
cd554b79
AA
1533 },
1534 };
1535
1536 die "ERROR: archive format not defined\n"
1537 if !defined($decompressor->{$format});
1538
1207620c
TL
1539 my $decomp;
1540 $decomp = $decompressor->{$format}->{$comp} if $comp;
cd554b79
AA
1541
1542 my $info = {
1543 format => $format,
1544 compression => $comp,
1545 decompressor => $decomp,
1546 };
1547
1548 return $info;
1549}
1550
56897a92
FE
1551sub protection_file_path {
1552 my ($path) = @_;
1553
1554 return "${path}.protected";
1555}
1556
cd554b79
AA
1557sub archive_info {
1558 my ($archive) = shift;
1559 my $info;
1560
1561 my $volid = basename($archive);
18bf2e59 1562 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+$BACKUP_EXT_RE_2)$/) {
e34afeb1 1563 my $filename = "$1"; # untaint
18bf2e59
LS
1564 my ($type, $extension, $comp) = ($2, $3, $4);
1565 (my $format = $extension) =~ s/\..*//;
fb821c18 1566 $info = decompressor_info($format, $comp);
e34afeb1 1567 $info->{filename} = $filename;
fb821c18
FE
1568 $info->{type} = $type;
1569
18bf2e59 1570 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
1571 $info->{logfilename} = "$1".PVE::Storage::Plugin::LOG_EXT;
1572 $info->{notesfilename} = "$filename".PVE::Storage::Plugin::NOTES_EXT;
e34afeb1 1573 $info->{vmid} = int($2);
b1ddc54a 1574 $info->{ctime} = timelocal($8, $7, $6, $5, $4 - 1, $3);
fb821c18
FE
1575 $info->{is_std_name} = 1;
1576 } else {
1577 $info->{is_std_name} = 0;
1578 }
cd554b79 1579 } else {
bf5af0fb 1580 die "ERROR: couldn't determine archive info from '$archive'\n";
cd554b79
AA
1581 }
1582
1583 return $info;
1584}
1585
35a39532
FE
1586sub archive_remove {
1587 my ($archive_path) = @_;
1588
56897a92
FE
1589 die "cannot remove protected archive '$archive_path'\n"
1590 if -e protection_file_path($archive_path);
1591
e573445e 1592 unlink $archive_path or $! == ENOENT or die "removing archive $archive_path failed: $!\n";
c3e2ff80
DT
1593
1594 archive_auxiliaries_remove($archive_path);
1595}
1596
1597sub archive_auxiliaries_remove {
1598 my ($archive_path) = @_;
1599
35a39532
FE
1600 my $dirname = dirname($archive_path);
1601 my $archive_info = eval { archive_info($archive_path) } // {};
35a39532 1602
c3e2ff80
DT
1603 for my $type (qw(log notes)) {
1604 my $filename = $archive_info->{"${type}filename"} or next;
1605 my $path = "$dirname/$filename";
35a39532 1606
c3e2ff80 1607 if (-e $path) {
3048641b 1608 unlink $path or $! == ENOENT or log_warn("Removing $type file failed: $!");
35a39532
FE
1609 }
1610 }
1611}
1612
8898dd7b
FG
1613sub extract_vzdump_config_tar {
1614 my ($archive, $conf_re) = @_;
1615
1616 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1617
1618 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1619 die "unable to open file '$archive'\n";
1620
1621 my $file;
1622 while (defined($file = <$fh>)) {
086c4bf1 1623 if ($file =~ $conf_re) {
8898dd7b
FG
1624 $file = $1; # untaint
1625 last;
1626 }
1627 }
1628
1629 kill 15, $pid;
1630 waitpid $pid, 0;
1631 close $fh;
1632
1633 die "ERROR: archive contains no configuration file\n" if !$file;
1634 chomp $file;
1635
1636 my $raw = '';
1637 my $out = sub {
1638 my $output = shift;
1639 $raw .= "$output\n";
1640 };
1641
63e89295 1642 run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
8898dd7b
FG
1643
1644 return wantarray ? ($raw, $file) : $raw;
1645}
1646
1647sub extract_vzdump_config_vma {
1648 my ($archive, $comp) = @_;
1649
8898dd7b 1650 my $raw = '';
63e89295 1651 my $out = sub { $raw .= "$_[0]\n"; };
8898dd7b 1652
cd554b79
AA
1653 my $info = archive_info($archive);
1654 $comp //= $info->{compression};
1655 my $decompressor = $info->{decompressor};
1656
8898dd7b 1657 if ($comp) {
63e89295 1658 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
8898dd7b 1659
63e89295 1660 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
8898dd7b
FG
1661 my $broken_pipe;
1662 my $errstring;
1663 my $err = sub {
1664 my $output = shift;
576e560d 1665 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error.*Broken pipe/) {
8898dd7b
FG
1666 $broken_pipe = 1;
1667 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1668 $errstring = "Failed to extract config from VMA archive: $output\n";
1669 }
1670 };
1671
63e89295 1672 my $rc = eval { run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1) };
8898dd7b
FG
1673 my $rerr = $@;
1674
63e89295
TL
1675 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1676
1677 if (!$errstring && !$broken_pipe && $rc != 0) {
8898dd7b
FG
1678 die "$rerr\n" if $rerr;
1679 die "config extraction failed with exit code $rc\n";
1680 }
1681 die "$errstring\n" if $errstring;
1682 } else {
63e89295 1683 run_command(["vma", "config", $archive], outfunc => $out);
8898dd7b
FG
1684 }
1685
1686 return wantarray ? ($raw, undef) : $raw;
1687}
1688
1689sub extract_vzdump_config {
1690 my ($cfg, $volid) = @_;
1691
c855ac15
DM
1692 my ($storeid, $volname) = parse_volume_id($volid);
1693 if (defined($storeid)) {
1694 my $scfg = storage_config($cfg, $storeid);
1695 if ($scfg->{type} eq 'pbs') {
1696 storage_check_enabled($cfg, $storeid);
1697 return PVE::Storage::PBSPlugin->extract_vzdump_config($scfg, $volname, $storeid);
1698 }
1699 }
1700
8898dd7b 1701 my $archive = abs_filesystem_path($cfg, $volid);
cd554b79
AA
1702 my $info = archive_info($archive);
1703 my $format = $info->{format};
1704 my $comp = $info->{compression};
1705 my $type = $info->{type};
8898dd7b 1706
cd554b79 1707 if ($type eq 'lxc' || $type eq 'openvz') {
086c4bf1 1708 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
cd554b79 1709 } elsif ($type eq 'qemu') {
8898dd7b
FG
1710 if ($format eq 'tar') {
1711 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1712 } else {
1713 return extract_vzdump_config_vma($archive, $comp);
1714 }
1715 } else {
1716 die "cannot determine backup guest type for backup archive '$volid'\n";
1717 }
1718}
1719
8f26b391
FE
1720sub prune_backups {
1721 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1722
1723 my $scfg = storage_config($cfg, $storeid);
1724 die "storage '$storeid' does not support backups\n" if !$scfg->{content}->{backup};
1725
1726 if (!defined($keep)) {
1727 die "no prune-backups options configured for storage '$storeid'\n"
1728 if !defined($scfg->{'prune-backups'});
1729 $keep = PVE::JSONSchema::parse_property_string('prune-backups', $scfg->{'prune-backups'});
1730 }
1731
883c811f
FE
1732 activate_storage($cfg, $storeid);
1733
8f26b391
FE
1734 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1735 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1736}
1737
1738my $prune_mark = sub {
1739 my ($prune_entries, $keep_count, $id_func) = @_;
1740
1741 return if !$keep_count;
1742
1743 my $already_included = {};
1744 my $newly_included = {};
1745
1746 foreach my $prune_entry (@{$prune_entries}) {
1747 my $mark = $prune_entry->{mark};
1748 my $id = $id_func->($prune_entry->{ctime});
10dfeb9e
FE
1749 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1750 }
8f26b391 1751
10dfeb9e
FE
1752 foreach my $prune_entry (@{$prune_entries}) {
1753 my $mark = $prune_entry->{mark};
1754 my $id = $id_func->($prune_entry->{ctime});
8f26b391 1755
10dfeb9e 1756 next if defined($mark) || $already_included->{$id};
8f26b391
FE
1757
1758 if (!$newly_included->{$id}) {
1759 last if scalar(keys %{$newly_included}) >= $keep_count;
1760 $newly_included->{$id} = 1;
1761 $prune_entry->{mark} = 'keep';
1762 } else {
1763 $prune_entry->{mark} = 'remove';
1764 }
1765 }
1766};
1767
1768sub prune_mark_backup_group {
1769 my ($backup_group, $keep) = @_;
1770
a000e26c 1771 my @positive_opts = grep { $_ ne 'keep-all' && $keep->{$_} > 0 } keys $keep->%*;
1b87f013 1772
a000e26c 1773 if ($keep->{'keep-all'} || scalar(@positive_opts) == 0) {
f514181d 1774 foreach my $prune_entry (@{$backup_group}) {
9a4c0e84
FE
1775 # preserve additional information like 'protected'
1776 next if $prune_entry->{mark} && $prune_entry->{mark} ne 'remove';
f514181d
FE
1777 $prune_entry->{mark} = 'keep';
1778 }
1779 return;
1780 }
1781
8f26b391
FE
1782 my $prune_list = [ sort { $b->{ctime} <=> $a->{ctime} } @{$backup_group} ];
1783
1784 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1785 my ($ctime) = @_;
1786 return $ctime;
1787 });
1788 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1789 my ($ctime) = @_;
1790 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1791 return "$hour/$day/$month/$year";
1792 });
1793 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1794 my ($ctime) = @_;
1795 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1796 return "$day/$month/$year";
1797 });
1798 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1799 my ($ctime) = @_;
1800 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
189e67ff
FE
1801 my $iso_week = int(strftime("%V", $sec, $min, $hour, $day, $month, $year));
1802 my $iso_week_year = int(strftime("%G", $sec, $min, $hour, $day, $month, $year));
8f26b391
FE
1803 return "$iso_week/$iso_week_year";
1804 });
1805 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1806 my ($ctime) = @_;
1807 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1808 return "$month/$year";
1809 });
1810 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1811 my ($ctime) = @_;
1812 my $year = (localtime($ctime))[5];
1813 return "$year";
1814 });
1815
1816 foreach my $prune_entry (@{$prune_list}) {
1817 $prune_entry->{mark} //= 'remove';
1818 }
1819}
1820
3cc29a04 1821sub volume_export : prototype($$$$$$$) {
47f37b53
WB
1822 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1823
1824 my ($storeid, $volname) = parse_volume_id($volid, 1);
1825 die "cannot export volume '$volid'\n" if !$storeid;
1826 my $scfg = storage_config($cfg, $storeid);
1827 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1828 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
618bdfd9 1829 $snapshot, $base_snapshot, $with_snapshots);
47f37b53
WB
1830}
1831
3cc29a04
WB
1832sub volume_import : prototype($$$$$$$$) {
1833 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
47f37b53
WB
1834
1835 my ($storeid, $volname) = parse_volume_id($volid, 1);
1836 die "cannot import into volume '$volid'\n" if !$storeid;
1837 my $scfg = storage_config($cfg, $storeid);
1838 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
3cc29a04
WB
1839 return $plugin->volume_import(
1840 $scfg,
1841 $storeid,
1842 $fh,
1843 $volname,
1844 $format,
1845 $snapshot,
1846 $base_snapshot,
1847 $with_snapshots,
1848 $allow_rename,
1849 ) // $volid;
1850}
1851
1852sub volume_export_formats : prototype($$$$$) {
d390328b
WB
1853 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1854
1855 my ($storeid, $volname) = parse_volume_id($volid, 1);
1856 return if !$storeid;
1857 my $scfg = storage_config($cfg, $storeid);
1858 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1859 return $plugin->volume_export_formats($scfg, $storeid, $volname,
618bdfd9
PH
1860 $snapshot, $base_snapshot,
1861 $with_snapshots);
d390328b
WB
1862}
1863
3cc29a04
WB
1864sub volume_import_formats : prototype($$$$$) {
1865 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
d390328b
WB
1866
1867 my ($storeid, $volname) = parse_volume_id($volid, 1);
1868 return if !$storeid;
1869 my $scfg = storage_config($cfg, $storeid);
1870 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
3cc29a04
WB
1871 return $plugin->volume_import_formats(
1872 $scfg,
1873 $storeid,
1874 $volname,
1875 $snapshot,
1876 $base_snapshot,
1877 $with_snapshots,
1878 );
d390328b
WB
1879}
1880
1881sub volume_transfer_formats {
1882 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1883 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
3cc29a04 1884 my @import_formats = volume_import_formats($cfg, $dst_volid, $snapshot, $base_snapshot, $with_snapshots);
d390328b
WB
1885 my %import_hash = map { $_ => 1 } @import_formats;
1886 my @common = grep { $import_hash{$_} } @export_formats;
1887 return @common;
1888}
1889
a97d3ee4
FE
1890sub volume_imported_message {
1891 my ($volid, $want_pattern) = @_;
1892
1893 if ($want_pattern) {
1894 return qr/successfully imported '([^']*)'$/;
1895 } else {
1896 return "successfully imported '$volid'\n";
1897 }
1898}
1899
3363fcf6
FG
1900# $format and $volname are requests and might be overruled depending on $opts
1901# $opts:
1902# - with_snapshots: passed to `pvesm import` and used to select import format
1903# - allow_rename: passed to `pvesm import`
1904# - export_formats: used to select common transport format
1905# - unix: unix socket path
1906sub volume_import_start {
1907 my ($cfg, $storeid, $volname, $format, $vmid, $opts) = @_;
1908
1909 my $with_snapshots = $opts->{'with_snapshots'} ? 1 : 0;
1910
1911 $volname = $volname_for_storage->($cfg, $storeid, $volname, $vmid, $format);
1912
1913 my $volid = "$storeid:$volname";
1914
1915 # find common import/export format, like volume_transfer_formats
1916 my @import_formats = PVE::Storage::volume_import_formats($cfg, $volid, $opts->{snapshot}, undef, $with_snapshots);
1917 my @export_formats = PVE::Tools::split_list($opts->{export_formats});
1918 my %import_hash = map { $_ => 1 } @import_formats;
1919 my @common = grep { $import_hash{$_} } @export_formats;
1920 die "no matching import/export format found for storage '$storeid'\n"
1921 if !@common;
1922 $format = $common[0];
1923
1924 my $input = IO::File->new();
1925 my $info = IO::File->new();
1926
1927 my $unix = $opts->{unix} // "/run/pve/storage-migrate-$vmid.$$.unix";
1928 my $import = $volume_import_prepare->($volid, $format, "unix://$unix", APIVER, $opts);
1929
1930 unlink $unix;
1931 my $cpid = open3($input, $info, $info, @$import)
1932 or die "failed to spawn disk-import child - $!\n";
1933
1934 my $ready;
1935 eval {
1936 PVE::Tools::run_with_timeout(5, sub { $ready = <$info>; });
1937 };
1938
1939 die "failed to read readyness from disk import child: $@\n" if $@;
1940
1941 print "$ready\n";
1942
1943 return {
1944 fh => $info,
1945 pid => $cpid,
1946 socket => $unix,
1947 format => $format,
1948 };
1949}
1950
1951sub volume_export_start {
1952 my ($cfg, $volid, $format, $log, $opts) = @_;
1953
71460c8a
FG
1954 my $known_format = [ grep { $_ eq $format } $KNOWN_EXPORT_FORMATS->@* ];
1955 if (!$known_format->@*) {
1956 die "Cannot export '$volid' using unknown export format '$format'\n";
1957 }
1958 $format = $known_format->[0];
1959
3363fcf6
FG
1960 my $run_command_params = delete $opts->{cmd} // {};
1961
1962 my $cmds = $volume_export_prepare->($cfg, $volid, $format, $log, $opts);
1963
1964 PVE::Tools::run_command($cmds, %$run_command_params);
1965}
1966
f7621c01
DM
1967# bash completion helper
1968
1969sub complete_storage {
746e530f 1970 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1971
746e530f 1972 my $cfg = PVE::Storage::config();
180c8b02 1973
746e530f 1974 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
f7621c01
DM
1975}
1976
1977sub complete_storage_enabled {
746e530f 1978 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1979
746e530f 1980 my $res = [];
f7621c01 1981
746e530f
DM
1982 my $cfg = PVE::Storage::config();
1983 foreach my $sid (keys %{$cfg->{ids}}) {
1984 next if !storage_check_enabled($cfg, $sid, undef, 1);
1985 push @$res, $sid;
1986 }
1987 return $res;
f7621c01
DM
1988}
1989
98437f4c
DM
1990sub complete_content_type {
1991 my ($cmdname, $pname, $cvalue) = @_;
1992
7c7ae12f 1993 return [qw(rootdir images vztmpl iso backup snippets)];
98437f4c
DM
1994}
1995
bf7aed26
DM
1996sub complete_volume {
1997 my ($cmdname, $pname, $cvalue) = @_;
1998
1999 my $cfg = config();
2000
2001 my $storage_list = complete_storage_enabled();
2002
b70b0c58
DM
2003 if ($cvalue =~ m/^([^:]+):/) {
2004 $storage_list = [ $1 ];
2005 } else {
2006 if (scalar(@$storage_list) > 1) {
2007 # only list storage IDs to avoid large listings
2008 my $res = [];
2009 foreach my $storeid (@$storage_list) {
2010 # Hack: simply return 2 artificial values, so that
2011 # completions does not finish
2012 push @$res, "$storeid:volname", "$storeid:...";
2013 }
2014 return $res;
2015 }
2016 }
2017
bf7aed26
DM
2018 my $res = [];
2019 foreach my $storeid (@$storage_list) {
2020 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
2021
2022 foreach my $item (@$vollist) {
2023 push @$res, $item->{volid};
2024 }
2025 }
2026
2027 return $res;
2028}
2029
95dfa44c
AL
2030sub rename_volume {
2031 my ($cfg, $source_volid, $target_vmid, $target_volname) = @_;
2032
2033 die "no source volid provided\n" if !$source_volid;
2034 die "no target VMID or target volname provided\n" if !$target_vmid && !$target_volname;
2035
2036 my ($storeid, $source_volname) = parse_volume_id($source_volid);
2037
2038 activate_storage($cfg, $storeid);
2039
2040 my $scfg = storage_config($cfg, $storeid);
2041 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
2042
2043 $target_vmid = ($plugin->parse_volname($source_volname))[3] if !$target_vmid;
2044
2045 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
2046 return $plugin->rename_volume($scfg, $storeid, $source_volname, $target_vmid, $target_volname);
2047 });
2048}
2049
9edb99a5
WB
2050# Various io-heavy operations require io/bandwidth limits which can be
2051# configured on multiple levels: The global defaults in datacenter.cfg, and
2052# per-storage overrides. When we want to do a restore from storage A to storage
2053# B, we should take the smaller limit defined for storages A and B, and if no
2054# such limit was specified, use the one from datacenter.cfg.
2055sub get_bandwidth_limit {
2056 my ($operation, $storage_list, $override) = @_;
2057
2058 # called for each limit (global, per-storage) with the 'default' and the
ffc31266 2059 # $operation limit and should update $override for every limit affecting
9edb99a5
WB
2060 # us.
2061 my $use_global_limits = 0;
2062 my $apply_limit = sub {
2063 my ($bwlimit) = @_;
2064 if (defined($bwlimit)) {
2065 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
2066 my $limit = $limits->{$operation} // $limits->{default};
2067 if (defined($limit)) {
2068 if (!$override || $limit < $override) {
2069 $override = $limit;
2070 }
2071 return;
2072 }
2073 }
2074 # If there was no applicable limit, try to apply the global ones.
2075 $use_global_limits = 1;
2076 };
2077
77445e9b
WB
2078 my ($rpcenv, $authuser);
2079 if (defined($override)) {
2080 $rpcenv = PVE::RPCEnvironment->get();
2081 $authuser = $rpcenv->get_user();
2082 }
9edb99a5
WB
2083
2084 # Apply per-storage limits - if there are storages involved.
0227e28e 2085 if (defined($storage_list) && grep { defined($_) } $storage_list->@*) {
9edb99a5
WB
2086 my $config = config();
2087
2088 # The Datastore.Allocate permission allows us to modify the per-storage
2089 # limits, therefore it also allows us to override them.
2090 # Since we have most likely multiple storages to check, do a quick check on
2091 # the general '/storage' path to see if we can skip the checks entirely:
77445e9b 2092 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
9edb99a5
WB
2093
2094 my %done;
2095 foreach my $storage (@$storage_list) {
396aedff 2096 next if !defined($storage);
9edb99a5
WB
2097 # Avoid duplicate checks:
2098 next if $done{$storage};
2099 $done{$storage} = 1;
2100
2101 # Otherwise we may still have individual /storage/$ID permissions:
77445e9b 2102 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
9edb99a5
WB
2103 # And if not: apply the limits.
2104 my $storecfg = storage_config($config, $storage);
2105 $apply_limit->($storecfg->{bwlimit});
2106 }
2107 }
2108
2109 # Storage limits take precedence over the datacenter defaults, so if
2110 # a limit was applied:
2111 return $override if !$use_global_limits;
2112 }
2113
2114 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
2115 # global default limits.
77445e9b 2116 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
9edb99a5
WB
2117 # So if we cannot modify global limits, apply them to our currently
2118 # requested override.
2119 my $dc = cfs_read_file('datacenter.cfg');
2120 $apply_limit->($dc->{bwlimit});
2121 }
2122
2123 return $override;
2124}
2125
76c1e57b 2126# checks if the storage id is available and dies if not
9280153e
TL
2127sub assert_sid_unused {
2128 my ($sid) = @_;
76c1e57b
DC
2129
2130 my $cfg = config();
9280153e
TL
2131 if (my $scfg = storage_config($cfg, $sid, 1)) {
2132 die "storage ID '$sid' already defined\n";
76c1e57b
DC
2133 }
2134
2135 return undef;
2136}
2137
edda43ed
LS
2138# removes leading/trailing spaces and (back)slashes completely
2139# substitutes every non-ASCII-alphanumerical char with '_', except '_.-'
2140sub normalize_content_filename {
2141 my ($filename) = @_;
2142
2143 chomp $filename;
2144 $filename =~ s/^.*[\/\\]//;
2145 $filename =~ s/[^a-zA-Z0-9_.-]/_/g;
2146
2147 return $filename;
2148}
2149
b6cf0a66 21501;