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