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