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