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