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