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