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