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