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