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