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