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