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