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