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