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