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