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